83 lines
2.6 KiB
Go
83 lines
2.6 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) {
|
|
allTorrents := t.GetAll()
|
|
allTorrentsResponse, err := createMultiTorrentResponse(allTorrents)
|
|
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(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", requestPath)
|
|
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 (%s): %v\n", requestPath, err.Error())
|
|
http.Error(w, "Cannot read directory", http.StatusInternalServerError)
|
|
return nil, nil
|
|
}
|
|
return xml.MarshalIndent(torrentResponse, "", " ")
|
|
}
|