package dav
import (
"fmt"
"net/http"
"path"
"sort"
"strings"
"github.com/debridmediamanager/zurg/internal/torrent"
"github.com/debridmediamanager/zurg/pkg/dav"
"go.uber.org/zap"
)
func HandlePropfindRequest(w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager, log *zap.SugaredLogger) {
requestPath := path.Clean(r.URL.Path)
var output *string
var err error
filteredSegments := splitIntoSegments(requestPath)
switch {
case len(filteredSegments) == 0:
output, err = handleListDirectories(w, t)
case len(filteredSegments) == 1:
output, err = handleListTorrents(w, requestPath, t)
case len(filteredSegments) == 2:
output, err = handleListFiles(w, requestPath, t)
default:
log.Warnf("Request %s %s not found", r.Method, requestPath)
http.Error(w, "Not Found", http.StatusNotFound)
return
}
if err != nil {
if strings.Contains(err.Error(), "cannot find") {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
log.Errorf("Error processing request: %v", 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.StatusOK)
fmt.Fprint(w, *output)
}
}
func handleListDirectories(w http.ResponseWriter, t *torrent.TorrentManager) (*string, error) {
davDoc := ""
// initial response is the directory itself
davDoc += dav.BaseDirectory("", "")
directories := t.DirectoryMap.Keys()
sort.Strings(directories)
for _, directory := range directories {
if strings.HasPrefix(directory, "int__") {
continue
}
davDoc += dav.Directory(directory, "")
}
davDoc += ""
return &davDoc, nil
}
func handleListTorrents(w http.ResponseWriter, requestPath string, t *torrent.TorrentManager) (*string, error) {
basePath := path.Base(requestPath)
_, ok := t.DirectoryMap.Get(basePath)
if !ok {
return nil, fmt.Errorf("cannot find directory %s", basePath)
}
resp, _ := t.ResponseCache.Get(basePath + ".dav")
davDoc := resp.(string)
return &davDoc, nil
}
func handleListFiles(w http.ResponseWriter, requestPath string, t *torrent.TorrentManager) (*string, error) {
requestPath = strings.Trim(requestPath, "/")
basePath := path.Base(path.Dir(requestPath))
torrents, ok := t.DirectoryMap.Get(basePath)
if !ok {
return nil, fmt.Errorf("cannot find directory %s", basePath)
}
accessKey := path.Base(requestPath)
tor, ok := torrents.Get(accessKey)
if !ok {
return nil, fmt.Errorf("cannot find torrent %s", accessKey)
}
davDoc := "" + dav.BaseDirectory(requestPath, tor.LatestAdded)
filenames := tor.SelectedFiles.Keys()
sort.Strings(filenames)
for _, filename := range filenames {
file, _ := tor.SelectedFiles.Get(filename)
if file == nil || !strings.HasPrefix(file.Link, "http") {
continue
}
davDoc += dav.File(filename, file.Bytes, file.Ended)
}
davDoc += ""
return &davDoc, nil
}