Files
zurg/internal/dav/getfile.go
2023-10-20 01:49:06 +02:00

87 lines
2.8 KiB
Go

package dav
import (
"fmt"
"log"
"net/http"
"path"
"path/filepath"
"strings"
"github.com/debridmediamanager.com/zurg/internal/config"
"github.com/debridmediamanager.com/zurg/internal/torrent"
"github.com/debridmediamanager.com/zurg/pkg/davextra"
"github.com/debridmediamanager.com/zurg/pkg/realdebrid"
)
// HandleGetRequest handles a GET request to a file
func HandleGetRequest(w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager, c config.ConfigInterface) {
requestPath := path.Clean(r.URL.Path)
segments := strings.Split(requestPath, "/")
// If there are less than 3 segments, return an error or adjust as needed
if len(segments) < 3 {
log.Println("Invalid url", requestPath)
// http.Error(w, "Cannot find file", http.StatusNotFound)
handleSingleTorrent(requestPath, w, r, t)
return
}
// Get the last two segments
baseDirectory := segments[len(segments)-3]
torrentName := segments[len(segments)-2]
filename := segments[len(segments)-1]
torrents := findAllTorrentsWithName(t, baseDirectory, torrentName)
if torrents == nil {
log.Println("Cannot find torrent", torrentName)
http.Error(w, "Cannot find file", http.StatusNotFound)
return
}
filenameV2, linkFragment := davextra.ExtractLinkFragment(filename)
link := getLink(torrents, filenameV2, linkFragment)
if link == "" {
log.Println("Link not found", filename)
http.Error(w, "Cannot find file", http.StatusNotFound)
return
}
unrestrictFn := func() (*realdebrid.UnrestrictResponse, error) {
return realdebrid.UnrestrictLink(c.GetToken(), link)
}
resp := realdebrid.RetryUntilOk(unrestrictFn)
if resp == nil {
// TODO: Readd the file
// when unrestricting fails, it means the file is not available anymore, but still in their database
// if it's the only file, tough luck
// if it's the only file, try to readd it
// delete the old one, add a new one
log.Println("Cannot unrestrict link", link, filenameV2)
http.Error(w, "Cannot find file", http.StatusNotFound)
return
}
if resp.Filename != filenameV2 {
// TODO: Redo the logic to handle mismatch
// [SRS] Pokemon S22E01-35 1080p WEBRip AAC 2.0 x264 CC.rar
// Pokemon.S22E24.The.Secret.Princess.DUBBED.1080p.WEBRip.AAC.2.0.x264-SRS.mkv
// Action: schedule a "cleanup" job for the parent torrent
// If the file extension changed, that means it's a different file
log.Println("Filename mismatch", resp.Filename, filenameV2)
}
http.Redirect(w, r, resp.Download, http.StatusFound)
}
// getLink finds a link by a fragment, it might be wrong
func getLink(torrents []torrent.Torrent, filename, fragment string) string {
for _, torrent := range torrents {
for _, file := range torrent.SelectedFiles {
fname := filepath.Base(file.Path)
if filename == fname && strings.HasPrefix(file.Link, fmt.Sprintf("https://real-debrid.com/d/%s", fragment)) {
return file.Link
}
}
}
return ""
}