Optimizations

This commit is contained in:
Ben Sarmiento
2023-10-22 11:26:20 +02:00
parent 7009d78003
commit c789ebc96d
8 changed files with 61 additions and 237 deletions

View File

@@ -1,129 +0,0 @@
package dav
import (
"encoding/xml"
"fmt"
"log"
"net/http"
"strings"
"github.com/aerogo/aero"
"github.com/debridmediamanager.com/zurg/internal/config"
"github.com/debridmediamanager.com/zurg/internal/torrent"
"github.com/debridmediamanager.com/zurg/pkg/dav"
"github.com/debridmediamanager.com/zurg/pkg/davextra"
"github.com/debridmediamanager.com/zurg/pkg/realdebrid"
)
func Setup(app *aero.Application, c config.ConfigInterface, t *torrent.TorrentManager) {
// hack to make PROPFIND work
app.Rewrite(func(ctx aero.RewriteContext) {
newCtx := ctx.(aero.Context)
if newCtx.Request().Internal().Method == "PROPFIND" {
newCtx.Request().Internal().Method = http.MethodGet
}
})
app.Router().Add(http.MethodOptions, "/", func(ctx aero.Context) error {
ctx.SetStatus(http.StatusOK)
return nil
})
// hardcode the root directory
app.Get("/", func(ctx aero.Context) error {
var responses []dav.Response
responses = append(responses, dav.Directory("/"))
for _, directory := range c.GetDirectories() {
responses = append(responses, dav.Directory(fmt.Sprintf("/%s", directory)))
}
resp := dav.MultiStatus{
XMLNS: "DAV:",
Response: responses,
}
return xmlResponse(ctx, resp)
})
for _, directoryPtr := range c.GetDirectories() {
directory := directoryPtr
app.Get(fmt.Sprintf("/%s/", directory), func(ctx aero.Context) error {
torrentsInDirectory := t.GetByDirectory(directory)
resp, err := createMultiTorrentResponse(fmt.Sprintf("/%s", directory), torrentsInDirectory)
if err != nil {
log.Printf("Cannot read directory (%s): %v\n", directory, err)
return ctx.Error(http.StatusInternalServerError, "Cannot read directory")
}
return xmlResponse(ctx, *resp)
})
app.Get(fmt.Sprintf("/%s/:torrentName/", directory), func(ctx aero.Context) error {
torrentName := ctx.Get("torrentName")
sameNameTorrents := findAllTorrentsWithName(t, directory, torrentName)
resp, err := createSingleTorrentResponse(fmt.Sprintf("/%s", directory), sameNameTorrents, t)
if err != nil {
log.Printf("Cannot read directory (%s): %v\n", directory, err)
return ctx.Error(http.StatusInternalServerError, "Cannot read directory")
}
return xmlResponse(ctx, *resp)
})
app.Get(fmt.Sprintf("/%s/:torrentName/:filename", directory), func(ctx aero.Context) error {
torrentName := strings.TrimSpace(ctx.Get("torrentName"))
filename := strings.TrimSpace(ctx.Get("filename"))
torrents := findAllTorrentsWithName(t, directory, torrentName)
if torrents == nil {
log.Println("Cannot find torrent", torrentName)
return ctx.Error(http.StatusNotFound, "Cannot find file")
}
filenameV2, linkFragment := davextra.ExtractLinkFragment(filename)
torrent, file := getFile(torrents, filenameV2, linkFragment)
if file == nil {
log.Println("Cannot find file", filename)
return ctx.Error(http.StatusNotFound, "Cannot find file")
}
if file.Link == "" {
log.Println("Link not found", filename)
return ctx.Error(http.StatusNotFound, "Cannot find file")
}
link := file.Link
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
// if it's the only file, tough luck
log.Println("Cannot unrestrict link", link, filenameV2)
t.MarkFileAsDeleted(torrent, file)
return ctx.Error(http.StatusNotFound, "Cannot find file")
}
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
// do it in 2 batches with different selections
log.Println("Filename mismatch", resp.Filename, filenameV2)
}
return ctx.Redirect(http.StatusFound, resp.Download)
})
}
}
func xmlResponse(ctx aero.Context, resp dav.MultiStatus) error {
output, err := xml.MarshalIndent(resp, "", " ")
if err != nil {
log.Printf("Cannot marshal xml: %v\n", err)
return ctx.Error(http.StatusInternalServerError, "Cannot read directory")
}
ctx.SetStatus(http.StatusMultiStatus)
ctx.Response().SetHeader("Content-Type", "text/xml; charset=\"utf-8\"")
return ctx.String(fmt.Sprintf("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n%s\n", output))
}

View File

@@ -22,7 +22,7 @@ func HandlePropfindRequest(w http.ResponseWriter, r *http.Request, t *torrent.To
pathSegments := strings.Split(requestPath, "/")
// Remove empty segments caused by leading or trailing slashes
filteredSegments := make([]string, 0, len(pathSegments))
filteredSegments := pathSegments[:0]
for _, segment := range pathSegments {
if segment != "" {
filteredSegments = append(filteredSegments, segment)
@@ -30,36 +30,35 @@ func HandlePropfindRequest(w http.ResponseWriter, r *http.Request, t *torrent.To
}
switch len(filteredSegments) {
case 0: // Just the root "/"
case 0:
output, err = handleRoot(w, r, c)
case 1: // It's just the basedir e.g. "/basedir"
case 1:
output, err = handleListOfTorrents(requestPath, w, r, t, c)
case 2: // It's a specific torrent under a basedir e.g. "/basedir/torrentname/"
case 2:
output, err = handleSingleTorrent(requestPath, w, r, t)
default:
// Handle any other paths, e.g., send a 404 Not Found response
http.Error(w, "Not Found", http.StatusNotFound)
return
}
if err != nil {
log.Printf("Cannot marshal xml: %v\n", err)
http.Error(w, "Cannot read directory", http.StatusInternalServerError)
log.Printf("Error processing request: %v\n", err)
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
if output != nil {
w.Header().Set("Content-Type", "text/xml; charset=\"utf-8\"")
w.WriteHeader(http.StatusMultiStatus)
fmt.Fprintf(w, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n%s\n", output)
return
}
}
// handleRoot handles a PROPFIND request to the root directory
func handleRoot(w http.ResponseWriter, r *http.Request, c config.ConfigInterface) ([]byte, error) {
var responses []dav.Response
responses = append(responses, dav.Directory("/"))
for _, directory := range c.GetDirectories() {
responses = append(responses, dav.Directory(fmt.Sprintf("/%s", directory)))
responses = append(responses, dav.Directory("/"+directory))
}
rootResponse := dav.MultiStatus{
XMLNS: "DAV:",
@@ -68,45 +67,40 @@ func handleRoot(w http.ResponseWriter, r *http.Request, c config.ConfigInterface
return xml.MarshalIndent(rootResponse, "", " ")
}
// handleListOfTorrents handles a PROPFIND request to the base directory
func handleListOfTorrents(requestPath string, w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager, c config.ConfigInterface) ([]byte, error) {
basePath := path.Base(requestPath)
found := false
for _, directory := range c.GetDirectories() {
directories := c.GetDirectories()
for _, directory := range directories {
if basePath == directory {
found = true
torrents := t.GetByDirectory(basePath)
resp, err := createMultiTorrentResponse("/"+basePath, torrents)
if err != nil {
log.Printf("Cannot read directory (%s): %v\n", basePath, err)
http.Error(w, "Cannot read directory", http.StatusInternalServerError)
return nil, nil
}
return xml.MarshalIndent(resp, "", " ")
}
}
if !found {
log.Println("Cannot find directory when generating list", requestPath)
http.Error(w, "Cannot find directory", http.StatusNotFound)
return nil, nil
}
torrents := t.GetByDirectory(basePath)
resp, err := createMultiTorrentResponse(fmt.Sprintf("/%s", basePath), torrents)
if err != nil {
log.Printf("Cannot read directory (%s): %v\n", basePath, err)
http.Error(w, "Cannot read directory", http.StatusInternalServerError)
return nil, nil
}
return xml.MarshalIndent(resp, "", " ")
log.Println("Cannot find directory when generating list", requestPath)
http.Error(w, "Cannot find directory", http.StatusNotFound)
return nil, nil
}
// handleSingleTorrent handles a PROPFIND request to a single torrent directory
func handleSingleTorrent(requestPath string, w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager) ([]byte, error) {
directory := strings.TrimPrefix(path.Dir(requestPath), "/")
torrentName := path.Base(requestPath)
sameNameTorrents := findAllTorrentsWithName(t, directory, torrentName)
if len(sameNameTorrents) == 0 {
log.Println("Cannot find directory when generating single torrent", requestPath)
http.Error(w, "Cannot find directory", http.StatusNotFound)
return nil, nil
}
var resp *dav.MultiStatus
resp, err := createSingleTorrentResponse(fmt.Sprintf("/%s", directory), sameNameTorrents, t)
resp, err := createSingleTorrentResponse("/"+directory, sameNameTorrents, t)
if err != nil {
log.Printf("Cannot read directory (%s): %v\n", requestPath, err)
http.Error(w, "Cannot read directory", http.StatusInternalServerError)