Proper caching

This commit is contained in:
Ben Sarmiento
2023-10-18 12:36:34 +02:00
parent bd72dc4540
commit acee02377e
9 changed files with 126 additions and 65 deletions

View File

@@ -1,7 +1,9 @@
package torrent
import (
"encoding/gob"
"log"
"os"
"strings"
"sync"
@@ -58,6 +60,14 @@ func (t *TorrentManager) GetAll() []Torrent {
}
func (t *TorrentManager) getInfo(torrentID string) *Torrent {
torrentFromFile := t.readFromFile(torrentID)
if torrentFromFile != nil {
torrent := t.getByID(torrentID)
if torrent != nil {
torrent.SelectedFiles = torrentFromFile.SelectedFiles
}
return torrent
}
info, err := realdebrid.GetTorrentInfo(t.token, torrentID)
if err != nil {
log.Printf("Cannot get info: %v\n", err.Error())
@@ -123,26 +133,58 @@ func (t *TorrentManager) getInfo(torrentID string) *Torrent {
if torrent != nil {
torrent.SelectedFiles = selectedFiles
}
log.Println("Fetched info for", info.Filename)
if len(torrent.SelectedFiles) > 0 {
t.writeToFile(torrentID, torrent)
}
return torrent
}
func (t *TorrentManager) GetInfo(torrentID string) *Torrent {
for _, torrent := range t.torrents {
if torrent.ID == torrentID {
if torrent.SelectedFiles != nil {
return t.getInfo(torrentID)
}
return &torrent
}
}
return t.getInfo(torrentID)
}
func (t *TorrentManager) getByID(torrentID string) *Torrent {
for i, torrent := range t.torrents {
if torrent.ID == torrentID {
return &t.torrents[i]
}
}
return nil
}
func (t *TorrentManager) getByID(torrentID string) *Torrent {
for _, torrent := range t.torrents {
if torrent.ID == torrentID {
return &torrent
}
func (t *TorrentManager) writeToFile(torrentID string, torrent *Torrent) {
filePath := "data/" + torrentID + ".bin"
file, err := os.Create(filePath)
if err != nil {
log.Fatalf("Failed creating file: %s", err)
return
}
return nil
defer file.Close()
dataEncoder := gob.NewEncoder(file)
dataEncoder.Encode(torrent)
}
func (t *TorrentManager) readFromFile(torrentID string) *Torrent {
filePath := "data/" + torrentID + ".bin"
file, err := os.Open(filePath)
if err != nil {
return nil
}
defer file.Close()
var torrent Torrent
dataDecoder := gob.NewDecoder(file)
err = dataDecoder.Decode(&torrent)
if err != nil {
log.Fatalf("Failed decoding file: %s", err)
return nil
}
return &torrent
}