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

114 lines
2.9 KiB
Go

package dav
import (
"fmt"
"path/filepath"
"github.com/debridmediamanager.com/zurg/internal/torrent"
"github.com/debridmediamanager.com/zurg/pkg/dav"
"github.com/debridmediamanager.com/zurg/pkg/realdebrid"
)
// createMultiTorrentResponse creates a WebDAV response for a list of torrents
func createMultiTorrentResponse(torrents []realdebrid.Torrent) (*dav.MultiStatus, error) {
var responses []dav.Response
responses = append(responses, dav.Directory("/torrents"))
seen := make(map[string]bool)
for _, item := range torrents {
if item.Progress != 100 {
continue
}
if _, exists := seen[item.Filename]; exists {
continue
}
seen[item.Filename] = true
path := filepath.Join("/torrents", item.Filename)
responses = append(responses, dav.Directory(path))
}
return &dav.MultiStatus{
XMLNS: "DAV:",
Response: responses,
}, nil
}
// createTorrentResponse creates a WebDAV response for torrents with the same name
func createCombinedTorrentResponse(torrents []realdebrid.Torrent, t *torrent.TorrentManager) (*dav.MultiStatus, error) {
var responses []dav.Response
// initial response is the directory itself
currentPath := filepath.Join("/torrents", torrents[0].Filename)
responses = append(responses, dav.Directory(currentPath))
seen := make(map[string]bool)
idx := 0
var torrentResponses []dav.Response
for _, torrent := range torrents {
info := t.GetInfo(torrent.ID)
if info == nil {
continue
}
var selectedFiles []realdebrid.File
for _, file := range info.Files {
if file.Selected == 0 {
continue
}
selectedFiles = append(selectedFiles, file)
}
if len(selectedFiles) != len(info.Links) {
fmt.Println("Links and files do not match", info.Filename)
// TODO: Add auto-healing for this
// for _, link := range info.Links {
// unrestrictFn := func() (*realdebrid.UnrestrictResponse, error) {
// return realdebrid.UnrestrictCheck(os.Getenv("RD_TOKEN"), link)
// }
// resp := realdebrid.RetryUntilOk(unrestrictFn)
// if resp == nil {
// continue
// } else {
// if _, exists := seen[resp.Filename]; exists {
// continue
// }
// seen[resp.Filename] = true
// filePath := filepath.Join(currentPath, resp.Filename)
// torrentResponses = append(torrentResponses,
// dav.File(
// filePath,
// resp.Filesize,
// info.Added,
// resp.Link,
// ),
// )
// }
// }
} else {
for _, file := range selectedFiles {
filename := filepath.Base(file.Path)
if _, exists := seen[filename]; exists {
continue
}
seen[filename] = true
filePath := filepath.Join(currentPath, filename)
torrentResponses = append(torrentResponses, dav.File(
filePath,
file.Bytes,
convertDate(info.Added),
info.Links[idx],
))
idx++
}
}
}
responses = append(responses, torrentResponses...)
return &dav.MultiStatus{
XMLNS: "DAV:",
Response: responses,
}, nil
}