Add support for configs

This commit is contained in:
Ben Sarmiento
2023-10-18 21:09:25 +02:00
parent f9b5b1efac
commit 4650213218
19 changed files with 359 additions and 48 deletions

View File

@@ -27,10 +27,11 @@ func HandleGetRequest(w http.ResponseWriter, r *http.Request, t *torrent.Torrent
}
// Get the last two segments
baseDirectory := segments[len(segments)-3]
torrentName := segments[len(segments)-2]
filename := segments[len(segments)-1]
torrents := findAllTorrentsWithName(t, torrentName)
torrents := findAllTorrentsWithName(t, baseDirectory, torrentName)
if torrents == nil {
log.Println("Cannot find torrent", torrentName)
http.Error(w, "Cannot find file", http.StatusNotFound)

View File

@@ -6,23 +6,40 @@ import (
"log"
"net/http"
"path"
"strings"
"github.com/debridmediamanager.com/zurg/internal/config"
"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) {
func HandlePropfindRequest(w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager, c config.ConfigInterface) {
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)
pathSegments := strings.Split(requestPath, "/")
// Remove empty segments caused by leading or trailing slashes
filteredSegments := make([]string, 0, len(pathSegments))
for _, segment := range pathSegments {
if segment != "" {
filteredSegments = append(filteredSegments, segment)
}
}
switch len(filteredSegments) {
case 0: // Just the root "/"
output, err = handleRoot(w, r, c)
case 1: // It's just the basedir e.g. "/basedir"
output, err = handleListOfTorrents(requestPath, w, r, t, c)
case 2: // It's a specific torrent under a basedir e.g. "/basedir/torrentname/"
output, err = handleSingleTorrent(requestPath, w, r, t)
default:
// Handle any other paths, e.g., send a 404 Not Found response
http.Error(w, "Not Found", http.StatusNotFound)
return
}
if err != nil {
log.Printf("Cannot marshal xml: %v\n", err.Error())
@@ -38,23 +55,39 @@ func HandlePropfindRequest(w http.ResponseWriter, r *http.Request, t *torrent.To
}
// handleRoot handles a PROPFIND request to the root directory
func handleRoot(w http.ResponseWriter, r *http.Request) ([]byte, error) {
func handleRoot(w http.ResponseWriter, r *http.Request, c config.ConfigInterface) ([]byte, error) {
var responses []dav.Response
responses = append(responses, dav.Directory("/"))
for _, directory := range c.GetDirectories() {
responses = append(responses, dav.Directory(fmt.Sprintf("/%s", directory)))
}
rootResponse := dav.MultiStatus{
XMLNS: "DAV:",
Response: []dav.Response{
dav.Directory("/"),
dav.Directory("/torrents"),
},
XMLNS: "DAV:",
Response: responses,
}
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)
func handleListOfTorrents(requestPath string, w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager, c config.ConfigInterface) ([]byte, error) {
basePath := path.Base(requestPath)
found := false
for _, directory := range c.GetDirectories() {
if basePath == directory {
found = true
}
}
if !found {
log.Println("Cannot find directory", requestPath)
http.Error(w, "Cannot find directory", http.StatusNotFound)
return nil, nil
}
torrents := t.GetByDirectory(basePath)
resp, err := createMultiTorrentResponse(fmt.Sprintf("/%s", basePath), torrents)
if err != nil {
log.Printf("Cannot read directory (/torrents): %v\n", err.Error())
log.Printf("Cannot read directory (%s): %v\n", basePath, err.Error())
http.Error(w, "Cannot read directory", http.StatusInternalServerError)
return nil, nil
}
@@ -62,17 +95,18 @@ func handleListOfTorrents(w http.ResponseWriter, r *http.Request, t *torrent.Tor
}
// 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)
func handleSingleTorrent(requestPath string, w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager) ([]byte, error) {
basePath := path.Dir(requestPath)
torrentName := path.Base(requestPath)
torrents := findAllTorrentsWithName(t, torrentName)
if len(torrents) == 0 {
sameNameTorrents := findAllTorrentsWithName(t, basePath, torrentName)
if len(sameNameTorrents) == 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)
resp, err := createSingleTorrentResponse(fmt.Sprintf("/%s", basePath), sameNameTorrents, t)
if err != nil {
log.Printf("Cannot read directory (%s): %v\n", requestPath, err.Error())
http.Error(w, "Cannot read directory", http.StatusInternalServerError)

View File

@@ -9,9 +9,9 @@ import (
)
// createMultiTorrentResponse creates a WebDAV response for a list of torrents
func createMultiTorrentResponse(torrents []torrent.Torrent) (*dav.MultiStatus, error) {
func createMultiTorrentResponse(basePath string, torrents []torrent.Torrent) (*dav.MultiStatus, error) {
var responses []dav.Response
responses = append(responses, dav.Directory("/torrents"))
responses = append(responses, dav.Directory(basePath))
seen := make(map[string]bool)
@@ -19,12 +19,12 @@ func createMultiTorrentResponse(torrents []torrent.Torrent) (*dav.MultiStatus, e
if item.Progress != 100 {
continue
}
if _, exists := seen[item.Filename]; exists {
if _, exists := seen[item.Name]; exists {
continue
}
seen[item.Filename] = true
seen[item.Name] = true
path := filepath.Join("/torrents", item.Filename)
path := filepath.Join(basePath, item.Name)
responses = append(responses, dav.Directory(path))
}
@@ -36,10 +36,10 @@ func createMultiTorrentResponse(torrents []torrent.Torrent) (*dav.MultiStatus, e
// createTorrentResponse creates a WebDAV response for a single torrent
// but it also handles the case where there are many torrents with the same name
func createCombinedTorrentResponse(torrents []torrent.Torrent, t *torrent.TorrentManager) (*dav.MultiStatus, error) {
func createSingleTorrentResponse(basePath string, torrents []torrent.Torrent, t *torrent.TorrentManager) (*dav.MultiStatus, error) {
var responses []dav.Response
// initial response is the directory itself
currentPath := filepath.Join("/torrents", torrents[0].Filename)
currentPath := filepath.Join(basePath, torrents[0].Name)
responses = append(responses, dav.Directory(currentPath))
seen := make(map[string]bool)

View File

@@ -5,20 +5,23 @@ import (
"net/http"
"os"
"github.com/debridmediamanager.com/zurg/internal/config"
"github.com/debridmediamanager.com/zurg/internal/torrent"
)
// Router creates a WebDAV router
func Router(mux *http.ServeMux) {
t := torrent.NewTorrentManager(os.Getenv("RD_TOKEN"))
c, err := config.LoadZurgConfig("./config.yml")
if err != nil {
log.Panicf("Config failed to load: %v", err)
}
t := torrent.NewTorrentManager(os.Getenv("RD_TOKEN"), c)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// requestPath := path.Clean(r.URL.Path)
// log.Println(r.Method, requestPath)
switch r.Method {
case "PROPFIND":
HandlePropfindRequest(w, r, t)
HandlePropfindRequest(w, r, t, c)
case http.MethodGet:
HandleGetRequest(w, r, t)

View File

@@ -19,12 +19,12 @@ func convertDate(input string) string {
}
// findAllTorrentsWithName finds all torrents with a given name
func findAllTorrentsWithName(t *torrent.TorrentManager, filename string) []torrent.Torrent {
func findAllTorrentsWithName(t *torrent.TorrentManager, directory, torrentName string) []torrent.Torrent {
var matchingTorrents []torrent.Torrent
torrents := t.GetAll()
torrents := t.GetByDirectory(directory)
for _, torrent := range torrents {
if torrent.Filename == filename || strings.HasPrefix(torrent.Filename, filename) {
if torrent.Name == torrentName || strings.HasPrefix(torrent.Name, torrentName) {
matchingTorrents = append(matchingTorrents, torrent)
}
}