The Audiobookshelf-compat surface sits outside the monitoring and kill design
entirely — neither architecture matrix mentioned it. Three routes pour full
media and none consulted the kill switch:
- /(abs/)api/items/{id}/file/{ino} and /download — bearer auth, no revocation
check, no in-flight cut.
- /(abs/)public/session/{sid}/track/{idx} — mounted outside bearerAuth (the
session id is the capability); it held a transport marker but was unkillable.
- /feed/{slug}/file/{ino} — no auth at all, the slug is the capability;
invisible and unkillable, and closing a feed only blocked the next request
rather than cutting a pour already in flight.
Each surface now passes its real credential-issue time, because a user
revocation is a cutoff, not a ban: it matches only streams whose credential
predates it. ABS bearer tokens are stateless JWTs that OnUserSessionsRevoked
does not delete, so passing request-entry time (as the jellycompat login path
safely does) would have meant a user kill never refused a later ABS request.
- bearerAuth carries the JWT's iat into ctxAuth; the authenticated file route
uses it.
- The public track uses the persisted playback session's StartedAt and passes
the native session id so session-level kills land too, plus the shared
metered writer for byte accounting.
- The feed file uses the feed's CreatedAt for an owner cutoff — a feed opened
before the revocation dies, one opened after re-authenticating serves — and
arms the in-flight cut.
The authenticated file route stays download-class: like the native and
jellycompat download routes it is exempt from the live-stream cap and from
streammonitor, and is covered by no download quota. It is now killable and
explicitly documented rather than quietly invisible. Bringing all three
download-class routes under one quota and one monitor record is tracked as a
follow-up rather than adding a fourth per-route model here.
Part of the stream monitoring & kill-switch epic.
250 lines
8.0 KiB
Go
250 lines
8.0 KiB
Go
package abs
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/oklog/ulid/v2"
|
|
|
|
"github.com/Silo-Server/silo-server/internal/models"
|
|
)
|
|
|
|
var slugRe = regexp.MustCompile(`^[a-z0-9-]{4,64}$`)
|
|
|
|
type feedOpenBody struct {
|
|
Slug string `json:"slug"`
|
|
Minified bool `json:"minified"`
|
|
}
|
|
|
|
func (h *Handler) handleListRSSFeeds(w http.ResponseWriter, r *http.Request) {
|
|
a, ok := absAuthFrom(r)
|
|
if !ok || a.UserID == "" {
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
if h.deps.RSSFeedStore == nil {
|
|
writeJSON(w, http.StatusOK, map[string]any{"feeds": []any{}})
|
|
return
|
|
}
|
|
rows, err := h.deps.RSSFeedStore.ListUserFeeds(r.Context(), a.UserID, a.ProfileID)
|
|
if err != nil {
|
|
slog.ErrorContext(r.Context(), "abs feed list failed", "component", "audiobooks", "err", err, "user", a.UserID)
|
|
http.Error(w, "feed list failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
base := h.absBaseURL(r)
|
|
out := make([]map[string]any, 0, len(rows))
|
|
for _, f := range rows {
|
|
out = append(out, rssFeedToABS(f, base))
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"feeds": out})
|
|
}
|
|
|
|
func (h *Handler) handleOpenItemFeed(w http.ResponseWriter, r *http.Request) {
|
|
a, ok := absAuthFrom(r)
|
|
if !ok || a.UserID == "" {
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
if h.deps.RSSFeedStore == nil {
|
|
http.Error(w, "feed store unavailable", http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
itemID := chi.URLParam(r, "itemId")
|
|
access, err := h.accessFilterForAuth(r.Context(), a)
|
|
if err != nil {
|
|
http.Error(w, "resolve access: "+err.Error(), http.StatusForbidden)
|
|
return
|
|
}
|
|
item, err := h.deps.MediaStore.GetAudiobookByID(r.Context(), itemID, access)
|
|
if err != nil || item == nil {
|
|
http.Error(w, "item not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
var body feedOpenBody
|
|
_ = json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body)
|
|
|
|
slug := strings.ToLower(strings.TrimSpace(body.Slug))
|
|
if slug == "" {
|
|
slug = randomSlug()
|
|
} else if !slugRe.MatchString(slug) {
|
|
http.Error(w, "invalid slug", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
f := RSSFeed{
|
|
ID: ulid.Make().String(),
|
|
UserID: a.UserID,
|
|
ProfileID: a.ProfileID,
|
|
LibraryItemID: itemID,
|
|
Slug: slug,
|
|
Minified: body.Minified,
|
|
}
|
|
if err := h.deps.RSSFeedStore.CreateFeed(r.Context(), f); err != nil {
|
|
if strings.Contains(err.Error(), "duplicate key") || strings.Contains(err.Error(), "unique") {
|
|
http.Error(w, "slug taken", http.StatusConflict)
|
|
return
|
|
}
|
|
slog.ErrorContext(r.Context(), "abs feed create failed", "component", "audiobooks", "err", err, "user", a.UserID)
|
|
http.Error(w, "feed persist failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
persisted, err := h.deps.RSSFeedStore.GetFeed(r.Context(), f.ID)
|
|
if errors.Is(err, ErrNotFound) || err != nil {
|
|
f.CreatedAt = time.Now()
|
|
persisted = f
|
|
}
|
|
writeJSON(w, http.StatusOK, rssFeedToABS(persisted, h.absBaseURL(r)))
|
|
}
|
|
|
|
func (h *Handler) handleCloseFeed(w http.ResponseWriter, r *http.Request) {
|
|
a, ok := absAuthFrom(r)
|
|
if !ok || a.UserID == "" {
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
if h.deps.RSSFeedStore == nil {
|
|
http.Error(w, "feed not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
f, err := h.deps.RSSFeedStore.GetFeed(r.Context(), id)
|
|
if errors.Is(err, ErrNotFound) || (err == nil && !sameABSPrincipal(a, f.UserID, f.ProfileID)) {
|
|
http.Error(w, "feed not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
if err != nil {
|
|
slog.ErrorContext(r.Context(), "abs feed get-for-close failed", "component", "audiobooks", "err", err, "id", id)
|
|
http.Error(w, "feed get failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if err := h.deps.RSSFeedStore.CloseFeed(r.Context(), id); err != nil {
|
|
slog.ErrorContext(r.Context(), "abs feed close failed", "component", "audiobooks", "err", err, "id", id)
|
|
http.Error(w, "feed close failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func randomSlug() string {
|
|
const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
|
|
buf := make([]byte, 16)
|
|
_, _ = rand.Read(buf)
|
|
for i, b := range buf {
|
|
buf[i] = alphabet[int(b)%len(alphabet)]
|
|
}
|
|
return string(buf)
|
|
}
|
|
|
|
// handlePublicFeed — GET /feed/{slug}.xml and GET /feed/{slug}.
|
|
// Public, no auth. The slug is the capability token.
|
|
func (h *Handler) handlePublicFeed(w http.ResponseWriter, r *http.Request) {
|
|
if h.deps.RSSFeedStore == nil {
|
|
http.Error(w, "feed not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
slug := strings.TrimSuffix(chi.URLParam(r, "slug"), ".xml")
|
|
f, err := h.deps.RSSFeedStore.GetFeedBySlug(r.Context(), slug)
|
|
if errors.Is(err, ErrNotFound) || (err == nil && f.ClosedAt != nil) {
|
|
http.Error(w, "feed not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
if err != nil {
|
|
slog.ErrorContext(r.Context(), "abs public feed get failed", "component", "audiobooks", "err", err, "slug", slug)
|
|
http.Error(w, "feed get failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
item, err := h.deps.MediaStore.GetAudiobookByID(r.Context(), f.LibraryItemID, emptyAccessFilter())
|
|
if err != nil || item == nil {
|
|
http.Error(w, "feed item not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
files, _ := h.deps.MediaStore.GetMediaFiles(r.Context(), f.LibraryItemID, emptyAccessFilter())
|
|
|
|
base := h.absBaseURL(r)
|
|
xml := renderFeedXML(f, item, files, base)
|
|
w.Header().Set("Content-Type", "application/rss+xml; charset=utf-8")
|
|
_, _ = w.Write([]byte(xml))
|
|
}
|
|
|
|
// renderFeedXML builds a minimal RSS 2.0 + iTunes document.
|
|
func renderFeedXML(f RSSFeed, item *models.MediaItem, files []*models.MediaFile, baseURL string) string {
|
|
var b strings.Builder
|
|
b.WriteString(`<?xml version="1.0" encoding="UTF-8"?>` + "\n")
|
|
b.WriteString(`<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">` + "\n")
|
|
b.WriteString("<channel>\n")
|
|
b.WriteString("<title>" + xmlEscape(item.Title) + "</title>\n")
|
|
b.WriteString("<link>" + xmlEscape(baseURL+"/feed/"+f.Slug+".xml") + "</link>\n")
|
|
b.WriteString("<description>silo audiobook feed</description>\n")
|
|
for _, mf := range files {
|
|
enc := baseURL + "/feed/" + f.Slug + "/file/" + strconv.Itoa(mf.ID)
|
|
b.WriteString("<item>\n")
|
|
b.WriteString("<title>" + xmlEscape(item.Title) + "</title>\n")
|
|
b.WriteString(`<enclosure url="` + xmlEscape(enc) + `" type="audio/mpeg" length="0"/>` + "\n")
|
|
b.WriteString("<guid>" + xmlEscape(f.Slug+"-"+strconv.Itoa(mf.ID)) + "</guid>\n")
|
|
b.WriteString("</item>\n")
|
|
}
|
|
b.WriteString("</channel>\n")
|
|
b.WriteString("</rss>\n")
|
|
return b.String()
|
|
}
|
|
|
|
func xmlEscape(s string) string {
|
|
r := strings.NewReplacer("&", "&", "<", "<", ">", ">", `"`, """)
|
|
return r.Replace(s)
|
|
}
|
|
|
|
// handlePublicFeedFile — GET /feed/{slug}/file/{ino}. Streams the
|
|
// media file when the slug is valid + open and the ino belongs to
|
|
// the underlying library item.
|
|
func (h *Handler) handlePublicFeedFile(w http.ResponseWriter, r *http.Request) {
|
|
if h.deps.RSSFeedStore == nil {
|
|
http.Error(w, "feed not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
slug := chi.URLParam(r, "slug")
|
|
f, err := h.deps.RSSFeedStore.GetFeedBySlug(r.Context(), slug)
|
|
if errors.Is(err, ErrNotFound) || (err == nil && f.ClosedAt != nil) {
|
|
http.Error(w, "feed not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
if err != nil {
|
|
http.Error(w, "feed get failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
userID, parseUserErr := strconv.Atoi(f.UserID)
|
|
if parseUserErr != nil || userID <= 0 {
|
|
http.Error(w, "feed not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
if h.deps.Revocation != nil && h.deps.Revocation.Refuse(w, "", userID, f.CreatedAt) {
|
|
return
|
|
}
|
|
inoStr := chi.URLParam(r, "ino")
|
|
ino, parseErr := strconv.Atoi(inoStr)
|
|
if parseErr != nil {
|
|
http.Error(w, "invalid ino", http.StatusBadRequest)
|
|
return
|
|
}
|
|
mf, mfErr := h.deps.MediaStore.GetMediaFileByID(r.Context(), ino)
|
|
if mfErr != nil || mf == nil || mf.ContentID != f.LibraryItemID {
|
|
http.Error(w, "file not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
stop := h.deps.Revocation.WatchAndCut(w, "", userID, f.CreatedAt)
|
|
defer stop()
|
|
http.ServeFile(w, r, mf.FilePath)
|
|
}
|