100 lines
2.6 KiB
Go
100 lines
2.6 KiB
Go
package dav
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/debridmediamanager.com/zurg/pkg/dav"
|
|
"github.com/debridmediamanager.com/zurg/pkg/realdebrid"
|
|
"github.com/debridmediamanager.com/zurg/pkg/repo"
|
|
)
|
|
|
|
func createMultiTorrentResponse(torrents []realdebrid.Torrent) (*dav.MultiStatus, error) {
|
|
var responses []dav.Response
|
|
|
|
// initial response is the directory itself
|
|
responses = append(responses, dav.Directory("/torrents"))
|
|
|
|
// add all files and directories in the directory
|
|
for _, item := range torrents {
|
|
if item.Progress != 100 {
|
|
continue
|
|
}
|
|
|
|
path := filepath.Join("/torrents", item.Filename)
|
|
responses = append(responses, dav.Directory(path))
|
|
}
|
|
|
|
return &dav.MultiStatus{
|
|
XMLNS: "DAV:",
|
|
Response: responses,
|
|
}, nil
|
|
}
|
|
|
|
func createSingleTorrentResponse(torrent realdebrid.Torrent, db *repo.Database) (*dav.MultiStatus, error) {
|
|
var responses []dav.Response
|
|
|
|
// initial response is the directory itself
|
|
currentPath := filepath.Join("/torrents", torrent.Filename)
|
|
responses = append(responses, dav.Directory(currentPath))
|
|
|
|
davFiles, err := db.GetMultiple(torrent.Hash)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Create a map for O(1) lookups of the cached links
|
|
cachedLinksMap := make(map[string]*repo.DavFile)
|
|
for _, u := range davFiles.Files {
|
|
cachedLinksMap[u.Link] = u
|
|
}
|
|
for _, link := range torrent.Links {
|
|
if u, exists := cachedLinksMap[link]; exists {
|
|
if u.Filesize == 0 {
|
|
// This link is cached but the filesize is 0
|
|
// This means that the link is dead
|
|
continue
|
|
}
|
|
path := filepath.Join(currentPath, u.Filename)
|
|
response := dav.File(
|
|
path,
|
|
int(u.Filesize),
|
|
torrent.Added, // Assuming you want to use the torrent added time here
|
|
)
|
|
responses = append(responses, response)
|
|
} else {
|
|
// This link is not cached yet
|
|
unrestrictFn := func() (realdebrid.UnrestrictResponse, error) {
|
|
return realdebrid.UnrestrictCheck(os.Getenv("RD_TOKEN"), link)
|
|
}
|
|
unrestrictResponse := realdebrid.RetryUntilOk(unrestrictFn)
|
|
if unrestrictResponse == nil {
|
|
db.Insert(torrent.Hash, torrent.Filename, realdebrid.UnrestrictResponse{
|
|
Filename: "",
|
|
Filesize: 0,
|
|
Link: link,
|
|
Host: "",
|
|
})
|
|
continue
|
|
} else {
|
|
db.Insert(torrent.Hash, torrent.Filename, *unrestrictResponse)
|
|
}
|
|
|
|
path := filepath.Join(currentPath, unrestrictResponse.Filename)
|
|
response := dav.File(
|
|
path,
|
|
int(unrestrictResponse.Filesize),
|
|
torrent.Added,
|
|
)
|
|
responses = append(responses, response)
|
|
}
|
|
}
|
|
|
|
// TODO: dedupe the links in the response
|
|
|
|
return &dav.MultiStatus{
|
|
XMLNS: "DAV:",
|
|
Response: responses,
|
|
}, nil
|
|
}
|