Optimize webdav

This commit is contained in:
Ben Sarmiento
2023-11-21 10:32:14 +01:00
parent 10980f4f3e
commit cbf14e953f
3 changed files with 54 additions and 53 deletions

View File

@@ -1,7 +1,6 @@
package dav package dav
import ( import (
"encoding/xml"
"fmt" "fmt"
"net/http" "net/http"
"path" "path"
@@ -20,18 +19,17 @@ func HandlePropfindRequest(w http.ResponseWriter, r *http.Request, t *torrent.To
requestPath := path.Clean(r.URL.Path) requestPath := path.Clean(r.URL.Path)
requestPath = strings.Trim(requestPath, "/") requestPath = strings.Trim(requestPath, "/")
var output []byte
var err error var err error
filteredSegments := strings.Split(requestPath, "/") filteredSegments := strings.Split(requestPath, "/")
switch { switch {
case len(filteredSegments) == 1 && filteredSegments[0] == "": case len(filteredSegments) == 1 && filteredSegments[0] == "":
output, err = handleRoot(t) err = handleRoot(w, t)
case len(filteredSegments) == 1: case len(filteredSegments) == 1:
output, err = handleListOfTorrents(requestPath, t) err = handleListOfTorrents(w, requestPath, t)
case len(filteredSegments) == 2: case len(filteredSegments) == 2:
output, err = handleSingleTorrent(requestPath, t) err = handleSingleTorrent(w, requestPath, t)
default: default:
log.Warnf("Request %s %s not found", r.Method, requestPath) log.Warnf("Request %s %s not found", r.Method, requestPath)
http.Error(w, "Not Found", http.StatusNotFound) http.Error(w, "Not Found", http.StatusNotFound)
@@ -48,68 +46,67 @@ func HandlePropfindRequest(w http.ResponseWriter, r *http.Request, t *torrent.To
return return
} }
if output != nil {
respBody := fmt.Sprintf("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n%s\n", output)
w.Header().Set("Content-Type", "text/xml; charset=\"utf-8\"") w.Header().Set("Content-Type", "text/xml; charset=\"utf-8\"")
w.WriteHeader(http.StatusMultiStatus)
fmt.Fprint(w, respBody)
}
} }
func handleRoot(t *torrent.TorrentManager) ([]byte, error) { func handleRoot(w http.ResponseWriter, t *torrent.TorrentManager) error {
var responses []dav.Response fmt.Fprint(w, "<?xml?><d:multistatus xmlns:d=\"DAV:\">")
responses = append(responses, dav.Directory("")) // initial response is the directory itself
fmt.Fprint(w, dav.Directory("", ""))
directories := t.DirectoryMap.Keys() directories := t.DirectoryMap.Keys()
sort.Strings(directories) sort.Strings(directories)
for _, directory := range directories { for _, directory := range directories {
responses = append(responses, dav.Directory(directory)) fmt.Fprint(w, dav.Directory(directory, ""))
}
rootResponse := dav.MultiStatus{
XMLNS: "DAV:",
Response: responses,
}
return xml.Marshal(rootResponse)
} }
func handleListOfTorrents(requestPath string, t *torrent.TorrentManager) ([]byte, error) { fmt.Fprint(w, "</d:multistatus>")
return nil
}
func handleListOfTorrents(w http.ResponseWriter, requestPath string, t *torrent.TorrentManager) error {
basePath := path.Base(requestPath) basePath := path.Base(requestPath)
torrents, ok := t.DirectoryMap.Get(basePath) torrents, ok := t.DirectoryMap.Get(basePath)
if !ok { if !ok {
return nil, fmt.Errorf("cannot find directory %s", basePath) return fmt.Errorf("cannot find directory %s", basePath)
} }
var responses []dav.Response
fmt.Fprint(w, "<?xml?><d:multistatus xmlns:d=\"DAV:\">")
// initial response is the directory itself // initial response is the directory itself
responses = append(responses, dav.Directory(basePath+"/")) fmt.Fprint(w, dav.Directory(basePath+"/", ""))
accessKeys := torrents.Keys() var allTorrents []*torrent.Torrent
sort.Strings(accessKeys) torrents.IterCb(func(_ string, tor *torrent.Torrent) {
for _, accessKey := range accessKeys { allTorrents = append(allTorrents, tor)
responses = append(responses, dav.Directory(filepath.Join(basePath, accessKey))) })
sort.Slice(allTorrents, func(i, j int) bool {
return allTorrents[i].AccessKey < allTorrents[j].AccessKey
})
for _, tor := range allTorrents {
fmt.Fprint(w, dav.Directory(filepath.Join(basePath, tor.AccessKey), tor.LatestAdded))
} }
resp := &dav.MultiStatus{ fmt.Fprint(w, "</d:multistatus>")
XMLNS: "DAV:", return nil
Response: responses,
}
return xml.Marshal(resp)
} }
func handleSingleTorrent(requestPath string, t *torrent.TorrentManager) ([]byte, error) { func handleSingleTorrent(w http.ResponseWriter, requestPath string, t *torrent.TorrentManager) error {
basePath := path.Base(path.Dir(requestPath)) basePath := path.Base(path.Dir(requestPath))
torrents, ok := t.DirectoryMap.Get(basePath) torrents, ok := t.DirectoryMap.Get(basePath)
if !ok { if !ok {
return nil, fmt.Errorf("cannot find directory %s", basePath) return fmt.Errorf("cannot find directory %s", basePath)
} }
accessKey := path.Base(requestPath) accessKey := path.Base(requestPath)
tor, ok := torrents.Get(accessKey) tor, ok := torrents.Get(accessKey)
if !ok { if !ok {
return nil, fmt.Errorf("cannot find torrent %s", accessKey) return fmt.Errorf("cannot find torrent %s", accessKey)
} }
var responses []dav.Response fmt.Fprint(w, "<?xml?><d:multistatus xmlns:d=\"DAV:\">")
// initial response is the directory itself // initial response is the directory itself
responses = append(responses, dav.Directory(requestPath+"/")) fmt.Fprint(w, dav.Directory(requestPath+"/", tor.LatestAdded))
filenames := tor.SelectedFiles.Keys() filenames := tor.SelectedFiles.Keys()
sort.Strings(filenames) sort.Strings(filenames)
for _, filename := range filenames { for _, filename := range filenames {
@@ -117,16 +114,9 @@ func handleSingleTorrent(requestPath string, t *torrent.TorrentManager) ([]byte,
if file == nil || !strings.HasPrefix(file.Link, "http") { if file == nil || !strings.HasPrefix(file.Link, "http") {
continue continue
} }
responses = append(responses, dav.File( fmt.Fprint(w, dav.File(filepath.Join(requestPath, filename), file.Bytes, tor.LatestAdded))
filepath.Join(requestPath, filename),
file.Bytes,
convertRFC3339toRFC1123(tor.LatestAdded),
file.Link,
))
} }
resp := &dav.MultiStatus{
XMLNS: "DAV:", fmt.Fprint(w, "</d:multistatus>")
Response: responses, return nil
}
return xml.Marshal(resp)
} }

View File

@@ -1,27 +1,39 @@
package dav package dav
func Directory(path string) Response { import "fmt"
func DavDirectory(path, added string) Response {
return Response{ return Response{
Href: "/" + customPathEscape(path), Href: "/" + customPathEscape(path),
Propstat: PropStat{ Propstat: PropStat{
Prop: Prop{ Prop: Prop{
ResourceType: ResourceType{Value: "<d:collection/>"}, ResourceType: ResourceType{Value: "<d:collection/>"},
},
Status: "HTTP/1.1 200 OK",
},
}
}
func File(path string, fileSize int64, added string, link string) Response {
return Response{
Href: "/" + customPathEscape(path),
Propstat: PropStat{
Prop: Prop{
ContentLength: fileSize,
CreationDate: added,
LastModified: added, LastModified: added,
}, },
Status: "HTTP/1.1 200 OK", Status: "HTTP/1.1 200 OK",
}, },
} }
} }
func DavFile(path string, fileSize int64, added string, link string) Response {
return Response{
Href: "/" + customPathEscape(path),
Propstat: PropStat{
Prop: Prop{
ContentLength: fileSize,
LastModified: added,
},
Status: "HTTP/1.1 200 OK",
},
}
}
// optimized versions, no more marshalling
func Directory(path, added string) string {
return fmt.Sprintf("<d:response><d:href>/%s</d:href><d:propstat><d:prop><d:resourcetype><d:collection/></d:resourcetype></d:prop><d:prop><d:getlastmodified>%s</d:getlastmodified></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>", customPathEscape(path), added)
}
func File(path string, fileSize int64, added string) string {
return fmt.Sprintf("<d:response><d:href>/%s</d:href><d:propstat><d:prop><d:resourcetype></d:resourcetype><d:getcontentlength>%d</d:getcontentlength><d:getlastmodified>%s</d:getlastmodified></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>", customPathEscape(path), fileSize, added)
}

View File

@@ -23,7 +23,6 @@ type PropStat struct {
type Prop struct { type Prop struct {
ResourceType ResourceType `xml:"d:resourcetype"` ResourceType ResourceType `xml:"d:resourcetype"`
ContentLength int64 `xml:"d:getcontentlength,omitempty"` ContentLength int64 `xml:"d:getcontentlength,omitempty"`
CreationDate string `xml:"d:creationdate,omitempty"`
LastModified string `xml:"d:getlastmodified,omitempty"` LastModified string `xml:"d:getlastmodified,omitempty"`
} }