package torrent import ( "log" "github.com/debridmediamanager.com/zurg/pkg/realdebrid" "github.com/dgraph-io/ristretto" ) type TorrentManager struct { token string cache *ristretto.Cache workerPool chan bool } // NewTorrentManager creates a new torrent manager // it will fetch all torrents and their info in the background // and cache them func NewTorrentManager(token string) *TorrentManager { cache, err := ristretto.NewCache(&ristretto.Config{ NumCounters: 1e7, // number of keys to track frequency of (10M). MaxCost: 1 << 30, // maximum cost of cache (1GB). BufferItems: 64, // number of keys per Get buffer. }) if err != nil { panic(err) } handler := &TorrentManager{ token: token, cache: cache, workerPool: make(chan bool, 10), } torrents := handler.getAll() for _, torrent := range torrents { go func(id string) { handler.workerPool <- true handler.getInfo(id) // sleep for 1 second to avoid rate limiting <-handler.workerPool }(torrent.ID) } return handler } func (t *TorrentManager) getAll() []realdebrid.Torrent { cacheKey := "t:all" torrents, err := realdebrid.GetTorrents(t.token) if err != nil { log.Printf("Cannot get torrents: %v\n", err.Error()) return nil } t.cache.Set(cacheKey, torrents, 0) return torrents } func (t *TorrentManager) GetAll() []realdebrid.Torrent { cacheKey := "t:all" if data, found := t.cache.Get(cacheKey); found { if cachedTorrents, ok := data.([]realdebrid.Torrent); ok { return cachedTorrents } else { t.cache.Del(cacheKey) } } return t.getAll() } func (t *TorrentManager) getInfo(torrentID string) *realdebrid.Torrent { cacheKey := "t:" + torrentID info, err := realdebrid.GetTorrentInfo(t.token, torrentID) if err != nil { log.Printf("Cannot get info: %v\n", err.Error()) return nil } t.cache.Set(cacheKey, info, 0) return info } func (t *TorrentManager) GetInfo(torrentID string) *realdebrid.Torrent { cacheKey := "t:" + torrentID if data, found := t.cache.Get(cacheKey); found { if torrent, ok := data.(*realdebrid.Torrent); ok { return torrent } else { t.cache.Del(cacheKey) } } return t.getInfo(torrentID) }