Files
zurg/internal/http/listing.go
2023-11-09 02:34:04 +01:00

101 lines
2.9 KiB
Go

package http
import (
"fmt"
"net/http"
"net/url"
"path"
"path/filepath"
"strings"
"github.com/debridmediamanager.com/zurg/internal/config"
"github.com/debridmediamanager.com/zurg/internal/torrent"
"github.com/debridmediamanager.com/zurg/pkg/logutil"
)
func HandleDirectoryListing(w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager, c config.ConfigInterface) {
log := logutil.NewLogger().Named("http")
requestPath := path.Clean(r.URL.Path)
var output *string
var err error
filteredSegments := removeEmptySegments(strings.Split(requestPath, "/"))
switch {
case len(filteredSegments) == 1:
output, err = handleRoot(w, r, c)
case len(filteredSegments) == 2:
output, err = handleListOfTorrents(requestPath, w, r, t, c)
case len(filteredSegments) == 3:
output, err = handleSingleTorrent(requestPath, w, r, t)
default:
log.Errorf("Request %s %s not found", r.Method, requestPath)
http.Error(w, "Not Found", http.StatusNotFound)
return
}
if err != nil {
log.Errorf("Error processing request: %v", err)
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
if output != nil {
w.Header().Set("Content-Type", "text/html; charset=\"utf-8\"")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, *output)
}
}
func handleRoot(w http.ResponseWriter, r *http.Request, c config.ConfigInterface) (*string, error) {
htmlDoc := "<ul>"
for _, directory := range c.GetDirectories() {
directoryPath := url.PathEscape(directory)
htmlDoc += fmt.Sprintf("<li><a href=\"/http/%s/\">%s</a></li>", directoryPath, directory)
}
return &htmlDoc, nil
}
func handleListOfTorrents(requestPath string, w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager, c config.ConfigInterface) (*string, error) {
basePath := path.Base(requestPath)
for _, directory := range c.GetDirectories() {
if basePath == directory {
htmlDoc := "<ol>"
for name, torrent := range t.TorrentMap {
if len(torrent.SelectedFiles) == 0 {
continue
}
for _, dir := range torrent.Directories {
if dir == basePath {
htmlDoc += fmt.Sprintf("<li><a href=\"%s/\">%s</a></li>", filepath.Join(requestPath, url.PathEscape(name)), name)
break
}
}
}
return &htmlDoc, nil
}
}
return nil, fmt.Errorf("cannot find directory when generating list: %s", requestPath)
}
func handleSingleTorrent(requestPath string, w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager) (*string, error) {
torrentName := path.Base(requestPath)
htmlDoc := "<ol>"
for _, file := range t.TorrentMap[torrentName].SelectedFiles {
if file.Link == "" {
// TODO: fix the file?
fmt.Printf("File %s has no link, skipping\n", file.Path)
continue
}
filename := filepath.Base(file.Path)
filePath := filepath.Join(requestPath, url.PathEscape(filename))
htmlDoc += fmt.Sprintf("<li><a href=\"%s\">%s</a></li>", filePath, filename)
}
return &htmlDoc, nil
}