A lot of rewrite here

This commit is contained in:
Ben Sarmiento
2023-10-18 00:17:07 +02:00
parent 44216343e2
commit 0886c93250
14 changed files with 399 additions and 482 deletions

82
internal/dav/propfind.go Normal file
View File

@@ -0,0 +1,82 @@
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, fmt.Sprintf("Cannot marshal xml: %v", err.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) ([]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) {
allTorrents := t.GetAll()
allTorrentsResponse, err := createMultiTorrentResponse(allTorrents)
if err != nil {
log.Printf("Cannot read directory: %v\n", err.Error())
http.Error(w, fmt.Sprintf("Cannot read directory: %v", err.Error()), http.StatusInternalServerError)
return nil, nil
}
return xml.MarshalIndent(allTorrentsResponse, "", " ")
}
// 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)
foundTorrents := findAllTorrentsWithName(t, torrentName)
if len(foundTorrents) == 0 {
log.Println("Cannot find directory")
http.Error(w, "Cannot find directory", http.StatusNotFound)
return nil, nil
}
var torrentResponse *dav.MultiStatus
torrentResponse, err := createCombinedTorrentResponse(foundTorrents, t)
if err != nil {
log.Printf("Cannot read directory: %v\n", err.Error())
http.Error(w, fmt.Sprintf("Cannot read directory: %v", err.Error()), http.StatusInternalServerError)
return nil, nil
}
return xml.MarshalIndent(torrentResponse, "", " ")
}