Finish config mapping

This commit is contained in:
Ben Sarmiento
2023-10-19 18:02:30 +02:00
parent ce0b2445b2
commit faba4e53ab
14 changed files with 397 additions and 89 deletions

View File

@@ -68,7 +68,7 @@ func handleRoot(w http.ResponseWriter, r *http.Request, c config.ConfigInterface
return xml.MarshalIndent(rootResponse, "", " ")
}
// handleListOfTorrents handles a PROPFIND request to the /torrents directory
// 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)
@@ -79,7 +79,7 @@ func handleListOfTorrents(requestPath string, w http.ResponseWriter, r *http.Req
}
}
if !found {
log.Println("Cannot find directory", requestPath)
log.Println("Cannot find directory when generating list", requestPath)
http.Error(w, "Cannot find directory", http.StatusNotFound)
return nil, nil
}
@@ -96,17 +96,17 @@ func handleListOfTorrents(requestPath string, w http.ResponseWriter, r *http.Req
// 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) {
basePath := path.Dir(requestPath)
directory := strings.TrimPrefix(path.Dir(requestPath), "/")
torrentName := path.Base(requestPath)
sameNameTorrents := findAllTorrentsWithName(t, basePath, torrentName)
sameNameTorrents := findAllTorrentsWithName(t, directory, torrentName)
if len(sameNameTorrents) == 0 {
log.Println("Cannot find directory", requestPath)
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", basePath), sameNameTorrents, t)
resp, err := createSingleTorrentResponse(fmt.Sprintf("/%s", directory), sameNameTorrents, t)
if err != nil {
log.Printf("Cannot read directory (%s): %v\n", requestPath, err.Error())
http.Error(w, "Cannot read directory", http.StatusInternalServerError)

View File

@@ -1,6 +1,7 @@
package dav
import (
"log"
"path/filepath"
"github.com/debridmediamanager.com/zurg/internal/torrent"
@@ -47,6 +48,12 @@ func createSingleTorrentResponse(basePath string, torrents []torrent.Torrent, t
var torrentResponses []dav.Response
for _, torrent := range torrents {
for _, file := range torrent.SelectedFiles {
if file.Link == "" {
// TODO: trigger a re-add for the file
log.Println("File has no link, skipping", file.Path)
t.RefreshInfo(torrent.ID)
continue
}
filename := filepath.Base(file.Path)
fragment := davextra.GetLinkFragment(file.Link)
filename = davextra.InsertLinkFragment(filename, fragment)

View File

@@ -1,23 +1,23 @@
package dav
import (
"encoding/xml"
"fmt"
"log"
"net/http"
"os"
"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"
)
// Router creates a WebDAV router
func Router(mux *http.ServeMux) {
c, err := config.LoadZurgConfig("./config.yml")
if err != nil {
log.Panicf("Config failed to load: %v", err)
}
t := torrent.NewTorrentManager(os.Getenv("RD_TOKEN"), c)
func Router(mux *http.ServeMux, c config.ConfigInterface, t *torrent.TorrentManager) {
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "PROPFIND":
@@ -25,7 +25,6 @@ func Router(mux *http.ServeMux) {
case http.MethodGet:
HandleGetRequest(w, r, t)
// default return
case http.MethodOptions:
w.WriteHeader(http.StatusOK)
@@ -36,3 +35,110 @@ func Router(mux *http.ServeMux) {
}
})
}
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.Error())
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.Error())
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)
link := getLink(torrents, filenameV2, linkFragment)
if link == "" {
log.Println("Link not found")
return ctx.Error(http.StatusNotFound, "Cannot find file")
}
unrestrictFn := func() (*realdebrid.UnrestrictResponse, error) {
return realdebrid.UnrestrictLink(os.Getenv("RD_TOKEN"), 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")
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.Error())
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

@@ -18,7 +18,7 @@ func convertDate(input string) string {
return t.Format("Mon, 02 Jan 2006 15:04:05 GMT")
}
// findAllTorrentsWithName finds all torrents with a given name
// findAllTorrentsWithName finds all torrents in a given directory with a given name
func findAllTorrentsWithName(t *torrent.TorrentManager, directory, torrentName string) []torrent.Torrent {
var matchingTorrents []torrent.Torrent