Files
zurg/internal/dav/response.go
2023-10-17 10:50:10 +02:00

102 lines
2.8 KiB
Go

package dav
import (
"os"
"path/filepath"
"github.com/debridmediamanager.com/zurg/pkg/dav"
"github.com/debridmediamanager.com/zurg/pkg/davextra"
"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 _, cached := range davFiles.Files {
cachedLinksMap[cached.Link] = cached
}
for _, link := range torrent.Links {
if unrestrict, exists := cachedLinksMap[link]; exists {
if unrestrict.Filesize == 0 {
// This link is cached but the filesize is 0
// This means that the link is dead
continue
}
filenameV2 := davextra.InsertLinkFragment(unrestrict.Filename, davextra.GetLinkFragment(unrestrict.Link))
path := filepath.Join(currentPath, filenameV2)
response := dav.File(
path,
int(unrestrict.Filesize),
torrent.Added, // Assuming you want to use the torrent added time here
link,
)
responses = append(responses, response)
} else {
// This link is not cached yet
unrestrictFn := func() (realdebrid.UnrestrictResponse, error) {
return realdebrid.UnrestrictCheck(os.Getenv("RD_TOKEN"), link)
}
unrestrict := realdebrid.RetryUntilOk(unrestrictFn)
if unrestrict == nil {
db.Insert(torrent.Hash, torrent.Filename, realdebrid.UnrestrictResponse{
Filename: "",
Filesize: 0,
Link: link,
Host: "",
})
continue
} else {
db.Insert(torrent.Hash, torrent.Filename, *unrestrict)
}
filenameV2 := davextra.InsertLinkFragment(unrestrict.Filename, davextra.GetLinkFragment(unrestrict.Link))
path := filepath.Join(currentPath, filenameV2)
response := dav.File(
path,
int(unrestrict.Filesize),
torrent.Added,
link,
)
responses = append(responses, response)
}
}
return &dav.MultiStatus{
XMLNS: "DAV:",
Response: responses,
}, nil
}