Files
zurg/internal/dav/propfind.go
Ben Sarmiento f9b5b1efac Clean up
2023-10-18 15:26:45 +02:00

83 lines
2.5 KiB
Go

package dav
import (
"encoding/xml"
"fmt"
"log"
"net/http"
"path"
"github.com/debridmediamanager.com/zurg/internal/torrent"
"github.com/debridmediamanager.com/zurg/pkg/dav"
)
// HandlePropfindRequest handles a PROPFIND request
func HandlePropfindRequest(w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager) {
var output []byte
var err error
requestPath := path.Clean(r.URL.Path)
if requestPath == "/" {
output, err = handleRoot(w, r)
} else if requestPath == "/torrents" {
output, err = handleListOfTorrents(w, r, t)
} else {
output, err = handleSingleTorrent(w, r, t)
}
if err != nil {
log.Printf("Cannot marshal xml: %v\n", err.Error())
http.Error(w, "Cannot read directory", 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) ([]byte, error) {
rootResponse := dav.MultiStatus{
XMLNS: "DAV:",
Response: []dav.Response{
dav.Directory("/"),
dav.Directory("/torrents"),
},
}
return xml.MarshalIndent(rootResponse, "", " ")
}
// handleListOfTorrents handles a PROPFIND request to the /torrents directory
func handleListOfTorrents(w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager) ([]byte, error) {
torrents := t.GetAll()
resp, err := createMultiTorrentResponse(torrents)
if err != nil {
log.Printf("Cannot read directory (/torrents): %v\n", err.Error())
http.Error(w, "Cannot read directory", http.StatusInternalServerError)
return nil, nil
}
return xml.MarshalIndent(resp, "", " ")
}
// handleSingleTorrent handles a PROPFIND request to a single torrent directory
func handleSingleTorrent(w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager) ([]byte, error) {
requestPath := path.Clean(r.URL.Path)
torrentName := path.Base(requestPath)
torrents := findAllTorrentsWithName(t, torrentName)
if len(torrents) == 0 {
log.Println("Cannot find directory", requestPath)
http.Error(w, "Cannot find directory", http.StatusNotFound)
return nil, nil
}
var resp *dav.MultiStatus
resp, err := createCombinedTorrentResponse(torrents, t)
if err != nil {
log.Printf("Cannot read directory (%s): %v\n", requestPath, err.Error())
http.Error(w, "Cannot read directory", http.StatusInternalServerError)
return nil, nil
}
return xml.MarshalIndent(resp, "", " ")
}