From 2d6f78e379f11d36f967e38bb7745921f8174a9d Mon Sep 17 00:00:00 2001 From: Timothy Date: Sun, 26 Jul 2026 00:34:09 +0200 Subject: [PATCH 1/3] fix(617): make the cross-repo skills real symlinks and reconcile the ersatztv skill MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `.claude/skills/jellyfin/` was a real directory holding a stale fork of the canonical server-management copy, not the symlink CLAUDE.md described. It documented `X-Emby-Token` as *the* auth pattern (v12 only accepts it via `EnableLegacyAuthorization`, slated for removal in v13) and omitted the `DELETE /Items/{id}` data-loss warning that has destroyed files three times. Replaced with a relative symlink, matching the pattern server-management already uses for beets/radarr/sonarr. `.claude/skills/ersatztv/` had diverged in BOTH directions, so a replace in either direction would have lost correct content. Contrary to the issue's framing, server-management's copy was stale only in its `description:` — its body already said "Full REST CRUD is available under /api/v1" and carried ~150 lines the ersatztv copy lacked (backup/deploy, test/prod topology, streaming-mode analysis, VAAPI-vs-QSV, table schema notes, checklists). So that file is the base, reconciled here as the canonical copy: - fixed the dangerous `description:` claiming CRUD requires SQLite scripting - ported ersatztv-only content: the silent root-owned api.key 401 trap, the lying OCI labels, the local-vs-UTC log timestamp trap, the endpoint-index pointer, `settings/ffmpeg` ordering, scoped test-image refresh - added the #616 paging facts (0-based pageNum, per-endpoint pageSize cap, playout/reset takes a CHANNEL id) per the request on #617 - corrected prod auto-update: `auto_update: false`, manual DeployStack only, no 03:00 fallback (contradicted the fork's CLAUDE.md) - corrected the ErsatzTV library ids: Music Videos is 16 and Standup 14, not 8/9 — verified live via GET /api/v1/media-sources - unpinned the stale v26.8.0 image reference (current release is v26.12.0) fixes #617 --- .claude/skills/ersatztv/SKILL.md | 388 ++++++++++++++++++++++++------- .claude/skills/jellyfin | 1 + .claude/skills/jellyfin/SKILL.md | 120 ---------- CLAUDE.md | 4 +- 4 files changed, 304 insertions(+), 209 deletions(-) create mode 120000 .claude/skills/jellyfin delete mode 100644 .claude/skills/jellyfin/SKILL.md diff --git a/.claude/skills/ersatztv/SKILL.md b/.claude/skills/ersatztv/SKILL.md index 218e98b58..7b4627449 100644 --- a/.claude/skills/ersatztv/SKILL.md +++ b/.claude/skills/ersatztv/SKILL.md @@ -1,37 +1,125 @@ --- name: ersatztv -description: ErsatzTV custom IPTV channel management — REST API, SQLite DB, Jellyfin integration, FFmpeg profiles. Use when managing custom TV channels. +description: ErsatzTV custom IPTV channel management — REST API, SQLite DB, Jellyfin integration, FFmpeg profiles. Use when creating or modifying IPTV channels, managing collections and schedules, building playouts, adding channel logos, scanning media libraries, troubleshooting channel issues, or resetting playouts. Also use for any questions about the ErsatzTV database schema (Channel, Collection, ProgramSchedule, Playout tables), M3U/XMLTV feeds, custom TV channel setup, or the channel creation checklist. IMPORTANT: the fork has a full versioned REST API at /api/v1 including write paths — prefer it over SQLite scripting, which is a recovery fallback only. --- +> **Canonical copy: `~/ersatztv/.claude/skills/ersatztv/SKILL.md`** (ersatztv owns this skill per that +> repo's `CLAUDE.md` → Project Boundaries). `~/server-management/.claude/skills/ersatztv` is a symlink +> to it. Edit it in the ersatztv repo; never fork a second copy (ersatztv#617). + # ErsatzTV Channel Management -Host: **jazz (192.168.1.29)**. Prod container `ersatztv` port **8409**; test `ersatztv-test` port -**8410** (tracks `:latest` via Komodo auto-update, daily 03:00 — a same-day validation needs the -manual pull below). +Container: `ersatztv` | Port: `8409` +Web UI: `https://ersatztv.tblindustries.be` (via bumblebee's `external-proxy` → `192.168.1.29:8409`) or `http://localhost:8409` on the host +Host: **jazz** (`192.168.1.29`) since 2026-07-20 (#633) — moved off bumblebee together with Jellyfin. `dispatcharr` and `plex` stayed on bumblebee, so Dispatcharr now reaches ErsatzTV **by IP** (`http://192.168.1.29:8409`), not by Docker DNS name. +Compose env: `ForwardedHeaders__KnownNetworks=192.168.1.99/32` (proxied traffic arrives SNAT'd from bumblebee's LAN address; wrong value breaks Authelia OIDC login only, plain HTTP still works) SQLite DB: `~/downloadswarm/ersatztv/ersatztv.sqlite3` (owned by root — use `sudo sqlite3`) -Image: **our fork**, `192.168.1.95:3000/timothy/ersatztv` (`:prod` / `:latest`). Upstream -`ghcr.io/ersatztv/ersatztv` was archived at v26.3.0 and is NOT what runs here. +Image: `192.168.1.95:3000/timothy/ersatztv:prod` (our fork; **floating** release tag — check `git tag -l 'v*' --sort=-v:refname | head -1` in `~/ersatztv` for the current release rather than trusting a version written here). Upstream `ghcr.io/ersatztv/ersatztv` was archived at v26.3.0 and is **not** what runs here. +Release tags are `vYY..` — year · sequential release-within-year · patch — **not** year.month. + +## Test/Prod topology — fork CI images (#481) + +We maintain an **ErsatzTV fork** (`~/ersatztv`); its Gitea Actions pipeline builds and pushes images to the +private Gitea registry `192.168.1.95:3000/timothy/ersatztv` on every push to `main` (`:latest` + `:`) +and, on a `v*` tag, additionally `:prod` + `:`. jazz is `docker login`'d to that registry and has `192.168.1.95:3000` in `insecure-registries`. + +| | Prod | Test | +|---|---|---| +| Container | `ersatztv` | `ersatztv-test` | +| Host port | 8409 | 8410 | +| Stack | Komodo **`jazz-media`**; source `docker/jazz/stacks/media-servers/compose.yaml` (stack name ≠ directory — `media-servers` is bumblebee's; Komodo stack names are globally unique) | Komodo `ersatztv`; source `docker/jazz/stacks/ersatztv/compose.yaml` | +| Image | `192.168.1.95:3000/timothy/ersatztv:prod` (floating release tag) | `192.168.1.95:3000/timothy/ersatztv:latest` (fork CI) | +| Config (host) | `~/downloadswarm/ersatztv/` → `/config` | `~/downloadswarm/ersatztv-test/` → `/config` (one-time prod snapshot, refresh on demand) | +| Jellyfin/Dispatcharr tuner | connected (live lineup) | **NOT** wired downstream (avoids ghost channels) | +| Media mounts | RO | same mounts, RO | +| `/dev/dri` | yes (**VAAPI on Intel iHD**, jazz — see hw note) | yes (`/dev/dri` + `group_add: '992'`) | +| Auto-update | **None** (`auto_update: false`) — promotion is a manual `DeployStack jazz-media`, with no 03:00 fallback | Komodo auto-update, daily 03:00 (tracks `:latest`) | +| Env | `TZ`, restricted forwarded-header network, empty-by-default local-admin seed hook | `TZ`, `ETV_CONFIG_FOLDER=/config`, `ETV_TRANSCODE_FOLDER=/transcode`, `ETV_DISABLE_VULKAN=1` | + +**Watchtower is retired.** Test auto-updates via Komodo; **prod does not** — `auto_update: false`, so +promoting a release is always a manual `DeployStack jazz-media`. Prod's stack has a +fail-closed pre-deploy hook: a changed compose block or `:prod` digest triggers a PBS-backed snapshot and then a +migration rehearsal against a throwaway copy of that snapshot before container recreation (#585/#589). + +**Refresh test snapshot from prod** (zero prod downtime — WAL online backup): +```bash +ssh timothy@192.168.1.29 +docker stop ersatztv-test +sudo sqlite3 ~/downloadswarm/ersatztv/ersatztv.sqlite3 ".backup '/home/timothy/downloadswarm/ersatztv-test/ersatztv.sqlite3'" +sudo rsync -a --exclude='ersatztv.sqlite3*' --exclude='logs/' ~/downloadswarm/ersatztv/ ~/downloadswarm/ersatztv-test/ +docker start ersatztv-test +``` + +**Prod cutover to the fork** — ✅ DONE 2026-06-27 (#481). Prod runs `…/timothy/ersatztv:prod` (v26.3.1); +validated `:prod` on test first, then `etv-prod-deploy.sh` backed up + cut over (43 channels, healthy, +clean migrations). Downstream (Dispatcharr M3U acct 3 + EPG src 9) is name-based, so the container IP +change was transparent. Prod stays a **manual** gate (no Watchtower label) and still lives in the +`media-servers` stack (the optional move into the `ersatztv` stack was not done). + +**Future prod releases** (push `v*` tag in `~/ersatztv` → CI builds `:prod`/`:`): scan the immutable +`:` image on jazz first, then execute Komodo `DeployStack` for `jazz-media`. The pre-deploy hook +backs up and runs the migration-on-prod-copy smoke before recreation. **There is no auto-update fallback for +prod** — if you don't `DeployStack`, nothing ships. Note the stack is named **`jazz-media`** even though the +compose *project* is still `media-servers`; a dead `media-servers` stack lingers on bumblebee and deploying it +fails silently. Roll back with the immutable prior image plus the pre-deploy DB snapshot; migrations are +forward-only. See the `komodo` skill and `docs/Docker/ErsatzTV.md` for the current procedure. + +## Backup & deploy safety (#482) + +Every prod deploy runs forward-only EF Core migrations against the live 285 MB SQLite DB — a bad one +can't be undone by re-deploying the old image, so the **only** rollback is restoring a pre-deploy DB +snapshot. Three scripts in `~/scripts/` (source of truth: `scripts/` in this repo) handle +them. **⚠️ These were installed on bumblebee, where ErsatzTV no longer runs (#633) — verify they exist on +jazz and that the Komodo `pre_deploy` hook is set on the `jazz-media` stack before relying on +"no backup, no deploy". Until confirmed, take a manual `etv-backup.sh` snapshot before every prod deploy.** +this. **Run as root** (DB + PBS creds are root-owned) except the deploy wrapper (run as `timothy`). + +| Script | Run as | What it does | +|---|---|---| +| `etv-backup.sh [--target prod\|test] [--no-offbox]` | root (sudo) | Online `sqlite3 .backup` (zero-downtime) + `integrity_check`, provenance `manifest.txt` (image ref/digest + last `__EFMigrationsHistory` id), bundles `data-protection/` + `*-secrets.json`. Local **keep-last-5** under `~/downloadswarm/ersatztv-backups//`; prod also pushes off-box to PBS. Prints the snapshot dir on stdout. | +| `etv-prod-deploy.sh` | **timothy** (needs private-registry creds; sudo's for the backup) | Backup (abort deploy if it fails) → `compose pull` + `up -d ersatztv` → health + M3U gate → prints a copy-paste rollback block on trouble. | +| `etv-restore.sh --target prod\|test --from ` | root (sudo) | Verifies snapshot → stop → saves current DB aside (`*.pre-restore-`) → swaps DB, drops stale `-wal/-shm`, restores `data-protection` → start → health/channel check. | + +- **Off-box:** prod backups go to PBS `data-local` (.68) as backup-id **`ersatztv-predeploy`** (own + group, dedups against the nightly host backup), via the existing `/root/.proxmox-backup-client.env`. +- **Retention:** local keep-last-5 (instant rollback); PBS via the datastore-wide `data-local-prune` + job (7 daily / 4 weekly / 6 monthly), no separate prune job needed. +- **Restore from PBS** instead of a local dir: + ```bash + source /root/.proxmox-backup-client.env + proxmox-backup-client restore ersatztv-predeploy/ etv.pxar + sudo ~/scripts/etv-restore.sh --target prod --from + ``` +- `docker exec` always curls the container-internal port **8409** (even for test, whose host port is + 8410). `etv-restore.sh` leaves a `*.pre-restore-` safety copy in `/config` — delete once happy. +- Validated 2026-06-27: first prod backup → PBS group created; full restore round-trip on `ersatztv-test` + returned 43 channels. Design: `plans/2026-06-27-ersatztv-backup-before-deploy-design.md`. ## Architecture -**This section described upstream v26.3.0 and was wrong for the fork — corrected 2026-07-21.** +**ErsatzTV is for channel creation only.** Consumers (Jellyfin, Kodi) never connect to ErsatzTV directly — everything goes through Dispatcharr as the single aggregation point. Pipeline: ErsatzTV → Dispatcharr → Jellyfin/Kodi. -- The **Blazor UI is gone** (#91 phase b). The only UI is the ChicoryTV React SPA at `/app`; legacy - routes 302 there. -- There **is** a full versioned REST API under **`/api/v1`**, write paths included — channels, - collections, schedules, playouts and media sources have CRUD. **Do not hand-edit SQLite for - something the API can do.** The DB-scripting recipes below survive only for gaps with no endpoint. -- Controllers stay thin and delegate to MediatR handlers; the SPA talks to `/api/v1` only. -- Authoritative endpoint list: `docs/endpoint-index.md` (generated) + `docs/api-conventions.md`. - Prefer those over any list in this file — a hand-maintained copy drifts. +ErsatzTV uses **MediatR + the ChicoryTV React SPA**. The legacy Blazor UI was removed in v26.7.0 (#91 +phase b) — the SPA at `/app` is the **only** UI, and legacy routes 302 there. The versioned `/api/v1` +surface provides full CRUD — channels, collections, schedules, playouts and media sources; browser calls +use a local-admin/OIDC session cookie plus `X-CSRF` on mutations, and machine clients use `X-Api-Key`. +**Do not hand-edit SQLite for something the API can do** — direct SQLite writes are a recovery fallback, +not the normal management path, and the DB recipes below survive only for gaps with no endpoint. -## REST API access (auth-gated — read before curling) +Controllers stay thin and delegate to MediatR handlers. **Authoritative endpoint list: +`docs/endpoint-index.md` (generated) + `docs/api-conventions.md` in the ersatztv repo — prefer those +over any list in this file**, which is hand-maintained and drifts. -Calls need **`X-Api-Key`** (machine clients) or a browser session. An unauthenticated call returns a -401 JSON body that is easy to mistake for real data — see the silent-401 trap in Gotchas. +## REST API -The key file is **root-owned `0600`**, so `cat` as `timothy` fails *silently* and yields an empty -header. Read it with `sudo`, inline, so the value is never printed: +```bash +# Via docker exec (api.key is readable inside the container) +docker exec ersatztv curl -s -H "X-Api-Key: $(docker exec ersatztv cat /config/api.key)" \ + http://localhost:8409/api/v1/ENDPOINT +``` + +From the **host**, the key file is root-owned `0600`, so an unsudo'd `cat` fails *silently* and sends an +empty header. Read it with `sudo`, inline, so the value is never printed: ```bash # prod (8409); test is identical with .../ersatztv-test/api.key and port 8410 @@ -39,12 +127,23 @@ ssh timothy@192.168.1.29 'K=$(sudo -n cat /home/timothy/downloadswarm/ersatztv/a curl -s -H "X-Api-Key: $K" http://localhost:8409/api/v1/channels' ``` +### Paging — 0-based (ersatztv#616, `api.paging-zero-based`) + +- **`pageNum` is 0-based** across the whole `/api/v1` surface and every wrapper of it (MCP tools, SPA + hooks, docs). Starting at 1 silently skips a page and returns a short set **with no error**. +- **`pageSize` is clamped per-endpoint** — 100 typical, 200 auto-tune members, 1000 search/all-items — + and the offset derives from the *effective* (clamped) size, not the requested one. Page to + completeness against `totalCount`; never conclude "that's all of them" from a single page. +- **`POST /api/v1/channels/{id}/playout/reset` takes a CHANNEL id, not the playout id.** The id spaces + overlap numerically, so passing a playout row's `Id` returns a plausible 202 against a *different* + channel. Playout rows carry `channelId` — use that. + Settings live under `/api/v1/settings/*` — `settings/ffmpeg` (`workAheadSegmenterLimit`, `qsvExtraHardwareFrames`) and `settings/logging` (`streamingMinimumLogLevel`). Note the order: it is `settings/ffmpeg`, **not** `ffmpeg/settings`. -Refresh test to the newest `:latest` without waiting for 03:00 — scope it to the service, since a -bare `up -d` would recreate everything else in the compose project: +Refresh test to the newest `:latest` without waiting for the 03:00 auto-update — scope it to the +service, since a bare `up -d` would recreate everything else in the compose project: ```bash D=/etc/komodo/stacks/ersatztv/docker/jazz/stacks/ersatztv @@ -52,26 +151,18 @@ docker compose -f $D/compose.yaml pull ersatztv-test docker compose -f $D/compose.yaml up -d --no-deps ersatztv-test ``` -The unversioned `/api/*` endpoints below predate the `/api/v1` surface — verify one against -`docs/endpoint-index.md` before relying on it. - -```bash -# Via docker exec -docker exec ersatztv curl -s http://localhost:8409/api/ENDPOINT -``` - ### Read Endpoints (GET) ``` -/api/channels # List channels -/api/collections # List collections -/api/schedules # List schedules -/api/playouts # List playouts -/api/shows # List shows -/api/movies # List movies -/api/artists # List artists -/api/search # Search items -/api/ffmpeg/profiles # FFmpeg profiles -/api/watermarks # Watermarks +/api/v1/channels # List channels +/api/v1/collections # List collections +/api/v1/schedules # List schedules +/api/v1/playouts # List playouts +/api/v1/media-items # List media items +/api/v1/search # Search items +/api/v1/ffmpeg/profiles # FFmpeg profiles +/api/v1/settings/ffmpeg # Global FFmpeg settings — workAheadSegmenterLimit, + # initialSegmentCount, hlsSegmenterIdleTimeout +/api/v1/watermarks # Watermarks /iptv/channels.m3u # M3U playlist (for Jellyfin) /iptv/xmltv.xml # XMLTV guide data ``` @@ -79,14 +170,14 @@ docker exec ersatztv curl -s http://localhost:8409/api/ENDPOINT ### Mutation Endpoints (POST) ```bash # Library scan -POST /api/libraries/{id}/scan +POST /api/v1/libraries/{id}/scan # Scan single show -POST /api/libraries/{id}/scan-show \ +POST /api/v1/libraries/{id}/scan-show \ -H "Content-Type: application/json" -d '{"ShowTitle":"Name","DeepScan":false}' # Reset channel playout (rebuilds schedule) -POST /api/channels/{channelNumber}/playout/reset +POST /api/v1/channels/{channelId}/playout/reset ``` ## SQLite DB Operations @@ -106,25 +197,56 @@ docker start ersatztv -- List channels SELECT Id, Number, Name FROM Channel ORDER BY CAST(Number AS INTEGER); --- List collections with item counts -SELECT c.Id, c.Name, COUNT(ci.Id) as items FROM Collection c LEFT JOIN CollectionItem ci ON ci.CollectionId = c.Id GROUP BY c.Id; +-- List collections with item counts (CollectionItem has no Id column — use rowid) +SELECT c.Id, c.Name, COUNT(ci.rowid) as items +FROM Collection c LEFT JOIN CollectionItem ci ON ci.CollectionId = c.Id GROUP BY c.Id; -- List schedules SELECT Id, Name FROM ProgramSchedule; --- Playout (channel-schedule links) -SELECT p.Id, c.Number, c.Name, ps.Name as Schedule FROM Playout p JOIN Channel c ON p.ChannelId = c.Id LEFT JOIN ProgramSchedule ps ON p.ProgramScheduleId = ps.Id; +-- Playout with item count (check if playout is actually built) +SELECT p.Id, c.Number, c.Name, ps.Name as Schedule, p.ScheduleKind, COUNT(pi.Id) as items +FROM Playout p JOIN Channel c ON p.ChannelId = c.Id +LEFT JOIN ProgramSchedule ps ON p.ProgramScheduleId = ps.Id +LEFT JOIN PlayoutItem pi ON pi.PlayoutId = p.Id +GROUP BY p.Id ORDER BY CAST(c.Number AS INTEGER); -- Media counts SELECT 'Shows' as type, COUNT(*) FROM Show UNION ALL SELECT 'Movies', COUNT(*) FROM Movie UNION ALL SELECT 'Episodes', COUNT(*) FROM Episode UNION ALL SELECT 'MusicVideos', COUNT(*) FROM MusicVideo; +-- Collection content (via file paths — Movie table has only Id, metadata is via MediaVersion→MediaFile) +SELECT ci.MediaItemId, mf.Path +FROM CollectionItem ci +JOIN MediaVersion mv ON mv.MovieId = ci.MediaItemId +JOIN MediaFile mf ON mf.MediaVersionId = mv.Id +WHERE ci.CollectionId = +ORDER BY mf.Path; + -- Jellyfin source SELECT jms.Id, jc.Address, jms.ServerName FROM JellyfinMediaSource jms JOIN JellyfinConnection jc ON jc.JellyfinMediaSourceId = jms.Id; -- Library sync status SELECT l.Id, l.Name, l.MediaKind, jl.ShouldSyncItems FROM Library l JOIN JellyfinLibrary jl ON jl.Id = l.Id; + +-- Music library folder breakdown +SELECT DISTINCT substr(mf.Path, 1, instr(substr(mf.Path, 13), '/') + 12) as folder, COUNT(*) as items +FROM MediaFile mf WHERE mf.Path LIKE '/data/music/%' GROUP BY folder ORDER BY folder; ``` +### Table Schema Notes + +**CollectionItem**: Has `CollectionId` + `MediaItemId` columns only (no `Id` column — use `rowid` for counting). + +**MediaVersion**: Links to content via `MovieId`, `EpisodeId`, `MusicVideoId` columns (NOT a generic `MediaItemId`). Use `mv.MovieId = ci.MediaItemId` for movie/music video collections. + +**Movie / Show / Episode / MusicVideo**: Inheritance from `MediaItem`. These tables have only an `Id` column (PK = MediaItem.Id). Titles and metadata are in separate `*Metadata` tables. + +**Artwork**: Channel logos use `ArtworkKind=2` with `ChannelId` set. `Path` column is SHA256 hash (uppercase) of the image file. Files stored at `/config/cache/artwork/logos/{Path[0:2]}/{Path}`. + +**ChannelWatermark**: Global watermark config (Id=1, "Channel Bug"). All channels share this via `Channel.WatermarkId=1`. This is the burn-in watermark overlay, NOT the channel logo. + +**ProgramScheduleItem subtype tables**: `ProgramScheduleOneItem`, `ProgramScheduleDurationItem`, `ProgramScheduleFloodItem`, `ProgramScheduleMultipleItem`. MUST insert into the matching subtype table (usually `ProgramScheduleOneItem`). + ### Channel Setup Workflow (DB) **Show-specific channel** (single TV show, shuffled): @@ -136,26 +258,65 @@ VALUES (, 0, 0, '', 1, 0, 1); INSERT INTO ProgramScheduleItem (Id, CollectionType, FillWithGroupMode, GuideMode, "Index", MarathonGroupBy, MarathonShuffleGroups, MarathonShuffleItems, MediaItemId, PlaybackOrder, ProgramScheduleId) VALUES (, 1, 0, 0, 0, 0, 0, 0, , 3, ); INSERT INTO ProgramScheduleOneItem (Id) VALUES (); --- 3. Channel +-- 3. Channel (StreamingMode=4 = HLS Segmenter — ETV default; works fine through Dispatcharr. See Gotchas → Streaming mode.) INSERT INTO Channel (Id, Categories, FFmpegProfileId, FallbackFillerId, "Group", IdleBehavior, IsEnabled, MirrorSourceChannelId, MusicVideoCreditsMode, MusicVideoCreditsTemplate, Name, Number, PlayoutMode, PlayoutOffset, PlayoutSource, PreferredAudioLanguageCode, PreferredAudioTitle, PreferredSubtitleLanguageCode, ShowInEpg, SongVideoMode, SortNumber, StreamSelector, StreamSelectorMode, StreamingMode, SubtitleMode, TranscodeMode, UniqueId, WatermarkId) VALUES (, '', 1, NULL, '', 0, 1, NULL, 0, NULL, '', '', 0, NULL, 0, NULL, NULL, 'eng', 1, 0, .0, NULL, 0, 4, 2, 0, lower(hex(randomblob(4)))||'-'||lower(hex(randomblob(2)))||'-4'||substr(lower(hex(randomblob(2))),2)||'-'||lower(hex(randomblob(2)))||'-'||lower(hex(randomblob(6))), 1); --- 4. Playout +-- 4. Playout (ScheduleKind=1 required — 0 is broken) INSERT INTO Playout (Id, ChannelId, ProgramScheduleId, ScheduleKind, Seed) -VALUES (, , , 0, abs(random()) % 1000000); +VALUES (, , , 1, abs(random()) % 1000000); ``` -**Collection-based channel** (multiple shows, shuffled): +**Collection-based channel** (multiple movies/videos, shuffled): ```sql --- 1. Collection + items (MediaItemId = Show.Id) +-- 1. Collection + items (MediaItemId = Movie.Id from MediaVersion→MediaFile lookup) INSERT INTO Collection (Id, Name, UseCustomPlaybackOrder) VALUES (, '', 0); -INSERT INTO CollectionItem (CollectionId, MediaItemId) VALUES (, ); --- 2. Schedule (same as above but CollectionType=0, CollectionId set instead of MediaItemId) -INSERT INTO ProgramScheduleItem (Id, CollectionId, CollectionType, ..., PlaybackOrder, ProgramScheduleId) -VALUES (, , 0, ..., 3, ); --- 3-4. Channel + Playout same as show-specific +INSERT INTO CollectionItem (CollectionId, MediaItemId) VALUES (, ); +-- To bulk-add items from a folder: +INSERT INTO CollectionItem (CollectionId, MediaItemId) +SELECT , mv.MovieId FROM MediaFile mf +JOIN MediaVersion mv ON mf.MediaVersionId = mv.Id +WHERE mf.Path LIKE '/data/music//%' +AND mv.MovieId NOT IN (SELECT MediaItemId FROM CollectionItem WHERE CollectionId = ); + +-- 2. Schedule + item (CollectionType=0, PlaybackOrder=3) +INSERT INTO ProgramSchedule (Id, FixedStartTimeBehavior, KeepMultiPartEpisodesTogether, Name, RandomStartPoint, ShuffleScheduleItems, TreatCollectionsAsShows) +VALUES (, 0, 0, '', 1, 1, 0); +INSERT INTO ProgramScheduleItem (Id, CollectionId, CollectionType, FillWithGroupMode, GuideMode, "Index", MarathonGroupBy, MarathonShuffleGroups, MarathonShuffleItems, PlaybackOrder, ProgramScheduleId) +VALUES (, , 0, 0, 0, 0, 0, 0, 0, 3, ); +INSERT INTO ProgramScheduleOneItem (Id) VALUES (); +-- 3-4. Channel + Playout same as show-specific (ScheduleKind=1) ``` -After creating: `POST /api/channels/{number}/playout/reset` +After creating: `POST /api/v1/channels/{id}/playout/reset` + +### Channel Logo Workflow + +Logos are stored as `Artwork` rows (ArtworkKind=2) with images in the cache directory. + +```bash +# 1. Create logo PNG (transparent background, white text) +magick -size 512x180 xc:transparent -font "DejaVu-Sans-Bold" -pointsize 48 \ + -fill white -stroke black -strokewidth 2 -gravity center \ + -annotate +0+0 "CHANNEL NAME" PNG32:/tmp/logo.png + +# 2. Calculate SHA256 and place in ErsatzTV cache +HASH=$(sha256sum /tmp/logo.png | cut -d' ' -f1 | tr 'a-f' 'A-F') +LOGO_DIR=~/downloadswarm/ersatztv/cache/artwork/logos +sudo mkdir -p "$LOGO_DIR/${HASH:0:2}" +sudo cp /tmp/logo.png "$LOGO_DIR/${HASH:0:2}/$HASH" + +# 3. Insert Artwork row (stop container first for writes) +docker stop ersatztv +sudo sqlite3 ~/downloadswarm/ersatztv/ersatztv.sqlite3 " +INSERT INTO Artwork (ArtworkKind, ChannelId, DateAdded, DateUpdated, Path) +VALUES (2, , datetime('now'), datetime('now'), '$HASH'); +" +docker start ersatztv + +# 4. After ETV restarts, push logos to Jellyfin (see docs/Docker/ErsatzTV.md for fix_logos.py) +``` + +**Important**: Channel DB Id (from Channel table) is NOT the channel number. E.g., channel #407 might have DB Id 43. ## Volume Mounts (matches Jellyfin) @@ -170,46 +331,99 @@ After creating: `POST /api/channels/{number}/playout/reset` ## FFmpeg & Hardware -- QSV (Intel Quick Sync) hardware acceleration +- **VAAPI on Intel (iHD)** hardware acceleration — ErsatzTV runs on **jazz** (i7-10700K, Intel iGPU) since #633. The single `FFmpegProfile` row (`Id = 1`, referenced by all 43 channels) has `HardwareAcceleration = 3` (Vaapi), `VaapiDevice = /dev/dri/renderD128`, `VaapiDriver = 0` (auto → iHD), `VaapiDisplay = drm`. +- **Do NOT set QSV (1) here, despite the Intel hardware.** It was tried on 2026-07-20 and **regressed**: QSV's *decoder* is far stricter than VAAPI about malformed NAL units and failed **3 of 6 channel cold-starts** (`Error splitting the input into NAL units` → `dec:h264_qsv Error while opening decoder: Invalid data found`). ErsatzTV has a **single** `HardwareAcceleration` column governing *both* decode and encode, so it cannot express Jellyfin's working combination of VAAPI-decode + QSV-encode. Tracked upstream: timothy/ersatztv#498. Jellyfin **does** use QSV successfully, because it splits the two. +- Fallback if VAAPI also misbehaves (see #631, VAAPI `hwupload -22` on 10-bit): `HardwareAcceleration = 0` (software). jazz has 16 threads at load ~2, so it is affordable and maximally tolerant of imperfect sources. - Resolution: 1920x1080, H264, AAC stereo -- Device: `/dev/dri` passed through -- HardwareAccelerationKind: 0=None, 1=Qsv, 2=Nvenc, 3=Vaapi, 4=VideoToolbox, 5=Amf +- Device: `/dev/dri` passed through (`renderD128`) +- HardwareAccelerationKind: 0=None, 1=Qsv, 2=Nvenc, 3=Vaapi, 4=VideoToolbox, 5=Amf — **use 3 (Vaapi)** on jazz (not Qsv — see above) +- jazz's iGPU is shared with Jellyfin only (Frigate stayed on bumblebee); render GID is 992 on both hosts, so `group_add: '992'` carried over unchanged ## Jellyfin Integration - Secrets: `/config/jellyfin-secrets.json` (`{"Address":"http://jellyfin:8096","ApiKey":"978033be716d46678a5d3c54ae0e0ff9"}`) -- Libraries: Movies(10), TV Shows(11), Music Videos(8), Standup(9) +- **ErsatzTV** library ids (verified 2026-07-26): Jellyfin source → Movies **10**, TV Shows **11**, + Music Videos **16**; Local source → Standup **14**. These are *ErsatzTV* ids and are **not** the same + as Jellyfin's own library ids — don't reuse one for the other. Re-derive with + `GET /api/v1/media-sources` rather than trusting this list. +- Scan a library with `POST /api/v1/libraries/{id}/scan` (there is no `PUT …/sync`). - `JellyfinLibrary.ShouldSyncItems` must be `1` for scans to work ## Gotchas -- DB owned by root — always use `sudo sqlite3` -- **The api.key file is root-owned too, and an unsudo'd read fails SILENTLY.** `cat` returns nothing, - the header goes out empty, and the 401 body parses as a dict — so a naive script reports "0 - channels" rather than an auth error. If a query returns a suspiciously empty result, check auth - before believing it. (Cost a wrong reading on 2026-07-21.) -- WAL mode: reads OK while running, stop container for writes -- ~~No REST API for channel/collection/schedule CRUD~~ — **false since the fork's `/api/v1`**; use the - API, not DB scripting, wherever an endpoint exists -- **A container's OCI labels lie about what is running** — they are inherited from the linuxserver - base image (they claimed `2026-06-27` on an image built minutes earlier). To prove which build is - live, compare `docker inspect --format '{{.Image}}'` to the registry's `Docker-Content-Digest` - for that tag +### Post-move to jazz (#633) +- **Any rsync from bumblebee's `~/downloadswarm/ersatztv/` re-reverts the QSV setting** — it overwrites `ersatztv.sqlite3`, restoring bumblebee's AMD-era values. Apply config changes **after** the final sync, then re-verify. (Same trap for Jellyfin's `encoding.xml` and `livetv.xml`.) +- **The config dir has root-owned files** (`ersatztv.sqlite3`, `cache/channel-guide/*`), so rsync needs sudo at **both** ends: + ```bash + sudo rsync -a --delete -e "ssh -i /home/timothy/.ssh/id_rsa" --rsync-path="sudo rsync" \ + timothy@192.168.1.99:/home/timothy/downloadswarm/ersatztv/ /home/timothy/downloadswarm/ersatztv/ + ``` +- **Dispatcharr caches ErsatzTV's XMLTV.** Repointing its DB rows is not enough — it keeps serving a stale EPG full of dead `ersatztv:8409` artwork URLs (breaks Kodi artwork). Force a refresh (EPG source 9): + ```bash + ssh timothy@192.168.1.99 'docker exec dispatcharr python manage.py shell -c \ + "from apps.epg.tasks import refresh_epg_data; refresh_epg_data(9)"' + ``` +- **`/api/health` returns 401** (needs an API key). The Telegraf probe has no `response_string_match`, so ErsatzTV reads as **unhealthy in Grafana** — a false alarm, and **pre-existing**, not caused by the move. The container healthcheck uses the unauthenticated internal `/health` and is unaffected. +- **A Komodo deploy alone may not apply bind-mounted config changes** — containers kept serving the pre-checkout inode despite a current `deployed_hash`. `docker restart` explicitly and verify inside the container. + +### Common Mistakes (check every time) +- **Playout not building**: Three things must all be correct: (1) `ProgramScheduleOneItem` row exists for the schedule item, (2) `PlaybackOrder=3` (Shuffle), (3) `ScheduleKind=1` on Playout. Missing any one results in 0 playout items — this is the most common issue. +- **Collection queries fail**: `CollectionItem` has no `Id` column — use `rowid` for counting. Content lookup goes through `MediaVersion.MovieId` → `MediaFile.Path` (not a generic MediaItemId join). +- **Channel logos forgotten**: After creating a channel, add an Artwork row (ArtworkKind=2) + logo file, then run `fix_logos.py` to push to Jellyfin. Without this, the channel shows no logo in the EPG. +- **Playout reset required**: After any schedule/collection change, run `POST /api/v1/channels/{id}/playout/reset`. Wait 5-10s for the playout to build before verifying item count. + +### Streaming mode + the Dispatcharr reliability fix — #500 +Consumers reach ETV **only through Dispatcharr** (`ErsatzTV → Dispatcharr → Jellyfin/Kodi`), which proxies every channel with `ffmpeg -i -c copy -f mpegts`. **Both HLS Segmenter (`StreamingMode=4`) and MPEG-TS (`StreamingMode=1`, `ts-legacy`) work** — Dispatcharr remuxes either to mpegts, and ETV's HLS segments are themselves mpegts with in-band SPS/PPS, so `-c copy` carries codec init either way. We run **42 channels on HLS** (ETV default; ts-legacy showed more visual glitching) + Jungle(407) on TS. +- **What the ~6 s cold-start actually was — ersatztv#350 (fixed 2026-07-20).** `-readrate 1.05` paces input at wall clock so the channel behaves like live TV, and it applies from the **first** read; with 4 s HLS segments a throttled session could not serve the playlist sooner than ~3.8 s. Only `workAheadSegmenterLimit` sessions (prod: **1**, see `/api/v1/settings/ffmpeg`) start unthrottled, so **concurrent tune-ins are the slow ones** — measured 866 ms for the slot winner vs 3845/6357 ms for two simultaneous tunes. Subtitle burn-in, source GOP length and NFS were investigated and **ruled out** (accurate-seek costs 30–100 ms). Fixed with `-readrate_initial_burst` (5369 → 648 ms at the ffmpeg level); end-to-end verification tracked in `timothy/ersatztv#519`, so until that lands treat it as expected rather than confirmed. Diagnose with `docker logs ersatztv | grep "HLS cold-start"` — the line splits `setup / startup (prep + ffmpegInit + firstGop) / fill`. +- **The reliability bug was NOT the streaming mode — it was a Dispatcharr teardown race.** Any tune spins up a fresh ETV transcode (historically ~6 s cold-start, same for HLS and TS — see above). With Dispatcharr's default `channel_shutdown_delay=0`, the instant a client's open-timeout drops it the channel tears down, and the retry hits a 503 → ETV cold-starts again → death-spiral (Dispatcharr#503/#851). **Fix lives in Dispatcharr: `channel_shutdown_delay=15`** (see dispatcharr skill → Gotchas). Verified by reverting all channels to HLS while keeping the delay → reliable starts + correct audio sync (2026-06-28). +- **Corrected theory:** the first #500 pass blamed HLS for `Invalid avcC`/codec-init and switched everything to MPEG-TS. **That was wrong** — `-c copy` of mpegts HLS segments carries SPS/PPS fine; the `avcC` log line was transient/info-level and appeared on TS too. The isolation test (HLS + the delay) proved `channel_shutdown_delay` was the actual fix, and we reverted to HLS for better quality. +- Flip a channel's mode live (no restart — ETV reads it per M3U request): `UPDATE Channel SET StreamingMode=4 WHERE …;` then sync Dispatcharr's stored stream URL for that channel (`.m3u8?mode=segmenter` ↔ `.ts?mode=ts-legacy`). +- **Open / in progress:** through Dispatcharr's `-c copy` proxy, HLS showed a one-time skip-back shortly after start (Dispatcharr's `new_client_behind_seconds` repositioning the client behind live — set to 0 to test) and TS showed more glitching. Artifact tuning continues — see the dispatcharr skill and the #500 follow-up. + +### Measuring what is actually deployed / what actually happened +- **The api.key file is root-owned, and an unsudo'd read fails SILENTLY.** `cat` returns nothing, the + header goes out empty, and the 401 body parses as a dict — so a naive script reports "0 channels" + rather than an auth error. If a query returns a suspiciously empty result, **check auth before + believing it.** (Cost a wrong reading on 2026-07-21.) +- **A container's OCI labels lie about what is running** — they are inherited from the base image (they + claimed `2026-06-27` on an image built minutes earlier). Tags and `StartedAt` lie too. To prove which + build is live, compare `docker inspect --format '{{.Image}}'` (the manifest digest on jazz) to the + registry's `Docker-Content-Digest` header for that tag — not `.config.digest`. (ersatztv#350) - **Container log lines carry a LOCAL-time bracket (`[18:48:13 DBG]`) while `docker logs -t` emits - UTC**, so `--since` windows silently mis-slice. For before/after measurements capture by line - offset instead (`wc -l` before, `tail -n +N` after) + UTC**, so `--since` windows silently mis-slice. For before/after measurements capture by **line + offset** instead (`wc -l` before, `tail -n +N` after). + +### DB & Architecture +- DB owned by root — always use `sudo sqlite3` +- WAL mode: reads OK while running, stop container for writes +- Full REST CRUD is available under `/api/v1`; prefer it over direct DB writes - Secrets file uses PascalCase JSON (`Address`, `ApiKey`) - Scanner is separate binary (`ErsatzTV.Scanner`) — check with `docker top ersatztv | grep Scanner` -- EF TPT inheritance: `ProgramScheduleItem` has subtype tables (`ProgramScheduleOneItem`, etc.) — MUST insert into subtype table -- External URL logos work for M3U but NOT for watermark burn-in (code checks `File.Exists()`) -- `/api/health` predates the Blazor removal; verify the API with an authenticated `/api/v1/channels` instead -- PlaybackOrder enum: 3=Shuffle, 6=SeasonEpisode (use 3 for all channels) -- CollectionType enum: 0=Collection, 1=Show (direct show reference via MediaItemId) +- EF TPT inheritance: `ProgramScheduleItem` has subtype tables (`ProgramScheduleOneItem`, etc.) — inserting into the subtype table is required or EF Core won't recognize the row +- `/health` is the unauthenticated container-health gate; use an authenticated `/api/v1` read to verify the API + +### Enums +- PlaybackOrder: 2=Chronological (broken for collections — produces empty playouts), 3=Shuffle, 6=SeasonEpisode — use 3 for reliable results +- CollectionType: 0=Collection, 1=Show (direct show reference via MediaItemId) - SubtitleMode: 0=None, 2=Burn-in. Set to 2 with PreferredSubtitleLanguageCode='eng' for non-music channels - MediaItem.State: 0=Normal, 1=FileNotFound — clean up state=1 items by deleting cascading deps -- ProgramSchedule required NOT NULL columns: FixedStartTimeBehavior, KeepMultiPartEpisodesTogether, RandomStartPoint, ShuffleScheduleItems, TreatCollectionsAsShows -- Channel required NOT NULL columns: SongVideoMode (set 0), plus all standard columns (see Channel table schema) -- After schedule changes, rebuild playout: `POST /api/channels/{number}/playout/reset` -- Playout `ScheduleKind` must be `1` (not `0`/None) — `0` causes "Cannot build playout type None" error -- M3U `tvg-logo` URLs hardcode `http://localhost:8409` — Jellyfin can't fetch these from inside its container. Fix by downloading logos from ETV and base64-uploading to Jellyfin (see `docs/Docker/ErsatzTV.md` for script). Tracked in issue #171 -- Repo archived Feb 2026, v26.3.0 is final stable version. Maintainer welcomes forks +- ScheduleKind: 0=None (broken — playout never builds), 1=Fixed — use 1 +- StreamingMode: 4=HLS Segmenter (`…/channel/N.m3u8?mode=segmenter`) — **ETV default, what we run** (42 channels); 1=MPEG-TS (`…/channel/N.ts?mode=ts-legacy`, Jungle/407 only). Both work through Dispatcharr (it remuxes either to mpegts via `-c copy`). Read live per M3U request → flipping needs **no container restart**. The #500 reliability fix was a Dispatcharr setting (`channel_shutdown_delay`), NOT the mode — see "Streaming mode" gotcha. + +### Channel Creation Checklist +1. Collection + CollectionItems (for collection-based) OR MediaItemId (for show-specific) +2. ProgramSchedule (all NOT NULL columns: FixedStartTimeBehavior, KeepMultiPartEpisodesTogether, RandomStartPoint, ShuffleScheduleItems, TreatCollectionsAsShows) +3. ProgramScheduleItem (PlaybackOrder=3) + ProgramScheduleOneItem subtype row +4. Channel (SongVideoMode=0, WatermarkId=1, all required columns) +5. Playout (ScheduleKind=1) +6. Artwork (ArtworkKind=2) + logo file in cache +7. `POST /api/v1/channels/{id}/playout/reset` +8. Run `fix_logos.py` to push logo to Jellyfin + +### Logo System +- External URL logos work for M3U but NOT for watermark burn-in (code checks `File.Exists()`) +- M3U `tvg-logo` URLs hardcode `http://localhost:8409` — Jellyfin can't fetch these from inside its container. Fix by downloading logos from ETV and base64-uploading to Jellyfin (see `docs/Docker/ErsatzTV.md` for script) +- `logo_XX.png` files in the logos root dir are HTML garbage (broken downloads), not actual logos — ignore them + +### Other +- Upstream was archived in Feb 2026; `timothy/ersatztv` is the maintained fork and release source diff --git a/.claude/skills/jellyfin b/.claude/skills/jellyfin new file mode 120000 index 000000000..b5e798640 --- /dev/null +++ b/.claude/skills/jellyfin @@ -0,0 +1 @@ +../../../server-management/.claude/skills/jellyfin \ No newline at end of file diff --git a/.claude/skills/jellyfin/SKILL.md b/.claude/skills/jellyfin/SKILL.md deleted file mode 100644 index 16e747920..000000000 --- a/.claude/skills/jellyfin/SKILL.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -name: jellyfin -description: Jellyfin media server management — API for libraries, items, streaming, users. Use when managing media library or checking Jellyfin status. ---- - -# Jellyfin Management - -Container: `jellyfin` | Port: `8096` | IP: `172.16.238.20` (may change on restart) -API Token: `978033be716d46678a5d3c54ae0e0ff9` -Web UI: `https://jellyfin.tblindustries.be` (NO Authelia — native login, password: `coup1802`) -Config: `/home/timothy/downloadswarm/jellyfin/` on jazz - -## Access Pattern - -```bash -docker exec jellyfin curl -s 'http://localhost:8096/ENDPOINT' \ - -H 'X-Emby-Token: 978033be716d46678a5d3c54ae0e0ff9' -``` - -## Volume Mounts - -| Host Path | Container Path | Content | -|-----------|---------------|---------| -| `/mnt/teramind/episodes` | `/data/tvshows` | TV shows | -| `/mnt/episodes` | `/data/episodes` | More episodes | -| `/mnt/media/movies` | `/data/movies` | Movies | -| `/mnt/media/standup` | `/data/standup` | Standup | -| `/mnt/media/music_videos` | `/data/music` | Music videos | -| `/mnt/media/audio/music` | `/data/audio` | Music audio (ro) | - -## API Endpoints - -### System -``` -GET /System/Info # Server info, version -GET /System/Info/Public # Public info (no auth needed) -POST /System/Restart # Restart server -``` - -### Items (Search & Browse) -```bash -# Search items -GET /Items?includeItemTypes=Movie,Episode,Series&recursive=true&searchTerm=QUERY&fields=Path&limit=20 - -# Get item details -GET /Items?ids=ITEM_ID&fields=Path,MediaStreams,Overview - -# Get all movies -GET /Items?includeItemTypes=Movie&recursive=true&fields=Path&limit=1000 - -# Get series -GET /Items?includeItemTypes=Series&recursive=true&fields=Path - -# Get episodes for a series -GET /Shows/{seriesId}/Episodes?fields=Path,MediaStreams - -# Filter by library (parentId) -GET /Items?parentId=LIBRARY_ID&recursive=true&fields=Path -``` - -### Libraries -``` -GET /Library/VirtualFolders # List all libraries -POST /Library/Refresh # Trigger full library scan -POST /Items/{id}/Refresh # Refresh single item metadata -``` - -### Streaming -```bash -# Test stream URL -GET /Videos/{itemId}/stream?static=true - -# Get playback info -GET /Items/{itemId}/PlaybackInfo -``` - -### Users -``` -GET /Users # List users -GET /Users/{userId} # User details -``` - -## Library IDs - -Check with: `curl -s -H "X-Emby-Token: TOKEN" http://localhost:8096/Library/VirtualFolders` - -## Live TV - -- **ErsatzTV** (channels <1000): M3U `http://ersatztv:8409/iptv/channels.m3u`, XMLTV `http://ersatztv:8409/iptv/xmltv.xml` -- **Dispatcharr** (channels 1000+): IPTV stream manager on port 9191, separate tuner -- Configured in Jellyfin Admin > Live TV -- Guide refresh task ID: `bea9b218c97bbf98c5dc1303bdb9a0ca` — trigger via `POST /ScheduledTasks/Running/{id}` -- **Logo fix after guide refresh**: ErsatzTV logos break (aspect ratio=0) because M3U uses `localhost:8409`. Fix script in `docs/Docker/ErsatzTV.md` downloads from ETV and base64-uploads to `POST /Items/{id}/Images/Primary` (body = base64, Content-Type = image/png) -- **Image upload format**: Jellyfin expects base64-encoded body (NOT raw binary) for `POST /Items/{id}/Images/Primary` - -## Gotchas - -- **Passwords**: `coup1802` (NOT `ded89Lm4`) — Jellyfin has native auth, no Authelia -- Auth header is `X-Emby-Token` (Jellyfin is an Emby fork) -- **Music videos are typed `MusicVideo`, NOT `Movie`** (corrected 2026-07-21, ersatztv#177). The old - "typed as Movie" note described a deliberate DB reclassification workaround that existed only because - ErsatzTV could not consume `MusicVideo` items — ersatztv#42 shipped that sync, so the workaround's - premise is gone. Verified live: the `Music Videos` library (`/data/music`, collection type - `musicvideos`) holds 1437 items typed `MusicVideo` and **zero** typed `Movie`. Query with - `includeItemTypes=MusicVideo`. (Reclassification to `Movie` may still apply to concert/standup content - in the `movies`/`mixed` libraries — that is a different set; see the server-management jellyfin skill.) -- **`Album` is not an `ItemFields` value.** It is a plain `BaseItemDto` property serialized whenever set, - so it comes back regardless of the `fields=` query param — do NOT add it to `fields` (verified: 111 of - 1437 music videos returned `Album` with `fields=Path` alone). Contrast `Genres`/`People`/`Chapters`, - which ARE `ItemFields` and must be requested. Check the enum before extending `fields`. -- **`IndexNumber` is the track number; `ParentIndexNumber` is the disc/season axis.** Frequency misleads - here — on the live music video library `ParentIndexNumber` is populated on 66 items vs 4 for - `IndexNumber`, but where both exist `ParentIndexNumber` is `1` while `IndexNumber` holds the real - ordinal, and where only `ParentIndexNumber` exists it is a collection grouping tracking the album - (`Glastonbury: 2022` -> 230). `AlbumId` is always null on these items. -- Music library at `/data/music` maps to `/mnt/media/music_videos` on host (not actual music) -- Items return 404 on stream if source volume is unmounted -- Jellyfin preserves item IDs across restarts unless files are renamed -- Full library scan can take a long time — prefer targeted `/Items/{id}/Refresh` -- `ffprobe` available in container for checking media streams: `docker exec jellyfin ffprobe -v quiet -print_format json -show_streams FILE` diff --git a/CLAUDE.md b/CLAUDE.md index e718b9c27..f3ab6f648 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -73,13 +73,13 @@ when finishing a task that closes an issue. ## Project Boundaries -**ersatztv OWNS**: ErsatzTV fork code (C#/.NET), channel/collection/schedule management, M3U/XMLTV generation, the ErsatzTV skill in server-management. +**ersatztv OWNS**: ErsatzTV fork code (C#/.NET), channel/collection/schedule management, M3U/XMLTV generation, and the **`ersatztv` skill** — whose canonical copy is `.claude/skills/ersatztv/SKILL.md` **here**; `~/server-management/.claude/skills/ersatztv` is a symlink to it (ersatztv#617). Edit it in this repo; never fork a second copy. **ersatztv does NOT own**: - Docker compose configs → server-management (`~/downloadswarm/stacks/ersatztv/`) - NFS mounts, Ansible, DNS, networking → server-management - Content sourcing (yt-dlp downloads, Sonarr/Radarr libraries) → media-management (planned) -- Jellyfin skill → server-management (symlinked) +- Jellyfin skill → server-management. `.claude/skills/jellyfin` here is a **relative symlink** to `~/server-management/.claude/skills/jellyfin` (ersatztv#617 — it had silently become a stale divergent copy). It therefore resolves only in a checkout at `~/ersatztv`, not inside a git worktree; that is inherent to the cross-repo symlink pattern server-management already uses (`beets`, `radarr`, `sonarr`, …). **For infrastructure changes** (Docker, NFS, ports, Authelia): open an issue in `timothy/server-management`. -- 2.47.3 From e7ae919959d4bc3dce1fd8ec9b73d4012db72088 Mon Sep 17 00:00:00 2001 From: Timothy Date: Sun, 26 Jul 2026 00:42:22 +0200 Subject: [PATCH 2/3] fix(617): correct two stale logo claims carried in from both copies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both copies still described pre-fix behavior: - "External URL logos work for M3U but NOT for watermark burn-in (code checks File.Exists())" — the WatermarkSelector File.Exists gate was removed in #502 (ffmpeg.external-logo-graphics-engine); logos are cached at save time (graphics.channel-logo-caching). - "M3U tvg-logo URLs hardcode http://localhost:8409" — #340 added the optional iptv.base_url advertised base URL (iptv.base-url). --- .claude/skills/ersatztv/SKILL.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/.claude/skills/ersatztv/SKILL.md b/.claude/skills/ersatztv/SKILL.md index 7b4627449..c0bb5361e 100644 --- a/.claude/skills/ersatztv/SKILL.md +++ b/.claude/skills/ersatztv/SKILL.md @@ -421,8 +421,18 @@ Consumers reach ETV **only through Dispatcharr** (`ErsatzTV → Dispatcharr → 8. Run `fix_logos.py` to push logo to Jellyfin ### Logo System -- External URL logos work for M3U but NOT for watermark burn-in (code checks `File.Exists()`) -- M3U `tvg-logo` URLs hardcode `http://localhost:8409` — Jellyfin can't fetch these from inside its container. Fix by downloading logos from ETV and base64-uploading to Jellyfin (see `docs/Docker/ErsatzTV.md` for script) +- **External-URL logos now work for the on-screen bug too** — fixed in ersatztv#502 (2026-07-20, + `ffmpeg.external-logo-graphics-engine`). The old claim that they work for M3U but not watermark + burn-in described a `WatermarkSelector` `File.Exists()` gate that is gone; an external logo is + fetched, decode-budget-validated and stored in the image cache at **save** time + (`graphics.channel-logo-caching`), so the render path never fetches over HTTP and a bad URL fails + the save with a 422. +- **M3U/XMLTV absolute URLs are no longer stuck on the request-derived host.** They used to bake in + whatever host fetched the feed (the historical `http://localhost:8409` symptom, Gitea #1/#171), + which Jellyfin can't resolve from inside its container. Set the optional advertised base URL — + `GET`/`PUT /api/v1/settings/iptv` (`iptv.base_url`, ersatztv#340, `iptv.base-url`) — to pin them to + a fixed public origin; unset falls back byte-identical to the old behavior. The base64-upload + workaround in `docs/Docker/ErsatzTV.md` is only needed if that setting is left unset. - `logo_XX.png` files in the logos root dir are HTML garbage (broken downloads), not actual logos — ignore them ### Other -- 2.47.3 From 01fb07ac9d5e484eb27c5fc7be6e9e099fb91c77 Mon Sep 17 00:00:00 2001 From: Timothy Date: Sun, 26 Jul 2026 00:58:42 +0200 Subject: [PATCH 3/3] fix(617): quote the description scalar so the embedded colon stays valid YAML MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The reconciled description ends with 'IMPORTANT: the fork has a full versioned REST API...'. An unquoted YAML scalar containing ': ' parses as a mapping, so the frontmatter failed to load ('mapping values are not allowed here') — which would have silently broken skill discovery, the one thing the description exists to drive. Quoting the value fixes it. Caught by parsing the frontmatter with yaml.safe_load rather than eyeballing it; the same latent defect exists in server-management's canonical jellyfin SKILL.md and is fixed there separately. --- .claude/skills/ersatztv/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/skills/ersatztv/SKILL.md b/.claude/skills/ersatztv/SKILL.md index c0bb5361e..6c5f8f7c2 100644 --- a/.claude/skills/ersatztv/SKILL.md +++ b/.claude/skills/ersatztv/SKILL.md @@ -1,6 +1,6 @@ --- name: ersatztv -description: ErsatzTV custom IPTV channel management — REST API, SQLite DB, Jellyfin integration, FFmpeg profiles. Use when creating or modifying IPTV channels, managing collections and schedules, building playouts, adding channel logos, scanning media libraries, troubleshooting channel issues, or resetting playouts. Also use for any questions about the ErsatzTV database schema (Channel, Collection, ProgramSchedule, Playout tables), M3U/XMLTV feeds, custom TV channel setup, or the channel creation checklist. IMPORTANT: the fork has a full versioned REST API at /api/v1 including write paths — prefer it over SQLite scripting, which is a recovery fallback only. +description: "ErsatzTV custom IPTV channel management — REST API, SQLite DB, Jellyfin integration, FFmpeg profiles. Use when creating or modifying IPTV channels, managing collections and schedules, building playouts, adding channel logos, scanning media libraries, troubleshooting channel issues, or resetting playouts. Also use for any questions about the ErsatzTV database schema (Channel, Collection, ProgramSchedule, Playout tables), M3U/XMLTV feeds, custom TV channel setup, or the channel creation checklist. IMPORTANT: the fork has a full versioned REST API at /api/v1 including write paths — prefer it over SQLite scripting, which is a recovery fallback only." --- > **Canonical copy: `~/ersatztv/.claude/skills/ersatztv/SKILL.md`** (ersatztv owns this skill per that -- 2.47.3