package settings import ( "encoding/json" "sort" "sync" "server/torr/state" "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"` Timestamp int64 `json:"timestamp,omitempty"` Size int64 `json:"size,omitempty"` Files []state.TorrentFileStat `json:"files,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() }