refactor and to go mod

This commit is contained in:
YouROK
2021-02-18 16:56:55 +03:00
parent 0e49a98626
commit 94f212fa75
50 changed files with 13 additions and 29 deletions

View File

@@ -0,0 +1,82 @@
package settings
import (
"encoding/json"
"sort"
"sync"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
)
type TorrentDB struct {
*torrent.TorrentSpec
Name string `json:"name"`
Title string `json:"title,omitempty"`
Poster string `json:"poster,omitempty"`
Data string `json:"data,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
Size int64 `json:"size,omitempty"`
}
type File struct {
Name string `json:"name,omitempty"`
Id int `json:"id,omitempty"`
Size int64 `json:"size,omitempty"`
}
var mu sync.Mutex
func AddTorrent(torr *TorrentDB) {
list := ListTorrent()
mu.Lock()
find := -1
for i, db := range list {
if db.InfoHash.HexString() == torr.InfoHash.HexString() {
find = i
break
}
}
if find != -1 {
list[find] = torr
} else {
list = append(list, torr)
}
for _, db := range list {
buf, err := json.Marshal(db)
if err == nil {
tdb.Set("Torrents", db.InfoHash.HexString(), buf)
}
}
mu.Unlock()
}
func ListTorrent() []*TorrentDB {
mu.Lock()
defer mu.Unlock()
var list []*TorrentDB
keys := tdb.List("Torrents")
for _, key := range keys {
buf := tdb.Get("Torrents", key)
if len(buf) > 0 {
var torr *TorrentDB
err := json.Unmarshal(buf, &torr)
if err == nil {
list = append(list, torr)
}
}
}
sort.Slice(list, func(i, j int) bool {
return list[i].Timestamp > list[j].Timestamp
})
return list
}
func RemTorrent(hash metainfo.Hash) {
mu.Lock()
tdb.Rem("Torrents", hash.HexString())
mu.Unlock()
}