Six defects on byte-serving paths, all of which made the PR's monitoring and
kill-switch claims narrower than documented.
#2/GAP-10 -- the ABS in-flight kill switch was a production no-op. accessLog
wraps every ABS route, and its statusRecorder implemented Write, WriteHeader,
Hijack and Flush but not Unwrap, so http.NewResponseController dead-ended and
SetWriteDeadline returned ErrNotSupported. A multi-GB audiobook pour survived a
RevokeUser. The existing test passed throughout because it called handlers
directly and never saw the middleware; the new test drives the mounted router
over a real socket, and both new assertions fail if Unwrap is removed again.
GAP-11 -- ebook, comic and PDF serving was invisible and un-killable: no meter,
no transfer record, no Refuse, no watcher, on a route that serves cbz/cbr/pdf
files routinely 100 MB-1 GB+. It now follows the ABS file-handler idiom. Note
guardRevocationCut is deliberately *not* reused here: it keys on a session_id
URL param and an ?st= token this route does not carry, so it would have
compiled and silently guarded nothing. Cap-exempt per decision A4 -- admission
is untouched and neither route consumes a stream slot.
#10 -- the no-proxy remote transcode hop forwarded segments through a bare
RollingDeadlineWriter, so bytes on the API hop went unaccounted for a supported
topology. Metering is scoped to media bodies; manifests are excluded so a
rewritten playlist is not counted as media, and a mid-copy failure is no longer
silently discarded.
#16 -- native, proxy and compat subtitle pours were entry-gated only. They now
carry a transport span, a meter and an in-flight watcher. Proxy subtitle bytes
are attributed only when a tracker record already exists: taking Track/Remove
lifecycle ownership per subtitle request would walk straight into the
overlapping-request defect (#1) that Batch 2 addresses. Compat subtitle
extraction is buffered and rejects bitmap formats, so a cut stops delivery but
not extraction already in progress.
M2 -- the proxy deferred tracker Remove with the request context, which is
already canceled on client disconnect, so the Redis DEL never happened and the
key lingered until TTL -- a false over-cap window that could get a legitimate
stream killed. Cleanup now uses a short bounded context.
GAP-13 -- mergeStreams took the freshest record wholesale and never merged
BytesServed, so a stream that poured 8 GiB at an edge could report 0. Merged as
a max, not a sum: the records are two observers of one pour. Fixed in
DedupeSessionInfos too, which had the same hole and feeds the admin view.
#11 needed no behaviour change -- that route was already metered, registered and
watched, and commit c24d8396 plus this Unwrap fix are what make its cut work.
Its comment claimed download-class exemption while the comment above it said the
?token= form is for iOS streaming; both facts and decision A4 are now stated.
Part of #305.
276 lines
9.0 KiB
Go
276 lines
9.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/google/uuid"
|
|
"github.com/oklog/ulid/v2"
|
|
|
|
"github.com/Silo-Server/silo-server/internal/httpstream"
|
|
"github.com/Silo-Server/silo-server/internal/models"
|
|
"github.com/Silo-Server/silo-server/internal/playback"
|
|
"github.com/Silo-Server/silo-server/internal/transfers"
|
|
)
|
|
|
|
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
|
|
}
|
|
r = r.WithContext(httpstream.WithCutLatch(r.Context(), &httpstream.CutLatch{}))
|
|
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
|
|
}
|
|
transfer := transfers.Transfer{
|
|
ID: uuid.NewString(),
|
|
UserID: userID,
|
|
ProfileID: f.ProfileID,
|
|
MediaFileID: mf.ID,
|
|
Route: "abs_feed",
|
|
ClientIP: requestClientIP(r),
|
|
ClientName: r.UserAgent(),
|
|
StartedAt: time.Now(),
|
|
}
|
|
if h.deps.Transfers != nil {
|
|
if err := h.deps.Transfers.Begin(transfer); err != nil {
|
|
slog.DebugContext(r.Context(), "ABS feed transfer not monitored", "component", "audiobooks", "transfer_id", transfer.ID, "error", err)
|
|
}
|
|
}
|
|
defer h.deps.Transfers.End(transfer.ID)
|
|
metered := playback.NewSessionMeteredWriter(w, h.deps.Transfers, transfer.ID)
|
|
defer func() { _ = metered.Close() }()
|
|
|
|
if h.deps.Revocation != nil {
|
|
stop := h.deps.Revocation.WatchAndCutContext(r.Context(), metered, "", userID, f.CreatedAt)
|
|
defer stop()
|
|
}
|
|
http.ServeFile(metered, r, mf.FilePath)
|
|
}
|