Vellum/internal/jellyfin/system.go
mithral 35442e4aff Phase 2: split the fat packages along real boundaries
Four extractions, each chosen because the two halves have different callers,
different failure modes or different testing needs. Not a line-count exercise.

internal/home out of internal/media
- media serves item RESOURCES (detail, file, cover, progress); home computes
  AGGREGATES (the five shelves). The 2328-line package was doing both.
- media keeps POST /items/{id}/view because it is item-scoped and must stay in
  the package that authorizes the item; it imports home.RecordView for that one
  thing. home does not import media.
- Verified live: all five shelves non-empty, and two consecutive /home calls
  return different explore ids, which is the non-determinism the Explore rewrite
  exists for.

internal/scanner out of internal/library
- The scanner walks the filesystem and reconciles; library CRUD is an admin HTTP
  surface. Different callers (a job vs a request), different failure modes.
- The registry deliberately STAYED in internal/library: three of its four callers
  are not the scanner (modules register types, handlers serve the list, metadata
  reads the group mode, subsonic calls CleanTitle). It is a property of the kind,
  not of the scan. The one genuinely scanner-owned helper became
  library.ExtensionsFor.
- Two tests moved with the code rather than being rewritten; they now exercise
  the boundary by calling library.ListMissing across it.
- Verified live: first scan updates, rescan reports unchanged=N, so change
  detection still short-circuits.

internal/providers out of internal/metadata
- Providers talk to third-party APIs; the enrich job owns the matching policy and
  the database writes. The split's whole point is that a provider is testable
  WITHOUT a database, so a DB-free test was added and OpenLibrary gained a
  BaseURL override to make it possible.
- providers imports zero internal packages — a true leaf.
- The matching policy (searchTitle, artistHint, pickBest) is untouched. It exists
  because real false matches were found.

dto packages out of internal/jellyfin and internal/subsonic
- The wire types and their mapping are now separate from the handler logic, so
  the contract with clients we do not control is reviewable on its own.
- Both dto packages are PURE: zero references to sql.DB or net/http, verified by
  grep. That is what makes them reviewable.
- No field name, tag or error code changed.

internal/arch did its job: it failed the build twice during this phase, once for
each new package that was not yet placed in a layer. That is the rule working,
not an obstacle.

Verified: gofmt clean, build exit 0, vet exit 0, 23 packages pass, svelte-check
0/0, and end to end against a running server — home shelves, a queued scan
reporting unchanged, Jellyfin /Items, and Subsonic ping.

Process note: one agent (dto) stopped mid-task and left the tree red — the dto
packages unlayered and its test still referencing constants that had moved. The
arch test caught it immediately. I finished it by hand: exported constant
references in the test, and both dto packages placed at layer 3.

Still open from Phase 1: internal/jellyfin has no test files, catalog is
item-centric while Subsonic is file-first, and subsonic loadAlbum now scopes to
the item's own library.
2026-10-11 16:03:10 -04:00

151 lines
4.1 KiB
Go

package jellyfin
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/mithral/vellum/internal/apitoken"
"github.com/mithral/vellum/internal/auth"
"github.com/mithral/vellum/internal/httpx"
"github.com/mithral/vellum/internal/jellyfin/dto"
)
func (h *Handlers) handleSystemInfoPublic(w http.ResponseWriter, r *http.Request) {
httpx.WriteJSON(w, http.StatusOK, dto.SystemInfoPublic{
Id: h.serverIDFor(r.Context()),
ServerName: "Vellum",
Version: dto.Version,
ProductName: "Vellum",
OperatingSystem: "Linux",
})
}
func (h *Handlers) handleAuthenticateByName(w http.ResponseWriter, r *http.Request) {
// Deliberately not httpx.DecodeJSON: that rejects unknown fields, and real
// clients add extras. We only read Username and Pw.
var req dto.AuthByNameRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
httpx.WriteError(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Username == "" || req.Pw == "" {
httpx.WriteError(w, http.StatusBadRequest, "username and password are required")
return
}
u, err := auth.Authenticate(r.Context(), h.db, req.Username, req.Pw)
if err != nil {
if errors.Is(err, auth.ErrInvalidCredentials) {
// Same message for unknown user and wrong password, as the web
// login does, so usernames are not enumerable.
httpx.WriteError(w, http.StatusUnauthorized, "invalid username or password")
return
}
h.fail(w, "authenticate", err)
return
}
label := deviceLabel(r)
token, err := apitoken.Mint(r.Context(), h.db, u.ID, apitoken.KindJellyfin, label)
if err != nil {
h.fail(w, "mint token", err)
return
}
dto, err := h.userDTO(r.Context(), u)
if err != nil {
h.fail(w, "build user", err)
return
}
h.log.Info("jellyfin login", "user", u.Username, "device", label)
httpx.WriteJSON(w, http.StatusOK, map[string]any{
"User": dto,
"AccessToken": token,
"ServerId": h.serverIDFor(r.Context()),
})
}
func (h *Handlers) handleUserMe(w http.ResponseWriter, r *http.Request, u auth.User) {
dto, err := h.userDTO(r.Context(), u)
if err != nil {
h.fail(w, "build user", err)
return
}
httpx.WriteJSON(w, http.StatusOK, dto)
}
func (h *Handlers) handleUserByID(w http.ResponseWriter, r *http.Request, u auth.User) {
id, _, ok := dto.DecodeID(r.PathValue("userId"))
if !ok || id != u.ID {
// A token may only address its own user. Cross-user reads (which
// Jellyfin permits for admins) are NOT implemented; a mismatched id is
// a 404 so account existence is not disclosed.
httpx.WriteError(w, http.StatusNotFound, "user not found")
return
}
dto, err := h.userDTO(r.Context(), u)
if err != nil {
h.fail(w, "build user", err)
return
}
httpx.WriteJSON(w, http.StatusOK, dto)
}
// userDTO renders the Jellyfin user shape, including the visible library
// folders so a client can scope its views.
func (h *Handlers) userDTO(ctx context.Context, u auth.User) (dto.UserDto, error) {
libs, err := auth.VisibleLibraryIDs(ctx, h.db, u)
if err != nil {
return dto.UserDto{}, err
}
return dto.User(u, h.serverIDFor(ctx), libs), nil
}
// deviceLabel best-effort extracts a human device name from the
// X-Emby-Authorization header so the token list in the UI is recognisable.
func deviceLabel(r *http.Request) string {
hdr := r.Header.Get("X-Emby-Authorization")
if hdr == "" {
hdr = r.Header.Get("Authorization")
}
for _, f := range splitParams(hdr) {
if v, ok := cutParam(f, "Device="); ok && v != "" {
return "Jellyfin: " + v
}
}
return "Jellyfin"
}
// splitParams splits a MediaBrowser-style parameter list on commas or spaces.
func splitParams(s string) []string {
out := []string{}
cur := ""
for _, r := range s {
if r == ',' || r == ' ' {
if cur != "" {
out = append(out, cur)
}
cur = ""
continue
}
cur += string(r)
}
if cur != "" {
out = append(out, cur)
}
return out
}
func cutParam(field, prefix string) (string, bool) {
if len(field) < len(prefix) || field[:len(prefix)] != prefix {
return "", false
}
v := field[len(prefix):]
if len(v) >= 2 && v[0] == '"' && v[len(v)-1] == '"' {
v = v[1 : len(v)-1]
}
return v, true
}