279 lines
11 KiB
Go
279 lines
11 KiB
Go
package main
|
|
|
|
import (
|
|
"embed"
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
"regexp"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
|
"github.com/tus/tusd/pkg/filestore"
|
|
tusd "github.com/tus/tusd/pkg/handler"
|
|
"github.com/tus/tusd/pkg/locker/memorylocker"
|
|
|
|
"scm.bstein.dev/pegasus/backend/internal"
|
|
)
|
|
|
|
//go:embed web/dist/*
|
|
var webFS embed.FS
|
|
|
|
var (
|
|
mediaRoot = env("PEGASUS_MEDIA_ROOT", "/media")
|
|
userMapFile = env("PEGASUS_USER_MAP_FILE", "/config/user-map.yaml")
|
|
tusDir = env("PEGASUS_TUS_DIR", filepath.Join(mediaRoot, ".pegasus-tus"))
|
|
jf = internal.NewJellyfin()
|
|
)
|
|
|
|
type loggingRW struct {
|
|
http.ResponseWriter
|
|
status int
|
|
}
|
|
func (l *loggingRW) WriteHeader(code int){ l.status = code; l.ResponseWriter.WriteHeader(code) }
|
|
|
|
func main() {
|
|
internal.Logf("PEGASUS_DEBUG=%v, DRY_RUN=%v, TUS_DIR=%s, MEDIA_ROOT=%s", internal.Debug, internal.DryRun, tusDir, mediaRoot)
|
|
|
|
um, err := internal.LoadUserMap(userMapFile)
|
|
must(err, "load user map")
|
|
|
|
// === tusd setup (resumable uploads) ===
|
|
store := filestore.FileStore{Path: tusDir}
|
|
locker := memorylocker.New()
|
|
composer := tusd.NewStoreComposer()
|
|
store.UseIn(composer)
|
|
locker.UseIn(composer)
|
|
|
|
completeC := make(chan tusd.HookEvent)
|
|
config := tusd.Config{
|
|
BasePath: "/tus/",
|
|
StoreComposer: composer,
|
|
NotifyCompleteUploads: true,
|
|
CompleteUploads: completeC,
|
|
MaxSize: 0, // unlimited
|
|
}
|
|
tusHandler, err := tusd.NewUnroutedHandler(config)
|
|
must(err, "init tus handler")
|
|
|
|
// ---- post-finish hook: enforce naming & mapping ----
|
|
go func() {
|
|
for ev := range completeC {
|
|
claims, err := claimsFromHook(ev)
|
|
if err != nil { internal.Logf("tus: no session: %v", err); continue }
|
|
|
|
// read metadata set by the UI
|
|
meta := ev.Upload.MetaData
|
|
desc := strings.TrimSpace(meta["desc"])
|
|
if desc == "" { internal.Logf("tus: missing desc; rejecting"); continue }
|
|
date := strings.TrimSpace(meta["date"]) // YYYY-MM-DD or empty
|
|
subdir := strings.Trim(strings.TrimSpace(meta["subdir"]), "/")
|
|
orig := meta["filename"]
|
|
if orig == "" { orig = "upload.bin" }
|
|
|
|
// resolve per-user root
|
|
userRootRel, err := um.Resolve(claims.Username)
|
|
if err != nil { internal.Logf("tus: user map missing: %v", err); continue }
|
|
|
|
// compose final name & target
|
|
finalName, err := internal.ComposeFinalName(date, desc, orig)
|
|
if err != nil { internal.Logf("tus: bad target name: %v", err); continue }
|
|
|
|
rootAbs, _ := internal.SafeJoin(mediaRoot, userRootRel)
|
|
var targetAbs string
|
|
if subdir == "" {
|
|
targetAbs, err = internal.SafeJoin(rootAbs, finalName)
|
|
} else {
|
|
targetAbs, err = internal.SafeJoin(rootAbs, filepath.Join(subdir, finalName))
|
|
}
|
|
if err != nil { internal.Logf("tus: path escape prevented: %v", err); continue }
|
|
|
|
srcPath := ev.Upload.Storage["Path"]
|
|
_ = os.MkdirAll(filepath.Dir(targetAbs), 0o755)
|
|
if internal.DryRun {
|
|
internal.Logf("[DRY] move %s -> %s", srcPath, targetAbs)
|
|
} else if err := os.Rename(srcPath, targetAbs); err != nil {
|
|
internal.Logf("move failed: %v", err); continue
|
|
}
|
|
internal.Logf("uploaded: %s", targetAbs)
|
|
|
|
// kick Jellyfin refresh
|
|
jf.RefreshLibrary(claims.JFToken)
|
|
}
|
|
}()
|
|
|
|
// === chi router ===
|
|
r := chi.NewRouter()
|
|
r.Use(corsForTus)
|
|
|
|
// auth
|
|
r.Post("/api/login", func(w http.ResponseWriter, r *http.Request) {
|
|
var f struct{ Username, Password string }
|
|
if err := json.NewDecoder(r.Body).Decode(&f); err != nil { http.Error(w, "bad json", 400); return }
|
|
res, err := jf.AuthenticateByName(f.Username, f.Password) // password login
|
|
if err != nil { http.Error(w, "invalid credentials", 401); return }
|
|
if err := internal.SetSession(w, res.User.Username, res.AccessToken); err != nil {
|
|
http.Error(w, "session error", 500); return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
|
|
})
|
|
r.Post("/api/logout", func(w http.ResponseWriter, _ *http.Request) { internal.ClearSession(w); _ = json.NewEncoder(w).Encode(map[string]any{"ok": true}) })
|
|
|
|
// whoami
|
|
r.Get("/api/whoami", func(w http.ResponseWriter, r *http.Request) {
|
|
cl, err := internal.CurrentUser(r); if err != nil { http.Error(w, "unauthorized", 401); return }
|
|
dr, err := um.Resolve(cl.Username); if err != nil { http.Error(w, "no mapping", 403); return }
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"username": cl.Username, "root": dr})
|
|
})
|
|
|
|
// list entries
|
|
r.Get("/api/list", func(w http.ResponseWriter, r *http.Request) {
|
|
cl, err := internal.CurrentUser(r); if err != nil { http.Error(w, "unauthorized", 401); return }
|
|
rootRel, err := um.Resolve(cl.Username); if err != nil { http.Error(w, "forbidden", 403); return }
|
|
q := strings.TrimPrefix(r.URL.Query().Get("path"), "/")
|
|
rootAbs, _ := internal.SafeJoin(mediaRoot, rootRel)
|
|
var dirAbs string
|
|
if q == "" { dirAbs = rootAbs } else {
|
|
dirAbs, err = internal.SafeJoin(rootAbs, q); if err != nil { http.Error(w, "forbidden", 403); return }
|
|
}
|
|
ents, err := os.ReadDir(dirAbs); if err != nil { http.Error(w, err.Error(), 500); return }
|
|
type entry struct{ Name, Path string; IsDir bool; Size int64; Mtime int64 }
|
|
var out []entry
|
|
for _, d := range ents {
|
|
info, _ := d.Info()
|
|
out = append(out, entry{
|
|
Name: d.Name(), Path: filepath.Join(q, d.Name()), IsDir: d.IsDir(),
|
|
Size: func() int64 { if info != nil && !d.IsDir() { return info.Size() }; return 0 }(),
|
|
Mtime: func() int64 { if info != nil { return info.ModTime().Unix() }; return 0 }(),
|
|
})
|
|
}
|
|
_ = json.NewEncoder(w).Encode(out)
|
|
})
|
|
|
|
// rename
|
|
var finalNameRe = regexp.MustCompile(`^\d{4}\.\d{2}\.\d{2}\.[A-Za-z0-9_-]{1,64}\.[A-Za-z0-9]{1,8}$`)
|
|
r.Post("/api/rename", func(w http.ResponseWriter, r *http.Request) {
|
|
cl, err := internal.CurrentUser(r); if err != nil { http.Error(w,"unauthorized",401); return }
|
|
var p struct{ From, To string }
|
|
if err := json.NewDecoder(r.Body).Decode(&p); err != nil { http.Error(w,"bad json",400); return }
|
|
|
|
// enforce final name on files (allow any name for directories)
|
|
if filepath.Ext(p.To) != "" && !finalNameRe.MatchString(filepath.Base(p.To)) {
|
|
http.Error(w, "new name must match YYYY.MM.DD.Description.ext", 400); return
|
|
}
|
|
|
|
rootRel, _ := um.Resolve(cl.Username)
|
|
rootAbs, _ := internal.SafeJoin(mediaRoot, rootRel)
|
|
fromAbs, err := internal.SafeJoin(rootAbs, p.From); if err != nil { http.Error(w,"forbidden",403); return }
|
|
toAbs, err := internal.SafeJoin(rootAbs, p.To); if err != nil { http.Error(w,"forbidden",403); return }
|
|
_ = os.MkdirAll(filepath.Dir(toAbs), 0o755)
|
|
if internal.DryRun { internal.Logf("[DRY] mv %s -> %s", fromAbs, toAbs) } else if err := os.Rename(fromAbs, toAbs); err != nil { http.Error(w, err.Error(), 500); return }
|
|
jf.RefreshLibrary(cl.JFToken)
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
|
|
})
|
|
|
|
// delete
|
|
r.Delete("/api/file", func(w http.ResponseWriter, r *http.Request) {
|
|
cl, err := internal.CurrentUser(r); if err != nil { http.Error(w, "unauthorized", 401); return }
|
|
rootRel, _ := um.Resolve(cl.Username)
|
|
path := r.URL.Query().Get("path"); rec := r.URL.Query().Get("recursive") == "true"
|
|
rootAbs, _ := internal.SafeJoin(mediaRoot, rootRel)
|
|
abs, err := internal.SafeJoin(rootAbs, path); if err != nil { http.Error(w, "forbidden", 403); return }
|
|
if rec { err = os.RemoveAll(abs) } else { err = os.Remove(abs) }
|
|
if err != nil { http.Error(w, err.Error(), 500); return }
|
|
jf.RefreshLibrary(cl.JFToken)
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
|
|
})
|
|
|
|
// mount tus (behind auth)
|
|
r.Route("/tus", func(rt chi.Router) {
|
|
rt.Use(sessionRequired)
|
|
rt.Post("/*", tusHandler.PostFile)
|
|
rt.Head("/*", tusHandler.HeadFile)
|
|
rt.Patch("/*", tusHandler.PatchFile)
|
|
rt.Del("/*", tusHandler.DelFile)
|
|
rt.Get("/*", tusHandler.GetFile) // optional
|
|
})
|
|
|
|
// static app
|
|
r.Handle("/metrics", promhttp.Handler())
|
|
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
|
http.FileServer(http.FS(webFS)).ServeHTTP(w, r)
|
|
})
|
|
r.Handle("/static/*", http.StripPrefix("/", http.FileServer(http.FS(webFS))))
|
|
|
|
addr := env("PEGASUS_BIND", ":8080")
|
|
log.Printf("Pegasus listening on %s", addr)
|
|
srv := &http.Server{Addr: addr, Handler: r, ReadTimeout: 0, WriteTimeout: 0}
|
|
log.Fatal(srv.ListenAndServe())
|
|
|
|
// debug endpoints
|
|
r.Get("/debug/env", func(w http.ResponseWriter, r *http.Request) {
|
|
if !internal.Debug { http.Error(w, "disabled", 403); return }
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"mediaRoot": mediaRoot, "tusDir": tusDir, "userMapFile": userMapFile,
|
|
})
|
|
})
|
|
r.Get("/debug/write-test", func(w http.ResponseWriter, r *http.Request) {
|
|
if !internal.Debug { http.Error(w, "disabled", 403); return }
|
|
cl, err := internal.CurrentUser(r); if err != nil { http.Error(w,"unauthorized",401); return }
|
|
rootRel, err := um.Resolve(cl.Username); if err != nil { http.Error(w,"forbidden",403); return }
|
|
rootAbs, _ := internal.SafeJoin(mediaRoot, rootRel)
|
|
test := filepath.Join(rootAbs, fmt.Sprintf("TEST.%d.txt", time.Now().Unix()))
|
|
if internal.DryRun { internal.Logf("[DRY] write %s", test) } else { _ = os.WriteFile(test, []byte("ok\n"), 0o644) }
|
|
_ = json.NewEncoder(w).Encode(map[string]string{"wrote": test})
|
|
})
|
|
}
|
|
|
|
// ---- wrap router with verbose request logging in debug ----
|
|
root := http.Handler(r)
|
|
if internal.Debug {
|
|
root = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
|
id := time.Now().UnixNano()
|
|
internal.Logf(">> %d %s %s %v", id, req.Method, req.URL.Path, internal.RedactHeaders(req.Header))
|
|
rw := &loggingRW{ResponseWriter:w, status:200}
|
|
start := time.Now()
|
|
r.ServeHTTP(rw, req)
|
|
internal.Logf("<< %d %s %s %d %s", id, req.Method, req.URL.Path, rw.status, time.Since(start))
|
|
})
|
|
}
|
|
srv := &http.Server{Addr: addr, Handler: root, ReadTimeout:0, WriteTimeout:0}
|
|
|
|
// === helpers & middleware ===
|
|
func sessionRequired(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if _, err := internal.CurrentUser(r); err != nil {
|
|
http.Error(w, "unauthorized", 401); return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func corsForTus(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Allow tus headers for resumable uploads
|
|
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
|
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Tus-Resumable, Upload-Length, Upload-Metadata, Upload-Offset, X-Requested-With")
|
|
w.Header().Set("Access-Control-Expose-Headers", "Location, Upload-Offset, Upload-Length, Tus-Resumable")
|
|
if r.Method == "OPTIONS" { w.WriteHeader(204); return }
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func claimsFromHook(ev tusd.HookEvent) (internal.Claims, error) {
|
|
// Parse our session cookie from incoming request headers captured by tusd
|
|
req := ev.HTTPRequest
|
|
if req.Header == nil { return internal.Claims{}, http.ErrNoCookie }
|
|
// Re-create a dummy http.Request to reuse cookie parsing & jwt verification
|
|
r := http.Request{Header: http.Header(req.Header)}
|
|
return internal.CurrentUser(&r)
|
|
}
|
|
|
|
func env(k, def string) string { if v := os.Getenv(k); v != "" { return v }; return def }
|
|
func must(err error, msg string) { if err != nil { log.Fatalf("%s: %v", msg, err) } }
|