Compare commits

..
5 Commits
Author SHA1 Message Date
timothy 65d88b5167 test(#289): pin BoundedLineReader cap/CRLF boundaries + document per-segment path assumption
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 4m29s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m42s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Non-blocking polish from the fix-commit re-review (verdict MERGEABLE):
- BuildPath: comment the assumption that each {param} is its own path segment
  (revalidate the whole path if a template ever concatenates adjacent params).
- Two additive BoundedLineReader tests: exactly-at-cap line returned intact
  (inclusive max), and \r\n carriage-return stripping. No logic change.

36 tests (was 34).

Refs #289
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 01:24:35 +02:00
timothy 4f68805d9a security(#289): review fixes — body-read timeout, transport-error response, bounded stdin, env clamps
Folds in findings from the independent reviews of the initial hardening diff
(a cold adversarial pass + a Codex pass — complementary catches).

Fork (HIGH/MED):
- Body-read timeout regression: ResponseHeadersRead moved the body read outside
  HttpClient.Timeout and it used CancellationToken.None, so a slow-drip upstream
  hung the single-threaded session. Now a per-request linked CTS (options
  .EffectiveRequestTimeout) covers headers + body; HttpClient.Timeout set to
  Infinite so one timer owns it. Verified live against a black-hole upstream:
  1s timeout → -32603 in ~1s, no hang.
- Transport/timeout exceptions escaped HandleAsync's catch filter → no response
  for the id → client hangs. Added a broad final catch → -32603 when hasId.

Codex (env/input robustness):
- ERSATZTV_REQUEST_TIMEOUT_SECONDS / ERSATZTV_MAX_RESPONSE_BYTES at int.MaxValue
  crashed at startup / overflowed `cap+1` to a negative alloc. ParseInt now
  clamps to [min,max]; the client also hard-ceils the cap (MaxAllowedResponseBytes).
- A ".."/"." path param collapsed the URL onto another route under Uri
  canonicalization — rejected in BuildPath.

Both reviewers (stdin OOM): ReadLineAsync buffered an unbounded line before any
guard. New BoundedLineReader drains+drops oversized lines (memory-bounded),
keeping subsequent lines aligned.

Nits: case-insensitive ParseBool fallback; UTF-8 boundary backoff so a mid-
codepoint truncation doesn't emit U+FFFD; renamed a misleading test.

34 tests (was 26); +8 covering the transport-error path, dot-segment rejection,
cap-overflow fallback, UTF-8 seam, and the bounded reader.

Refs #289 #197
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 01:20:10 +02:00
timothyandClaude Opus 4.8 55fc210385 security(#289): harden MCP server (read-only posture, JSON-DoS, response cap, arg validation)
From the #197 cold review's MCP-consumer pass. Hardens `ErsatzTV.Mcp` (PR #76)
before it can go live against a soon-remote-exposed API.

- HIGH verb-guard: runtime read-only *posture* (ERSATZTV_ALLOW_WRITES, default
  false) enforced in the executor — a wrong catalog entry can't mutate/delete,
  and future write tools (#58) slot in behind the opt-in. Not a hardcoded
  GET-only clamp, so the non-read-only final design stays reachable.
- HIGH JSON-crash DoS: guard JsonDocument.Parse in HandleAsync (-32700, id null),
  handle missing/non-string method (-32600) instead of throwing, and wrap the
  Program.Main read loop so one bad stdin line can never kill the session.
- MED unbounded response / LOW no-timeout: cap the buffered body
  (ERSATZTV_MAX_RESPONSE_BYTES, truncation marker) + explicit HttpClient.Timeout.
- MED args unvalidated: ToolArgumentValidator checks caller args against each
  tool's InputSchema (required present, no unknown args, basic types) before a
  request is built.
- MED prompt injection: documented untrusted-data posture in docs/mcp.md.
- LOW base-URL prefix: preserve a reverse-proxy path prefix in the URL join.

Also documents that ERSATZTV_API_KEY is now effectively required (Bundle A gates
all /api reads behind X-Api-Key). 14 new tests (26 total); live stdin smoke
confirms malformed/no-method/non-object lines no longer crash the loop.

Refs #289 #197 #58

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 01:08:07 +02:00
timothy d1c04030af chore: retrigger CI (MySQL service port collision with concurrent run)
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 4m0s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m29s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
2026-07-07 11:58:29 +02:00
timothy 945d108334 feat(mcp): add read-only API server foundation refs #58
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 4m13s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Failing after 0s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
2026-07-07 11:44:44 +02:00
1373 changed files with 47475 additions and 230461 deletions
-54
View File
@@ -1,54 +0,0 @@
#!/usr/bin/env bash
# ersatztv#303 H9 — docs/decisions.md is append-only. This blocks a commit / PR that DELETES or
# MODIFIES an existing line of that file; pure INSERTIONS anywhere are always allowed (adding a new
# entry inserts a TOC line near the top AND appends a block at the bottom — both are insertions, so
# numstat reports 0 deleted lines). A genuine factual fix to a past entry is the one legitimate edit:
# put the literal token [decisions-edit] in the commit message to override.
#
# Fail-open: any tooling trouble (unknown mode, non-numeric numstat, missing refs) -> allow. The point
# is to catch the accidental rewrite-history case, never to wedge a legitimate commit.
#
# Assumes decisions.md ends with a trailing newline (it does; .editorconfig enforces it). If that final
# newline were ever dropped, git would render the next append as a modify of the last line (deleted=1)
# and this would false-block the append until the author adds [decisions-edit] — cheap and self-correcting.
#
# Modes:
# staged <msgfile> pre-commit/commit-msg — staged diff vs HEAD; trailer read from <msgfile>
# range <base> <head> CI (PR) — merge-base diff base...head; trailer scanned across base..head msgs
set -euo pipefail
FILE="docs/decisions.md"
mode="${1:-}"
case "$mode" in
staged)
deleted=$(git diff --cached --numstat -- "$FILE" 2>/dev/null | awk '{print $2}' | head -1)
msg=$(cat "${2:-/dev/null}" 2>/dev/null || true)
;;
range)
base="${2:-}"; head="${3:-}"
[ -n "$base" ] && [ -n "$head" ] || exit 0 # missing refs -> fail-open
deleted=$(git diff --numstat "$base...$head" -- "$FILE" 2>/dev/null | awk '{print $2}' | head -1)
msg=$(git log --format='%B' "$base..$head" 2>/dev/null || true)
;;
*)
exit 0 # unknown mode -> fail-open
;;
esac
# Empty (no change to the file) or '-' (binary) -> treat as 0 (fail-open / nothing to guard).
deleted="${deleted:-0}"
case "$deleted" in ''|*[!0-9]*) deleted=0 ;; esac
[ "$deleted" -gt 0 ] || exit 0 # pure insertion / no change -> allow
# Explicit override for a documented factual fix.
if printf '%s' "$msg" | grep -qiF '[decisions-edit]'; then
exit 0
fi
{
echo "decisions-guard (ersatztv#303 H9): docs/decisions.md is append-only — this change deletes/modifies ${deleted} existing line(s)."
echo " Append new entries at the bottom (plus a TOC line in the Index); do not rewrite settled entries."
echo " To fix a genuine factual error in a past entry, add the token [decisions-edit] to the commit message."
} >&2
exit 1
-58
View File
@@ -1,58 +0,0 @@
#!/usr/bin/env bash
# design-sync-reminder — single hook, both directions (#388). Keeps the Claude Design project
# (`ChicoryTV Design System`, eb3b6122 / local mirror `design-system/`) in step with the shipped
# SPA. Trigger is PURELY MECHANICAL: "touching the UI" == a file matching UI_RE below. No prompt
# keyword guessing. Wired to two boundaries:
#
# start (PreToolUse / Write|Edit) — the FIRST time this session edits a UI file, remind to PULL
# the current design from Claude Design first.
# finish (Stop) — if the working tree actually changed a UI file, remind to
# MIRROR/PUSH the change back before wrapping up.
#
# UI_RE is the one place the "what counts as UI" fileset is defined: SPA .tsx/.css under web/src
# (test files excluded). Widen it here if the design surface grows.
#
# Fail-open: any parse trouble / non-match → emit nothing, exit 0. Throttled once per session per
# phase so it informs without nagging. DesignSync runs only from the main session (docs/design-sync.md).
# This is a reminder, never a hard gate — `start` only injects context; `finish` is a one-shot Stop nudge.
set -euo pipefail
UI_RE='(^|/)web/src/.*\.(tsx|css)$'
TEST_RE='\.test\.(tsx|ts)$'
phase="${1:-}"
input=$(cat)
me=$(printf '%s' "$input" | jq -r '.session_id // "nosess"' 2>/dev/null || true)
cwd=$(printf '%s' "$input" | jq -r '.cwd // ""' 2>/dev/null || true)
[ -z "$cwd" ] && cwd="$PWD"
marker="${TMPDIR:-/tmp}/ctv-designsync-${phase}-${me}"
case "$phase" in
start)
fp=$(printf '%s' "$input" | jq -r '.tool_input.file_path // ""' 2>/dev/null || true)
[ -z "$fp" ] && exit 0
printf '%s' "$fp" | grep -qE "$TEST_RE" && exit 0 # skip test files
printf '%s' "$fp" | grep -qE "$UI_RE" || exit 0 # not a UI file → nothing
[ -f "$marker" ] && exit 0
: > "$marker" 2>/dev/null || true
read -r -d '' MSG <<'EOF' || true
[design-sync #388] About to edit a ChicoryTV SPA UI file. The `design-system/` prototypes mirror the Claude Design project (eb3b6122). If you're changing how a screen LOOKS, first PULL its current prototype from Claude Design so you start from the live design (docs/design-sync.md, pull = DesignSync list_files/get_file → design-system/, incremental). You'll be reminded to MIRROR the change back when the task finishes. DesignSync runs only from the main session.
EOF
jq -n --arg m "$MSG" '{hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:$m}}'
exit 0
;;
finish)
# Did this turn actually change a UI file? (tracked diff vs HEAD + untracked, minus tests)
changed=$( { git -C "$cwd" diff --name-only HEAD 2>/dev/null; git -C "$cwd" ls-files --others --exclude-standard 2>/dev/null; } | grep -vE "$TEST_RE" | grep -E "$UI_RE" || true )
[ -z "$changed" ] && exit 0
[ -f "$marker" ] && exit 0
: > "$marker" 2>/dev/null || true
n=$(printf '%s\n' "$changed" | sed '/^$/d' | wc -l | tr -d ' ')
reason="[design-sync #388] This task changed ${n} SPA UI file(s) under web/src. Before wrapping up, MIRROR the visual change into the matching design-system/templates/chicorytv-admin/*.jsx prototype and push it to Claude Design (eb3b6122) in this same session, per docs/design-sync.md — so the design system does not drift from prod. If you already synced, or are deliberately deferring the mirror (say why), just note it and stop. DesignSync runs only from the main session. This one-shot reminder won't fire again this session."
jq -n --arg r "$reason" '{decision:"block",reason:$r}'
exit 0
;;
*)
exit 0
;;
esac
@@ -1,37 +0,0 @@
#!/usr/bin/env bash
# PostToolUse / Bash — after a successful `git worktree add`, stamp the new worktree with
# this session's id (.claude-worktree-owner) so pretooluse-worktree-guard.sh (H7) can tell
# a sibling worktree another session created apart from this session's own.
# Fail-safe: any parse trouble → do nothing (the guard stays fail-open without a marker).
set -euo pipefail
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""' 2>/dev/null || true)
cwd=$(printf '%s' "$input" | jq -r '.cwd // ""' 2>/dev/null || true)
me=$(printf '%s' "$input" | jq -r '.session_id // ""' 2>/dev/null || true)
printf '%s' "$cmd" | grep -qE 'git[[:space:]]+worktree[[:space:]]+add\b' || exit 0
[ -z "$me" ] && exit 0
[ -z "$cwd" ] && cwd="$PWD"
# Extract the <path> arg of `git worktree add [flags] <path> [<commit-ish>]`.
# Skip flags; skip the values of the value-taking flags (-b/-B/--reason). Worktree paths
# in this repo have no spaces, so whitespace tokenization is safe.
add_args=$(printf '%s' "$cmd" | sed -E 's/.*git[[:space:]]+worktree[[:space:]]+add[[:space:]]+//')
path=""
skip=0
for tok in $add_args; do
if [ "$skip" = 1 ]; then skip=0; continue; fi
case "$tok" in
-b|-B|--reason) skip=1; continue ;;
--) continue ;;
-*) continue ;;
*) path=$(printf '%s' "$tok" | tr -d '"'"'"''); break ;;
esac
done
[ -z "$path" ] && exit 0
case "$path" in /*) abs="$path" ;; *) abs="$cwd/$path" ;; esac
[ -d "$abs" ] || exit 0
# Don't clobber a marker a different session already planted.
[ -f "$abs/.claude-worktree-owner" ] && exit 0
printf '%s\n' "$me" > "$abs/.claude-worktree-owner" 2>/dev/null || true
exit 0
@@ -1,43 +0,0 @@
#!/usr/bin/env bash
# H13 (ersatztv#416 session) — refuse to push when a file in the pushed diff still has UNCOMMITTED
# changes in the working tree or index. That is the "I left part of my intended change behind"
# failure: a fix edited into the working file but never committed (e.g. after a `git reset --soft`
# that re-staged a stale index) gets pushed WITHOUT the fix — while local tests and a working-tree
# review both see the fix that never shipped. This bit the #416 session: a `--no-renames` review fix
# lived only in the working tree, so the pushed commit, CI, and the first re-review each saw a
# different tree, and a PR went out still carrying the bug the review had "confirmed" fixed.
#
# Scope is deliberately PRECISE to keep false positives near zero: it blocks only when a dirty
# tracked file is ALSO part of this branch's diff vs origin/main. Unrelated uncommitted scratch in a
# file the push doesn't touch is fine; untracked files are ignored.
#
# Fail-OPEN on anything we can't decide (a git pre-push hook has no "ask"): not a git repo, offline /
# no origin/main, HEAD unresolved -> allow. Deliberate escape: ETV_ALLOW_DIRTY_PUSH=1.
set -uo pipefail
[ "${ETV_ALLOW_DIRTY_PUSH:-}" = "1" ] && exit 0
git rev-parse --git-dir >/dev/null 2>&1 || exit 0
# Files with uncommitted changes vs HEAD — unstaged AND staged-but-uncommitted, tracked only.
dirty="$( { git diff --name-only; git diff --cached --name-only; } 2>/dev/null | sort -u )"
[ -z "$dirty" ] && exit 0 # clean tree -> nothing to guard
# The set of files this branch introduces vs origin/main (the "pushed diff"). Best-effort fetch;
# if origin/main is unavailable we cannot scope precisely -> fail open rather than over-block.
git fetch origin main --quiet 2>/dev/null || exit 0
git rev-parse --verify --quiet origin/main >/dev/null 2>&1 || exit 0
pushed="$( git diff --name-only "origin/main...HEAD" 2>/dev/null | sort -u )"
[ -z "$pushed" ] && exit 0
# Intersection: dirty files that are part of the pushed diff.
both="$( comm -12 <(printf '%s\n' "$dirty") <(printf '%s\n' "$pushed") )"
[ -z "$both" ] && exit 0
branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo HEAD)
echo "husky - push blocked (H13): '$branch' has UNCOMMITTED changes to file(s) that are part of"
echo " what you're pushing — the pushed commit does NOT match your working tree, so a local fix"
echo " or review may be shipping without its change (the #416 index/worktree trap):"
printf '%s\n' "$both" | sed 's/^/ /'
echo " Commit them (or 'git checkout --' to discard), then push. If the difference is intentional"
echo " and unrelated, bypass with: ETV_ALLOW_DIRTY_PUSH=1 git push"
exit 1
-69
View File
@@ -1,69 +0,0 @@
#!/usr/bin/env bash
# Husky pre-push backstop for ersatztv#303 H6 — the fast-forward-to-main path the Claude merge
# hook (pretooluse-merge-consent.sh) can't see. Reads git's pre-push ref lines on stdin; for a push
# to main it scans the pushed commits for a Gitea close-keyword (`fixes #N`), and if the linked
# issue's "## Done-when" checklist still has unticked boxes it BLOCKS the push.
#
# A git hook has no interactive "ask", so this is deliberately fail-OPEN: it only blocks when it can
# positively prove an unticked box (creds present, issue fetched, non-docs change). No creds, Gitea
# unreachable, docs-only diff, or no linked issue -> allow (a loud warning at most). The authoritative
# gate is the merge hook; this just catches a direct `git push origin main`.
#
# Auth (never committed): ETV_GITEA_TOKEN or ETV_GITEA_BASICAUTH; ETV_GITEA_URL overrides the base.
set -euo pipefail
# git passes "<localref> <localsha> <remoteref> <remotesha>" lines on stdin.
refs=$(cat || true)
printf '%s\n' "$refs" | grep -q 'refs/heads/main' || exit 0 # only gate pushes to main
base_url="${ETV_GITEA_URL:-http://192.168.1.95:3000}/api/v1"
if [ -z "${ETV_GITEA_TOKEN:-}" ] && [ -z "${ETV_GITEA_BASICAUTH:-}" ]; then
exit 0 # can't verify -> fail-open (the merge hook is the real gate)
fi
gq() {
if [ -n "${ETV_GITEA_TOKEN:-}" ]; then
curl -sf -H "Authorization: token $ETV_GITEA_TOKEN" "$base_url/$1" 2>/dev/null || true
else
curl -sf -u "$ETV_GITEA_BASICAUTH" "$base_url/$1" 2>/dev/null || true
fi
}
zero=0000000000000000000000000000000000000000
blocked=""
while read -r localref localsha remoteref remotesha; do
[ "$remoteref" = "refs/heads/main" ] || continue
[ "$localsha" = "$zero" ] && continue # branch deletion
# Commit range being pushed. New branch (remotesha all-zero) -> just the tip, don't rescan history.
if [ "$remotesha" = "$zero" ]; then range="$localsha -1"; else range="$remotesha..$localsha"; fi
msgs=$(git log --format='%B' $range 2>/dev/null || true)
issues=$(printf '%s' "$msgs" | grep -ioE '(close[sd]?|fix(e[sd])?|resolve[sd]?) +#[0-9]+' | grep -oE '[0-9]+' | sort -u || true)
[ -n "$issues" ] || continue
# Docs-only exemption over the pushed range.
changed=$(git diff --name-only $range 2>/dev/null || true)
if [ -n "$changed" ] && ! printf '%s\n' "$changed" | grep -qvE '^(docs/|\.claude/|\.husky/|\.gitea/|.*\.md$)'; then
continue
fi
for n in $issues; do
ibody=$(gq "repos/timothy/ersatztv/issues/$n" | jq -r '.body // ""' 2>/dev/null || true)
[ -n "$ibody" ] || continue # can't fetch -> fail-open
unchecked=$(printf '%s\n' "$ibody" | awk '
/^##[[:space:]]+[Dd]one-when/ {grab=1; next}
grab && /^##[[:space:]]/ {grab=0}
grab {print}' | grep -cE '^[[:space:]]*[-*][[:space:]]+\[[[:space:]]\]' || true)
if [ "${unchecked:-0}" -gt 0 ]; then
blocked="${blocked} - issue #$n has $unchecked unticked ## Done-when box(es)\n"
fi
done
done <<EOF
$refs
EOF
if [ -n "$blocked" ]; then
printf 'husky - H6 merge-consent (ersatztv#303): push to main BLOCKED\n' >&2
printf '%b' "$blocked" >&2
printf 'Finish/tick every Done-when criterion (incl. adversarial review) first, or push a docs-only change.\n' >&2
exit 1
fi
exit 0
-32
View File
@@ -1,32 +0,0 @@
#!/usr/bin/env bash
# H11 (ersatztv#311) — refuse to push a branch that is BEHIND origin/main: rebase first, do NOT
# merge main in. A merge commit drags in files you never touched (e.g. the ~2500 legacy-BOM .cs),
# which then trips the pre-commit `dotnet format` hook on code that isn't yours (the #309 session).
# Rebasing keeps your diff to exactly what you changed.
#
# Fail-OPEN on anything we can't decide (a git pre-push hook has no "ask"): not a git repo,
# offline / fetch fails, no origin/main, HEAD unresolved -> allow the push. The only hard block is
# a positively-proven "behind origin/main". Deliberate exception: ETV_SKIP_REBASE_CHECK=1.
set -uo pipefail
[ "${ETV_SKIP_REBASE_CHECK:-}" = "1" ] && exit 0
git rev-parse --git-dir >/dev/null 2>&1 || exit 0
# Best-effort fetch of the latest main; offline / no network -> don't block.
git fetch origin main --quiet 2>/dev/null || exit 0
git rev-parse --verify --quiet origin/main >/dev/null 2>&1 || exit 0
# Pushing main itself, or a branch already rebased on top of it, means origin/main is an ANCESTOR
# of HEAD -> nothing to rebase, allow.
if git merge-base --is-ancestor origin/main HEAD 2>/dev/null; then
exit 0
fi
behind=$(git rev-list --count HEAD..origin/main 2>/dev/null || echo '?')
branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo HEAD)
echo "husky - push blocked (H11): '$branch' is behind origin/main by $behind commit(s)."
echo " Rebase before pushing — do NOT merge main in (a merge drags in files you didn't touch,"
echo " e.g. legacy-BOM .cs, and trips the format hook on code that isn't yours):"
echo " git fetch origin main && git rebase origin/main"
echo " Deliberate exception: ETV_SKIP_REBASE_CHECK=1 git push"
exit 1
-14
View File
@@ -1,14 +0,0 @@
#!/usr/bin/env bash
# PreToolUse / Agent (subagent spawn) — RAM-gate the fan-out.
# The historic 8-9-way crash was RAM starvation, not CPU load; gate on FREE RAM.
# Fail-open: if memory_pressure is unavailable/unparsable → allow.
set -euo pipefail
free=$(memory_pressure -Q 2>/dev/null | grep -oE 'free percentage: [0-9]+' | grep -oE '[0-9]+' || true)
[ -z "${free:-}" ] && exit 0
if [ "$free" -lt 10 ]; then
jq -n --arg f "$free" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:("Free RAM \($f)% (<10%): do NOT spawn more agents — the historic crash was RAM starvation from an 8-9-way fan-out. Wait for memory_pressure -Q to recover, then retry.")}}'
elif [ "$free" -lt 20 ]; then
jq -n --arg f "$free" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:("Free RAM \($f)% (<20%): near the fan-out ceiling. Confirm before adding another build/implementer agent (read-only recon agents are cheap).")}}'
fi
exit 0
-15
View File
@@ -1,15 +0,0 @@
#!/usr/bin/env bash
# PreToolUse / Bash — deny commands that violate a HARD RULE.
# Fail-open: any parse trouble → allow (exit 0 with no output).
set -euo pipefail
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""' 2>/dev/null || true)
# Match an actual env ASSIGNMENT in COMMAND POSITION — line start or right after a shell
# separator (; && || | ( ), optionally `export`. This deliberately does NOT match the name
# when it sits inside a quoted string (echo, git commit -m, jq test payloads), where the
# preceding char is a quote/word, not a separator — so mentions of the rule never false-trip.
if printf '%s' "$cmd" | grep -qE '(^|[;&|(]|&&|\|\|)[[:space:]]*(export[[:space:]]+)?ETV_UPDATE_GOLDENS='; then
jq -n '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Blocked: ETV_UPDATE_GOLDENS regenerates golden-test baselines — HARD RULE (docs/handoffs lore); never set it in a session. Update a golden deliberately and reviewed, not via a guarded run."}}'
fi
exit 0
-99
View File
@@ -1,99 +0,0 @@
#!/usr/bin/env bash
# PreToolUse / Bash — deny `git commit` / `git push` when a .cs file this branch touches carries a
# UTF-8 BOM. `.editorconfig` sets charset=utf-8 (no BOM), and the #311 fix-as-you-touch gate
# ("Formatting (changed .cs conform to .editorconfig)") FAILS THE PR for any touched file that has one.
#
# Why a hook and not a note: the ~2500 legacy .cs files carry a BOM, so it becomes *your* problem the
# moment you touch one — and the usual ways of touching them re-add it silently. Python
# `io.open(..., encoding='utf-8-sig')` WRITES a BOM back; perl/sed round-trips preserve it. On
# 2026-07-17 this cost two separate sessions a red CI job on the same day (PR #405 x6 files;
# #70/PR #402 x19), and a memory describing the trap did not prevent either — the second session
# re-added a BOM an hour after writing that memory down. A check that runs is worth more than one you
# have to remember.
#
# Generated files are excluded: dotnet format skips *.Designer.cs and TvContextModelSnapshot.cs as
# generated code, and so does the CI verify, so `dotnet ef` may leave its BOM there.
#
# Fail-open by design: any parse/lookup trouble → allow (exit 0, no output). This gate must never be
# the reason a commit can't happen; CI is still the backstop.
set -uo pipefail
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""' 2>/dev/null || true)
[ -n "$cmd" ] || exit 0
# Only gate real `git commit` / `git push` invocations (allowing global flags like `git -c x=y commit`).
# Matched in command position so the words inside a commit message or an echo never false-trip.
printf '%s' "$cmd" \
| grep -qE '(^|[;&|(]|&&|\|\|)[[:space:]]*git([[:space:]]+-[^[:space:]]+([[:space:]]+[^[:space:]]+)?)*[[:space:]]+(commit|push)([[:space:]]|$)' \
|| exit 0
# Which tree does this act on? Commits here are typically `cd <worktree>` followed by git, and the
# harness resets the shell cwd between calls, so an in-command `cd` is the most reliable signal.
# Fall back to the payload cwd, then the project dir.
dir=$(printf '%s' "$cmd" \
| grep -oE '(^|[;&|(]|&&|\|\|)[[:space:]]*cd[[:space:]]+[^;&|)]+' \
| tail -1 | sed -E 's/.*cd[[:space:]]+//; s/[[:space:]]+$//' | tr -d "\"'" || true)
if [ -z "${dir:-}" ] || [ ! -d "$dir" ]; then
dir=$(printf '%s' "$input" | jq -r '.cwd // empty' 2>/dev/null || true)
fi
if [ -z "${dir:-}" ] || [ ! -d "$dir" ]; then
dir="${CLAUDE_PROJECT_DIR:-$PWD}"
fi
root=$(git -C "$dir" rev-parse --show-toplevel 2>/dev/null) || exit 0
# Scoped to this repo — the .editorconfig rule it enforces is ours.
case "$root" in
*ersatztv*) ;;
*) exit 0 ;;
esac
# The touched set: what this branch changes vs origin/main, plus anything staged or dirty right now
# (a commit can introduce a BOM that isn't in the pushed diff yet).
base=$(git -C "$root" rev-parse --verify --quiet origin/main 2>/dev/null || true)
{
[ -n "$base" ] && git -C "$root" diff --name-only --diff-filter=ACM "$base"...HEAD -- '*.cs' 2>/dev/null
git -C "$root" diff --name-only --diff-filter=ACM --cached -- '*.cs' 2>/dev/null
git -C "$root" diff --name-only --diff-filter=ACM -- '*.cs' 2>/dev/null
} | sort -u > /tmp/.bom-guard-files.$$ 2>/dev/null || { rm -f /tmp/.bom-guard-files.$$; exit 0; }
bad=""
while IFS= read -r f; do
[ -n "$f" ] || continue
case "$f" in
*.Designer.cs|*TvContextModelSnapshot.cs) continue ;;
esac
p="$root/$f"
[ -f "$p" ] || continue
if [ "$(head -c3 "$p" 2>/dev/null | xxd -p 2>/dev/null)" = "efbbbf" ]; then
bad="${bad} ${f}"$'\n'
fi
done < /tmp/.bom-guard-files.$$
rm -f /tmp/.bom-guard-files.$$
[ -n "$bad" ] || exit 0
reason="Blocked: these .cs files carry a UTF-8 BOM, which .editorconfig forbids (charset=utf-8). The #311 Formatting CI job fails the PR for any file this branch touches that has one:
${bad}
Strip it, then re-run this command:
python3 - <<'EOF'
import subprocess
def g(*a): return subprocess.run(['git','diff','--name-only',*a,'--','*.cs'],
capture_output=True, text=True).stdout.split()
# same detection set as the guard: branch diff + staged + dirty (a brand-new staged
# file is exactly what fires the deny and is absent from origin/main...HEAD)
fs = set(g('origin/main...HEAD')) | set(g('--cached')) | set(g())
for f in sorted(fs):
try: b = open(f,'rb').read()
except OSError: continue
if b[:3] == b'\xef\xbb\xbf':
open(f,'wb').write(b[3:]); print('stripped', f)
EOF
Usual cause: an edit that rewrote a legacy file preserved its BOM — Python io.open(..., encoding='utf-8-sig') WRITES one back; sed/perl round-trips keep it. Touching a legacy file makes its inherited BOM yours to remove (docs/contributing.md; ersatztv#311). Generated *.Designer.cs / TvContextModelSnapshot.cs are exempt and not listed here."
jq -n --arg r "$reason" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:$r}}'
exit 0
-183
View File
@@ -1,183 +0,0 @@
#!/usr/bin/env bash
# PreToolUse / mcp__gitea__pull_request_write — derive merge consent from STATE instead of
# trusting the agent's judgment (ersatztv#303 H6 + H10). A PR merge is the one irreversible op; allow it
# only when ALL are true:
# (a) the PR's CI combined status is green, AND
# (b) every checkbox in the linked issue's "## Done-when" section is ticked, AND
# (c) a review-verdict comment on the PR references the CURRENT head sha (H10) — proving the
# LATEST commit was reviewed, not a stale earlier diff (the ersatztv#242 failure mode:
# "re-review the fix commit, not just the initial PR diff").
# The "## Done-when" issue-body checklist is the convention (docs/decisions.md, CLAUDE.md Task
# Completion Protocol). One box is "adversarial review passed"; the others are per-issue.
# The H10 review-verdict convention: after reviewing a PR (or its latest fix commit), post a PR
# comment carrying a line `Review-verdict: <MERGEABLE|APPROVED|BLOCKED|NOT-MERGEABLE> @ <head-sha>`.
#
# Decision policy — a CONSENT gate, so it does NOT fail silently open:
# - state derivable and satisfied -> grant (auto-approve: permissionDecision "allow",
# so NO redundant permission prompt fires —
# the derived state IS the consent, ersatztv#314)
# - state derivable and NOT satisfied -> deny (actionable reason)
# - state NOT derivable (no creds, Gitea down,
# no linked issue, no Done-when section) -> ask (surface to a human/session judgment)
# Only a real merge is gated; every other pull_request_write method is passed through UNTOUCHED
# (bare exit 0 → normal permissioning still applies), NOT auto-granted.
#
# WHY "grant" (not a bare exit 0) on the satisfied path (ersatztv#314 root cause): a PreToolUse hook
# that exits 0 with no JSON does NOT auto-approve — it only declines to block, so control falls through
# to the normal permission system and the raw MCP prompt still fires. The gate therefore only ever
# ADDED a deny/ask net; it never REMOVED the baseline prompt on the happy path, so a satisfied merge
# was confirmed twice (conversationally + a redundant mechanical prompt). Emitting permissionDecision
# "allow" is what actually suppresses the prompt — "derive consent from state" made real.
#
# Gitea auth from env (never committed): ETV_GITEA_TOKEN (a token) OR ETV_GITEA_BASICAUTH (user:pass).
# ETV_GITEA_URL overrides the base (default: the LAN instance; a LAN address, not a secret).
set -euo pipefail
input=$(cat)
decide() { # $1=grant|allow|deny|ask $2=reason
case "$1" in
# grant = the gate is SATISFIED → auto-approve so no redundant permission prompt fires.
grant) jq -n --arg r "$2" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:$r}}'; exit 0 ;;
# allow = not our concern (non-merge method) → pass through untouched; normal permissioning applies.
allow) exit 0 ;;
deny) jq -n --arg r "$2" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:$r}}'; exit 0 ;;
ask) jq -n --arg r "$2" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:$r}}'; exit 0 ;;
esac
}
method=$(printf '%s' "$input" | jq -r '.tool_input.method // ""' 2>/dev/null || true)
[ "$method" = "merge" ] || decide allow ""
owner=$(printf '%s' "$input" | jq -r '.tool_input.owner // ""' 2>/dev/null || true)
repo=$(printf '%s' "$input" | jq -r '.tool_input.repo // ""' 2>/dev/null || true)
pr=$(printf '%s' "$input" | jq -r '.tool_input.pull_number // ""' 2>/dev/null || true)
mwcs=$(printf '%s' "$input" | jq -r '.tool_input.merge_when_checks_succeed // false' 2>/dev/null || true)
[ -n "$owner" ] && [ -n "$repo" ] && [ -n "$pr" ] || decide ask "H6 merge gate: could not read owner/repo/pull_number from the merge call; confirm manually that CI is green and the issue's Done-when boxes are ticked."
base_url="${ETV_GITEA_URL:-http://192.168.1.95:3000}/api/v1"
# curl wrapper carrying whichever auth is configured; empty output on any failure.
gq() {
local path="$1"
if [ -n "${ETV_GITEA_TOKEN:-}" ]; then
curl -sf -H "Authorization: token $ETV_GITEA_TOKEN" "$base_url/$path" 2>/dev/null || true
elif [ -n "${ETV_GITEA_BASICAUTH:-}" ]; then
curl -sf -u "$ETV_GITEA_BASICAUTH" "$base_url/$path" 2>/dev/null || true
else
return 1
fi
}
if [ -z "${ETV_GITEA_TOKEN:-}" ] && [ -z "${ETV_GITEA_BASICAUTH:-}" ]; then
decide ask "H6 merge gate: no Gitea credentials in env (ETV_GITEA_TOKEN or ETV_GITEA_BASICAUTH), so CI/Done-when state can't be verified. Confirm manually that CI is green and the linked issue's Done-when boxes are all ticked, then approve."
fi
prjson=$(gq "repos/$owner/$repo/pulls/$pr")
[ -n "$prjson" ] || decide ask "H6 merge gate: could not fetch PR #$pr from Gitea (unreachable or auth rejected). Verify CI-green + Done-when manually before merging."
sha=$(printf '%s' "$prjson" | jq -r '.head.sha // ""' 2>/dev/null || true)
body=$(printf '%s' "$prjson" | jq -r '.body // ""' 2>/dev/null || true)
# --- Docs-only exemption: if every changed file is docs/process, skip the gate. ---
files=$(gq "repos/$owner/$repo/pulls/$pr/files?limit=100" | jq -r '.[].filename // empty' 2>/dev/null || true)
if [ -n "$files" ] && ! printf '%s\n' "$files" | grep -qvE '^(docs/|\.claude/|\.husky/|\.gitea/|.*\.md$)'; then
# Docs/process-only PR: the Done-when + review-verdict gate doesn't apply — but this exemption is a
# file-TYPE bypass, NOT the a+b+c "provably reviewed & ready" proof, so it does NOT auto-grant. It
# passes through to normal permissioning (one prompt). This deliberately keeps a human in the loop for
# process-control files (.claude/ / .gitea/ / .husky/ — the gate, CI, and git hooks themselves): a PR
# that weakens the gate must not silently self-merge (ersatztv#317 review nit). Only the satisfied
# merge path below auto-grants.
decide allow "" # passthrough (exit 0 → normal prompt), NOT grant
fi
# --- Linked issue: Gitea auto-close keywords in the PR body. ---
issues=$(printf '%s' "$body" | grep -ioE '(close[sd]?|fix(e[sd])?|resolve[sd]?) +#[0-9]+' | grep -oE '[0-9]+' | sort -u || true)
[ -n "$issues" ] || decide ask "H6 merge gate: PR #$pr has no linked issue (no 'fixes #N' / 'closes #N' in its body), so there is no Done-when checklist to derive consent from. Confirm the work is complete + reviewed, then approve."
# --- (b) Done-when checkboxes: every linked issue must have an all-ticked section. ---
for n in $issues; do
ibody=$(gq "repos/$owner/$repo/issues/$n" | jq -r '.body // ""' 2>/dev/null || true)
[ -n "$ibody" ] || decide ask "H6 merge gate: could not fetch linked issue #$n. Verify its Done-when checklist manually before merging."
# Slice the "## Done-when" section: from that header to the next "## " (or EOF).
section=$(printf '%s\n' "$ibody" | awk '
/^##[[:space:]]+[Dd]one-when/ {grab=1; next}
grab && /^##[[:space:]]/ {grab=0}
grab {print}')
if [ -z "$(printf '%s' "$section" | tr -d '[:space:]')" ]; then
decide ask "H6 merge gate: linked issue #$n has no '## Done-when' checklist section (the merge-consent convention — see CLAUDE.md Task Completion Protocol). Add one, or confirm completion manually and approve."
fi
unchecked=$(printf '%s\n' "$section" | grep -cE '^[[:space:]]*[-*][[:space:]]+\[[[:space:]]\]' || true)
if [ "${unchecked:-0}" -gt 0 ]; then
decide deny "H6 merge gate: BLOCKED — linked issue #$n has $unchecked unticked box(es) in its ## Done-when checklist. Finish (or explicitly tick) every completion criterion — including the adversarial-review box — before merging PR #$pr."
fi
done
# --- (a) CI combined status must be green (unless deferring to Gitea's own check-gate). ---
if [ "$mwcs" != "true" ]; then
[ -n "$sha" ] || decide ask "H6 merge gate: could not resolve PR #$pr head sha to check CI. Verify CI is green before merging."
state=$(gq "repos/$owner/$repo/commits/$sha/status" | jq -r '.state // ""' 2>/dev/null || true)
case "$state" in
success) : ;;
"") decide ask "H6 merge gate: could not read CI status for PR #$pr ($sha). Verify CI is green before merging." ;;
*) decide deny "H6 merge gate: BLOCKED — PR #$pr CI status is '$state', not 'success'. Wait for a green build (or pass merge_when_checks_succeed to let Gitea gate it) before merging." ;;
esac
fi
# --- (c) Review-verdict freshness (ersatztv#303 H10): a review-verdict comment must reference the
# CURRENT head sha, so the latest commit is proven-reviewed (ersatztv#242: re-review the fix
# commit, not just the initial diff). Graceful adoption mirrors (b): a verdict comment that
# references head must be positive -> allow; one that exists only for an OLDER commit -> deny
# (the stale-review failure mode); NO verdict comment at all -> ask (convention not yet used).
[ -n "$sha" ] || decide ask "H10 merge gate: could not resolve PR #$pr head sha to verify a review verdict. Confirm the review covered the latest commit before merging."
short=${sha:0:7}
comments=$(gq "repos/$owner/$repo/issues/$pr/comments?limit=100")
if [ -z "$comments" ]; then
decide ask "H10 merge gate: could not fetch PR #$pr comments to verify a head-referencing review verdict ($short). Confirm the adversarial/Codex review covered the latest commit before merging."
fi
# Verdict lines across all comment bodies: a real verdict line STARTS with the marker (after optional
# leading whitespace). Anchoring to line-start is deliberate — it rejects a comment that merely QUOTES
# the positive template mid-sentence (an instruction "please post: Review-verdict: MERGEABLE @ <sha>",
# or the gate's own suggestion text echoed back), which would otherwise self-approve the merge.
verdicts=$(printf '%s' "$comments" | jq -r '.[].body // empty' 2>/dev/null | grep -iE '^[[:space:]]*review-verdict:' || true)
if [ -z "$verdicts" ]; then
decide ask "H10 merge gate: no 'Review-verdict:' comment found on PR #$pr referencing head $short. Post the adversarial/Codex verdict (e.g. 'Review-verdict: MERGEABLE @ $short'), or confirm the review covered the latest commit and approve."
fi
# Classify each verdict line by the sha it references (its "@ <sha>" field) and its verdict word.
# A line references the CURRENT head iff head BEGINS WITH that sha token AND the token is >=7 chars
# (git short-sha prefix semantics) — NOT a loose substring test: an older sha that merely contains
# the head prefix, or the head prefix appearing in an unrelated URL on the line, must NOT count
# (adversarial false-opens). The verdict token must sit right after the marker on the same line.
head_pos=0; head_neg=0; stale=0
while IFS= read -r line; do
[ -n "$line" ] || continue
# The sha the line references: the hex token in its "@ <sha>" field (>=7 chars), lowercased.
ref=$(printf '%s' "$line" | grep -ioE '@[[:space:]]*[0-9a-f]{7,40}' | head -1 \
| grep -oiE '[0-9a-f]{7,40}' | tr 'A-F' 'a-f' || true)
is_pos=0
# Positive iff the line's OWN leading verdict word (right after the line-start marker) is positive —
# anchored so a second, later `review-verdict: mergeable` substring on a BLOCKED line can't flip it.
if printf '%s' "$line" | grep -iqE '^[[:space:]]*review-verdict:[[:space:]]*(mergeable|approved|lgtm)'; then is_pos=1; fi
[ -z "$ref" ] && continue # marker present but no @<sha> -> falls through to the final ask
case "$sha" in
"$ref"*) if [ "$is_pos" = 1 ]; then head_pos=1; else head_neg=1; fi ;;
*) stale=1 ;;
esac
done <<VERDICTS
$verdicts
VERDICTS
# A negative verdict on head wins over a positive one (a later BLOCKED retracts an earlier MERGEABLE
# on the SAME head; and if the head were fixed the sha would change, so this can't wrongly block).
if [ "$head_neg" = 1 ]; then
decide deny "H10 merge gate: BLOCKED — a review verdict for the current head ($short) is negative (BLOCKED/NOT-MERGEABLE). Resolve the findings and post a fresh 'Review-verdict: MERGEABLE @ $short' before merging PR #$pr."
fi
if [ "$head_pos" = 1 ]; then
# (a) CI green + (b) all Done-when ticked + (c) positive verdict @ current head -> SATISFIED. Auto-grant.
decide grant "H6/H10 merge gate: satisfied — CI green, all Done-when boxes ticked, and a positive Review-verdict references the current head ($short). Auto-granted (no separate confirmation needed)."
fi
if [ "$stale" = 1 ]; then
decide deny "H10 merge gate: BLOCKED — a review-verdict comment references an older commit, not the current head ($short). The latest commit(s) are unreviewed (ersatztv#242: re-review the fix commit, not just the initial diff). Re-review the head and post 'Review-verdict: MERGEABLE @ $short'."
fi
# Marker(s) exist but reference no sha at all -> ask (don't mislabel as a stale older-commit review).
decide ask "H10 merge gate: a 'Review-verdict:' comment on PR #$pr references no commit sha. Post one referencing the current head ($short) — e.g. 'Review-verdict: MERGEABLE @ $short' — or confirm the review covered the latest commit and approve."
# All derivable and satisfied -> auto-grant (defensive: the head_pos branch above already exits here).
decide grant "H6/H10 merge gate: satisfied — auto-granted."
-11
View File
@@ -1,11 +0,0 @@
#!/usr/bin/env bash
# PreToolUse / browser-navigate — deny opening download/stream endpoints in a tab
# (they hang the MCP session; curl them instead). Fail-open on parse trouble.
set -euo pipefail
input=$(cat)
url=$(printf '%s' "$input" | jq -r '.tool_input.url // ""' 2>/dev/null || true)
if printf '%s' "$url" | grep -qE '/iptv/|\.m3u8|/artwork/|playback\.m3u8'; then
jq -n '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Blocked: do not open download/stream endpoints (/iptv, .m3u8, /artwork, playback.m3u8) in a browser tab — they stall the MCP session. curl them instead (docs/handoffs lore)."}}'
fi
exit 0
@@ -1,45 +0,0 @@
#!/usr/bin/env bash
# PreToolUse / Bash — deny `git commit`/`git merge` inside a sibling worktree that
# a DIFFERENT session created (burned us twice — #289 path-leak, the plumbing-merge
# workaround exists precisely because of this). Ownership is a `.claude-worktree-owner`
# marker (session id) written at `git worktree add` time by posttooluse-worktree-marker.sh.
#
# Fail-open by design: no marker, unparsable input, or marker == this session → allow.
# So the main tree (never marked) and pre-convention worktrees (no marker) are unaffected;
# only a commit/merge into another session's marked worktree is blocked.
set -euo pipefail
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""' 2>/dev/null || true)
cwd=$(printf '%s' "$input" | jq -r '.cwd // ""' 2>/dev/null || true)
me=$(printf '%s' "$input" | jq -r '.session_id // ""' 2>/dev/null || true)
# Only guard the state-mutating ops. Match `git commit`/`git merge` in command position
# (line start or after a shell separator) so a quoted mention never false-trips.
printf '%s' "$cmd" | grep -qE '(^|[;&|(]|&&|\|\|)[[:space:]]*git[[:space:]]+(-C[[:space:]]+[^[:space:]]+[[:space:]]+)?(commit|merge)\b' || exit 0
[ -z "$cwd" ] && cwd="$PWD"
# Determine the effective directory the git op runs in. Two common redirections in the
# lore's usage move it off the session cwd: `git -C <path>` and a leading `cd <path> &&`.
effdir="$cwd"
cpath=$(printf '%s' "$cmd" | grep -oE 'git[[:space:]]+-C[[:space:]]+[^[:space:]&|;]+' | head -1 | sed -E 's/^git[[:space:]]+-C[[:space:]]+//' | tr -d '"'"'"'' || true)
cdpath=$(printf '%s' "$cmd" | grep -oE '^[[:space:]]*cd[[:space:]]+[^[:space:]&|;]+' | head -1 | sed -E 's/^[[:space:]]*cd[[:space:]]+//' | tr -d '"'"'"'' || true)
if [ -n "${cpath:-}" ]; then
effdir="$cpath"
elif [ -n "${cdpath:-}" ]; then
effdir="$cdpath"
fi
# Resolve a relative effective dir against the session cwd.
case "$effdir" in /*) : ;; *) effdir="$cwd/$effdir" ;; esac
root=$(git -C "$effdir" rev-parse --show-toplevel 2>/dev/null || true)
[ -z "$root" ] && exit 0
marker="$root/.claude-worktree-owner"
[ -f "$marker" ] || exit 0
owner=$(tr -d '[:space:]' < "$marker" 2>/dev/null || true)
[ -z "$owner" ] && exit 0
[ "$owner" = "$me" ] && exit 0
# Marker names a DIFFERENT session → deny.
jq -n --arg o "$owner" --arg r "$root" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:("Blocked: worktree \($r) is owned by session \($o), not this one. Never commit/merge inside a sibling worktree another session created (#289 path-leak, plumbing-merge workaround). Commit from your own tree; if you genuinely own this worktree now, overwrite its .claude-worktree-owner marker with your session id.")}}'
exit 0
-90
View File
@@ -1,90 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-bash-guard.sh\"",
"timeout": 10
},
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-worktree-guard.sh\"",
"timeout": 10
},
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-bom-guard.sh\"",
"timeout": 10
}
]
},
{
"matcher": "mcp__plugin_playwright_playwright__browser_navigate|mcp__claude-in-chrome__navigate",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-nav-guard.sh\"",
"timeout": 10
}
]
},
{
"matcher": "Agent|Task",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-agent-ram.sh\"",
"timeout": 10
}
]
},
{
"matcher": "mcp__gitea__pull_request_write",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-merge-consent.sh\"",
"timeout": 15
}
]
},
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/design-sync-reminder.sh\" start",
"timeout": 10
}
]
}
],
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/posttooluse-worktree-marker.sh\"",
"timeout": 10
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/design-sync-reminder.sh\" finish",
"timeout": 10
}
]
}
]
}
}
+1 -1
View File
@@ -3,7 +3,7 @@
"isRoot": true,
"tools": {
"jetbrains.resharper.globaltools": {
"version": "2025.3.4.1",
"version": "2025.3.0.2",
"commands": [
"jb"
],
+5 -9
View File
@@ -106,17 +106,13 @@ ij_json_wrap_long_lines = false
dotnet_diagnostic.ca1848.severity = none
# --- Static-analysis pack adoption (ersatztv#15) ---
# Threading analyzers and Roslynator / SonarAnalyzer / Meziantou / AsyncFixer are enabled centrally.
# Default their diagnostics to `suggestion`; the SDK's exact per-rule suggestion baseline lives in
# eng/analyzers/sdk-all-suggestion.globalconfig because AnalysisLevel=latest-All otherwise injects
# exact warning severities that outrank this bulk setting. High-value rules are promoted one at a
# time. Explicit per-rule severities (e.g. ca1848 above) take precedence over both baselines.
# Roslynator / SonarAnalyzer / Meziantou / AsyncFixer are referenced centrally
# (Directory.Build.targets). Default every analyzer diagnostic to `suggestion` so the new
# packs don't fail the TreatWarningsAsErrors build; high-value rules get promoted to
# warning/error one at a time (see ersatztv#15 / docs/contributing.md). Explicit per-rule
# severities (e.g. ca1848 above) still take precedence over this bulk default.
dotnet_analyzer_diagnostic.severity = suggestion
# A collection count can never be negative. Treat comparisons that therefore collapse to a
# constant as errors; the first promotion caught a busy/idle branch that was permanently busy.
dotnet_diagnostic.S3981.severity = warning
# Blazor components: analyzers run on .razor/.cshtml @code too, and TWAE would otherwise
# turn their default-severity findings into build errors — keep them at suggestion as well.
[*.razor]
-136
View File
@@ -1,136 +0,0 @@
name: Build CI Toolchain Image
# Builds the shared CI toolchain image (.NET 10 SDK + Node 22 + prod-identical ffmpeg) and
# pushes it to the Gitea container registry (ersatztv#390). The toolchain jobs in
# docker-build.yml consume it via `container:`, pinned to an immutable :<sha>.
#
# push touching docker/ci/** -> :<short-sha> (+ :latest only from main)
# workflow_dispatch -> manual rebuild
# schedule (weekly) -> picks up base-image security updates
#
# Deliberately separate from docker-build.yml: this image changes rarely (a Dockerfile edit or
# the weekly cron), while docker-build.yml runs on every push/PR. Coupling them would rebuild a
# ~2GB toolchain image on every commit.
#
# ROLLOUT NOTE: the jobs pin an immutable :<sha>, never :latest — a broken toolchain image would
# otherwise block every converted job the moment it was pushed. Bumping the toolchain is therefore
# a deliberate two-step: merge a docker/ci/Dockerfile change (this workflow publishes a new :<sha>),
# then update the pin in docker-build.yml in a follow-up PR whose CI proves the new image works.
# See docs/ci-cd.md -> "CI toolchain image".
#
# Like docker-build.yml: the Gitea registry is HTTP-only, so BuildKit needs the inline
# `http = true` config (it does not inherit the host daemon's insecure-registries setting).
on:
workflow_dispatch:
push:
paths:
- 'docker/ci/**'
- '.gitea/workflows/ci-image.yml'
schedule:
# Mondays 05:00 UTC. Gitea registers `schedule` only from the default branch (main).
#
# What this cron does and does NOT do — it does **not** update any running job. The jobs in
# docker-build.yml pin an immutable :<sha> (deliberately), so a rebuilt image is consumed only
# when a human bumps that pin. Its actual value is twofold:
# 1. a weekly CANARY — catches "the toolchain image no longer builds" (a NodeSource/apt/base
# change) at a time of our choosing, rather than when you next need to bump the pin;
# 2. it leaves a freshly-patched :latest so the next pin bump starts from a current base.
# `no-cache` on this path is what makes both real: with the shared :buildcache, the
# `apt-get update && apt-get install` layer would restore from cache and re-fetch nothing.
- cron: '0 5 * * 1'
# Serialize per ref: concurrent builds would race on the shared :buildcache tag.
# No cancel-in-progress — a half-pushed toolchain image is worse than a redundant build.
concurrency:
group: ersatztv-ci-image-${{ github.ref }}
cancel-in-progress: false
env:
REGISTRY: 192.168.1.95:3000
CI_IMAGE: 192.168.1.95:3000/timothy/ersatztv-ci
jobs:
build:
name: Build & push CI image
# `small` = the small-jobs runner lane. This is a docker-only job (no toolchain needed —
# it *builds* the toolchain), same as docker-build.yml's `build` job.
runs-on: small
steps:
- name: Checkout
uses: actions/checkout@v4
with:
# only docker/ci/Dockerfile is needed; no git describe/log here
fetch-depth: 1
- name: Compute tags
id: meta
run: |
set -euo pipefail
SHORT=$(git rev-parse --short HEAD)
# Always publish the immutable :<sha> — that is what docker-build.yml pins.
TAGS=("${CI_IMAGE}:${SHORT}")
# :latest is a convenience/floating pointer for humans and the weekly rebuild; jobs must
# never consume it. Only main may move it.
if [ "${GITHUB_REF}" = "refs/heads/main" ]; then
TAGS+=("${CI_IMAGE}:latest")
fi
echo "short=${SHORT}" >> "$GITHUB_OUTPUT"
{
echo "tags<<__EOT__"
printf '%s\n' "${TAGS[@]}"
echo "__EOT__"
} >> "$GITHUB_OUTPUT"
printf 'tag: %s\n' "${TAGS[@]}"
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
buildkitd-config-inline: |
[registry."192.168.1.95:3000"]
http = true
- name: Login to Gitea registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
file: ./docker/ci/Dockerfile
platforms: linux/amd64
push: true
provenance: false
tags: ${{ steps.meta.outputs.tags }}
# The scheduled rebuild must bypass the cache or it is pointless: `mode=max` buildcache
# would restore the `apt-get update && apt-get install` layer verbatim and pull in none of
# the base updates the cron exists to collect. Push-triggered builds keep the cache.
no-cache: ${{ github.event_name == 'schedule' }}
cache-from: type=registry,ref=192.168.1.95:3000/timothy/ersatztv-ci:buildcache
cache-to: type=registry,ref=192.168.1.95:3000/timothy/ersatztv-ci:buildcache,mode=max,ignore-error=true
# The Dockerfile's own build-time smoke test (dotnet --info, node, ffmpeg, ...) already ran
# inside the build. This re-checks the *pushed* artifact end-to-end: that the registry copy
# pulls and its toolchain runs, which is exactly what `container:` will do on every job.
- name: Verify the pushed image
run: |
set -euo pipefail
IMG="${CI_IMAGE}:${{ steps.meta.outputs.short }}"
echo "Pulling ${IMG}"
docker pull "$IMG"
docker run --rm --entrypoint /bin/bash "$IMG" -euxc '
dotnet --version
dotnet ef --version
node --version
ffmpeg -version | head -1
git --version
python3 --version
# reportgenerator --version exits 1 ("No report files specified"); probe the shim.
command -v reportgenerator
'
echo "CI image OK. Pin this in .gitea/workflows/docker-build.yml -> CI_IMAGE_REF:"
echo " ${IMG}"
-11
View File
@@ -22,17 +22,6 @@ concurrency:
group: ersatztv-depscan
cancel-in-progress: true
# No persistent MSBuild/Roslyn servers (ersatztv#406). Workflow `env:` does not cross workflow
# files, so docker-build.yml's copy of these does not apply here and this has to be repeated.
# Smaller stakes than the build pipeline — `dotnet restore` + `dotnet list` are MSBuild-driven and
# never invoke csc, so this is lingering worker nodes (hundreds of MiB), not a 7.8 GB VBCSCompiler.
# Worth setting anyway: this runs unattended on a Monday 06:00 cron against the same host that runs
# prod media, and node reuse keeps workers alive ~15 min after the job.
env:
UseSharedCompilation: "false"
DOTNET_CLI_USE_MSBUILD_SERVER: "0"
MSBUILDDISABLENODEREUSE: "1"
jobs:
scan:
name: NuGet vulnerable packages
+29 -659
View File
@@ -12,38 +12,6 @@ name: Build ErsatzTV Image
#
# `:latest` is intentionally the test/dev channel (per ersatztv#3); prod pins
# `:prod`, never `:latest` (enforced in the prod compose — server-management#481).
#
# TOOLCHAIN IMAGE (ersatztv#390): the jobs that need a toolchain (`test`, `migrations`,
# `functional-e2e`, `api-docs`, `format`) run inside our shared CI image via `container:`
# instead of installing .NET/Node/ffmpeg per run. It ships the .NET 10 SDK, Node 22,
# prod-identical ffmpeg, and the dotnet-ef/reportgenerator global tools — so those jobs carry
# no setup-dotnet, no setup-node, no apt, no `dotnet tool install`. Built by ci-image.yml from
# docker/ci/Dockerfile. Project deps (NuGet/npm) are NOT baked in and stay on actions/cache.
#
# The pin below is an IMMUTABLE :<sha>, never :latest — a bad toolchain push would otherwise
# break every converted job at once. It is repeated per job because `jobs.<id>.container.image`
# cannot read the workflow `env` context. **Bump all five together**; see docs/ci-cd.md ->
# "CI toolchain image" for the two-step procedure.
#
# CI image pin: 192.168.1.95:3000/timothy/ersatztv-ci:07048b8
#
# DOCS-ONLY SKIP (ersatztv#416): a change that touches only docs/** or *.md has nothing for the
# heavy jobs to validate. `test`, `migrations`, `functional-e2e` and `build` each run
# `scripts/ci-detect-docs-only.sh` as their first post-checkout step (id: detect) and gate every
# real step on `steps.detect.outputs.docs_only != 'true'`. Crucially they STILL RUN and STILL
# report `success` in seconds — the two REQUIRED contexts (`Build & test (.NET)`, `EF migration
# integrity (SQLite + MySql)`) must keep reporting or a docs-only PR could never merge. We do NOT
# `if:`-skip a required job: on Gitea 1.25.4 a skipped job reports commit-status state `skipped`
# (verified, throwaway PR #418) and we don't rely on how branch protection treats a skipped
# REQUIRED context. See docs/ci-cd.md -> "Docs-only skip".
#
# ALREADY-VALIDATED SKIP (ersatztv#420): a second, sibling gate in `test`, `migrations` and
# `functional-e2e` only (NOT `build`). On a push-to-main merge commit, `id: revalidate` runs
# `scripts/ci-detect-already-validated.sh`, which emits `skip=true` only when the merged tree is
# byte-identical to a PR head that already has a green Gitea combined status — i.e. the exact
# source was already validated in the PR run. Every heavy step in those three jobs additionally
# gates on `steps.revalidate.outputs.skip != 'true'`. `build` is untouched and always runs on
# main, so the image is still built (from already-validated source) even when the skip fires.
on:
workflow_dispatch:
@@ -54,214 +22,77 @@ on:
tags:
- 'v*'
# Concurrency is scoped per ref (originally one global group for the single
# jazz runner; with 3 runners that serialized the whole queue). PR runs
# parallelize across PRs and a new sync auto-cancels its superseded run.
# Real image builds (main / v* tags) still serialize within their own ref;
# don't push main and a v* tag simultaneously — they share :buildcache and
# the smoke container name.
# Single runner on jazz: serialize all runs so the push-main-then-tag release
# flow can't collide on the shared :buildcache tag or the smoke container.
concurrency:
group: ersatztv-build-${{ github.event_name }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# Inside a `container:`, act_runner does NOT default `run` steps to bash — it falls back to
# `sh -e {0}` (dash), because it can't assume bash exists in an arbitrary image. Every multi-line
# script here is bash (`set -o pipefail`, arrays, `shopt`, `mapfile`), so dash fails them
# immediately: `set: Illegal option -o pipefail`. Declare the shell once for the whole workflow
# rather than per step. Non-container jobs already defaulted to bash, so this changes nothing for
# them. (ersatztv#390 — see docs/ci-cd.md -> "CI toolchain image".)
defaults:
run:
shell: bash
group: ersatztv-build
cancel-in-progress: false
env:
REGISTRY: 192.168.1.95:3000
IMAGE: 192.168.1.95:3000/timothy/ersatztv
# --- CI build memory (ersatztv#406, server-management#604) ---
# Roslyn's `VBCSCompiler` is a *persistent* compiler server: it outlives the `dotnet build` that
# started it and keeps its managed heap warm for the next one. Locally that is a real speedup.
# In CI it buys nothing — each job container is torn down at the end of the run, so there is
# never a "next build" to warm — while costing a lot: 7.8 GB RSS was measured live on bumblebee,
# the single largest consumer on a 25 GiB host that also runs prod media. Several of those, one
# per concurrent job container, is what drove the host to load 340 with 21 GiB swapped.
#
# These are MSBuild properties/switches, set here as environment variables so they apply to every
# dotnet invocation in every job (restore/build/test/format/api-docs) without touching each call
# site. MSBuild surfaces environment variables as properties, and `UseSharedCompilation` is only
# defaulted to true when empty, so setting it here wins.
#
# NOTE: this reaches the *runner-side* dotnet jobs only. The `build` job compiles inside
# `docker build`, where these do not propagate — the same switches are set as ENV in the
# Dockerfile's SDK stage (docker/Dockerfile) to cover it.
UseSharedCompilation: "false" # no persistent VBCSCompiler; csc runs per-project and exits
DOTNET_CLI_USE_MSBUILD_SERVER: "0" # no persistent MSBuild server process
MSBUILDDISABLENODEREUSE: "1" # MSBuild worker nodes exit with the build instead of lingering
jobs:
test:
name: Build & test (.NET)
runs-on: ubuntu-latest
container:
image: 192.168.1.95:3000/timothy/ersatztv-ci:07048b8
credentials:
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_PASSWORD }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
# git history/tags are needed by the `build` job's `git describe` (ersatztv#190) and,
# here, by the #420 revalidate step's `HEAD^2` tree comparison on a main merge commit.
fetch-depth: 2
fetch-depth: 0
# ersatztv#416: is this a docs-only change? If so, every heavy step below is skipped and this
# REQUIRED job reports success in seconds. It still RUNS (never `if:`-skipped) so the required
# context keeps reporting — see the workflow header and docs/ci-cd.md -> "Docs-only skip".
- name: Detect docs-only changes
id: detect
run: scripts/ci-detect-docs-only.sh
- name: Detect already-validated tree (#420)
id: revalidate
env:
ETV_STATUS_AUTH: ${{ secrets.REGISTRY_USER }}:${{ secrets.REGISTRY_PASSWORD }}
run: scripts/ci-detect-already-validated.sh
- name: Cache NuGet packages
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
uses: actions/cache@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
path: ~/.nuget/packages
key: nuget-${{ runner.os }}-${{ hashFiles('Directory.Packages.props', 'global.json') }}
restore-keys: nuget-${{ runner.os }}-
dotnet-version: '10.0.x'
- name: Restore
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
run: dotnet restore
# Replaces setup-node's built-in `cache: npm`. The toolchain image supplies node/npm, but
# the SPA's package downloads are project deps, so they stay cached per lockfile.
- name: Cache npm packages
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
uses: actions/cache@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('web/package-lock.json') }}
restore-keys: npm-${{ runner.os }}-
node-version: '22.x'
cache: npm
cache-dependency-path: web/package-lock.json
- name: Install SPA dependencies
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
working-directory: web
run: npm ci
- name: Check generated SPA API client
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
working-directory: web
run: npm run check:api
- name: Lint SPA
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
working-directory: web
run: npm run lint
- name: Typecheck SPA
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
working-directory: web
run: npm run typecheck
- name: Test SPA
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
working-directory: web
run: npm test -- --run
- name: Build SPA
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
working-directory: web
run: npm run build
- name: Strip Scanner project ref (matches Docker build)
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
run: sed -i '/Scanner/d' ErsatzTV/ErsatzTV.csproj
# Start the true peak-anon sampler just before the memory-heavy dotnet Build/Test/Coverage so
# its high-water mark spans them (SPA build/test above are comparatively light). Paired with the
# "Report peak container memory" step below. continue-on-error + a fail-open script => this
# instrumentation never reddens a build. Why anon and not memory.peak: ersatztv#412 /
# scripts/ci-peak-anon.sh header / docs/ci-cd.md "CI build memory".
- name: Start peak-anon sampler (ersatztv#412)
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
continue-on-error: true
run: scripts/ci-peak-anon.sh start
- name: Build
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
run: dotnet build --configuration Release --no-restore
- name: Test
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
run: >-
dotnet test --configuration Release --no-build --blame-hang-timeout "2m" --verbosity normal
--collect:"XPlat Code Coverage" --settings coverlet.runsettings --results-directory ./coverage
# Coverage reporting (ersatztv#15 scope item 4): coverlet.collector emits a Cobertura report
# per test project (via --collect above); ReportGenerator merges them into a human-readable
# summary printed to the log and the job step summary. No floor is enforced yet ("decide on a
# floor later"), so this step is purely informational — continue-on-error keeps a missing
# report or a transient tool-install failure from ever blocking a build.
- name: Coverage summary
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
continue-on-error: true
run: |
set -euo pipefail
shopt -s globstar nullglob
reports=(coverage/**/coverage.cobertura.xml)
if [ ${#reports[@]} -eq 0 ]; then
echo "No coverage reports found under ./coverage -- skipping summary."
exit 0
fi
echo "Found ${#reports[@]} coverage report(s)."
# reportgenerator is baked into the CI toolchain image (docker/ci/Dockerfile) and already
# on PATH — no per-run `dotnet tool` install. Bump its version there (ersatztv#390).
reportgenerator \
"-reports:coverage/**/coverage.cobertura.xml" \
"-targetdir:coverage/report" \
"-reporttypes:TextSummary;MarkdownSummaryGithub"
echo "::group::Coverage summary"
cat coverage/report/Summary.txt
echo "::endgroup::"
if [ -n "${GITHUB_STEP_SUMMARY:-}" ] && [ -f coverage/report/SummaryGithub.md ]; then
cat coverage/report/SummaryGithub.md >> "$GITHUB_STEP_SUMMARY"
fi
# Memory of THIS job container, reported every run (ersatztv#406/#412, server-management#604).
# #604 sizes the runners' per-job caps on these numbers. The headline is the TRUE PEAK ANON
# sampled by the "Start peak-anon sampler" step above — NOT `memory.peak`, which is the
# high-water mark of memory.current and charges reclaimable page cache to the cgroup (a build
# job does heavy NuGet/npm/obj/bin/coverage I/O, so cache can dominate the peak). Page cache is
# reclaimed under a tighter cap, not OOM-killed, so sizing a cap off `memory.peak` inverts the
# decision. peak anon is the OOM-forcing number. Full rationale + the bumblebee demo:
# scripts/ci-peak-anon.sh header and docs/ci-cd.md "CI build memory".
#
# Runs LAST on purpose (after Coverage summary / reportgenerator, the job's last real workload)
# and stops the sampler. `always()` so a failed Build/Test still gets a peak reading; the split
# is read here (end-of-job = composition then, not at the peak instant — that is exactly why the
# sampler exists). Skipped on docs-only/already-validated runs (nothing ran to measure).
- name: Report peak container memory
# `always()` controls whether this step RUNS, not whether its failure fails the job. With
# `defaults.run.shell: bash` (`-e -o pipefail`) a stray non-zero here would redden a green
# test job, so `continue-on-error` makes it advisory — the same guarantee Coverage summary uses.
if: ${{ always() && steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true' }}
continue-on-error: true
run: scripts/ci-peak-anon.sh report
run: dotnet test --configuration Release --no-build --blame-hang-timeout "2m" --verbosity normal
migrations:
name: EF migration integrity (SQLite + MySql)
runs-on: ubuntu-latest
container:
image: 192.168.1.95:3000/timothy/ersatztv-ci:07048b8
credentials:
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_PASSWORD }}
# Independent gate (not a 'needs' of build yet) so the new MySql-service dependency
# can't block image builds until it's proven reliable on the runner. Promote to a
# required check / build dependency once green. (ersatztv#13)
@@ -271,45 +102,9 @@ jobs:
env:
MYSQL_ROOT_PASSWORD: ersatztv
MYSQL_DATABASE: ersatztv_migrations
# No host-port binding: the job reaches this service as mysql:3306 on the shared
# runner network. Publishing 3306 made concurrent runs collide ("port is already
# allocated") whenever two migrations jobs overlapped.
#
# `--memory`/`--cpus` here because the runner's `container.options` (`--memory=10g`)
# applies to the JOB container ONLY, not to `services:` — verified by inspecting a live
# migrations job: the job container reported HostConfig.Memory=10737418240, its mysql
# service reported `mem=0 nanocpus=0`, i.e. unbounded. So every migrations run was adding
# an uncapped MySQL to an already-tight host (ersatztv#406, server-management#604).
#
# NOTE (ersatztv#416): a `services:` container starts whenever the JOB starts, regardless
# of step `if:`. So a docs-only migrations run still spins this mysql (capped, seconds) even
# though the DDL-replay steps below are skipped. Fully skipping the service would require an
# `if:`-skipped job, which we deliberately do NOT do for a required context — the heavy cost
# (the 787-migration replay) is what the step gating removes.
#
# `--memory-swap=2g` is NOT redundant with `--memory=2g` — it is the point. Docker defaults
# an unset `--memory-swap` to *twice* `--memory`, so `--memory=2g` alone would grant 2g RAM
# **plus 2g of swap** (verified on bumblebee: `--memory=2g` alone → memory.max=2147483648
# AND memory.swap.max=2147483648; with `--memory-swap=2g` → memory.swap.max=0). Setting it
# equal to --memory disables swap for this container. That matters more here than anywhere:
# swap thrash on this host is the whole reason this cap exists, and a swapping mysqld mid-DDL
# is precisely the pathology behind the known `Command Timeout expired` migrations flake. We
# want a loud OOM over silent swapping — an OOM is a clear signal to raise the cap.
#
# 2g is sized on measurement rather than inheritance, but honestly: a mysql:8.4 container
# with this exact env peaked at 543 MiB during init and settled at 481 MiB idle (probed on
# bumblebee 2026-07-17). That is init+idle, NOT the 787-migration replay, which grows caches
# idle never touches — so treat 2g as a measured floor with headroom, not a measured
# ceiling. The migrations job going green is what validates it. If this OOM-kills the
# service, raise it deliberately — do not remove the cap, and do not re-enable swap.
#
# `--cpus=2` is a ceiling, not a reservation, and is the one number here with no measurement
# behind it: 787 sequential DDL statements on one connection are ~1-core-bound, so 2 is
# judgement. Revisit if the apply step's tail latency grows.
ports:
- 3306:3306
options: >-
--memory=2g
--memory-swap=2g
--cpus=2
--health-cmd="mysqladmin ping -h 127.0.0.1 -uroot -persatztv --silent"
--health-interval=5s
--health-timeout=5s
@@ -317,46 +112,26 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
with:
# was the default fetch-depth: 1 (ersatztv#190); bumped to 2 so the #420 revalidate
# step's `HEAD^2` tree comparison can resolve on a main merge commit.
fetch-depth: 2
# ersatztv#416: docs-only? Skip the build + migration replay; the job still reports success in
# seconds. REQUIRED context, so it always RUNS (never `if:`-skipped). See the workflow header.
- name: Detect docs-only changes
id: detect
run: scripts/ci-detect-docs-only.sh
- name: Detect already-validated tree (#420)
id: revalidate
env:
ETV_STATUS_AUTH: ${{ secrets.REGISTRY_USER }}:${{ secrets.REGISTRY_PASSWORD }}
run: scripts/ci-detect-already-validated.sh
- name: Cache NuGet packages
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
uses: actions/cache@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
path: ~/.nuget/packages
key: nuget-${{ runner.os }}-${{ hashFiles('Directory.Packages.props', 'global.json') }}
restore-keys: nuget-${{ runner.os }}-
dotnet-version: '10.0.x'
- name: Restore
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
run: dotnet restore
- name: Build
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
run: dotnet build --configuration Release --no-restore
# dotnet-ef is baked into the CI toolchain image (docker/ci/Dockerfile) and already on PATH
# — no per-run `dotnet tool install`. Bump its version there (ersatztv#390).
- name: Install dotnet-ef
run: dotnet tool install --global dotnet-ef --version 9.0.12
# SQLite is the prod provider; both checks validated locally.
- name: SQLite — model drift + apply all migrations to a fresh DB
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
run: |
set -euo pipefail
export PATH="$PATH:$HOME/.dotnet/tools"
echo "::group::SQLite model drift (has-pending-model-changes)"
dotnet ef migrations has-pending-model-changes --no-build --configuration Release \
--context TvContext --startup-project ErsatzTV --project ErsatzTV.Infrastructure.Sqlite -- --provider Sqlite
@@ -370,138 +145,23 @@ jobs:
# MySql uses ServerVersion.AutoDetect (connects at config time), so it runs against the
# service container above. MySql__ConnectionString maps to config key "MySql:ConnectionString".
- name: MySql — model drift + apply all migrations to a fresh DB
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
env:
# DefaultCommandTimeout is raised from MySqlConnector's 30s default: replaying every
# migration to a fresh DB issues DDL commands that can exceed 30s when two migration jobs
# share a runner host (each spins its own mysql:8.4 service) and starve each other. That
# contention produced both "Command Timeout expired" and mid-replay connection drops
# (MySqlEndOfStreamException) — neither is a model problem. See #13 / #236.
MySql__ConnectionString: "Server=mysql;Port=3306;Database=ersatztv_migrations;Uid=root;Pwd=ersatztv;DefaultCommandTimeout=300;"
MySql__ConnectionString: "Server=mysql;Port=3306;Database=ersatztv_migrations;Uid=root;Pwd=ersatztv;"
run: |
set -euo pipefail
export PATH="$PATH:$HOME/.dotnet/tools"
echo "::group::MySql model drift (has-pending-model-changes)"
dotnet ef migrations has-pending-model-changes --no-build --configuration Release \
--context TvContext --startup-project ErsatzTV --project ErsatzTV.Infrastructure.MySql -- --provider MySql
echo "::endgroup::"
echo "::group::MySql apply all migrations to a fresh DB"
# Retry the apply: under concurrent-runner MySQL contention the server can drop the
# connection mid-replay. Each attempt resumes from __EFMigrationsHistory (EF wraps each
# migration in its own transaction, so an interrupted migration rolls back cleanly and the
# retry continues from the last committed one) — so this only papers over infra flakiness,
# never a real migration failure, which fails deterministically on every attempt.
attempt=1
max=3
until dotnet ef database update --no-build --configuration Release \
--context TvContext --startup-project ErsatzTV --project ErsatzTV.Infrastructure.MySql -- --provider MySql; do
if [ "$attempt" -ge "$max" ]; then
echo "MySql apply failed after ${max} attempts" >&2
exit 1
fi
echo "MySql apply attempt ${attempt} failed (likely runner MySQL contention); retrying in 15s..." >&2
attempt=$((attempt + 1))
sleep 15
done
dotnet ef database update --no-build --configuration Release \
--context TvContext --startup-project ErsatzTV --project ErsatzTV.Infrastructure.MySql -- --provider MySql
echo "::endgroup::"
functional-e2e:
name: Functional E2E (curl contracts)
runs-on: ubuntu-latest
# Advisory gate (ersatztv#299): boots the app from source and drives the manual live-E2E
# flows (legacy->SPA redirects, auth/CSRF/security-stamp, library-scan status contract,
# If-Match/412, and since ersatztv#363 two lock-contention 409s) that sessions have been
# re-running by hand. Deliberately NOT a `needs:` of `build` and not (yet) a required check, so a
# functional-E2E flake can't block image builds or the unit-test gate — promote it to a required
# check / build dependency once it's proven reliable (same rollout the `migrations` job used).
# SQLite default provider -> no DB service. Runs on PRs and on main (regression net); skipped for
# v* tag builds.
if: github.event_name == 'pull_request' || github.ref == 'refs/heads/main'
container:
image: 192.168.1.95:3000/timothy/ersatztv-ci:07048b8
credentials:
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_PASSWORD }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
# bumped from 1 (ersatztv#190 default) so the #420 revalidate step's `HEAD^2` tree
# comparison can resolve on a main merge commit.
fetch-depth: 2
# ersatztv#416: docs-only? Skip the boot + curl harness (advisory job; safe to no-op).
- name: Detect docs-only changes
id: detect
run: scripts/ci-detect-docs-only.sh
- name: Detect already-validated tree (#420)
id: revalidate
env:
ETV_STATUS_AUTH: ${{ secrets.REGISTRY_USER }}:${{ secrets.REGISTRY_PASSWORD }}
run: scripts/ci-detect-already-validated.sh
- name: Cache NuGet packages
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
uses: actions/cache@v4
with:
path: ~/.nuget/packages
key: nuget-${{ runner.os }}-${{ hashFiles('Directory.Packages.props', 'global.json') }}
restore-keys: nuget-${{ runner.os }}-
- name: Restore
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
run: dotnet restore
- name: Cache npm packages
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
uses: actions/cache@v4
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('web/package-lock.json') }}
restore-keys: npm-${{ runner.os }}-
- name: Install SPA dependencies
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
working-directory: web
run: npm ci
- name: Build SPA
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
working-directory: web
run: npm run build
- name: Build (Release)
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
run: dotnet build ErsatzTV.sln --configuration Release --no-restore
# The old `command -v ffmpeg || sudo apt-get install ffmpeg` step is gone (ersatztv#390):
# the toolchain image ships the same ffmpeg build prod runs, so the binary is already here.
# That step also cost 110s of every run. The harness never *transcodes*, but since ersatztv#363
# it does use ffmpeg to synthesize ~60 tiny testsrc clips to seed the scan-lock 409 flow (and
# python3's stdlib sqlite3 to seed the DB rows the API can't create) — both already present in
# the image, so still no per-run install. The scan flow self-skips if ffmpeg is ever absent.
- name: Boot instance and run functional-E2E harness
if: steps.detect.outputs.docs_only != 'true' && steps.revalidate.outputs.skip != 'true'
run: |
set -euo pipefail
export ETV_BUILD_CONFIG=Release ETV_UI_PORT=8409
CFG="$(mktemp -d)"
# e2e-local.sh copies wwwroot, launches the DLL in the background (logging to a file, so
# this command substitution returns as soon as the app is ready), and prints PID/CONFIG_DIR.
OUT="$(scripts/e2e-local.sh "$CFG")"
printf '%s\n' "$OUT"
PID="$(printf '%s\n' "$OUT" | awk -F= '/^PID=/{print $2}')"
trap 'kill "$PID" 2>/dev/null || true' EXIT
scripts/e2e-functional.sh "http://localhost:${ETV_UI_PORT}" "$CFG"
build:
name: Build & push image (amd64)
# `small` = the dedicated small-jobs runner lane (server-management#574).
# On PR runs this job only resolves its skip, but Gitea still dispatches it
# as a task — on the ubuntu-latest runners that skip queued behind long
# builds (observed 31 min). Real builds (main/tags) run on bumblebee,
# capped at 4 CPUs / 10g.
runs-on: small
runs-on: ubuntu-latest
needs: [test, migrations]
if: github.event_name != 'pull_request'
steps:
@@ -510,16 +170,8 @@ jobs:
with:
fetch-depth: 0
# ersatztv#416: a docs-only push to main has nothing to rebuild (docs are not in the image),
# so skip the build/push/smoke steps — the job still reports success. Tag builds force
# docs_only=false in the script, so a release is never skipped.
- name: Detect docs-only changes
id: detect
run: scripts/ci-detect-docs-only.sh
- name: Compute version and tags
id: meta
if: steps.detect.outputs.docs_only != 'true'
run: |
SHORT=$(git rev-parse --short HEAD)
if [ "${GITHUB_REF_TYPE}" = "tag" ]; then
@@ -542,7 +194,6 @@ jobs:
printf 'tag: %s\n' "${TAGS[@]}"
- name: Set up Docker Buildx
if: steps.detect.outputs.docs_only != 'true'
uses: docker/setup-buildx-action@v3
with:
buildkitd-config-inline: |
@@ -550,7 +201,6 @@ jobs:
http = true
- name: Login to Gitea registry
if: steps.detect.outputs.docs_only != 'true'
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
@@ -558,7 +208,6 @@ jobs:
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: Build and push
if: steps.detect.outputs.docs_only != 'true'
uses: docker/build-push-action@v6
with:
context: .
@@ -574,16 +223,14 @@ jobs:
cache-to: type=registry,ref=192.168.1.95:3000/timothy/ersatztv:buildcache,mode=max,ignore-error=true
- name: Smoke + IPTV E2E (assert key endpoints)
if: ${{ (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) && steps.detect.outputs.docs_only != 'true' }}
if: ${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') }}
run: |
IMG="${IMAGE}:${{ steps.meta.outputs.short }}"
NAME="etv-smoke-${{ github.run_id }}"
trap 'docker rm -f "$NAME" >/dev/null 2>&1 || true' EXIT
echo "Pulling ${IMG}"
docker pull "$IMG"
# --memory-swap equal to --memory disables swap. Without it Docker defaults --memory-swap
# to 2x --memory, so `--memory 2g` alone silently grants 2g RAM + 2g swap (ersatztv#406).
docker run -d --name "$NAME" --memory 2g --memory-swap 2g \
docker run -d --name "$NAME" --memory 2g \
-e ETV_CONFIG_FOLDER=/tmp/etv/config \
-e ETV_TRANSCODE_FOLDER=/tmp/etv/transcode \
"$IMG"
@@ -633,280 +280,3 @@ jobs:
echo "===== container logs (tail) ====="; docker logs "$NAME" 2>&1 | tail -n 40 || true
exit 1
fi
# BLOCKING (ersatztv#390): the CI toolchain image pin in this file must name the image that
# ci-image.yml actually last published — i.e. the short sha of the last commit to touch the image's
# sources. Without this detector, a PR that edits docker/ci/** publishes a NEW image but runs its own
# jobs against the OLD pin: CI green-lights a toolchain it never executed, and once merged, main's
# Dockerfile silently disagrees with what CI runs. **Renovate actively generates exactly that PR** —
# it manages docker/ci/Dockerfile's base pins (dockerfile manager) but cannot bump an opaque
# `:<sha>` in `container.image`, so it would leave the pin behind every time.
#
# Failing here forces the documented two-step (docs/ci-cd.md -> "CI toolchain image"): push the
# Dockerfile change, let ci-image.yml publish `:<sha>`, then update the pin to that sha. Seconds-long
# git+grep -> keep it off the build runners.
ci-image-pin:
name: CI image pin matches docker/ci
runs-on: small
if: github.event_name == 'pull_request'
steps:
- name: Checkout
uses: actions/checkout@v4
with:
# need real history: `git log -- <path>` on a shallow clone can't find the last
# commit that touched the image sources
fetch-depth: 0
- name: Verify the pin matches the last-published image
run: |
set -euo pipefail
# ci-image.yml tags the image `git rev-parse --short HEAD` of the push that built it, and it
# only builds on pushes touching these paths — so the published image is named by the last
# commit to touch them.
#
# Compare RESOLVED FULL shas, never the abbreviations: git auto-scales abbreviation length
# with the repo's object count, so the tag built in CI from a `fetch-depth: 1` shallow clone
# is 7 chars while `%h` here (full clone) is 8. Comparing those strings would fail always.
expected="$(git log -1 --format=%H -- docker/ci .gitea/workflows/ci-image.yml)"
mapfile -t pins < <(grep -oE 'ersatztv-ci:[0-9a-f]+' .gitea/workflows/docker-build.yml | cut -d: -f2 | sort -u)
echo "Image sources last changed in: ${expected}"
echo "Pins found in docker-build.yml: ${pins[*]} (${#pins[@]} distinct)"
if [ "${#pins[@]}" -ne 1 ]; then
echo "::error::docker-build.yml pins MORE THAN ONE ersatztv-ci tag (${pins[*]}). All jobs must pin the same image — bump them together."
exit 1
fi
pin_full="$(git rev-parse --verify --quiet "${pins[0]}^{commit}" || true)"
if [ -z "$pin_full" ]; then
echo "::error::The pinned CI image tag ersatztv-ci:${pins[0]} does not resolve to a commit in this repo, so it cannot correspond to an image ci-image.yml built from these sources. Rebuild the image and pin the sha it prints."
exit 1
fi
if [ "$pin_full" != "$expected" ]; then
echo "::error::CI toolchain image pin is stale: docker-build.yml pins ersatztv-ci:${pins[0]} ($pin_full), but docker/ci was last changed in $expected. Your jobs are testing an image that is NOT built from this PR's docker/ci. Let ci-image.yml publish the new :<sha>, then update the pin in ALL jobs to it (docs/ci-cd.md -> 'CI toolchain image')."
exit 1
fi
echo "Pin is current: ersatztv-ci:${pins[0]} resolves to $pin_full = docker/ci's last change."
# Non-blocking nudge: if a PR migrates/adds a route but forgets the parity tracker, warn.
# The rule lives in CLAUDE.md → Conventions; this only surfaces an easy-to-miss omission.
# Deliberately no setup-dotnet/setup-node (and thus no actions/cache) so it can't hit the
# cache-save issues seen on the relocated runner (server-management#570).
docs-reminder:
name: Docs update reminder
runs-on: small # seconds-long git diff; keep it off the build runners
if: github.event_name == 'pull_request'
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Warn when a screen/route change skips the parity doc
run: |
base_ref="${{ github.base_ref }}"
git fetch --no-tags --depth=100 origin "$base_ref" || true
changed="$(git diff --name-only "origin/${base_ref}...HEAD" 2>/dev/null || true)"
echo "Changed files in this PR:"; printf '%s\n' "$changed"
screen_or_route=no
if printf '%s\n' "$changed" | grep -Eq '^web/src/screens/.+\.tsx$|^ErsatzTV/LegacyUiRedirects\.cs$'; then
screen_or_route=yes
fi
parity=no
if printf '%s\n' "$changed" | grep -qx 'docs/blazor-route-parity.md'; then
parity=yes
fi
if [ "$screen_or_route" = yes ] && [ "$parity" = no ]; then
echo "::warning::This PR touches a SPA screen or LegacyUiRedirects.cs but does not update docs/blazor-route-parity.md. If you added/migrated/redirected a route, update the parity tracker (and docs/domain-model.md) in THIS PR — see CLAUDE.md → Conventions."
else
echo "Parity-doc reminder: nothing to flag."
fi
# BLOCKING (ersatztv#303 H9): docs/decisions.md is an append-only log. Fails a PR that deletes or
# rewrites a settled entry (numstat reports >0 deleted lines) unless a commit in the range carries
# the [decisions-edit] override token for a documented factual fix. Same script the Husky commit-msg
# hook calls, so local and CI enforcement can't drift. Seconds-long git diff -> keep it off the build runners.
decisions-guard:
name: decisions.md append-only
runs-on: small
if: github.event_name == 'pull_request'
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Enforce append-only
run: |
base_ref="${{ github.base_ref }}"
git fetch --no-tags --depth=200 origin "$base_ref" || true
./.claude/hooks/decisions-guard.sh range "origin/${base_ref}" HEAD
- name: Consolidation-floor reminder (non-blocking)
run: |
# Consolidation is primarily a release step; this is the between-releases floor. The metric is
# the file's LINE COUNT — the context an agent actually burns reading the log — not entry count.
# Floor 1800 keeps the whole log inside one default 2000-line Read (headroom for the reader's
# own overhead). Nudge (never fail) past it so append-only can't grow past what agents can read.
n=$(wc -l < docs/decisions.md | tr -d ' ')
echo "docs/decisions.md is ${n} lines (consolidation floor: 1800; one Read caps at 2000)."
if [ "${n:-0}" -gt 1800 ]; then
echo "::warning::docs/decisions.md is ${n} lines (>1800) — larger than agents can comfortably read in one pass. Do a consolidation pass (prune/merge superseded entries with [decisions-edit]); don't wait for the next release. See the decisions.md header."
fi
# BLOCKING (unlike docs-reminder): the mechanizable half of the "docs-update in the
# same PR" rule for the API contract (ersatztv#303 H4/H5). If a PR touches the API
# surface (ErsatzTV/Controllers/Api/** or ErsatzTV.Core/Api/**), the generated
# artifacts — v1.json (OpenAPI spec), v1.d.ts (SPA client), endpoint-index.md — MUST
# already be regenerated in the diff. We rebuild them from source and fail on any drift.
# Also covers the "regenerate artifacts after merging main into a PR branch" lore bullet.
#
# Path-gated INSIDE the job (not via top-level `if:`) so the check always reports a
# status on every PR and can be a required check without stalling API-free PRs: when no
# API path changed, the expensive steps skip and the job passes trivially.
api-docs:
name: API docs in sync (OpenAPI + endpoint index)
# `small` lane (ersatztv#390): this job is ~5s on the ~90% of PRs that touch no API path, but
# it was queueing ~29 min behind the heavy jobs in the contended `ubuntu-latest` lane, which
# only has bumblebee-runner (capacity 2) + ci-runner. `small` has capacity 4, the same base
# image, and answers in ~5s. Moving it here (and `format`) also drops `ubuntu-latest` from 5
# jobs to 3, which shortens the queue for `test`/`migrations`/`functional-e2e` too.
# This is only possible because `container:` makes the job self-contained — it no longer needs
# the runner image to supply .NET/Node.
#
# REVERTED to `ubuntu-latest` (server-management#604 / ersatztv#406). The caveat below the
# original #390 rationale turned out to be the deciding factor: on an API-touching PR this
# job does a full `dotnet build`, so it is NOT a small job, and "capacity 4 absorbs that" was
# only true while nothing enforced the SUM of the lanes' memory caps. It didn't: 6 slots x 10g
# on a 25 GiB host drove bumblebee to load 713 with 21 GiB swapped. The `small` lane is now
# sized for genuinely-tiny jobs, and #604 grew the `ubuntu-latest` lane instead (ci-runner
# 48 GiB at capacity 4 + a bumblebee overflow slot), which fixes the queue at the source.
runs-on: ubuntu-latest
container:
image: 192.168.1.95:3000/timothy/ersatztv-ci:07048b8
credentials:
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_PASSWORD }}
if: github.event_name == 'pull_request'
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Detect API-surface changes
id: detect
run: |
base_ref="${{ github.base_ref }}"
git fetch --no-tags --depth=100 origin "$base_ref" || true
changed="$(git diff --name-only "origin/${base_ref}...HEAD" 2>/dev/null || true)"
echo "Changed files in this PR:"; printf '%s\n' "$changed"
if printf '%s\n' "$changed" | grep -Eq '^ErsatzTV/Controllers/Api/|^ErsatzTV\.Core/Api/'; then
echo "api_changed=true" >> "$GITHUB_OUTPUT"
echo "API surface changed -> will verify generated artifacts are in sync."
else
echo "api_changed=false" >> "$GITHUB_OUTPUT"
echo "No API-surface change -> skipping regeneration (job passes)."
fi
- name: Cache NuGet packages
if: steps.detect.outputs.api_changed == 'true'
uses: actions/cache@v4
with:
path: ~/.nuget/packages
key: nuget-${{ runner.os }}-${{ hashFiles('Directory.Packages.props', 'global.json') }}
restore-keys: nuget-${{ runner.os }}-
- name: Restore
if: steps.detect.outputs.api_changed == 'true'
run: dotnet restore
- name: Cache npm packages
if: steps.detect.outputs.api_changed == 'true'
uses: actions/cache@v4
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('web/package-lock.json') }}
restore-keys: npm-${{ runner.os }}-
- name: Install SPA dependencies
if: steps.detect.outputs.api_changed == 'true'
working-directory: web
run: npm ci
- name: Regenerate OpenAPI spec + endpoint index
if: steps.detect.outputs.api_changed == 'true'
run: ./scripts/update-openapi.sh
- name: Regenerate SPA API client types
if: steps.detect.outputs.api_changed == 'true'
working-directory: web
run: npm run generate:api
- name: Fail on stale generated artifacts
if: steps.detect.outputs.api_changed == 'true'
run: |
if ! git diff --exit-code -- \
ErsatzTV/wwwroot/openapi/v1.json \
web/src/api/generated/v1.d.ts \
docs/endpoint-index.md; then
echo "::error::This PR changes the API surface but its generated artifacts are stale. Run './scripts/update-openapi.sh && (cd web && npm run generate:api)' and commit v1.json / v1.d.ts / endpoint-index.md in THIS PR (CLAUDE.md → Conventions; ersatztv#303 H4/H5)."
exit 1
fi
echo "Generated API artifacts are in sync."
# Formatting-as-you-touch gate (ersatztv#311): verify the .cs files THIS PR changed conform to
# .editorconfig whitespace + charset=utf-8 (i.e. no UTF-8 BOM). Scoped to changed files so it
# enforces "normalize a legacy file when you touch it" WITHOUT a big-bang reformat of the ~2500
# pre-existing BOM files. A PR that touches no .cs skips the check and passes trivially (always
# reports a status, so it is safe as a required check).
#
# ersatztv#469: uses `dotnet format whitespace . --folder`, NOT the full `dotnet format <sln>`.
# `--folder` treats the tree as a plain folder of files and skips the MSBuild/Roslyn workspace load
# + per-project compilation that dominated the old recipe (~8 min locally on a whole-solution run) —
# `--include` only ever narrowed *which* files were checked, never what got loaded. Folder mode
# reads .editorconfig and still flags WHITESPACE (indent/EOL/trailing/final-newline) and CHARSET
# (BOM) violations — exactly what this gate exists to catch — in ~0.5s with no `dotnet restore`.
# What it drops is the style/analyzer pass (naming/`var`/qualification), which this gate never
# meaningfully enforced: those .editorconfig rules are :suggestion/:none severity. Full rationale +
# non-vacuity evidence: docs/ci-cd.md → Formatting; docs/decisions.md.
format:
name: Formatting (changed .cs conform to .editorconfig)
# Folder-mode whitespace is now a seconds-long, low-memory job (no Roslyn workspace, unlike the
# 3.95 GiB full `dotnet format` measured in #406), so it no longer needs the memory headroom that
# kept it on `ubuntu-latest`. Left here to avoid re-touching the lane/memory-cap accounting; a
# move to a lighter lane is a server-management capacity call (#604).
runs-on: ubuntu-latest
container:
image: 192.168.1.95:3000/timothy/ersatztv-ci:07048b8
credentials:
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_PASSWORD }}
if: github.event_name == 'pull_request'
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Detect changed C# files
id: detect
run: |
base_ref="${{ github.base_ref }}"
git fetch --no-tags --depth=100 origin "$base_ref" || true
changed="$(git diff --name-only --diff-filter=ACM "origin/${base_ref}...HEAD" -- '*.cs' 2>/dev/null || true)"
echo "Changed .cs files in this PR:"; printf '%s\n' "$changed"
if [ -n "$changed" ]; then
printf '%s\n' "$changed" > /tmp/changed-cs.txt
echo "cs_changed=true" >> "$GITHUB_OUTPUT"
echo "-> will verify these files conform to .editorconfig."
else
echo "cs_changed=false" >> "$GITHUB_OUTPUT"
echo "No .cs change -> skipping format verify (job passes)."
fi
- name: Verify formatting of changed .cs files
if: steps.detect.outputs.cs_changed == 'true'
shell: bash
run: |
mapfile -t files < /tmp/changed-cs.txt
echo "Verifying ${#files[@]} changed .cs file(s) against .editorconfig (whitespace + charset)..."
if ! dotnet format whitespace . --folder --verify-no-changes --include "${files[@]}"; then
echo "::error::One or more .cs files this PR touches don't conform to .editorconfig (whitespace or a UTF-8 BOM). Run 'dotnet format whitespace . --folder --include <files>' (or the full 'dotnet format ErsatzTV.sln --include <files>') and commit the result in THIS PR — the fix-as-you-touch convention (docs/contributing.md §7; ersatztv#311). Legacy files you did NOT touch are unaffected."
exit 1
fi
echo "All changed .cs files conform to .editorconfig."
+1 -10
View File
@@ -2,8 +2,6 @@
*.*~
project.lock.json
.DS_Store
# Code-coverage output (dotnet test --results-directory ./coverage, ersatztv#15)
/coverage/
*.pyc
.worktrees/
@@ -56,11 +54,4 @@ docker-compose.override.yml
ErsatzTV/wwwroot/v2/
ErsatzTV/wwwroot/app/
web/dist/
web/node_modules
# E2E / screenshot scratch (from Playwright/live-E2E runs) — never committed
/*.png
.playwright-mcp/
# Per-session worktree-ownership marker (H7, ersatztv#303) — local, never committed
.claude-worktree-owner
web/node_modules/
-15
View File
@@ -1,15 +0,0 @@
# Enforce the CLAUDE.md protocol: every commit message must carry a Co-Authored-By
# trailer. Merge commits are exempt (their MERGE_MSG has no trailer and shouldn't be
# rewritten).
if git rev-parse -q --verify MERGE_HEAD >/dev/null 2>&1; then
exit 0
fi
grep -q '^Co-Authored-By:' "$1" || {
echo 'husky - commit message missing Co-Authored-By trailer'
exit 1
}
# H9 (ersatztv#303) — docs/decisions.md is append-only. Block a commit that rewrites a settled
# entry unless the message carries [decisions-edit]. commit-msg runs after the index is final, so
# the staged diff is what's being committed; the message file ($1) supplies the override token.
./.claude/hooks/decisions-guard.sh staged "$1" || exit 1
-27
View File
@@ -1,27 +0,0 @@
cd web && npx lint-staged || exit 1
cd ..
# H3 (ersatztv#303) — never commit a screenshot dropped at the repo root. Belt-and-suspenders with
# .gitignore (catches a forced `git add -f`). Root-level *.png only; nested paths are legit assets.
root_png=$(git diff --cached --name-only --diff-filter=ACM | grep -iE '^[^/]+\.png$' || true)
if [ -n "$root_png" ]; then
echo "husky - refusing to commit root-level screenshot(s):"
printf ' %s\n' $root_png
echo " Move it out of the repo root or drop it (root *.png are review/debug artifacts; see .gitignore)."
exit 1
fi
# dotnet format on staged .cs files (repo root). Uses `whitespace . --folder` — same recipe as
# the CI `format` job (ersatztv#469): folder mode checks .editorconfig whitespace + charset (BOM)
# without the MSBuild/Roslyn workspace load, so it runs in ~0.5s instead of the old ~20-40s sln
# load. Keeping this identical to CI avoids a local hook that blocks on rules CI no longer enforces.
# Skip entirely when no .cs is staged (avoids any cost for web-only commits).
cs_files=$(git diff --cached --name-only --diff-filter=ACM -- '*.cs')
if [ -n "$cs_files" ]; then
echo "husky - dotnet format (whitespace verify) on staged .cs files"
# shellcheck disable=SC2086
dotnet format whitespace . --folder --verify-no-changes --include $cs_files || {
echo "husky - dotnet format found whitespace/BOM issues in staged .cs files; run 'dotnet format whitespace . --folder --include <files>' to fix"
exit 1
}
fi
-28
View File
@@ -1,28 +0,0 @@
# H6 merge-consent backstop (ersatztv#303): gate a direct push to main on the linked issue's
# ## Done-when checklist. Read git's pre-push ref lines FIRST (before the web checks below, which
# may consume stdin) and forward them. Fail-open: no creds / not main / docs-only -> allow.
_prepush_refs="$(cat)"
printf '%s\n' "$_prepush_refs" | ./.claude/hooks/prepush-donewhen.sh || exit 1
# Git exports GIT_DIR/GIT_WORK_TREE/GIT_INDEX_FILE while running hooks. In a worktree
# (or any subdir), an explicit GIT_DIR makes nested `git` commands mislocate the working
# tree — notably `check:api`'s `git diff --exit-code` (run from web/) silently reports "no
# diff" and lets drift through. Unset them so nested git rediscovers the repo normally.
unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE
# H11 (ersatztv#311): refuse to push a branch that is BEHIND origin/main — rebase, don't merge
# main in (a merge drags in files you never touched, e.g. legacy-BOM .cs, and trips the format
# hook on code that isn't yours). Fail-open; escape with ETV_SKIP_REBASE_CHECK=1.
./.claude/hooks/prepush-rebase-check.sh || exit 1
# H13 (ersatztv#416 session): refuse to push when a file in the pushed diff still has uncommitted
# working-tree/index changes — the pushed commit wouldn't match what you built/reviewed (the #416
# index/worktree trap: a review fix left in the working tree shipped without being committed).
# Runs before the slow CI-parity checks so it fails fast. Fail-open; escape ETV_ALLOW_DIRTY_PUSH=1.
./.claude/hooks/prepush-clean-worktree-check.sh || exit 1
# CI-parity checks: catch "green locally, red in CI" before the push leaves the machine.
# check:api guards the generated OpenAPI types (v1.json / v1.d.ts drift); the full
# lint/typecheck/build catch a staged change that breaks an UNstaged file (lint-staged
# only sees staged files).
cd web && npm run check:api && npm run lint && npm run typecheck && npm run build
+6 -24
View File
@@ -5,7 +5,7 @@ Custom IPTV channel server for Jellyfin. Forked from [ErsatzTV/ErsatzTV](https:/
## Architecture
- **Language**: C# / .NET 10
- **UI**: ChicoryTV React SPA (`web/`, Vite, served at `/app`) over the REST API — the ONLY UI. The legacy Blazor Server UI (MudBlazor) was removed in #91 phase (b); root `/` and every legacy route now 302 to `/app`, either via an explicit redirect in `ErsatzTV/LegacyUiRedirects.cs` or the Startup catch-all fallback (any unmatched non-`/api`/`/artwork`/`/docs`/`/openapi` path → `/app`). Historical parity work: media detail pages + image folder browser landed via #141 (PR #183); scheduling parity #144/#162, #141/#158/#161/#180, #145, #151/#152/#153/#155, and the media-source write API/SPA #202 are all DONE.
- **UI**: ChicoryTV React SPA (`web/`, Vite, served at `/app`) over the REST API — the default UI; root `/` and migrated legacy routes 302 there (`ErsatzTV/LegacyUiRedirects.cs`). The legacy Blazor Server UI (MudBlazor) still serves un-migrated admin screens (collections, media browse, trakt, filler, watermarks, ffmpeg profiles, blocks/decos/templates, playout editors, logs, troubleshooting; Blazor home = `/system/health`); its removal is #91 phase (b), gated on parity issues #140#147
- **Pattern**: CQRS via MediatR — queries/commands in `ErsatzTV.Application/`
- **Database**: EF Core (SQLite default, MySQL optional) — context in `ErsatzTV.Infrastructure/Data/TvContext.cs`
- **Media**: FFmpeg via CliWrap, SkiaSharp for logo generation
@@ -15,7 +15,7 @@ Custom IPTV channel server for Jellyfin. Forked from [ErsatzTV/ErsatzTV](https:/
| Project | Role |
|---------|------|
| `ErsatzTV/` | ASP.NET Core host, API controllers, SPA static hosting, DI setup |
| `ErsatzTV/` | ASP.NET Core host, API controllers, SPA static hosting, legacy Blazor pages, DI setup |
| `web/` | ChicoryTV React SPA (Vite + TypeScript; builds into `ErsatzTV/wwwroot/app`) |
| `ErsatzTV.Application/` | MediatR handlers (business logic) |
| `ErsatzTV.Core/` | Domain entities, interfaces, no infrastructure deps |
@@ -35,10 +35,10 @@ Custom IPTV channel server for Jellyfin. Forked from [ErsatzTV/ErsatzTV](https:/
## Deployment
- **Docker host**: **jazz (192.168.1.29)**, container `ersatztv`, port 8409. Media transcoders (Jellyfin, `ersatztv`, `ersatztv-test`) moved here from bumblebee on 2026-07-20 (server-management#633); bumblebee (192.168.1.99) still hosts the **CI runners** and the rest of the stacks. **Name-reuse trap**: `jazz` was an *earlier* name for the .99 host, so pre-2026-07-20 docs/commits saying "jazz" mean today's **bumblebee** — go by the IP, not the name.
- **Docker host**: jazz (192.168.1.99), container `ersatztv`, port 8409
- **Config volume**: `~/downloadswarm/ersatztv/` on jazz → `/config` in container
- **SQLite DB**: `/config/ersatztv.sqlite3` (WAL mode, root-owned)
- **Images** (our fork, built by `.gitea/workflows/docker-build.yml``192.168.1.95:3000/timothy/ersatztv`): push to `main``:latest` + `:<sha>` (test image); push `v*` tag → `:prod` + `:<version>` + `:<sha>`. Prod's **Komodo GitOps** `media-servers` stack follows floating `:prod`; after the immutable `:<version>` candidate passes the release scans, manually deploy the stack (Global Auto Update is the daily fallback). Both paths run the fail-closed pre-deploy backup and prod-copy migration smoke before recreation. Test tracks `:latest`. Pipeline details: `docs/ci-cd.md`.
- **Images** (our fork, built by `.gitea/workflows/docker-build.yml``192.168.1.95:3000/timothy/ersatztv`): push to `main``:latest` + `:<sha>` (test image); push `v*` tag → `:prod` + `:<version>` + `:<sha>`. Prod deploys via **Komodo GitOps**: the `media-servers` compose in `timothy/server-management` (`docker/bumblebee/stacks/media-servers/compose.yaml`) pins the version tag (currently `26.5.0`, deployed 2026-07-07); releasing = tag here, wait for the image build, bump that pin and push (the Komodo pre-deploy hook backs up before recreating). Test container tracks `:latest`. Pipeline details: `docs/ci-cd.md`.
## Development
@@ -55,22 +55,10 @@ docker build -f docker/Dockerfile -t ersatztv:dev .
## Conventions
- **Read [`docs/contributing.md`](docs/contributing.md)** before non-trivial changes — it documents the established patterns (layering, CQRS handlers, LanguageExt, the ChicoryTV SPA, EF Core + dual-provider migrations, the FFmpeg pipeline, analyzers, testing) and the **deviation policy**: match the established style; diverge only with a concrete, stated reason.
- **Docs-first is a HARD RULE — read before you explore**: before ANY API / SPA / E2E / parity / scheduling work, read `docs/README.md` (index) → the convention docs (`api-conventions`, `spa-conventions`, `e2e-local`, `domain-model`, `blazor-route-parity`, `decisions`). **Do NOT reverse-engineer conventions from source (Grep/Read) before reading these** — they exist precisely so you don't. Only recon the task-specific delta the docs deliberately don't freeze (a merged endpoint's exact DTO, a Blazor page's field list). **This applies to delegated subagents too**: tell each agent which doc section to read; never let one re-derive conventions from code.
- **Docs-update is part of "done" — same PR, never a follow-up**: any PR that changes a convention, adds/migrates/redirects a route, adds/changes a `/api/*` endpoint, or reverses a decision MUST update the relevant doc in that same PR:
| Change | Update in the same PR |
|---|---|
| Migrate / add / redirect a route (new `web/src/screens/*.tsx`, `LegacyUiRedirects.cs`) | `docs/blazor-route-parity.md` + `docs/domain-model.md` |
| Add / change a `/api/*` endpoint | `docs/api-conventions.md` checklist, then regenerate `v1.json` + `endpoint-index.md` via `./scripts/update-openapi.sh` |
| Change a SPA screen convention | `docs/spa-conventions.md` |
| Establish / reverse a convention or decision | `docs/decisions.md` (append-only) + the affected doc |
| Add / remove / retitle a doc | `docs/README.md` index |
The `docs-reminder` CI job flags a screen/route change that skips `blazor-route-parity.md`, but it's a **non-blocking** nudge — the rule is on you, not the check.
- **Read [`docs/contributing.md`](docs/contributing.md)** before non-trivial changes — it documents the established patterns (layering, CQRS handlers, LanguageExt, Blazor/MudBlazor, EF Core + dual-provider migrations, the FFmpeg pipeline, analyzers, testing) and the **deviation policy**: match the established style; diverge only with a concrete, stated reason.
- Follow existing MediatR CQRS pattern for new features
- Domain logic in `ErsatzTV.Core`, infrastructure in `ErsatzTV.Infrastructure`
- Keep UI thin: the SPA talks to `/api/*` only; controllers delegate to MediatR handlers. All UI is in the SPA (`web/`)
- Keep UI thin: the SPA talks to `/api/*` only; legacy Blazor pages delegate to MediatR handlers. New screens go in the SPA (`web/`), never in Blazor
- Test with **NUnit** + Shouldly + NSubstitute (the existing `*.Tests` projects); xUnit is **not** used here
- **Dependencies use Central Package Management**: versions live in the repo-root `Directory.Packages.props`; csproj reference packages by name only. Add/upgrade by editing the central `<PackageVersion>` — never put `Version=` back on a `<PackageReference>` (trips `NU1008`). See `docs/ci-cd.md` → Dependency management.
- **DB migrations target BOTH providers**: a `TvContext` model change needs a migration in `ErsatzTV.Infrastructure.Sqlite` **and** `ErsatzTV.Infrastructure.MySql` — run `scripts/add-migration.sh <Name>` (does both). CI's `migrations` job enforces model-drift + apply-to-fresh-DB per provider. See `docs/ci-cd.md` → Migration integrity.
@@ -82,12 +70,6 @@ docker build -f docker/Dockerfile -t ersatztv:dev .
Every task that closes a Gitea issue MUST complete ALL of these before it is considered done. Use `/done <issue>` to run through this automatically.
**Merge-consent is derived from state, not asserted (`## Done-when` convention — ersatztv#303 H6 + H10).** Any issue whose PR will merge to `main` should carry a `## Done-when` section in its **issue body** — a checklist of completion criteria (always include an "adversarial review passed" box; add per-issue criteria like tests-green, docs-updated, live-E2E). Two hooks derive merge-consent from it so a premature merge is blocked *by construction*, not by memory:
- `pretooluse-merge-consent.sh` (Claude PreToolUse on the Gitea merge tool) — **auto-grants** a merge (emits `permissionDecision: allow`, so **no** redundant mechanical prompt fires) only when the PR's CI is green **and** every `## Done-when` box on the linked issue (`fixes #N`) is ticked **and** a `Review-verdict:` comment references the PR's *current head sha* (**H10**); **denies** on an unticked box, red CI, or a stale/negative review verdict; **asks** (falls back to a human prompt) when it can't derive state (no linked issue, no `## Done-when` section, no `Review-verdict:` comment yet, no creds, Gitea down). On the auto-grant (satisfied) path the derived state **is** the consent — do not also ask conversationally to merge; a separate human confirmation is warranted only when the gate **asks** (ersatztv#314). **The H10 review-verdict convention**: after an adversarial/Codex review of a PR (or its latest fix commit), post a PR comment with a line `Review-verdict: <MERGEABLE|APPROVED|BLOCKED> @ <head-sha>` — this proves the *latest* commit was reviewed, not a stale earlier diff (ersatztv#242).
- `.husky/pre-push``prepush-donewhen.sh` — a fail-open backstop that blocks a direct `git push origin main` whose commits `fix #N` an issue with unticked boxes.
Both need Gitea read creds in the env to enforce (**`ETV_GITEA_BASICAUTH=user:pass`** or `ETV_GITEA_TOKEN`; `ETV_GITEA_URL` overrides the base). Without them the merge hook asks and the push backstop is a no-op — the gate degrades to today's manual confirmation, never a silent pass. Docs-only PRs/pushes are exempt.
1. **Root cause** (bug fixes / incidents only): Document WHY the problem existed, not just what was changed. If root cause is unknown, say so explicitly and open a follow-up investigation issue. Fixing symptoms without understanding causes creates recurring problems.
2. **Comment on issues** as you work — what you found, what approach you're taking, any deviations from the suggested fix.
3. **Push changes**: `git push` all commits before closing. Use `fixes #N` in commit messages to auto-close where appropriate.
+2 -13
View File
@@ -3,12 +3,6 @@
<InformationalVersion>develop</InformationalVersion>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<AllowMissingPrunePackageData>true</AllowMissingPrunePackageData>
<!-- Analyzer posture (ersatztv#15): enable the complete SDK rule set and the
threading analyzer in every centrally managed project. The checked-in globalconfig
keeps the SDK baseline at suggestion; individually promoted rules become CI-blocking. -->
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest-All</AnalysisLevel>
<EnableThreadingAnalyzers>true</EnableThreadingAnalyzers>
<!-- NuGet audit (on by default in .NET 10) reports vulnerable transitive
packages as NU1901-1904 warnings. Several projects set
TreatWarningsAsErrors=true, which would otherwise fail `dotnet restore`
@@ -16,13 +10,8 @@
advisories to warnings (still printed in build logs); NU1904 (critical)
stays an error so criticals still block. Track fixes separately.
WarningsAsErrors promotes NU1904 in EVERY project (even those without
TreatWarningsAsErrors), so "criticals block" actually holds repo-wide.
S3981 is the first explicitly promoted analyzer rule (ersatztv#15). -->
TreatWarningsAsErrors), so "criticals block" actually holds repo-wide. -->
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903</WarningsNotAsErrors>
<WarningsAsErrors>$(WarningsAsErrors);NU1904;S3981</WarningsAsErrors>
<WarningsAsErrors>$(WarningsAsErrors);NU1904</WarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<EditorConfigFiles Include="$(MSBuildThisFileDirectory)eng/analyzers/sdk-all-suggestion.globalconfig" />
</ItemGroup>
</Project>
+10 -8
View File
@@ -1,7 +1,9 @@
<Project>
<!-- Guard on CPM so the gitignored .mcp tool, which deliberately uses inline package
versions, does not inherit a versionless analyzer PackageReference. -->
<ItemGroup Condition="'$(ManagePackageVersionsCentrally)' == 'true'">
<PropertyGroup>
<EnableThreadingAnalyzers Condition="'$(EnableThreadingAnalyzers)' == ''">false</EnableThreadingAnalyzers>
</PropertyGroup>
<ItemGroup>
<PackageReference
Include="Microsoft.VisualStudio.Threading.Analyzers"
Condition="'$(EnableThreadingAnalyzers)' == 'true'">
@@ -10,11 +12,11 @@
</PackageReference>
</ItemGroup>
<!-- Curated static-analysis packs (ersatztv#15), applied to every centrally managed project.
Versions are central (Directory.Packages.props / CPM). Guarded on CPM so the gitignored
.mcp tool (which opts out of CPM) doesn't pull versionless references. They start at
`suggestion` severity in .editorconfig so they don't fail the TreatWarningsAsErrors build;
high-value rules are promoted to warning/error incrementally. -->
<!-- Curated static-analysis packs (ersatztv#15), applied to every project. Versions are
central (Directory.Packages.props / CPM). Guarded on CPM so the gitignored .mcp tool
(which opts out of CPM) doesn't pull versionless references. They start at `suggestion`
severity in .editorconfig so they don't fail the TreatWarningsAsErrors build; high-value
rules are promoted to warning/error incrementally. -->
<ItemGroup Condition="'$(ManagePackageVersionsCentrally)' == 'true'">
<PackageReference Include="Roslynator.Analyzers">
<PrivateAssets>all</PrivateAssets>
+13 -9
View File
@@ -5,21 +5,26 @@
<ItemGroup>
<PackageVersion Include="AsyncFixer" Version="2.1.0" />
<PackageVersion Include="Blazored.FluentValidation" Version="2.2.0" />
<PackageVersion Include="BlazorSortable" Version="5.2.1" />
<PackageVersion Include="Blurhash.SkiaSharp" Version="2.0.0" />
<PackageVersion Include="CliWrap" Version="3.10.2" />
<PackageVersion Include="Chronic.Core" Version="0.4.0" />
<PackageVersion Include="CliWrap" Version="3.10.0" />
<PackageVersion Include="coverlet.collector" Version="6.0.4" />
<PackageVersion Include="Dapper" Version="2.1.79" />
<PackageVersion Include="Dapper" Version="2.1.66" />
<PackageVersion Include="Destructurama.Attributed" Version="5.2.0" />
<PackageVersion Include="EFCore.BulkExtensions" Version="[9.0.2,10)" />
<PackageVersion Include="EFCore.BulkExtensions.MySql" Version="[9.0.2,10)" />
<PackageVersion Include="EFCore.BulkExtensions.Sqlite" Version="[9.0.2,10)" />
<PackageVersion Include="Elastic.Clients.Elasticsearch" Version="9.3.0" />
<PackageVersion Include="EntityFrameworkProfiler.Appender" Version="6.0.6053" />
<PackageVersion Include="EntityFrameworkProfiler.Appender" Version="6.0.6049" />
<PackageVersion Include="FluentValidation" Version="12.1.1" />
<PackageVersion Include="FluentValidation.AspNetCore" Version="11.3.1" />
<PackageVersion Include="Flurl" Version="4.0.0" />
<PackageVersion Include="Hardware.Info" Version="101.1.1.1" />
<PackageVersion Include="Humanizer.Core" Version="3.0.10" />
<PackageVersion Include="Heron.MudCalendar" Version="3.4.0" />
<PackageVersion Include="HtmlSanitizer" Version="9.0.892" />
<PackageVersion Include="Humanizer.Core" Version="3.0.1" />
<PackageVersion Include="Jint" Version="4.5.0" />
<PackageVersion Include="JsonSchema.Net" Version="9.0.0" />
<PackageVersion Include="LanguageExt.Core" Version="4.4.9" />
@@ -28,17 +33,14 @@
<PackageVersion Include="Lucene.Net" Version="4.8.0-beta00017" />
<PackageVersion Include="Lucene.Net.Analysis.Common" Version="4.8.0-beta00017" />
<PackageVersion Include="Lucene.Net.QueryParser" Version="4.8.0-beta00017" />
<PackageVersion Include="Markdig" Version="0.44.0" />
<PackageVersion Include="MediatR" Version="[12.5.0]" />
<PackageVersion Include="MediatR.Courier.DependencyInjection" Version="5.0.0" />
<PackageVersion Include="Meziantou.Analyzer" Version="3.0.115" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.2" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="10.0.2" />
<PackageVersion Include="Microsoft.Extensions.Identity.Core" Version="10.0.2" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="10.0.2" />
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.2" />
<!-- Direct-pin over the 2.0.0 transitive (from Microsoft.AspNetCore.OpenApi + Scalar.AspNetCore):
2.0.0 is GHSA-v5pm-xwqc-g5wc (High — stack overflow parsing a circular $ref). Fixed in 2.7.5.
Referenced directly in ErsatzTV.csproj so the override actually resolves (CPM). See ersatztv#314/#8. -->
<PackageVersion Include="Microsoft.OpenApi" Version="2.7.5" />
<PackageVersion Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="10.0.2" />
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="[9.0.12,10)" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="[9.0.12,10)" />
@@ -59,6 +61,8 @@
<PackageVersion Include="Microsoft.IO.RecyclableMemoryStream" Version="3.0.1" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.14.15" />
<PackageVersion Include="MudBlazor" Version="8.15.0" />
<PackageVersion Include="NaturalSort.Extension" Version="4.4.1" />
<PackageVersion Include="NCalcSync" Version="6.3.2" />
<PackageVersion Include="NetArchTest.eNhancedEdition" Version="1.4.5" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.4" />
@@ -1,5 +1,5 @@
using System.Net;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Images;
namespace ErsatzTV.Application.Artworks;
@@ -11,14 +11,7 @@ public record ArtworkContentTypeModel(string Path, string ContentType)
public bool HasContentType => !string.IsNullOrWhiteSpace(ContentType);
// The artwork serve routes now sniff the content type from the stored file and no longer honor a
// client-supplied ?contentType= (issue #283 — that reflection was the stored-XSS sink), so the
// directly-usable URL is just the path.
public string UrlWithContentType => Path;
// Defense-in-depth: never persist a content type outside the image allow-list, so a value that
// slipped in via the {path, contentType} JSON DTOs can't later be reflected anywhere. The serve
// path derives the type from the file regardless; this only keeps stored metadata honest.
public ArtworkContentTypeModel Sanitized() =>
ImageContentTypes.IsAccepted(ContentType) ? this : this with { ContentType = string.Empty };
public string UrlWithContentType => string.IsNullOrWhiteSpace(ContentType)
? Path
: $"{Path}?contentType={WebUtility.UrlEncode(ContentType)}";
}
@@ -9,5 +9,5 @@ namespace ErsatzTV.Application.Artworks;
/// landing it in the same on-disk cache the Blazor UI uses (via <c>IImageCache</c>),
/// so the returned path is equivalent to a Blazor-uploaded image.
/// </summary>
public record UploadArtwork(Stream Stream, ArtworkKind ArtworkKind)
public record UploadArtwork(Stream Stream, string ContentType, ArtworkKind ArtworkKind)
: IRequest<Either<BaseError, ArtworkUploadResponseModel>>;
@@ -1,13 +1,22 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Artwork;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Images;
using ErsatzTV.Core.Interfaces.Images;
namespace ErsatzTV.Application.Artworks;
public class UploadArtworkHandler : IRequestHandler<UploadArtwork, Either<BaseError, ArtworkUploadResponseModel>>
{
// png/jpeg/gif/webp are all decoded by SkiaSharp and read by FFmpeg, matching the
// formats the Blazor logo/watermark upload already accepts. Format expansion is ersatztv#66.
private static readonly System.Collections.Generic.HashSet<string> AcceptedContentTypes = new(StringComparer.OrdinalIgnoreCase)
{
"image/png",
"image/jpeg",
"image/gif",
"image/webp"
};
private readonly IImageCache _imageCache;
public UploadArtworkHandler(IImageCache imageCache) => _imageCache = imageCache;
@@ -16,31 +25,15 @@ public class UploadArtworkHandler : IRequestHandler<UploadArtwork, Either<BaseEr
UploadArtwork request,
CancellationToken cancellationToken)
{
// Buffer the upload so we can sniff its true format before storing it. The request body is
// already bounded by the Kestrel MaxRequestBodySize / the controller's size check, so this
// is a bounded read.
byte[] bytes;
await using (var buffer = new MemoryStream())
{
await request.Stream.CopyToAsync(buffer, cancellationToken);
bytes = buffer.ToArray();
}
// Derive the content type from the actual bytes, never from the client-declared value
// (issue #283 — a spoofed image/png header let a <script> payload be stored and later served
// as HTML). A payload that isn't a supported raster image is rejected here.
Option<string> maybeContentType = ImageContentTypes.DetectContentType(bytes);
if (maybeContentType.IsNone)
string contentType = (request.ContentType ?? string.Empty).Trim();
if (!AcceptedContentTypes.Contains(contentType))
{
return BaseError.New(
$"Uploaded file is not a supported image; supported types are: {string.Join(", ", ImageContentTypes.Accepted)}");
$"Unsupported image content type '{contentType}'; supported types are: {string.Join(", ", AcceptedContentTypes)}");
}
string contentType = maybeContentType.IfNone(string.Empty);
using var toCache = new MemoryStream(bytes, writable: false);
Either<BaseError, string> maybeFileName = await _imageCache.SaveArtworkToCache(
toCache,
request.Stream,
request.ArtworkKind);
return maybeFileName.Map(fileName => new ArtworkUploadResponseModel(
@@ -1,28 +0,0 @@
namespace ErsatzTV.Application.Auth;
/// <summary>
/// Shared constants for the browser-SPA session authentication (issue #295): the cookie scheme name,
/// the custom claim types the local-login path stamps onto the principal, and the auth-method marker
/// values. The web host (cookie <c>OnValidatePrincipal</c>, <c>AuthController</c>) and the Application
/// handlers both reference these so the claim contract has a single definition.
/// </summary>
public static class AuthConstants
{
/// <summary>The cookie authentication scheme name shared by local login and the OIDC callback.</summary>
public const string CookieScheme = "cookie";
/// <summary>The OIDC challenge scheme name.</summary>
public const string OidcScheme = "oidc";
/// <summary>Claim type recording how the principal signed in (<see cref="MethodLocal" /> / <see cref="MethodOidc" />).</summary>
public const string AuthMethodClaim = "etv:auth_method";
/// <summary>Claim type carrying the local admin's security stamp (checked on every request to revoke sessions).</summary>
public const string SecurityStampClaim = "etv:security_stamp";
public const string MethodLocal = "local";
public const string MethodOidc = "oidc";
/// <summary>Minimum length for a local admin password.</summary>
public const int MinPasswordLength = 8;
}
@@ -1,10 +0,0 @@
using ErsatzTV.Core;
namespace ErsatzTV.Application.Auth;
/// <summary>
/// Changes the local admin password after verifying the current one. Rotates the security stamp so all
/// other sessions are revoked. <see cref="Username" /> is the signed-in principal's name.
/// </summary>
public record ChangeLocalAdminPassword(string Username, string CurrentPassword, string NewPassword)
: IRequest<Either<BaseError, LocalAdminPrincipal>>;
@@ -1,68 +0,0 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Auth;
public class ChangeLocalAdminPasswordHandler(
IDbContextFactory<TvContext> dbContextFactory,
ILocalPasswordHasher passwordHasher)
: IRequestHandler<ChangeLocalAdminPassword, Either<BaseError, LocalAdminPrincipal>>
{
public async Task<Either<BaseError, LocalAdminPrincipal>> Handle(
ChangeLocalAdminPassword request,
CancellationToken cancellationToken)
{
foreach (BaseError error in LocalAdminHelpers.ValidatePassword(request.NewPassword))
{
return error;
}
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
List<ConfigElement> rows = await dbContext.ConfigElements
.Where(c => c.Key == ConfigElementKey.AuthLocalAdminUsername.Key
|| c.Key == ConfigElementKey.AuthLocalAdminPasswordHash.Key
|| c.Key == ConfigElementKey.AuthSecurityStamp.Key)
.ToListAsync(cancellationToken);
ConfigElement userRow = rows.Find(r => r.Key == ConfigElementKey.AuthLocalAdminUsername.Key);
ConfigElement hashRow = rows.Find(r => r.Key == ConfigElementKey.AuthLocalAdminPasswordHash.Key);
ConfigElement stampRow = rows.Find(r => r.Key == ConfigElementKey.AuthSecurityStamp.Key);
if (hashRow is null)
{
return BaseError.New("No local administrator is configured");
}
string username = (request.Username ?? string.Empty).Trim();
bool userMatches = userRow is not null
&& string.Equals(userRow.Value, username, StringComparison.OrdinalIgnoreCase);
LocalPasswordVerification result =
passwordHasher.Verify(hashRow.Value, request.CurrentPassword ?? string.Empty);
if (!userMatches || result == LocalPasswordVerification.Failed)
{
return BaseError.New("Current password is incorrect");
}
// Atomic: the new hash and rotated stamp commit together, so a crash can't leave the new password
// active with the old stamp still authorizing revoked sessions.
string stamp = LocalAdminHelpers.NewSecurityStamp();
hashRow.Value = passwordHasher.Hash(request.NewPassword);
if (stampRow is null)
{
dbContext.ConfigElements.Add(new ConfigElement { Key = ConfigElementKey.AuthSecurityStamp.Key, Value = stamp });
}
else
{
stampRow.Value = stamp;
}
await dbContext.SaveChangesAsync(cancellationToken);
return new LocalAdminPrincipal(userRow.Value, stamp);
}
}
@@ -1,9 +0,0 @@
using ErsatzTV.Core;
namespace ErsatzTV.Application.Auth;
/// <summary>
/// First-run setup-claim: creates the single local administrator. Fails if one already exists
/// (first-claim-wins), so a later anonymous call cannot take over the account.
/// </summary>
public record ClaimLocalAdmin(string Username, string Password) : IRequest<Either<BaseError, LocalAdminPrincipal>>;
@@ -1,68 +0,0 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Auth;
public class ClaimLocalAdminHandler(IDbContextFactory<TvContext> dbContextFactory, ILocalPasswordHasher passwordHasher)
: IRequestHandler<ClaimLocalAdmin, Either<BaseError, LocalAdminPrincipal>>
{
public async Task<Either<BaseError, LocalAdminPrincipal>> Handle(
ClaimLocalAdmin request,
CancellationToken cancellationToken)
{
foreach (BaseError error in LocalAdminHelpers.ValidateNewCredentials(request.Username, request.Password))
{
return error;
}
string username = request.Username.Trim();
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
// Fast path for the common already-configured case (clean 409). The real first-claim-wins guard is
// the unique index on ConfigElement.Key + the single atomic SaveChanges below: two concurrent claims
// both pass this check, but only one INSERT of the three credential rows commits — the loser's
// SaveChanges violates the unique Key index and rolls back wholesale (no mixed-state credential).
bool alreadyConfigured = await dbContext.ConfigElements
.AnyAsync(c => c.Key == ConfigElementKey.AuthLocalAdminPasswordHash.Key, cancellationToken);
if (alreadyConfigured)
{
return BaseError.New("A local administrator has already been configured");
}
string stamp = LocalAdminHelpers.NewSecurityStamp();
dbContext.ConfigElements.AddRange(
new ConfigElement { Key = ConfigElementKey.AuthLocalAdminUsername.Key, Value = username },
new ConfigElement
{
Key = ConfigElementKey.AuthLocalAdminPasswordHash.Key,
Value = passwordHasher.Hash(request.Password)
},
new ConfigElement { Key = ConfigElementKey.AuthSecurityStamp.Key, Value = stamp });
try
{
await dbContext.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateException)
{
// A write conflict here is (almost always) a lost first-claim race — a concurrent claim inserted
// these keys first (unique Key index). Confirm the row now exists on a fresh context before
// reporting "already configured"; otherwise this was a genuine/transient DB error → rethrow rather
// than mask it.
await using TvContext verifyContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
bool nowConfigured = await verifyContext.ConfigElements
.AnyAsync(c => c.Key == ConfigElementKey.AuthLocalAdminPasswordHash.Key, cancellationToken);
if (nowConfigured)
{
return BaseError.New("A local administrator has already been configured");
}
throw;
}
return new LocalAdminPrincipal(username, stamp);
}
}
@@ -1,8 +0,0 @@
namespace ErsatzTV.Application.Auth;
/// <summary>
/// The current local-admin security stamp, or <c>None</c> if no local admin is configured. The cookie
/// <c>OnValidatePrincipal</c> compares this to the principal's stamp claim on every request; a mismatch
/// (i.e. the password was changed) rejects the session.
/// </summary>
public record GetLocalAdminSecurityStamp : IRequest<Option<string>>;
@@ -1,11 +0,0 @@
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
namespace ErsatzTV.Application.Auth;
public class GetLocalAdminSecurityStampHandler(IConfigElementRepository configElementRepository)
: IRequestHandler<GetLocalAdminSecurityStamp, Option<string>>
{
public async Task<Option<string>> Handle(GetLocalAdminSecurityStamp request, CancellationToken cancellationToken) =>
await configElementRepository.GetValue<string>(ConfigElementKey.AuthSecurityStamp, cancellationToken);
}
@@ -1,27 +0,0 @@
namespace ErsatzTV.Application.Auth;
public enum LocalPasswordVerification
{
Failed,
Success,
SuccessRehashNeeded
}
/// <summary>
/// Wraps ASP.NET Core Identity's <c>PasswordHasher</c> (PBKDF2) behind a minimal, framework-agnostic
/// surface so the Auth handlers don't depend on Identity types directly.
/// </summary>
public interface ILocalPasswordHasher
{
/// <summary>Hashes a password for storage (random per-hash salt embedded in the returned string).</summary>
string Hash(string password);
/// <summary>Verifies a password against a stored hash in constant time (delegated to Identity).</summary>
LocalPasswordVerification Verify(string hash, string password);
/// <summary>
/// A stable, valid hash of a throwaway password. Verify against this when no real credential exists
/// so an unknown-username / unconfigured login costs the same as a real one (no user enumeration).
/// </summary>
string DummyHash { get; }
}
@@ -1,4 +0,0 @@
namespace ErsatzTV.Application.Auth;
/// <summary>True once a local administrator credential has been set (first-run setup is complete).</summary>
public record IsLocalAdminConfigured : IRequest<bool>;
@@ -1,15 +0,0 @@
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
namespace ErsatzTV.Application.Auth;
public class IsLocalAdminConfiguredHandler(IConfigElementRepository configElementRepository)
: IRequestHandler<IsLocalAdminConfigured, bool>
{
public async Task<bool> Handle(IsLocalAdminConfigured request, CancellationToken cancellationToken)
{
Option<ConfigElement> hash =
await configElementRepository.GetConfigElement(ConfigElementKey.AuthLocalAdminPasswordHash, cancellationToken);
return hash.IsSome;
}
}
@@ -1,49 +0,0 @@
using System.Security.Cryptography;
using ErsatzTV.Core;
namespace ErsatzTV.Application.Auth;
internal static class LocalAdminHelpers
{
public const int MaxUsernameLength = 256;
// Upper bound so an absurdly long password can't burn CPU in PBKDF2 (the request body is also capped
// by Kestrel, #283; this is defense-in-depth on the field itself).
public const int MaxPasswordLength = 1024;
/// <summary>128 bits of random, lowercase hex. Rotated on every password change to revoke sessions.</summary>
public static string NewSecurityStamp() =>
Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();
/// <summary>Validates a new username + password. Returns the error, or None if valid.</summary>
public static Option<BaseError> ValidateNewCredentials(string username, string password)
{
string trimmed = (username ?? string.Empty).Trim();
if (trimmed.Length == 0)
{
return BaseError.New("Username is required");
}
if (trimmed.Length > MaxUsernameLength)
{
return BaseError.New("Username is too long");
}
return ValidatePassword(password);
}
public static Option<BaseError> ValidatePassword(string password)
{
if (string.IsNullOrEmpty(password) || password.Length < AuthConstants.MinPasswordLength)
{
return BaseError.New($"Password must be at least {AuthConstants.MinPasswordLength} characters");
}
if (password.Length > MaxPasswordLength)
{
return BaseError.New($"Password must be at most {MaxPasswordLength} characters");
}
return Option<BaseError>.None;
}
}
@@ -1,9 +0,0 @@
namespace ErsatzTV.Application.Auth;
/// <summary>
/// The identity of the single local administrator, as returned by a successful claim / login / password
/// change. The web host turns this into a cookie principal: <see cref="Username" /> becomes the name claim
/// and <see cref="SecurityStamp" /> is stamped as <see cref="AuthConstants.SecurityStampClaim" /> so a later
/// password change (which rotates the stamp) revokes the session.
/// </summary>
public record LocalAdminPrincipal(string Username, string SecurityStamp);
@@ -1,33 +0,0 @@
using Microsoft.AspNetCore.Identity;
namespace ErsatzTV.Application.Auth;
/// <summary>
/// <see cref="ILocalPasswordHasher" /> backed by ASP.NET Core Identity's <see cref="PasswordHasher{TUser}" />
/// (PBKDF2-HMAC-SHA512, per-hash random salt, format-versioned so a future work-factor bump is a
/// transparent rehash-on-verify). Stateless and thread-safe → registered as a singleton.
/// </summary>
public sealed class LocalPasswordHasher : ILocalPasswordHasher
{
// The generic user parameter is unused by the hasher (it takes no per-user data), so a shared sentinel
// is fine.
private static readonly object Sentinel = new();
private readonly PasswordHasher<object> _hasher = new();
private readonly Lazy<string> _dummyHash;
public LocalPasswordHasher() =>
_dummyHash = new Lazy<string>(() => _hasher.HashPassword(Sentinel, "not-a-real-password"));
public string DummyHash => _dummyHash.Value;
public string Hash(string password) => _hasher.HashPassword(Sentinel, password);
public LocalPasswordVerification Verify(string hash, string password) =>
_hasher.VerifyHashedPassword(Sentinel, hash, password) switch
{
PasswordVerificationResult.Success => LocalPasswordVerification.Success,
PasswordVerificationResult.SuccessRehashNeeded => LocalPasswordVerification.SuccessRehashNeeded,
_ => LocalPasswordVerification.Failed
};
}
@@ -1,9 +0,0 @@
namespace ErsatzTV.Application.Auth;
/// <summary>
/// Rotates the local admin security stamp, revoking every outstanding local session server-side (their
/// cookies carry the old stamp and fail <c>OnValidatePrincipal</c> on their next request). Used by logout
/// so signing out actually ends the session server-side, not just client-side. A no-op when no local
/// admin is configured. OIDC sessions are unaffected (they carry no stamp).
/// </summary>
public record RotateLocalAdminSecurityStamp : IRequest<Unit>;
@@ -1,28 +0,0 @@
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Auth;
public class RotateLocalAdminSecurityStampHandler(IDbContextFactory<TvContext> dbContextFactory)
: IRequestHandler<RotateLocalAdminSecurityStamp, Unit>
{
public async Task<Unit> Handle(RotateLocalAdminSecurityStamp request, CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
ConfigElement stampRow = await dbContext.ConfigElements
.FirstOrDefaultAsync(c => c.Key == ConfigElementKey.AuthSecurityStamp.Key, cancellationToken);
// No local admin configured → nothing to revoke.
if (stampRow is null)
{
return Unit.Default;
}
stampRow.Value = LocalAdminHelpers.NewSecurityStamp();
await dbContext.SaveChangesAsync(cancellationToken);
return Unit.Default;
}
}
@@ -1,11 +0,0 @@
using ErsatzTV.Core;
namespace ErsatzTV.Application.Auth;
/// <summary>
/// Recovery/bootstrap path: (re)sets the local admin from configuration (env
/// <c>Auth:LocalAdmin:Username</c>/<c>Password</c>). Overwrites any existing credential and rotates the
/// stamp (revoking sessions), so an operator who is locked out can reset by setting the env and
/// restarting. Runs at startup only when a password is configured.
/// </summary>
public record SeedLocalAdminFromEnvironment(string Username, string Password) : IRequest<Either<BaseError, Unit>>;
@@ -1,63 +0,0 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Auth;
public class SeedLocalAdminFromEnvironmentHandler(
IDbContextFactory<TvContext> dbContextFactory,
ILocalPasswordHasher passwordHasher)
: IRequestHandler<SeedLocalAdminFromEnvironment, Either<BaseError, Unit>>
{
public async Task<Either<BaseError, Unit>> Handle(
SeedLocalAdminFromEnvironment request,
CancellationToken cancellationToken)
{
string username = (request.Username ?? string.Empty).Trim();
if (username.Length == 0)
{
username = "admin";
}
if (username.Length > LocalAdminHelpers.MaxUsernameLength)
{
return BaseError.New("Seed username is too long");
}
foreach (BaseError error in LocalAdminHelpers.ValidatePassword(request.Password))
{
return error;
}
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
List<ConfigElement> rows = await dbContext.ConfigElements
.Where(c => c.Key == ConfigElementKey.AuthLocalAdminUsername.Key
|| c.Key == ConfigElementKey.AuthLocalAdminPasswordHash.Key
|| c.Key == ConfigElementKey.AuthSecurityStamp.Key)
.ToListAsync(cancellationToken);
// Overwrite (recovery/bootstrap) atomically: username + new hash + rotated stamp commit together.
Upsert(dbContext, rows, ConfigElementKey.AuthLocalAdminUsername.Key, username);
Upsert(dbContext, rows, ConfigElementKey.AuthLocalAdminPasswordHash.Key, passwordHasher.Hash(request.Password));
Upsert(dbContext, rows, ConfigElementKey.AuthSecurityStamp.Key, LocalAdminHelpers.NewSecurityStamp());
await dbContext.SaveChangesAsync(cancellationToken);
return Unit.Default;
}
private static void Upsert(TvContext dbContext, List<ConfigElement> existing, string key, string value)
{
ConfigElement row = existing.Find(r => r.Key == key);
if (row is null)
{
dbContext.ConfigElements.Add(new ConfigElement { Key = key, Value = value });
}
else
{
row.Value = value;
}
}
}
@@ -1,9 +0,0 @@
using ErsatzTV.Core;
namespace ErsatzTV.Application.Auth;
/// <summary>
/// Verifies a local-login username/password. On success returns the principal (username + current
/// security stamp) to sign into a cookie. A generic error (no username enumeration) on any failure.
/// </summary>
public record VerifyLocalAdminLogin(string Username, string Password) : IRequest<Either<BaseError, LocalAdminPrincipal>>;
@@ -1,53 +0,0 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Auth;
public class VerifyLocalAdminLoginHandler(
IDbContextFactory<TvContext> dbContextFactory,
ILocalPasswordHasher passwordHasher)
: IRequestHandler<VerifyLocalAdminLogin, Either<BaseError, LocalAdminPrincipal>>
{
private static readonly BaseError InvalidCredentials = BaseError.New("Invalid username or password");
public async Task<Either<BaseError, LocalAdminPrincipal>> Handle(
VerifyLocalAdminLogin request,
CancellationToken cancellationToken)
{
string username = (request.Username ?? string.Empty).Trim();
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
// Read the hash and stamp in ONE snapshot so they are consistent (issue: a login racing a password
// change must not return a stamp newer than the hash it verified). A concurrent change is then either
// wholly before this read (the old password fails to verify) or wholly after it (we return the
// pre-change stamp, so the cookie AuthController issues is revoked on its very next request by
// CookieSecurityStampValidator). No writes happen here, so there is nothing to clobber.
Dictionary<string, string> config = await dbContext.ConfigElements
.Where(c => c.Key == ConfigElementKey.AuthLocalAdminUsername.Key
|| c.Key == ConfigElementKey.AuthLocalAdminPasswordHash.Key
|| c.Key == ConfigElementKey.AuthSecurityStamp.Key)
.ToDictionaryAsync(c => c.Key, c => c.Value, cancellationToken);
config.TryGetValue(ConfigElementKey.AuthLocalAdminUsername.Key, out string storedUser);
config.TryGetValue(ConfigElementKey.AuthLocalAdminPasswordHash.Key, out string storedHash);
config.TryGetValue(ConfigElementKey.AuthSecurityStamp.Key, out string stamp);
// Always run exactly one PBKDF2 verify — against a dummy hash when unconfigured/unknown — so response
// timing does not reveal whether the account exists (no user enumeration).
string candidateHash = storedHash ?? passwordHasher.DummyHash;
LocalPasswordVerification result = passwordHasher.Verify(candidateHash, request.Password ?? string.Empty);
bool userMatches = storedUser is not null
&& string.Equals(storedUser, username, StringComparison.OrdinalIgnoreCase);
if (storedHash is null || !userMatches || result == LocalPasswordVerification.Failed)
{
return InvalidCredentials;
}
return new LocalAdminPrincipal(storedUser, stamp ?? string.Empty);
}
}
@@ -1,96 +0,0 @@
using ErsatzTV.Core.Domain;
namespace ErsatzTV.Application.Channels;
public static class AutoTuneAxisMap
{
// Server-owned Lucene smart-collection query for an axis value.
public static string GenerateQuery(AutoTuneAxis axis, string value)
{
string escaped = EscapeLuceneValue(value);
return axis switch
{
AutoTuneAxis.TvShow => $"type:episode AND show_title:\"{escaped}\"",
AutoTuneAxis.TvGenre => $"type:episode AND genre:\"{escaped}\"",
AutoTuneAxis.MovieGenre => $"type:movie AND genre:\"{escaped}\"",
_ => throw new ArgumentOutOfRangeException(nameof(axis), axis, null)
};
}
// Human-facing channel name. Movie-genre channels are suffixed so a genre that exists for
// both TV and movies ("Comedy" vs "Comedy Movies") does not produce two identically-named channels.
public static string GenerateName(AutoTuneAxis axis, string value) =>
axis switch
{
AutoTuneAxis.TvShow => value,
AutoTuneAxis.TvGenre => value,
AutoTuneAxis.MovieGenre => $"{value} Movies",
_ => throw new ArgumentOutOfRangeException(nameof(axis), axis, null)
};
// PseudoTV per-type defaults: single-show channels play in episode order; genre channels shuffle.
public static PlaybackOrder PlaybackOrderFor(AutoTuneAxis axis) =>
axis switch
{
AutoTuneAxis.TvShow => PlaybackOrder.SeasonEpisode,
AutoTuneAxis.TvGenre => PlaybackOrder.Shuffle,
AutoTuneAxis.MovieGenre => PlaybackOrder.Shuffle,
_ => throw new ArgumentOutOfRangeException(nameof(axis), axis, null)
};
// Per-source member query for a weighted auto-tune channel (#425). The discriminator identifies ONE
// content source within the channel's axis:
// * TV axes -> the show title. Episodes carry no parent-show id in the search index (only show_title
// is denormalized onto them), so show_title is the only field that selects a show's episodes. It is
// the same discriminator the TvShow axis already uses, so this introduces no new fragility class;
// a post-create show rename empties the member (items fall through to the remainder) until re-tuned.
// * MovieGenre -> the movie's media-item id (the stable, rename-proof `id` field; a movie IS the
// played item, so its own id selects it exactly).
// Deliberately discriminator-ONLY (no genre clause): membership is decided when the channel is tuned,
// so a materialized show airs all its episodes and the remainder subtracts the whole source (below).
public static string GenerateSourceQuery(AutoTuneAxis axis, string discriminator) =>
axis switch
{
AutoTuneAxis.TvShow or AutoTuneAxis.TvGenre =>
$"type:episode AND show_title:\"{EscapeLuceneValue(discriminator)}\"",
AutoTuneAxis.MovieGenre => $"type:movie AND id:{discriminator}",
_ => throw new ArgumentOutOfRangeException(nameof(axis), axis, null)
};
// The bare clause used to subtract a materialized/excluded source from the remainder query (below).
// Mirrors GenerateSourceQuery's discriminator field, minus the type prefix.
public static string SourceDiscriminatorClause(AutoTuneAxis axis, string discriminator) =>
axis switch
{
AutoTuneAxis.TvShow or AutoTuneAxis.TvGenre =>
$"show_title:\"{EscapeLuceneValue(discriminator)}\"",
AutoTuneAxis.MovieGenre => $"id:{discriminator}",
_ => throw new ArgumentOutOfRangeException(nameof(axis), axis, null)
};
// The catch-all remainder query: the base axis query minus every materialized/excluded source, so the
// base set is partitioned across (member sources + remainder) with no item counted twice and none
// dropped. Returns the plain base query when there is nothing to subtract. Emitted as valid classic
// Lucene — `(base) AND NOT (d1 OR d2 ...)` — because a ParseException silently escapes the whole query
// into a literal (SearchQueryParser.ParseQuery fallback).
public static string GenerateRemainderQuery(
AutoTuneAxis axis,
string value,
IReadOnlyCollection<string> subtractedDiscriminators)
{
string baseQuery = GenerateQuery(axis, value);
if (subtractedDiscriminators is null || subtractedDiscriminators.Count == 0)
{
return baseQuery;
}
string negated = string.Join(
" OR ",
subtractedDiscriminators.Select(d => SourceDiscriminatorClause(axis, d)));
return $"({baseQuery}) AND NOT ({negated})";
}
// Escape a value for a Lucene double-quoted phrase: backslash first, then double-quote.
public static string EscapeLuceneValue(string value) =>
(value ?? string.Empty).Replace("\\", "\\\\").Replace("\"", "\\\"");
}
@@ -1,27 +0,0 @@
using System.Globalization;
namespace ErsatzTV.Application.Channels;
public static class AutoTuneNumberAllocator
{
// Allocate `count` sequential integer channel numbers starting at `startingNumber`,
// skipping any number already present in `existingNumbers`. Channel.Number is a string,
// so numbers are returned as invariant-culture strings.
public static List<string> Allocate(int startingNumber, int count, ISet<string> existingNumbers)
{
var result = new List<string>(count);
int next = startingNumber;
while (result.Count < count)
{
string candidate = next.ToString(CultureInfo.InvariantCulture);
if (!existingNumbers.Contains(candidate))
{
result.Add(candidate);
}
next++;
}
return result;
}
}
@@ -42,16 +42,6 @@ public class BulkDeleteChannelsHandler(
dbContext.Channels.RemoveRange(channels);
await dbContext.SaveChangesAsync(cancellationToken);
// Clean up the system-owned weighted-auto-tune artifacts these channels created (#425), inside the
// same transaction — see DeleteChannelHandler for the cascade rationale.
await dbContext.MultiCollections
.Where(mc => mc.OwnedByChannelId != null && channelIds.Contains(mc.OwnedByChannelId.Value))
.ExecuteDeleteAsync(cancellationToken);
await dbContext.SmartCollections
.Where(sc => sc.OwnedByChannelId != null && channelIds.Contains(sc.OwnedByChannelId.Value))
.ExecuteDeleteAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
searchTargets.SearchTargetsChanged();
@@ -65,9 +55,7 @@ public class BulkDeleteChannelsHandler(
}
}
// post-commit side effect runs on CancellationToken.None so a late request cancellation
// can't abort it after the commit landed (#254)
await workerChannel.WriteAsync(new RefreshChannelList(), CancellationToken.None);
await workerChannel.WriteAsync(new RefreshChannelList(), cancellationToken);
return Right<BaseError, Unit>(Unit.Default);
}
@@ -54,10 +54,7 @@ public class BulkMoveChannelsToGroupHandler(
await transaction.CommitAsync(cancellationToken);
searchTargets.SearchTargetsChanged();
// post-commit side effect runs on CancellationToken.None so a late request cancellation
// can't abort it after the commit landed (#254)
await workerChannel.WriteAsync(new RefreshChannelList(), CancellationToken.None);
await workerChannel.WriteAsync(new RefreshChannelList(), cancellationToken);
return Right<BaseError, Unit>(Unit.Default);
}
@@ -68,22 +68,19 @@ public class CreateChannelFromLineupHandler(
}
searchTargets.SearchTargetsChanged();
// post-commit side effect runs on CancellationToken.None so a late request cancellation
// can't abort it after the commit landed (#254)
await workerChannel.WriteAsync(
new BuildPlayout(prepared.Playout.Id, PlayoutBuildMode.Reset),
CancellationToken.None);
cancellationToken);
// Mirror CreateClassicPlayoutHandler: on-demand playouts must be time-shifted to "now" after build.
if (prepared.Channel.PlayoutMode is ChannelPlayoutMode.OnDemand)
{
await workerChannel.WriteAsync(
new TimeShiftOnDemandPlayout(prepared.Playout.Id, DateTimeOffset.Now, false),
CancellationToken.None);
cancellationToken);
}
await workerChannel.WriteAsync(new RefreshChannelList(), CancellationToken.None);
await workerChannel.WriteAsync(new RefreshChannelList(), cancellationToken);
return new CreateChannelFromLineupResponseModel(
prepared.Channel.Id,
@@ -197,25 +194,13 @@ public class CreateChannelFromLineupHandler(
bool multiItem = normalized.Count >= 2;
// MultiCollection entries only support Shuffle / ShuffleInOrder / WeightedShuffle
// (mirrors PlayoutModeMustBeValid -- keep the two lists in step).
// MultiCollection entries only support Shuffle / ShuffleInOrder (mirrors PlayoutModeMustBeValid).
if (normalized.Any(i => i.CollectionType is CollectionType.MultiCollection) &&
playbackOrder is not (PlaybackOrder.Shuffle or PlaybackOrder.ShuffleInOrder
or PlaybackOrder.WeightedShuffle))
playbackOrder is not (PlaybackOrder.Shuffle or PlaybackOrder.ShuffleInOrder))
{
return BaseError.New($"Invalid playback order for multi collection: '{playbackOrder}'");
}
// A lineup of 2+ entries is persisted as a Playlist, and PlaylistEnumerator has no default arm: an
// order it doesn't know leaves the enumerator null and the items are dropped from the playlist with
// nothing reported. This is the second (and less obvious) persisting writer of
// PlaylistItem.PlaybackOrder, alongside ReplacePlaylistItems (#70; the silent fallbacks are #403).
if (multiItem && playbackOrder is PlaybackOrder.WeightedShuffle)
{
return BaseError.New(
$"Playback order '{playbackOrder}' is not supported for a multi-item lineup; it is available on classic schedule items");
}
if (multiItem)
{
// The generated playlist cannot express rerun collections or nested playlists
@@ -47,37 +47,20 @@ public class DeleteChannelHandler : IRequestHandler<DeleteChannel, Either<BaseEr
private async Task<Unit> DoDeletion(TvContext dbContext, Channel channel, CancellationToken cancellationToken)
{
// Delete the guide cache file through the filesystem abstraction (so it's observable under a
// MockFileSystem) and BEFORE the commit: deleting after commit orphans {number}.xml if the
// process crashes in between (nothing reaps it, and GetChannelGuideHandler serves everything
// in the cache folder). The guide xml is regenerable on demand, so losing it pre-commit is safe (#254).
string cacheFile = Path.Combine(FileSystemLayout.ChannelGuideCacheFolder, $"{channel.Number}.xml");
if (_fileSystem.File.Exists(cacheFile))
{
_fileSystem.File.Delete(cacheFile);
}
int channelId = channel.Id;
dbContext.Channels.Remove(channel);
await dbContext.SaveChangesAsync(cancellationToken);
// Clean up the system-owned weighted-auto-tune artifacts this channel created (#425): the
// MultiCollection (its cascade removes the now-dangling flood schedule item) and its per-source
// SmartCollections (cascade removes their join rows). Null OwnedByChannelId = a user collection, left
// untouched. Non-weighted (#69 single-SmartCollection) auto-tune channels set no ownership, so their
// pre-existing orphan-on-delete behavior is unchanged.
await dbContext.MultiCollections
.Where(mc => mc.OwnedByChannelId == channelId)
.ExecuteDeleteAsync(cancellationToken);
await dbContext.SmartCollections
.Where(sc => sc.OwnedByChannelId == channelId)
.ExecuteDeleteAsync(cancellationToken);
_searchTargets.SearchTargetsChanged();
// refresh channel list to remove channel that has no playout — post-commit side effect runs on
// CancellationToken.None so a late request cancellation can't abort it after the delete committed (#254)
await _workerChannel.WriteAsync(new RefreshChannelList(), CancellationToken.None);
// delete channel data from channel guide cache
string cacheFile = Path.Combine(FileSystemLayout.ChannelGuideCacheFolder, $"{channel.Number}.xml");
if (_fileSystem.File.Exists(cacheFile))
{
File.Delete(cacheFile);
}
// refresh channel list to remove channel that has no playout
await _workerChannel.WriteAsync(new RefreshChannelList(), cancellationToken);
return Unit.Default;
}
@@ -1,4 +1,4 @@
using System.Globalization;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Threading.Channels;
using ErsatzTV.Application.Subtitles;
@@ -52,6 +52,16 @@ public class UpdateChannelHandler(
UpdateChannel update,
CancellationToken cancellationToken)
{
// don't save mirror when playout exists
if (c.Playouts.Count > 0)
{
update = update with
{
PlayoutSource = ChannelPlayoutSource.Generated,
MirrorSourceChannelId = null
};
}
bool hasEpgChange = c.PlayoutSource != update.PlayoutSource || c.ShowInEpg != update.ShowInEpg;
c.Name = update.Name;
@@ -130,8 +140,6 @@ public class UpdateChannelHandler(
c.PlayoutMode = ChannelPlayoutMode.Continuous;
hasEpgChange |= c.MirrorSourceChannelId != update.MirrorSourceChannelId;
hasEpgChange |= c.PlayoutOffset != update.PlayoutOffset;
c.MirrorSourceChannelId = update.MirrorSourceChannelId;
c.PlayoutOffset = update.PlayoutOffset;
}
else
{
@@ -139,6 +147,8 @@ public class UpdateChannelHandler(
c.PlayoutOffset = null;
}
c.MirrorSourceChannelId = update.MirrorSourceChannelId;
c.PlayoutOffset = update.PlayoutOffset;
c.StreamingMode = update.StreamingMode;
c.WatermarkId = update.WatermarkId;
c.FallbackFillerId = update.FallbackFillerId;
@@ -147,32 +157,23 @@ public class UpdateChannelHandler(
searchTargets.SearchTargetsChanged();
// post-commit side effect runs on CancellationToken.None so a late request cancellation
// can't abort it after the commit landed (#254)
if (c.SubtitleMode != ChannelSubtitleMode.None)
{
Option<Playout> maybePlayout = await dbContext.Playouts
.SelectOneAsync(p => p.ChannelId, p => p.ChannelId == c.Id, CancellationToken.None);
.SelectOneAsync(p => p.ChannelId, p => p.ChannelId == c.Id, cancellationToken);
foreach (Playout playout in maybePlayout)
{
await workerChannel.WriteAsync(new ExtractEmbeddedSubtitles(playout.Id), CancellationToken.None);
await workerChannel.WriteAsync(new ExtractEmbeddedSubtitles(playout.Id), cancellationToken);
}
}
await workerChannel.WriteAsync(new RefreshChannelList(), CancellationToken.None);
await workerChannel.WriteAsync(new RefreshChannelList(), cancellationToken);
if (hasEpgChange)
{
await workerChannel.WriteAsync(new RefreshChannelData(c.Number), CancellationToken.None);
await workerChannel.WriteAsync(new RefreshChannelData(c.Number), cancellationToken);
}
// Deliberately NOT Mapper.GetPlayoutsCount: this handler's query (see Handle) doesn't include
// MirrorSourceChannel, so the shared helper would read that navigation as null and return the
// same own-playouts-only count anyway — with a false air of Mirror-awareness. Harmless today
// because ChannelController discards this view model and re-projects through
// GetChannelByIdForApi, so this count never reaches the wire. If you ever return it directly,
// fix the QUERY first (add the MirrorSourceChannel ThenInclude) — swapping in the helper alone
// would report 0 playouts for a working mirror channel.
return ProjectToViewModel(c, c.Playouts?.Count ?? 0);
}
@@ -184,7 +185,7 @@ public class UpdateChannelHandler(
{
Validation<BaseError, Channel> channelValidation = (ValidateName(request),
await ValidateNumber(dbContext, request, cancellationToken),
await MirrorSourceMustBeValid(dbContext, request, channel, cancellationToken),
await MirrorSourceMustBeValid(dbContext, request, cancellationToken),
ValidateShowInEpg(request.IsEnabled, request.ShowInEpg),
ValidateLogo(request.Logo?.Path))
.Apply((_, _, _, _, _) => channel);
@@ -259,7 +260,6 @@ public class UpdateChannelHandler(
private static async Task<Validation<BaseError, Unit>> MirrorSourceMustBeValid(
TvContext dbContext,
UpdateChannel request,
Channel channel,
CancellationToken cancellationToken)
{
if (request.PlayoutSource is not ChannelPlayoutSource.Mirror)
@@ -267,18 +267,6 @@ public class UpdateChannelHandler(
return Unit.Default;
}
// a channel with its own playout already built (Generated mode) cannot become a Mirror —
// Mirror channels relay another channel's playout and never build one of their own, so
// switching this transition on would strand the existing playout. This used to be
// silently coerced back to Generated (issue #401); reject the transition instead so the
// caller sees why the requested Mirror source was not applied. A round-trip that keeps
// PlayoutSource as Generated never reaches this check.
if (channel.Playouts.Count > 0)
{
return BaseError.New(
"Channel cannot switch to Mirror playout source while it has a playout; reset or delete the existing playout first.");
}
Option<Channel> maybeMirrorSource = await dbContext.Channels
.AsNoTracking()
.SelectOneAsync(
@@ -81,12 +81,10 @@ public class UpdateChannelNumbersHandler(
await transaction.CommitAsync(cancellationToken);
// update channel list and xmltv
// post-commit side effect runs on CancellationToken.None so a late request cancellation
// can't abort it after the commit landed (#254)
await workerChannel.WriteAsync(new RefreshChannelList(), CancellationToken.None);
await workerChannel.WriteAsync(new RefreshChannelList(), cancellationToken);
foreach (var channel in channelsToUpdate)
{
await workerChannel.WriteAsync(new RefreshChannelData(channel.Number), CancellationToken.None);
await workerChannel.WriteAsync(new RefreshChannelData(channel.Number), cancellationToken);
}
return Option<BaseError>.None;
@@ -1,52 +0,0 @@
using ErsatzTV.Application.Artworks;
using ErsatzTV.Core.Domain;
using MediatR;
namespace ErsatzTV.Application.Channels;
public record CreateAutoTunedChannels(
int TemplateId,
string Group,
List<AutoTuneChannelSelection> Channels) : IRequest<AutoTuneResult>;
// The batch-level TemplateId is the default; any per-channel field set here overrides it for that one
// channel. Advanced/Logo/TemplateId are all optional so the older positional {axis, value, name, number}
// form (and every existing caller/test) keeps compiling and behaving identically.
public record AutoTuneChannelSelection(
AutoTuneAxis Axis,
string Value,
string Name,
string Number,
int? TemplateId = null,
ArtworkContentTypeModel Logo = null,
CreateChannelFromLineupAdvancedOptions Advanced = null,
List<AutoTuneSourceWeight> Sources = null);
// Per-content-source rotation weight + query correction for a weighted auto-tune channel (#425).
// SourceId is the show id (TV axes) or movie media-item id (movie axis) from the members list (#384).
// Weight is the relative share of airtime (weighted round-robin; 1 = fair-share). Excluded drops the
// source entirely. A SourceId that is not in the axis's base set is an "add-untagged" source — materialized
// like any other. When every entry is Weight 1 and not excluded (and adds nothing), the channel keeps the
// single-SmartCollection fair-share shape; otherwise it is built as a MultiCollection of per-source
// SmartCollections carrying the weights.
public record AutoTuneSourceWeight(int SourceId, int Weight = 1, bool Excluded = false);
public record AutoTuneResult(List<AutoTuneChannelOutcome> Results)
{
public int CreatedCount => Results.Count(r => r.Status == AutoTuneOutcomeStatus.Created);
public int SkippedCount => Results.Count(r => r.Status == AutoTuneOutcomeStatus.Skipped);
public int FailedCount => Results.Count(r => r.Status == AutoTuneOutcomeStatus.Failed);
}
public record AutoTuneChannelOutcome(
string Name,
AutoTuneOutcomeStatus Status,
int? ChannelId,
string Reason);
public enum AutoTuneOutcomeStatus
{
Created,
Skipped,
Failed
}
@@ -1,519 +0,0 @@
using ErsatzTV.Application.Artworks;
using ErsatzTV.Application.MediaCollections;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Api.LibraryBrowse;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.Core.Search;
using ErsatzTV.Infrastructure.Data;
using LanguageExt;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Channels;
public class CreateAutoTunedChannelsHandler(
ISender mediator,
IDbContextFactory<TvContext> dbContextFactory,
ISearchTargets searchTargets,
ISmartCollectionCache smartCollectionCache)
: IRequestHandler<CreateAutoTunedChannels, AutoTuneResult>
{
private const string NumberTakenError = "Channel number must be unique";
private const string DefaultGroup = "Auto-Tuned";
// The members enumeration caps its own search at 10k leaf items, so a channel's distinct source count is
// already bounded (dozens/hundreds). One large page pulls them all.
private const int MaxSources = 10_000;
public async Task<AutoTuneResult> Handle(
CreateAutoTunedChannels request,
CancellationToken cancellationToken)
{
string group = string.IsNullOrWhiteSpace(request.Group) ? DefaultGroup : request.Group.Trim();
var outcomes = new List<AutoTuneChannelOutcome>();
foreach (AutoTuneChannelSelection selection in request.Channels ?? [])
{
outcomes.Add(await CreateOne(request.TemplateId, group, selection, cancellationToken));
}
return new AutoTuneResult(outcomes);
}
private async Task<AutoTuneChannelOutcome> CreateOne(
int templateId,
string group,
AutoTuneChannelSelection selection,
CancellationToken cancellationToken)
{
string name = (selection.Name ?? string.Empty).Trim();
if (name.Length is 0 or > 50)
{
return new AutoTuneChannelOutcome(name, AutoTuneOutcomeStatus.Failed, null, "Invalid channel name");
}
// Per-channel template override falls back to the batch template.
int effectiveTemplateId = selection.TemplateId ?? templateId;
// Per-channel uploaded channel image; None = generate the on-the-fly fallback logo at serve time.
ArtworkContentTypeModel logo = selection.Logo ?? ArtworkContentTypeModel.None;
// Per-source rotation weights / query corrections (#425) turn the channel from one fair-share
// SmartCollection into a MultiCollection of per-source SmartCollections carrying the weights. Only
// when the caller actually customized a source (a non-default weight, an exclusion, or an added
// out-of-axis source) — otherwise the single-SmartCollection fair-share shape is kept (cheaper, and
// identical output for TV since the fake-collection path already groups per show).
WeightedPlan plan = await BuildWeightedPlan(selection, cancellationToken);
if (plan is not null)
{
return await CreateWeightedChannel(
effectiveTemplateId, group, name, logo, selection, plan, cancellationToken);
}
return await CreateSingleSmartCollectionChannel(
effectiveTemplateId,
group,
name,
logo,
selection,
cancellationToken);
}
private async Task<AutoTuneChannelOutcome> CreateSingleSmartCollectionChannel(
int effectiveTemplateId,
string group,
string name,
ArtworkContentTypeModel logo,
AutoTuneChannelSelection selection,
CancellationToken cancellationToken)
{
string query = AutoTuneAxisMap.GenerateQuery(selection.Axis, selection.Value);
// The axis default (SeasonEpisode for a single show, Shuffle for a genre) is the playback order
// unless the DetailPanel set an explicit per-channel override. Any other Advanced field the caller
// set is layered on top of the template by CreateChannelFromLineup's `advanced.X ?? template.X`
// stamp-at-create contract, so we only have to fill in the axis-derived PlaybackOrder default here.
PlaybackOrder axisOrder = AutoTuneAxisMap.PlaybackOrderFor(selection.Axis);
CreateChannelFromLineupAdvancedOptions advanced =
(selection.Advanced ?? new CreateChannelFromLineupAdvancedOptions()) with
{
PlaybackOrder = selection.Advanced?.PlaybackOrder ?? axisOrder
};
// 1. Create the smart collection that drives this channel.
Either<BaseError, SmartCollectionViewModel> scResult =
await mediator.Send(new CreateSmartCollection(query, name), cancellationToken);
SmartCollectionViewModel smartCollection = null;
foreach (BaseError error in scResult.LeftToSeq())
{
return new AutoTuneChannelOutcome(
name, AutoTuneOutcomeStatus.Failed, null, $"Smart collection: {error.Value}");
}
foreach (SmartCollectionViewModel vm in scResult.RightToSeq())
{
smartCollection = vm;
}
// 2. Create the channel from a single-item lineup referencing the smart collection.
var command = new CreateChannelFromLineup(
name,
selection.Number,
group,
string.Empty,
logo,
IsEnabled: true,
ShowInEpg: true,
effectiveTemplateId,
advanced,
[
new CreateChannelFromLineupItem(
LibraryBrowseMediaType.SmartCollection,
CollectionType.SmartCollection,
CollectionId: null,
MultiCollectionId: null,
SmartCollectionId: smartCollection.Id,
RerunCollectionId: null,
MediaItemId: null,
PlaylistId: null)
]);
Either<BaseError, CreateChannelFromLineupResponseModel> channelResult =
await mediator.Send(command, cancellationToken);
foreach (BaseError error in channelResult.LeftToSeq())
{
// Roll back the smart collection we just created so a retry of this
// axis/value doesn't fail on SmartCollection-name uniqueness. Best-effort;
// the primary outcome below is still Skipped/Failed regardless of the delete result.
// Swallow any exception (not just an Either.Left) so a transient infra failure
// during rollback never aborts this channel's outcome or the batch; the
// orphaned SmartCollection is an acceptable degraded outcome.
try
{
await mediator.Send(new DeleteSmartCollection(smartCollection.Id), cancellationToken);
}
catch (Exception)
{
// intentionally ignored; see comment above
}
AutoTuneOutcomeStatus status = error.Value.Contains(NumberTakenError, StringComparison.Ordinal)
? AutoTuneOutcomeStatus.Skipped
: AutoTuneOutcomeStatus.Failed;
return new AutoTuneChannelOutcome(name, status, null, error.Value);
}
int channelId = channelResult.Match(Left: _ => 0, Right: r => r.ChannelId);
return new AutoTuneChannelOutcome(name, AutoTuneOutcomeStatus.Created, channelId, null);
}
// A resolved weighting plan: the per-source member queries + their weights, and the catch-all remainder.
// Null when the caller did not actually customize anything (fall back to the single-SmartCollection path).
private sealed record WeightedPlan(List<WeightedMember> Members, WeightedMember Remainder);
private sealed record WeightedMember(string Query, int Weight);
// Resolve the caller's per-source overrides against the channel's live base source set. Returns null when
// no source was customized (all weights 1, nothing excluded, nothing added) so the caller keeps the
// single-SmartCollection fair-share shape.
private async Task<WeightedPlan> BuildWeightedPlan(
AutoTuneChannelSelection selection,
CancellationToken cancellationToken)
{
List<AutoTuneSourceWeight> sources = selection.Sources ?? [];
if (sources.Count == 0)
{
return null;
}
// Enumerate the axis's distinct base sources (parent shows for TV, movies for the movie axis) exactly
// as the DetailPanel members list does, so weight resolution matches what the user saw.
PagedLibraryBrowseItemsResponseModel members = await mediator.Send(
new GetAutoTuneChannelMembers(selection.Axis, selection.Value, 0, MaxSources),
cancellationToken);
var baseIds = members.Page.Select(i => i.Id).ToHashSet();
// Any override touching a non-default weight, an exclusion, or an id outside the base set means the
// channel really is customized; otherwise the plan would be identical to fair-share.
bool customized = sources.Any(s => s.Weight != 1 || s.Excluded || !baseIds.Contains(s.SourceId));
if (!customized)
{
return null;
}
Dictionary<int, AutoTuneSourceWeight> overridesById = sources
.GroupBy(s => s.SourceId)
.ToDictionary(g => g.Key, g => g.Last());
return selection.Axis switch
{
AutoTuneAxis.MovieGenre => BuildMoviePlan(selection, members, overridesById),
_ => await BuildTvPlan(selection, members, overridesById, cancellationToken)
};
}
// TV: every base show becomes its own weighted SmartCollection (discriminator-only `show_title`) so
// un-weighted shows keep per-show fair-share — a single merged remainder would regress them to
// item-proportional (a 200-episode show would swamp a 20-episode one). The remainder is the live
// catch-all for shows/episodes added after tune-in, at weight 1.
private async Task<WeightedPlan> BuildTvPlan(
AutoTuneChannelSelection selection,
PagedLibraryBrowseItemsResponseModel members,
Dictionary<int, AutoTuneSourceWeight> overridesById,
CancellationToken cancellationToken)
{
var weightedMembers = new List<WeightedMember>();
var subtracted = new List<string>();
// Base shows (title is the discriminator; the members list already carries it).
var baseIds = members.Page.Select(i => i.Id).ToHashSet();
foreach (LibraryBrowseItemResponseModel item in members.Page)
{
AutoTuneSourceWeight ov = overridesById.GetValueOrDefault(item.Id);
if (ov is { Excluded: true })
{
subtracted.Add(item.Title);
continue;
}
weightedMembers.Add(new WeightedMember(
AutoTuneAxisMap.GenerateSourceQuery(selection.Axis, item.Title),
NormalizeWeight(ov?.Weight ?? 1)));
subtracted.Add(item.Title);
}
// Added (out-of-axis) shows: resolve the title from metadata since the members list won't include them.
List<int> addedIds = overridesById.Keys.Where(id => !baseIds.Contains(id)).ToList();
if (addedIds.Count > 0)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Dictionary<int, string> titles = (await dbContext.ShowMetadata
.AsNoTracking()
.Where(sm => addedIds.Contains(sm.ShowId))
.Select(sm => new { sm.ShowId, sm.Title })
.ToListAsync(cancellationToken))
.GroupBy(x => x.ShowId)
.ToDictionary(g => g.Key, g => g.First().Title);
foreach (int id in addedIds)
{
AutoTuneSourceWeight ov = overridesById[id];
if (ov.Excluded || !titles.TryGetValue(id, out string title) || string.IsNullOrWhiteSpace(title))
{
continue;
}
weightedMembers.Add(new WeightedMember(
AutoTuneAxisMap.GenerateSourceQuery(selection.Axis, title),
NormalizeWeight(ov.Weight)));
subtracted.Add(title);
}
}
var remainder = new WeightedMember(
AutoTuneAxisMap.GenerateRemainderQuery(selection.Axis, selection.Value, subtracted),
1);
return new WeightedPlan(weightedMembers, remainder);
}
// Movies: materialize only the touched movies (a non-default weight, or an added out-of-axis movie) as
// individual `id:{n}` SmartCollections; every un-touched base movie stays in ONE remainder whose weight is
// its member count. Because the fake-collection path already pools all movies uniformly, a count-weighted
// remainder is exactly equivalent to materializing each movie individually — without hundreds of rows.
private static WeightedPlan BuildMoviePlan(
AutoTuneChannelSelection selection,
PagedLibraryBrowseItemsResponseModel members,
Dictionary<int, AutoTuneSourceWeight> overridesById)
{
var weightedMembers = new List<WeightedMember>();
var subtracted = new List<string>();
var baseIds = members.Page.Select(i => i.Id).ToHashSet();
var subtractedBase = 0;
foreach ((int id, AutoTuneSourceWeight ov) in overridesById)
{
bool inBase = baseIds.Contains(id);
string idClause = id.ToString(System.Globalization.CultureInfo.InvariantCulture);
if (ov.Excluded)
{
subtracted.Add(idClause);
if (inBase)
{
subtractedBase++;
}
continue;
}
// Materialize weighted base movies and every added (out-of-axis) movie; a base movie left at
// weight 1 is cheaper to leave in the remainder (same airtime either way).
if (ov.Weight != 1 || !inBase)
{
weightedMembers.Add(new WeightedMember(
AutoTuneAxisMap.GenerateSourceQuery(selection.Axis, idClause),
NormalizeWeight(ov.Weight)));
subtracted.Add(idClause);
if (inBase)
{
subtractedBase++;
}
}
}
// Remainder weight = the un-touched base movie count, so a weighted movie airs N× *each* remainder
// movie (the fake path already pools movies uniformly, so this is equivalent to materializing each).
// Clamped to MultiCollectionItemWeight.Maximum (1000): a genre with >1000 un-touched movies can't
// express the exact ratio (the weighted movie then airs slightly more than intended) — the same
// 1..1000 bound #70's weight column imposes everywhere. Realistic only at very large scale.
int remainderCount = baseIds.Count - subtractedBase;
var remainder = new WeightedMember(
AutoTuneAxisMap.GenerateRemainderQuery(selection.Axis, selection.Value, subtracted),
NormalizeWeight(remainderCount));
return new WeightedPlan(weightedMembers, remainder);
}
private static int NormalizeWeight(int weight) =>
Math.Clamp(weight, MultiCollectionItemWeight.Minimum, MultiCollectionItemWeight.Maximum);
private async Task<AutoTuneChannelOutcome> CreateWeightedChannel(
int effectiveTemplateId,
string group,
string name,
ArtworkContentTypeModel logo,
AutoTuneChannelSelection selection,
WeightedPlan plan,
CancellationToken cancellationToken)
{
// WeightedShuffle is the whole point; it overrides any axis default / caller Advanced.PlaybackOrder.
CreateChannelFromLineupAdvancedOptions advanced =
(selection.Advanced ?? new CreateChannelFromLineupAdvancedOptions()) with
{
PlaybackOrder = PlaybackOrder.WeightedShuffle
};
// Short unique token: the channel id isn't known until CreateChannelFromLineup runs, and both
// SmartCollection.Name and MultiCollection.Name are unique varchar(50).
string token = Guid.NewGuid().ToString("N")[..8];
int multiCollectionId;
List<int> smartCollectionIds;
await using (TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken))
{
var multiCollection = new MultiCollection
{
Name = $"at-mc:{token}",
MultiCollectionItems = [],
MultiCollectionSmartItems = []
};
var index = 0;
foreach (WeightedMember member in plan.Members.Append(plan.Remainder))
{
var smartCollection = new SmartCollection
{
Name = index == plan.Members.Count ? $"at:{token}:rem" : $"at:{token}:{index}",
Query = member.Query
};
dbContext.SmartCollections.Add(smartCollection);
multiCollection.MultiCollectionSmartItems.Add(new MultiCollectionSmartItem
{
MultiCollection = multiCollection,
SmartCollection = smartCollection,
ScheduleAsGroup = false,
PlaybackOrder = PlaybackOrder.Shuffle,
Weight = member.Weight
});
index++;
}
dbContext.MultiCollections.Add(multiCollection);
try
{
await dbContext.SaveChangesAsync(cancellationToken);
}
catch (Exception ex)
{
return new AutoTuneChannelOutcome(
name, AutoTuneOutcomeStatus.Failed, null, $"Weighted collections: {ex.Message}");
}
multiCollectionId = multiCollection.Id;
smartCollectionIds = multiCollection.MultiCollectionSmartItems
.Select(i => i.SmartCollectionId)
.ToList();
// New smart collections became visible; refresh targets + cache like CreateSmartCollectionHandler
// (post-commit, CancellationToken.None so a late cancel can't abort it after the commit landed).
searchTargets.SearchTargetsChanged();
await smartCollectionCache.Refresh(CancellationToken.None);
}
var command = new CreateChannelFromLineup(
name,
selection.Number,
group,
string.Empty,
logo,
IsEnabled: true,
ShowInEpg: true,
effectiveTemplateId,
advanced,
[
new CreateChannelFromLineupItem(
LibraryBrowseMediaType.MultiCollection,
CollectionType.MultiCollection,
CollectionId: null,
MultiCollectionId: multiCollectionId,
SmartCollectionId: null,
RerunCollectionId: null,
MediaItemId: null,
PlaylistId: null)
]);
Either<BaseError, CreateChannelFromLineupResponseModel> channelResult =
await mediator.Send(command, cancellationToken);
foreach (BaseError error in channelResult.LeftToSeq())
{
// Roll back the multi collection + its member smart collections so a retry doesn't collide on
// name uniqueness. Best-effort; the outcome below stands regardless of the cleanup result.
await TryDeleteOwnedArtifacts(multiCollectionId, smartCollectionIds, cancellationToken);
AutoTuneOutcomeStatus status = error.Value.Contains(NumberTakenError, StringComparison.Ordinal)
? AutoTuneOutcomeStatus.Skipped
: AutoTuneOutcomeStatus.Failed;
return new AutoTuneChannelOutcome(name, status, null, error.Value);
}
int channelId = channelResult.Match(Left: _ => 0, Right: r => r.ChannelId);
// Stamp ownership so the artifacts are hidden from user collection lists and cleaned up on channel
// delete. Best-effort: an unstamped artifact is a cosmetic/cleanup issue, never a failed channel.
await TryStampOwnership(multiCollectionId, smartCollectionIds, channelId);
return new AutoTuneChannelOutcome(name, AutoTuneOutcomeStatus.Created, channelId, null);
}
private async Task TryStampOwnership(
int multiCollectionId,
List<int> smartCollectionIds,
int channelId)
{
try
{
// Post-commit side effect: runs on CancellationToken.None so a late request cancellation can't
// abort it after the channel-create commit landed (#254) — an un-stamped artifact would be a
// permanent orphan (never cleaned on delete, and visible in the user collection lists). The MC +
// its member smart collections are stamped in one transaction so a mid-way failure can't leave the
// MC owned while the smart collections stay orphaned.
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(CancellationToken.None);
await using var transaction = await dbContext.Database.BeginTransactionAsync(CancellationToken.None);
await dbContext.MultiCollections
.Where(mc => mc.Id == multiCollectionId)
.ExecuteUpdateAsync(s => s.SetProperty(mc => mc.OwnedByChannelId, channelId), CancellationToken.None);
await dbContext.SmartCollections
.Where(sc => smartCollectionIds.Contains(sc.Id))
.ExecuteUpdateAsync(s => s.SetProperty(sc => sc.OwnedByChannelId, channelId), CancellationToken.None);
await transaction.CommitAsync(CancellationToken.None);
}
catch (Exception)
{
// intentionally ignored; see call site
}
}
private async Task TryDeleteOwnedArtifacts(
int multiCollectionId,
List<int> smartCollectionIds,
CancellationToken cancellationToken)
{
try
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
await dbContext.MultiCollections
.Where(mc => mc.Id == multiCollectionId)
.ExecuteDeleteAsync(cancellationToken);
await dbContext.SmartCollections
.Where(sc => smartCollectionIds.Contains(sc.Id))
.ExecuteDeleteAsync(cancellationToken);
searchTargets.SearchTargetsChanged();
await smartCollectionCache.Refresh(CancellationToken.None);
}
catch (Exception)
{
// intentionally ignored; see call site
}
}
}
@@ -1,13 +0,0 @@
using ErsatzTV.Core.Api.LibraryBrowse;
using ErsatzTV.Core.Domain;
namespace ErsatzTV.Application.Channels;
// Read-only enumeration of the distinct content-source members a proposed auto-tune channel's
// server-generated SmartCollection query resolves to (issue #384). The client passes axis+value; the
// server owns query generation (AutoTuneAxisMap.GenerateQuery) — the client never sends Lucene.
public record GetAutoTuneChannelMembers(
AutoTuneAxis Axis,
string Value,
int PageNum,
int PageSize) : IRequest<PagedLibraryBrowseItemsResponseModel>;
@@ -1,168 +0,0 @@
using ErsatzTV.Application.LibraryBrowse;
using ErsatzTV.Core.Api.LibraryBrowse;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.Core.Search;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Search;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Channels;
// Runs the server-owned SmartCollection query for an axis value through the same search index the
// built channel's playout uses, then rolls the matching leaf items up to their distinct content
// sources: parent shows for the episode axes, movies for the movie-genre axis. Feeds the Auto-Tune
// DetailPanel's read-only-by-default source list (#383/#384).
public class GetAutoTuneChannelMembersHandler(
ISearchIndex searchIndex,
IDbContextFactory<TvContext> dbContextFactory)
: IRequestHandler<GetAutoTuneChannelMembers, PagedLibraryBrowseItemsResponseModel>
{
// Mirrors MediaCollectionRepository.GetSmartCollectionItems: the index dislikes a zero limit, so
// pull up to 10k matching leaf items and group in memory. A source whose matches fall entirely
// beyond this cap would be under-counted (the same staleness bound the smart-collection path
// already accepts) — realistic axis values resolve to far fewer than 10k items.
private const int SearchLimit = 10_000;
public async Task<PagedLibraryBrowseItemsResponseModel> Handle(
GetAutoTuneChannelMembers request,
CancellationToken cancellationToken)
{
// An out-of-range numeric axis binds successfully (ModelState stays valid, so [ApiController]'s
// auto-400 does not fire); treat it as no results rather than letting GenerateQuery's
// ArgumentOutOfRangeException surface as a 500 — matching #69's EnumerateAxis `_ => []`.
if (string.IsNullOrWhiteSpace(request.Value) || !Enum.IsDefined(request.Axis))
{
return new PagedLibraryBrowseItemsResponseModel(0, []);
}
string query = AutoTuneAxisMap.GenerateQuery(request.Axis, request.Value);
SearchResult searchResults = await searchIndex.Search(
query,
string.Empty,
0,
SearchLimit,
cancellationToken);
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
return request.Axis switch
{
AutoTuneAxis.MovieGenre => await MovieMembers(dbContext, searchResults, request, cancellationToken),
_ => await ShowMembers(dbContext, searchResults, request, cancellationToken)
};
}
// Episode axes (TvShow / TvGenre): roll matching episodes up to their distinct parent shows.
private static async Task<PagedLibraryBrowseItemsResponseModel> ShowMembers(
TvContext dbContext,
SearchResult searchResults,
GetAutoTuneChannelMembers request,
CancellationToken cancellationToken)
{
List<int> episodeIds = searchResults.Items
.Where(i => i.Type == LuceneSearchIndex.EpisodeType)
.Select(i => i.Id)
.ToList();
if (episodeIds.Count == 0)
{
return new PagedLibraryBrowseItemsResponseModel(0, []);
}
// Per-show count is the number of episodes THIS channel's query contributes, not the show's
// total episode count (Episode -> Season -> ShowId; proven query style from LibraryBrowseItemMapper).
Dictionary<int, int> matchCountByShow = (await dbContext.Episodes
.AsNoTracking()
.Where(e => episodeIds.Contains(e.Id))
.Select(e => new { e.Id, e.Season.ShowId })
.ToListAsync(cancellationToken))
.GroupBy(x => x.ShowId)
.ToDictionary(g => g.Key, g => g.Count());
List<int> showIds = matchCountByShow.Keys.ToList();
// Order the distinct shows by title, then page (the show set is bounded — dozens, not thousands).
List<int> orderedShowIds = (await dbContext.ShowMetadata
.AsNoTracking()
.Where(sm => showIds.Contains(sm.ShowId))
.Select(sm => new { sm.ShowId, sm.Title })
.ToListAsync(cancellationToken))
.GroupBy(x => x.ShowId)
.Select(g => new { ShowId = g.Key, Title = g.OrderBy(x => x.Title).Select(x => x.Title).FirstOrDefault() })
.OrderBy(x => x.Title, StringComparer.OrdinalIgnoreCase)
.ThenBy(x => x.ShowId)
.Select(x => x.ShowId)
.ToList();
int total = orderedShowIds.Count;
List<int> pageIds = orderedShowIds
.Skip(request.PageNum * request.PageSize)
.Take(request.PageSize)
.ToList();
List<LibraryBrowseItemResponseModel> hydrated =
await LibraryBrowseItemMapper.GetShows(dbContext, pageIds, cancellationToken);
Dictionary<int, LibraryBrowseItemResponseModel> byId = hydrated.ToDictionary(s => s.Id);
// GetShows groups by show id, so restore the requested title order and override its total-episode
// ItemCount with the query-matching count.
List<LibraryBrowseItemResponseModel> ordered = pageIds
.Where(byId.ContainsKey)
.Select(id => byId[id] with
{
ItemCount = matchCountByShow.TryGetValue(id, out int count) ? count : byId[id].ItemCount
})
.ToList();
return new PagedLibraryBrowseItemsResponseModel(total, ordered);
}
// Movie-genre axis: the matching movies are themselves the distinct content sources.
private static async Task<PagedLibraryBrowseItemsResponseModel> MovieMembers(
TvContext dbContext,
SearchResult searchResults,
GetAutoTuneChannelMembers request,
CancellationToken cancellationToken)
{
List<int> movieIds = searchResults.Items
.Where(i => i.Type == LuceneSearchIndex.MovieType)
.Select(i => i.Id)
.Distinct()
.ToList();
if (movieIds.Count == 0)
{
return new PagedLibraryBrowseItemsResponseModel(0, []);
}
List<int> orderedMovieIds = (await dbContext.MovieMetadata
.AsNoTracking()
.Where(mm => movieIds.Contains(mm.MovieId))
.Select(mm => new { mm.MovieId, mm.Title })
.ToListAsync(cancellationToken))
.GroupBy(x => x.MovieId)
.Select(g => new { MovieId = g.Key, Title = g.OrderBy(x => x.Title).Select(x => x.Title).FirstOrDefault() })
.OrderBy(x => x.Title, StringComparer.OrdinalIgnoreCase)
.ThenBy(x => x.MovieId)
.Select(x => x.MovieId)
.ToList();
int total = orderedMovieIds.Count;
List<int> pageIds = orderedMovieIds
.Skip(request.PageNum * request.PageSize)
.Take(request.PageSize)
.ToList();
List<LibraryBrowseItemResponseModel> hydrated =
await LibraryBrowseItemMapper.GetMovies(dbContext, pageIds, cancellationToken);
Dictionary<int, LibraryBrowseItemResponseModel> byId = hydrated.ToDictionary(m => m.Id);
List<LibraryBrowseItemResponseModel> ordered = pageIds
.Where(byId.ContainsKey)
.Select(id => byId[id])
.ToList();
return new PagedLibraryBrowseItemsResponseModel(total, ordered);
}
}
+3 -88
View File
@@ -1,4 +1,4 @@
using ErsatzTV.Application.Artworks;
using ErsatzTV.Application.Artworks;
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Domain;
@@ -6,29 +6,6 @@ namespace ErsatzTV.Application.Channels;
internal static class Mapper
{
/// <summary>
/// A mirror channel has no playouts of its own; it relays the playouts of its mirror source, so both must be
/// counted for the total to answer "can this channel play anything?". Requires <see cref="Channel.Playouts" />
/// and, for mirrors, <see cref="Channel.MirrorSourceChannel" />.<see cref="Channel.Playouts" /> to be included
/// by the query — the repository reads are AsNoTracking, so an un-included navigation silently counts zero.
/// </summary>
internal static int GetPlayoutsCount(Channel channel)
{
var result = 0;
if (channel.Playouts != null)
{
result += channel.Playouts.Count;
}
if (channel.PlayoutSource is ChannelPlayoutSource.Mirror && channel.MirrorSourceChannel?.Playouts != null)
{
result += channel.MirrorSourceChannel.Playouts.Count;
}
return result;
}
internal static ChannelViewModel ProjectToViewModel(Channel channel, int playoutCount) =>
new(
channel.Id,
@@ -61,42 +38,7 @@ internal static class Mapper
channel.IsEnabled,
channel.ShowInEpg);
internal static ChannelDetailResponseModel ProjectToDetailResponseModel(Channel channel, int playoutCount)
{
ArtworkContentTypeModel logo = GetLogo(channel);
return new ChannelDetailResponseModel(
channel.Id,
channel.Number,
channel.Name,
channel.Group,
channel.Categories,
channel.FFmpegProfileId,
channel.SlugSeconds,
new ChannelLogoResponseModel(logo.Path, logo.ContentType),
channel.StreamSelectorMode,
channel.StreamSelector,
channel.PreferredAudioLanguageCode,
channel.PreferredAudioTitle,
channel.PlayoutSource,
channel.PlayoutMode,
channel.MirrorSourceChannelId,
channel.PlayoutOffset,
channel.StreamingMode,
channel.WatermarkId,
channel.FallbackFillerId,
playoutCount,
channel.PreferredSubtitleLanguageCode,
channel.SubtitleMode,
channel.MusicVideoCreditsMode,
channel.MusicVideoCreditsTemplate,
channel.SongVideoMode,
channel.TranscodeMode,
channel.IdleBehavior,
channel.IsEnabled,
channel.ShowInEpg);
}
internal static ChannelResponseModel ProjectToResponseModel(Channel channel, int playoutCount) =>
internal static ChannelResponseModel ProjectToResponseModel(Channel channel) =>
new(
channel.Id,
channel.Number,
@@ -108,9 +50,7 @@ internal static class Mapper
channel.PreferredAudioLanguageCode,
GetStreamingMode(channel),
channel.IsEnabled,
channel.ShowInEpg,
playoutCount,
GetLogoUrl(channel));
channel.ShowInEpg);
internal static ResolutionViewModel ProjectToViewModel(Resolution resolution) =>
new(resolution.Height, resolution.Width);
@@ -124,31 +64,6 @@ internal static class Mapper
channel.FFmpegProfile.VideoProfile,
channel.FFmpegProfile.AudioFormat);
// Rooted, directly-usable channel-logo URL for the SPA's <img src> on browse surfaces (guide grid +
// channels list), following the #181 artwork convention (docs/api-conventions.md §4): the SPA does no
// client-side path building. External logo URLs pass through as-is; an uploaded logo ("iptv/logos/{file}")
// is rooted with a leading slash so it resolves against the site root regardless of the current SPA route.
// Returns null when the channel has no logo, so the SPA falls back to the generated initials "bug".
#nullable enable
internal static string? GetLogoUrl(Channel channel)
{
// Browse surfaces must not crash the whole list over a missing Artwork include; GetLogo assumes
// the caller included Channel.Artwork (GetAll + the guide query do), but stay defensive here.
if (channel.Artwork is null)
{
return null;
}
ArtworkContentTypeModel logo = GetLogo(channel);
if (string.IsNullOrWhiteSpace(logo.Path))
{
return null;
}
return logo.IsExternalUrl || logo.Path.StartsWith('/') ? logo.Path : $"/{logo.Path}";
}
#nullable restore
private static ArtworkContentTypeModel GetLogo(Channel channel)
{
Option<Artwork> maybeArtwork = channel.Artwork
@@ -1,19 +0,0 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using LanguageExt;
using MediatR;
namespace ErsatzTV.Application.Channels;
public record PreviewAutoTuneChannels(
List<AutoTuneAxis> Axes,
int MinItems,
int StartingNumber) : IRequest<Either<BaseError, List<AutoTuneProposal>>>;
public record AutoTuneProposal(
AutoTuneAxis Axis,
string Value,
string Name,
string Number,
int ItemCount,
bool AlreadyExists);
@@ -1,144 +0,0 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using LanguageExt;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Channels;
public class PreviewAutoTuneChannelsHandler(IDbContextFactory<TvContext> dbContextFactory)
: IRequestHandler<PreviewAutoTuneChannels, Either<BaseError, List<AutoTuneProposal>>>
{
public async Task<Either<BaseError, List<AutoTuneProposal>>> Handle(
PreviewAutoTuneChannels request,
CancellationToken cancellationToken)
{
if (request.Axes is null || request.Axes.Count == 0)
{
return BaseError.New("At least one axis is required");
}
if (request.MinItems < 1)
{
return BaseError.New("Minimum items must be at least 1");
}
if (request.StartingNumber < 1)
{
return BaseError.New("Starting channel number must be at least 1");
}
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
// Enumerate (axis, value, count) triples per requested axis, preserving axis order.
var raw = new List<(AutoTuneAxis Axis, string Value, int Count)>();
foreach (AutoTuneAxis axis in request.Axes.Distinct())
{
raw.AddRange(await EnumerateAxis(dbContext, axis, request.MinItems, cancellationToken));
}
System.Collections.Generic.HashSet<string> existingNumbers = (await dbContext.Channels.AsNoTracking()
.Select(c => c.Number).ToListAsync(cancellationToken))
.ToHashSet();
System.Collections.Generic.HashSet<string> existingNames = (await dbContext.Channels.AsNoTracking()
.Select(c => c.Name).ToListAsync(cancellationToken))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
// Drop entries whose generated name would be rejected at create time (Channel name <= 50
// chars) before number allocation, so numbers aren't wasted on proposals that can never
// be created.
List<(AutoTuneAxis Axis, string Value, int Count, string Name)> survivors = raw
.Select(r => (r.Axis, r.Value, r.Count, Name: AutoTuneAxisMap.GenerateName(r.Axis, r.Value)))
.Where(r => r.Name.Length <= 50)
.ToList();
List<string> numbers = AutoTuneNumberAllocator.Allocate(
request.StartingNumber, survivors.Count, existingNumbers);
var proposals = new List<AutoTuneProposal>(survivors.Count);
for (int i = 0; i < survivors.Count; i++)
{
(AutoTuneAxis axis, string value, int count, string name) = survivors[i];
proposals.Add(new AutoTuneProposal(
axis, value, name, numbers[i], count, existingNames.Contains(name)));
}
return proposals;
}
private static async Task<List<(AutoTuneAxis, string, int)>> EnumerateAxis(
TvContext dbContext, AutoTuneAxis axis, int minItems, CancellationToken cancellationToken) =>
axis switch
{
AutoTuneAxis.TvShow => await EnumerateTvShows(dbContext, minItems, cancellationToken),
AutoTuneAxis.TvGenre => await EnumerateEpisodeGenres(dbContext, minItems, cancellationToken),
AutoTuneAxis.MovieGenre => await EnumerateMovieGenres(dbContext, minItems, cancellationToken),
_ => []
};
private static async Task<List<(AutoTuneAxis, string, int)>> EnumerateTvShows(
TvContext dbContext, int minItems, CancellationToken cancellationToken)
{
// Episode count per show id (Episode -> Season -> ShowId). Proven query style from LibraryBrowseItemMapper.
Dictionary<int, int> episodeCounts = await dbContext.Episodes.AsNoTracking()
.GroupBy(e => e.Season.ShowId)
.Select(g => new { ShowId = g.Key, Count = g.Count() })
.ToDictionaryAsync(g => g.ShowId, g => g.Count, cancellationToken);
var showTitles = await dbContext.ShowMetadata.AsNoTracking()
.Select(sm => new { sm.ShowId, sm.Title })
.ToListAsync(cancellationToken);
// Collapse shows that share a title (the generated show_title query matches them together).
var byTitle = new Dictionary<string, int>();
foreach (var row in showTitles)
{
if (string.IsNullOrWhiteSpace(row.Title))
{
continue;
}
episodeCounts.TryGetValue(row.ShowId, out int count);
byTitle[row.Title] = byTitle.GetValueOrDefault(row.Title) + count;
}
return byTitle
.Where(kv => kv.Value >= minItems)
.OrderBy(kv => kv.Key, StringComparer.OrdinalIgnoreCase)
.Select(kv => (AutoTuneAxis.TvShow, kv.Key, kv.Value))
.ToList();
}
private static async Task<List<(AutoTuneAxis, string, int)>> EnumerateEpisodeGenres(
TvContext dbContext, int minItems, CancellationToken cancellationToken)
{
var counts = await dbContext.EpisodeMetadata.AsNoTracking()
.SelectMany(m => m.Genres)
.GroupBy(g => g.Name)
.Select(grp => new { Name = grp.Key, Count = grp.Count() })
.ToListAsync(cancellationToken);
return counts
.Where(c => !string.IsNullOrWhiteSpace(c.Name) && c.Count >= minItems)
.OrderBy(c => c.Name, StringComparer.OrdinalIgnoreCase)
.Select(c => (AutoTuneAxis.TvGenre, c.Name, c.Count))
.ToList();
}
private static async Task<List<(AutoTuneAxis, string, int)>> EnumerateMovieGenres(
TvContext dbContext, int minItems, CancellationToken cancellationToken)
{
var counts = await dbContext.MovieMetadata.AsNoTracking()
.SelectMany(m => m.Genres)
.GroupBy(g => g.Name)
.Select(grp => new { Name = grp.Key, Count = grp.Count() })
.ToListAsync(cancellationToken);
return counts
.Where(c => !string.IsNullOrWhiteSpace(c.Name) && c.Count >= minItems)
.OrderBy(c => c.Name, StringComparer.OrdinalIgnoreCase)
.Select(c => (AutoTuneAxis.MovieGenre, c.Name, c.Count))
.ToList();
}
}
@@ -1,4 +1,4 @@
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using static ErsatzTV.Application.Channels.Mapper;
@@ -13,6 +13,6 @@ public class GetAllChannelsForApiHandler(IChannelRepository channelRepository)
CancellationToken cancellationToken)
{
IEnumerable<Channel> channels = Optional(await channelRepository.GetAll(cancellationToken)).Flatten();
return channels.Map(c => ProjectToResponseModel(c, GetPlayoutsCount(c))).ToList();
return channels.Map(ProjectToResponseModel).ToList();
}
}
@@ -1,4 +1,4 @@
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using static ErsatzTV.Application.Channels.Mapper;
@@ -11,4 +11,21 @@ public class GetAllChannelsHandler(IChannelRepository channelRepository)
await channelRepository.GetAll(cancellationToken)
.Map(list => list.Where(c => c.IsEnabled || request.ShowDisabled)
.Map(c => ProjectToViewModel(c, GetPlayoutsCount(c))).ToList());
private static int GetPlayoutsCount(Channel channel)
{
var result = 0;
if (channel.Playouts != null)
{
result += channel.Playouts.Count;
}
if (channel.PlayoutSource is ChannelPlayoutSource.Mirror && channel.MirrorSourceChannel?.Playouts != null)
{
result += channel.MirrorSourceChannel.Playouts.Count;
}
return result;
}
}
@@ -1,5 +0,0 @@
using ErsatzTV.Core.Api.Channels;
namespace ErsatzTV.Application.Channels;
public record GetChannelByIdForApi(int Id) : IRequest<Option<ChannelDetailResponseModel>>;
@@ -1,15 +0,0 @@
using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Interfaces.Repositories;
using static ErsatzTV.Application.Channels.Mapper;
namespace ErsatzTV.Application.Channels;
public class GetChannelByIdForApiHandler(IChannelRepository channelRepository)
: IRequestHandler<GetChannelByIdForApi, Option<ChannelDetailResponseModel>>
{
public Task<Option<ChannelDetailResponseModel>> Handle(
GetChannelByIdForApi request,
CancellationToken cancellationToken) =>
channelRepository.GetChannel(request.Id)
.MapT(channel => ProjectToDetailResponseModel(channel, GetPlayoutsCount(channel)));
}
@@ -47,7 +47,6 @@ public class GetChannelGuideDataHandler(
List<Channel> channels = await dbContext.Channels
.AsNoTracking()
.Where(c => c.ShowInEpg)
.Include(c => c.Artwork)
.Include(c => c.MirrorSourceChannel)
.ToListAsync(cancellationToken);
@@ -122,7 +121,6 @@ public class GetChannelGuideDataHandler(
new ChannelGuideChannelResponseModel(
channel.Number,
channel.Name,
Mapper.GetLogoUrl(channel),
programmes.OrderBy(p => p.Start).ToList()));
}
@@ -1,12 +1,9 @@
using System.Collections.Immutable;
using System.IO.Abstractions;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Metadata;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Iptv;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
@@ -18,8 +15,7 @@ public partial class GetChannelGuideHandler(
IDbContextFactory<TvContext> dbContextFactory,
RecyclableMemoryStreamManager recyclableMemoryStreamManager,
IFileSystem fileSystem,
ILocalFileSystem localFileSystem,
IConfigElementRepository configElementRepository)
ILocalFileSystem localFileSystem)
: IRequestHandler<GetChannelGuide, Either<BaseError, ChannelGuide>>
{
public async Task<Either<BaseError, ChannelGuide>> Handle(
@@ -27,21 +23,6 @@ public partial class GetChannelGuideHandler(
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Option<string> maybeBaseUrl =
await configElementRepository.GetValue<string>(ConfigElementKey.IptvBaseUrl, cancellationToken);
(string scheme, string host, string baseUrl) = AdvertisedBaseUrl.Resolve(
maybeBaseUrl.IfNone(string.Empty),
request.Scheme,
request.Host,
request.BaseUrl);
// The cache fragments are pre-built XML written raw (like {AccessTokenUri}, which is already
// emitted as &amp;), so the substituted base must be XML-escaped. A path prefix can legally
// contain '&' (Uri keeps it out of the query), which would otherwise emit a bare '&' and
// malform the whole guide. Normal URLs have no special chars, so this is a no-op for them.
string requestBase = SecurityElement.Escape($"{scheme}://{host}{baseUrl}");
var hiddenChannelNumbers = dbContext.Channels
.Where(c => c.ShowInEpg == false)
.Select(c => c.Number)
@@ -60,17 +41,14 @@ public partial class GetChannelGuideHandler(
var accessTokenUri = $"?v={mtime}";
if (!string.IsNullOrWhiteSpace(request.AccessToken))
{
// The token value is HTTP-request-derived and interpolated raw into the pre-built XMLTV
// cache fragments, so it must be XML-escaped like {RequestBase} above — a token containing
// '&', '<', '>', or '"' would otherwise malform the whole guide. Opaque tokens are a no-op.
accessTokenUri += $"&amp;access_token={SecurityElement.Escape(request.AccessToken)}";
accessTokenUri += $"&amp;access_token={request.AccessToken}";
}
string channelsFragment = await ReadAllTextShared(channelsFile, cancellationToken);
// TODO: is regex faster?
channelsFragment = channelsFragment
.Replace("{RequestBase}", requestBase)
.Replace("{RequestBase}", $"{request.Scheme}://{request.Host}{request.BaseUrl}")
.Replace("{AccessTokenUri}", accessTokenUri);
var channelDataFragments = new Dictionary<string, string>();
@@ -92,7 +70,7 @@ public partial class GetChannelGuideHandler(
string channelDataFragment = await ReadAllTextShared(fileName, cancellationToken);
channelDataFragment = channelDataFragment
.Replace("{RequestBase}", requestBase)
.Replace("{RequestBase}", $"{request.Scheme}://{request.Host}{request.BaseUrl}")
.Replace("{AccessTokenUri}", accessTokenUri);
channelDataFragment = EtvTagRegex().Replace(channelDataFragment, string.Empty);
@@ -4,31 +4,19 @@ using ErsatzTV.Core.Iptv;
namespace ErsatzTV.Application.Channels;
public class GetChannelPlaylistHandler(
IChannelRepository channelRepository,
IConfigElementRepository configElementRepository)
public class GetChannelPlaylistHandler(IChannelRepository channelRepository)
: IRequestHandler<GetChannelPlaylist, ChannelPlaylist>
{
public async Task<ChannelPlaylist> Handle(GetChannelPlaylist request, CancellationToken cancellationToken)
{
Option<string> maybeBaseUrl =
await configElementRepository.GetValue<string>(ConfigElementKey.IptvBaseUrl, cancellationToken);
(string scheme, string host, string baseUrl) = AdvertisedBaseUrl.Resolve(
maybeBaseUrl.IfNone(string.Empty),
public Task<ChannelPlaylist> Handle(GetChannelPlaylist request, CancellationToken cancellationToken) =>
channelRepository.GetAll(cancellationToken)
.Map(channels => EnsureMode(channels, request.Mode))
.Map(channels => new ChannelPlaylist(
request.Scheme,
request.Host,
request.BaseUrl);
List<Channel> channels = EnsureMode(await channelRepository.GetAll(cancellationToken), request.Mode);
return new ChannelPlaylist(
scheme,
host,
baseUrl,
request.BaseUrl,
channels,
request.UserAgent,
request.AccessToken);
}
request.AccessToken));
private static List<Channel> EnsureMode(IEnumerable<Channel> channels, string mode)
{
@@ -2,7 +2,6 @@ using ErsatzTV.Core.Api.Channels;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Interfaces.FFmpeg;
using ErsatzTV.Core.Interfaces.Streaming;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using PlayoutMapper = ErsatzTV.Application.Playouts.Mapper;
@@ -11,8 +10,7 @@ namespace ErsatzTV.Application.Channels;
public class GetChannelStatesForApiHandler(
IDbContextFactory<TvContext> dbContextFactory,
IFFmpegSegmenterService ffmpegSegmenterService,
IDirectStreamSessionTracker directStreamSessionTracker)
IFFmpegSegmenterService ffmpegSegmenterService)
: IRequestHandler<GetChannelStatesForApi, List<ChannelStateResponseModel>>
{
// a guide entry (program + surrounding filler) never spans anywhere near a day; the time
@@ -143,8 +141,7 @@ public class GetChannelStatesForApiHandler(
return new ChannelStateResponseModel(
channel.Id,
channel.Number,
ffmpegSegmenterService.IsActive(channel.Number) ||
directStreamSessionTracker.IsActive(channel.Number),
ffmpegSegmenterService.IsActive(channel.Number),
nowPlaying);
})
.ToList();
@@ -1,124 +0,0 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace ErsatzTV.Application;
public static class ConcurrencyExtensions
{
/// <summary>
/// Persist changes that touch a versioned root but do <b>not</b> participate in the If-Match
/// contract (e.g. a playout's settings/schedule-file/on-demand-checkpoint writer, a collection's
/// name edit). Because the root's <c>Version</c> is an <c>IsConcurrencyToken</c>, EF guards every
/// UPDATE of that row with <c>WHERE Version=@orig</c>, so a concurrent bump from a replace-all
/// editor would otherwise surface as an unhandled <see cref="DbUpdateConcurrencyException" /> →
/// 500 (issue #253 / #269). Phase-1 semantics for a missing <c>If-Match</c> is <b>force-write</b>,
/// so on a concurrency failure we rebase onto the stored token: original becomes the stored value
/// (the retry's WHERE then matches) and current becomes stored + our pending delta (a bumper's ++
/// still advances the ETag past the concurrent writer's value — #269 rotation; a non-bumper adopts
/// it unchanged) and retry; our own modified scalars still win. Bounded to avoid a livelock; if the row
/// was deleted out from under us, that's a genuine conflict and rethrows.
/// </summary>
public static async Task<int> SaveChangesForcingVersion(
this DbContext dbContext,
CancellationToken cancellationToken)
{
for (var attempt = 0; ; attempt++)
{
try
{
return await dbContext.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateConcurrencyException ex) when (attempt < 5)
{
var resolvedAny = false;
foreach (EntityEntry entry in ex.Entries)
{
if (entry.Entity is not IVersionedAggregate)
{
continue;
}
PropertyValues databaseValues = await entry.GetDatabaseValuesAsync(cancellationToken);
if (databaseValues is null)
{
// The row was deleted out from under us — a genuine conflict, not a token race.
throw;
}
PropertyEntry version = entry.Property(nameof(IVersionedAggregate.Version));
int dbVersion = (int)databaseValues[nameof(IVersionedAggregate.Version)]!;
// Rebase our pending delta on top of the stored token instead of adopting it verbatim:
// a Version-bumping sibling (pending current = original + 1) must still advance the
// ETag PAST the concurrent writer's value, or an editor holding that writer's ETag is
// never invalidated by our change (#269 rotation silently lost under race). Non-bumpers
// (delta 0, e.g. ErasePlayoutHistory) still adopt the stored token unchanged.
int pendingDelta = (int)version.CurrentValue! - (int)version.OriginalValue!;
version.OriginalValue = dbVersion;
version.CurrentValue = dbVersion + pendingDelta;
resolvedAny = true;
}
if (!resolvedAny)
{
throw;
}
}
}
}
/// <summary>
/// Like <see cref="SaveChangesForcingVersion" />, but additionally treats a unique / primary-key
/// constraint violation as an idempotent no-op: returns <c>false</c> instead of throwing when the
/// save fails because a concurrent request inserted a row we had membership-checked absent (the
/// composite-PK race on <c>CollectionItem</c> — issue #308). A <c>false</c> means "the desired row
/// already exists because a racing writer won; the winner ran the ETag rotation + fan-out, so skip
/// ours." <c>true</c> means our own change committed. Every other <see cref="DbUpdateException" />
/// (and the genuine deleted-row concurrency conflict rethrown by <see cref="SaveChangesForcingVersion" />)
/// still propagates. The only insert these callers stage is the <c>CollectionItem</c> join row, so the
/// sole unique/PK constraint that can fire here is that composite key.
/// </summary>
public static async Task<bool> TrySaveChangesForcingVersion(
this DbContext dbContext,
CancellationToken cancellationToken)
{
try
{
await dbContext.SaveChangesForcingVersion(cancellationToken);
return true;
}
catch (DbUpdateException ex) when (TvContext.IsUniqueConstraintViolation(ex))
{
return false;
}
}
/// <summary>
/// Persist pending changes, mapping the EF optimistic-concurrency failure to
/// <see cref="PreconditionFailedError" /> (→ 412). When a versioned root carries an
/// <c>IsConcurrencyToken</c> column and its <c>Version</c> is bumped before saving, EF emits
/// <c>UPDATE … WHERE Id=@id AND Version=@original</c>; a zero-row result (another writer won
/// the race between our load and save) throws <see cref="DbUpdateConcurrencyException" />.
/// This is the backstop that closes the load→save TOCTOU the handler pre-check cannot.
/// Issue #253.
/// </summary>
public static async Task<Either<BaseError, Unit>> SaveChangesWithConcurrencyGuard(
this DbContext dbContext,
CancellationToken cancellationToken)
{
try
{
await dbContext.SaveChangesAsync(cancellationToken);
return Unit.Default;
}
catch (DbUpdateConcurrencyException)
{
return new PreconditionFailedError(
"The resource was modified by another request. Reload and try again.");
}
}
}
@@ -1,5 +0,0 @@
using ErsatzTV.Core;
namespace ErsatzTV.Application.Configuration;
public record UpdateIptvSettings(IptvSettingsViewModel IptvSettings) : IRequest<Either<BaseError, Unit>>;
@@ -1,51 +0,0 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Iptv;
namespace ErsatzTV.Application.Configuration;
public class UpdateIptvSettingsHandler(IConfigElementRepository configElementRepository)
: IRequestHandler<UpdateIptvSettings, Either<BaseError, Unit>>
{
public async Task<Either<BaseError, Unit>> Handle(
UpdateIptvSettings request,
CancellationToken cancellationToken)
{
Validation<BaseError, Unit> validation = Validate(request);
return await validation.Apply<Unit, Unit>(_ => ApplyUpdate(request.IptvSettings, cancellationToken));
}
private async Task<Unit> ApplyUpdate(IptvSettingsViewModel iptvSettings, CancellationToken cancellationToken)
{
string baseUrl = (iptvSettings.BaseUrl ?? string.Empty).Trim();
// A blank value clears the setting so the request-derived behavior is restored.
if (string.IsNullOrWhiteSpace(baseUrl))
{
await configElementRepository.Delete(ConfigElementKey.IptvBaseUrl, cancellationToken);
}
else
{
await configElementRepository.Upsert(ConfigElementKey.IptvBaseUrl, baseUrl, cancellationToken);
}
return Unit.Default;
}
private static Validation<BaseError, Unit> Validate(UpdateIptvSettings request)
{
string baseUrl = request.IptvSettings.BaseUrl;
// Blank is valid (clears the override); a non-blank value must be a well-formed advertised base URL.
if (string.IsNullOrWhiteSpace(baseUrl))
{
return Unit.Default;
}
return AdvertisedBaseUrl.TryParse(baseUrl)
.Map(_ => Unit.Default)
.ToValidation<BaseError>(
"Advertised base URL must be an absolute http(s) URL with no credentials, query, or fragment");
}
}
@@ -1,6 +0,0 @@
namespace ErsatzTV.Application.Configuration;
public class IptvSettingsViewModel
{
public string BaseUrl { get; set; }
}
@@ -1,3 +0,0 @@
namespace ErsatzTV.Application.Configuration;
public record GetIptvSettings : IRequest<IptvSettingsViewModel>;
@@ -1,19 +0,0 @@
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
namespace ErsatzTV.Application.Configuration;
public class GetIptvSettingsHandler(IConfigElementRepository configElementRepository)
: IRequestHandler<GetIptvSettings, IptvSettingsViewModel>
{
public async Task<IptvSettingsViewModel> Handle(GetIptvSettings request, CancellationToken cancellationToken)
{
Option<string> maybeBaseUrl =
await configElementRepository.GetValue<string>(ConfigElementKey.IptvBaseUrl, cancellationToken);
return new IptvSettingsViewModel
{
BaseUrl = await maybeBaseUrl.IfNoneAsync(string.Empty)
};
}
}
@@ -29,22 +29,13 @@ public class DisconnectEmbyHandler : IRequestHandler<DisconnectEmby, Either<Base
public async Task<Either<BaseError, Unit>> Handle(
DisconnectEmby request,
CancellationToken cancellationToken)
{
// This is a terminal handler with no lock handoff (unlike the Plex pin-flow handlers) —
// release unconditionally so a throw from any awaited dependency (repo delete, search-index
// commit, secret store) can't wedge the Emby lock until restart (design #202 finding 7).
try
{
List<int> ids = await _mediaSourceRepository.DeleteAllEmby();
await _searchIndex.RemoveItems(ids);
_searchIndex.Commit();
await _embySecretStore.DeleteAll();
_entityLocker.UnlockRemoteMediaSource<EmbyMediaSource>();
return Unit.Default;
}
finally
{
_entityLocker.UnlockRemoteMediaSource<EmbyMediaSource>();
}
}
}
@@ -2,6 +2,6 @@ using ErsatzTV.Core;
namespace ErsatzTV.Application.Emby;
public record SynchronizeEmbyCollections(int EmbyMediaSourceId, bool ForceScan, bool DeepScan, bool Unlock = true)
public record SynchronizeEmbyCollections(int EmbyMediaSourceId, bool ForceScan, bool DeepScan)
: IRequest<Either<BaseError, Unit>>,
IScannerBackgroundServiceRequest;
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
@@ -12,29 +12,12 @@ public class UpdateEmbyPathReplacementsHandler : IRequestHandler<UpdateEmbyPathR
public UpdateEmbyPathReplacementsHandler(IMediaSourceRepository mediaSourceRepository) =>
_mediaSourceRepository = mediaSourceRepository;
public async Task<Either<BaseError, Unit>> Handle(
public Task<Either<BaseError, Unit>> Handle(
UpdateEmbyPathReplacements request,
CancellationToken cancellationToken)
{
Option<EmbyMediaSource> maybeSource =
await _mediaSourceRepository.GetEmby(request.EmbyMediaSourceId, cancellationToken);
return await maybeSource.Match(
Some: async embyMediaSource =>
{
Option<BaseError> maybeError = ValidateItems(request, embyMediaSource);
return await maybeError.Match(
Some: error => Task.FromResult(Left<BaseError, Unit>(error)),
None: async () =>
{
await MergePathReplacements(request, embyMediaSource);
return Right<BaseError, Unit>(Unit.Default);
});
},
None: () => Task.FromResult(
Left<BaseError, Unit>(
BaseError.New($"Emby media source {request.EmbyMediaSourceId} does not exist."))));
}
CancellationToken cancellationToken) =>
Validate(request, cancellationToken)
.MapT(pms => MergePathReplacements(request, pms))
.Bind(v => v.ToEitherAsync());
private Task<Unit> MergePathReplacements(
UpdateEmbyPathReplacements request,
@@ -54,38 +37,12 @@ public class UpdateEmbyPathReplacementsHandler : IRequestHandler<UpdateEmbyPathR
private static EmbyPathReplacement Project(EmbyPathReplacementItem vm) =>
new() { Id = vm.Id, EmbyPath = vm.EmbyPath, LocalPath = vm.LocalPath };
// Defense-in-depth for design #202 findings 2c/8 — the repo UPDATE is scoped by
// EmbyMediaSourceId, but reject a foreign/blank/null row here too, before any write, so the
// mutation is all-or-nothing.
private static Option<BaseError> ValidateItems(
UpdateEmbyPathReplacements request,
EmbyMediaSource embyMediaSource)
{
List<EmbyPathReplacementItem> items = request.PathReplacements ?? [];
private Task<Validation<BaseError, EmbyMediaSource>> Validate(UpdateEmbyPathReplacements request, CancellationToken cancellationToken) =>
EmbyMediaSourceMustExist(request, cancellationToken);
if (items.Any(item => item is null))
{
return BaseError.New("Path replacement items must not be null.");
}
if (items.Any(item => string.IsNullOrWhiteSpace(item.EmbyPath) || string.IsNullOrWhiteSpace(item.LocalPath)))
{
return BaseError.New("Each path replacement requires a non-blank Emby path and local path.");
}
var existingIds = (embyMediaSource.PathReplacements ?? new List<EmbyPathReplacement>())
.Map(pr => pr.Id)
.ToList();
var foreignIds = items.Filter(item => item.Id > 0 && !existingIds.Contains(item.Id))
.Map(item => item.Id)
.ToList();
if (foreignIds.Count > 0)
{
return BaseError.New(
$"Path replacement id(s) {string.Join(", ", foreignIds)} do not belong to Emby media source " +
$"{request.EmbyMediaSourceId}.");
}
return Option<BaseError>.None;
}
private Task<Validation<BaseError, EmbyMediaSource>> EmbyMediaSourceMustExist(
UpdateEmbyPathReplacements request, CancellationToken cancellationToken) =>
_mediaSourceRepository.GetEmby(request.EmbyMediaSourceId, cancellationToken)
.Map(v => v.ToValidation<BaseError>(
$"Emby media source {request.EmbyMediaSourceId} does not exist."));
}
@@ -4,6 +4,7 @@
<TargetFramework>net10.0</TargetFramework>
<NoWarn>VSTHRD200,CA1873</NoWarn>
<ImplicitUsings>enable</ImplicitUsings>
<AnalysisLevel>latest-Recommended</AnalysisLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Configurations>Debug;Release;Debug No Sync</Configurations>
</PropertyGroup>
@@ -14,7 +15,6 @@
<PackageReference Include="MediatR" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Identity.Core" />
<PackageReference Include="Newtonsoft.Json" />
<PackageReference Include="Serilog.Formatting.Compact.Reader" />
<PackageReference Include="WebMarkupMin.Core" />
@@ -26,10 +26,4 @@
<ProjectReference Include="..\ErsatzTV.Infrastructure\ErsatzTV.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>ErsatzTV.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
</Project>
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.FFmpeg;
@@ -34,5 +34,4 @@ public record CreateFFmpegProfile(
int AudioSampleRate,
bool NormalizeFramerate,
bool NormalizeColors,
bool DeinterlaceVideo,
bool QsvPreferNativeDecoder) : IRequest<Either<BaseError, CreateFFmpegProfileResult>>;
bool DeinterlaceVideo) : IRequest<Either<BaseError, CreateFFmpegProfileResult>>;
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Search;
@@ -105,8 +105,7 @@ public class CreateFFmpegProfileHandler :
AudioSampleRate = request.AudioSampleRate,
NormalizeFramerate = request.NormalizeFramerate,
NormalizeColors = request.NormalizeColors,
DeinterlaceVideo = request.DeinterlaceVideo,
QsvPreferNativeDecoder = request.QsvPreferNativeDecoder
DeinterlaceVideo = request.DeinterlaceVideo
};
});
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.FFmpeg;
@@ -35,5 +35,4 @@ public record UpdateFFmpegProfile(
int AudioSampleRate,
bool NormalizeFramerate,
bool NormalizeColors,
bool DeinterlaceVideo,
bool QsvPreferNativeDecoder) : IRequest<Either<BaseError, UpdateFFmpegProfileResult>>;
bool DeinterlaceVideo) : IRequest<Either<BaseError, UpdateFFmpegProfileResult>>;
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.FFmpeg;
@@ -102,7 +102,6 @@ public class UpdateFFmpegProfileHandler(IDbContextFactory<TvContext> dbContextFa
p.NormalizeFramerate = update.NormalizeFramerate;
p.NormalizeColors = update.NormalizeColors;
p.DeinterlaceVideo = update.DeinterlaceVideo;
p.QsvPreferNativeDecoder = update.QsvPreferNativeDecoder;
// don't save invalid preset
ICollection<string> presets = FFmpegLibraryHelper.PresetsForFFmpegProfile(
@@ -140,7 +139,7 @@ public class UpdateFFmpegProfileHandler(IDbContextFactory<TvContext> dbContextFa
TvContext dbContext,
UpdateFFmpegProfile updateFFmpegProfile)
{
if (string.IsNullOrWhiteSpace(updateFFmpegProfile.Name) || updateFFmpegProfile.Name.Length > 50)
if (updateFFmpegProfile.Name.Length > 50)
{
return BaseError.New($"FFmpeg profile name \"{updateFFmpegProfile.Name}\" is invalid");
}
@@ -1,4 +1,4 @@
using ErsatzTV.Application.Resolutions;
using ErsatzTV.Application.Resolutions;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.FFmpeg;
@@ -35,5 +35,4 @@ public record FFmpegProfileViewModel(
int AudioSampleRate,
bool NormalizeFramerate,
bool NormalizeColors,
bool DeinterlaceVideo,
bool QsvPreferNativeDecoder);
bool DeinterlaceVideo);
+3 -11
View File
@@ -1,4 +1,4 @@
using ErsatzTV.Core.Api.FFmpegProfiles;
using ErsatzTV.Core.Api.FFmpegProfiles;
using ErsatzTV.Core.Domain;
namespace ErsatzTV.Application.FFmpegProfiles;
@@ -37,8 +37,7 @@ internal static class Mapper
profile.AudioSampleRate,
profile.NormalizeFramerate,
profile.NormalizeColors,
profile.DeinterlaceVideo == true,
profile.QsvPreferNativeDecoder != false);
profile.DeinterlaceVideo == true);
internal static FFmpegProfileResponseModel ProjectToResponseModel(FFmpegProfile ffmpegProfile) =>
new(
@@ -53,17 +52,13 @@ internal static class Mapper
ffmpegProfile.Id,
ffmpegProfile.Name,
ffmpegProfile.ThreadCount,
ffmpegProfile.NormalizeAudio,
ffmpegProfile.NormalizeVideo,
ffmpegProfile.HardwareAcceleration,
ffmpegProfile.VaapiDisplay,
ffmpegProfile.VaapiDriver,
ffmpegProfile.VaapiDevice,
ffmpegProfile.QsvExtraHardwareFrames,
ffmpegProfile.ResolutionId,
ffmpegProfile.Resolution.Name,
ffmpegProfile.ScalingBehavior,
ffmpegProfile.PadMode,
ffmpegProfile.VideoFormat,
ffmpegProfile.VideoProfile,
ffmpegProfile.VideoPreset,
@@ -76,11 +71,8 @@ internal static class Mapper
ffmpegProfile.AudioBitrate,
ffmpegProfile.AudioBufferSize,
ffmpegProfile.NormalizeLoudnessMode,
ffmpegProfile.TargetLoudness,
ffmpegProfile.AudioChannels,
ffmpegProfile.AudioSampleRate,
ffmpegProfile.NormalizeFramerate,
ffmpegProfile.NormalizeColors,
ffmpegProfile.DeinterlaceVideo == true,
ffmpegProfile.QsvPreferNativeDecoder != false);
ffmpegProfile.DeinterlaceVideo);
}
@@ -20,6 +20,4 @@ public record CreateFillerPreset(
int? PlaylistId,
string Expression,
bool UseChaptersAsMediaItems
) : IRequest<Either<BaseError, CreateFillerPresetResult>>;
public record CreateFillerPresetResult(int FillerPresetId) : EntityIdResult(FillerPresetId);
) : IRequest<Either<BaseError, Unit>>;
@@ -6,25 +6,23 @@ using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Filler;
public class CreateFillerPresetHandler(IDbContextFactory<TvContext> dbContextFactory)
: IRequestHandler<CreateFillerPreset, Either<BaseError, CreateFillerPresetResult>>
: IRequestHandler<CreateFillerPreset, Either<BaseError, Unit>>
{
public async Task<Either<BaseError, CreateFillerPresetResult>> Handle(
CreateFillerPreset request,
CancellationToken cancellationToken)
public async Task<Either<BaseError, Unit>> Handle(CreateFillerPreset request, CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, FillerPreset> validation = await Validate(dbContext, request);
return await validation.Apply(fp => Persist(dbContext, fp, cancellationToken));
}
private static async Task<CreateFillerPresetResult> Persist(
private static async Task<Unit> Persist(
TvContext dbContext,
FillerPreset fillerPreset,
CancellationToken cancellationToken)
{
await dbContext.FillerPresets.AddAsync(fillerPreset, cancellationToken);
await dbContext.SaveChangesAsync(cancellationToken);
return new CreateFillerPresetResult(fillerPreset.Id);
return Unit.Default;
}
private static Task<Validation<BaseError, FillerPreset>> Validate(
@@ -1,6 +1,5 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
@@ -19,14 +18,8 @@ public class DeleteFillerPresetHandler : IRequestHandler<DeleteFillerPreset, Eit
CancellationToken cancellationToken)
{
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
Option<FillerPreset> maybeFillerPreset = await FillerPresetMustExist(dbContext, request, cancellationToken);
// must-exist maps to a NotFoundError Either directly (not via Validation, which
// aggregates errors and loses the subtype the API layer maps to 404)
return await maybeFillerPreset.Match(
Some: fillerPreset => DoDeletion(dbContext, fillerPreset).Map(Right<BaseError, Unit>),
None: () => Task.FromResult<Either<BaseError, Unit>>(
new NotFoundError($"FillerPreset {request.FillerPresetId} does not exist.")));
Validation<BaseError, FillerPreset> validation = await FillerPresetMustExist(dbContext, request, cancellationToken);
return await validation.Apply(ps => DoDeletion(dbContext, ps));
}
private static Task<Unit> DoDeletion(TvContext dbContext, FillerPreset fillerPreset)
@@ -35,10 +28,11 @@ public class DeleteFillerPresetHandler : IRequestHandler<DeleteFillerPreset, Eit
return dbContext.SaveChangesAsync().ToUnit();
}
private static Task<Option<FillerPreset>> FillerPresetMustExist(
private static Task<Validation<BaseError, FillerPreset>> FillerPresetMustExist(
TvContext dbContext,
DeleteFillerPreset request,
CancellationToken cancellationToken) =>
dbContext.FillerPresets
.SelectOneAsync(fp => fp.Id, ps => ps.Id == request.FillerPresetId, cancellationToken);
.SelectOneAsync(fp => fp.Id, ps => ps.Id == request.FillerPresetId, cancellationToken)
.Map(o => o.ToValidation<BaseError>($"FillerPreset {request.FillerPresetId} does not exist."));
}
@@ -1,6 +1,5 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
@@ -13,19 +12,8 @@ public class UpdateFillerPresetHandler(IDbContextFactory<TvContext> dbContextFac
public async Task<Either<BaseError, Unit>> Handle(UpdateFillerPreset request, CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Option<FillerPreset> maybeFillerPreset = await FillerPresetMustExist(dbContext, request, cancellationToken);
// must-exist maps to a NotFoundError Either directly (not via Validation, which
// aggregates errors and loses the subtype the API layer maps to 404)
return await maybeFillerPreset.Match(
Some: async fillerPreset =>
{
Validation<BaseError, string> validation = await ValidateName(dbContext, request);
return await validation.Apply((string _) =>
ApplyUpdateRequest(dbContext, fillerPreset, request, cancellationToken));
},
None: () => Task.FromResult<Either<BaseError, Unit>>(
new NotFoundError($"FillerPreset {request.Id} does not exist.")));
Validation<BaseError, FillerPreset> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(ps => ApplyUpdateRequest(dbContext, ps, request, cancellationToken));
}
private static async Task<Unit> ApplyUpdateRequest(
@@ -56,12 +44,20 @@ public class UpdateFillerPresetHandler(IDbContextFactory<TvContext> dbContextFac
return Unit.Default;
}
private static Task<Option<FillerPreset>> FillerPresetMustExist(
private static async Task<Validation<BaseError, FillerPreset>> Validate(
TvContext dbContext,
UpdateFillerPreset request,
CancellationToken cancellationToken) =>
(await FillerPresetMustExist(dbContext, request, cancellationToken), await ValidateName(dbContext, request))
.Apply((collectionToUpdate, _) => collectionToUpdate);
private static Task<Validation<BaseError, FillerPreset>> FillerPresetMustExist(
TvContext dbContext,
UpdateFillerPreset request,
CancellationToken cancellationToken) =>
dbContext.FillerPresets
.SelectOneAsync(ps => ps.Id, ps => ps.Id == request.Id, cancellationToken);
.SelectOneAsync(ps => ps.Id, ps => ps.Id == request.Id, cancellationToken)
.Map(o => o.ToValidation<BaseError>("Filler preset does not exist"));
private static async Task<Validation<BaseError, string>> ValidateName(
TvContext dbContext,
+1 -20
View File
@@ -6,26 +6,7 @@ namespace ErsatzTV.Application.Filler;
internal static class Mapper
{
internal static FillerPresetResponseModel ProjectToResponseModel(FillerPreset fillerPreset) =>
new(fillerPreset.Id, fillerPreset.Name, fillerPreset.FillerKind);
internal static FillerPresetFullResponseModel ProjectToFullResponseModel(FillerPreset fillerPreset) =>
new(
fillerPreset.Id,
fillerPreset.Name,
fillerPreset.FillerKind,
fillerPreset.FillerMode,
fillerPreset.Duration,
fillerPreset.Count,
fillerPreset.PadToNearestMinute,
fillerPreset.AllowWatermarks,
fillerPreset.CollectionType,
fillerPreset.CollectionId,
fillerPreset.MediaItemId,
fillerPreset.MultiCollectionId,
fillerPreset.SmartCollectionId,
fillerPreset.PlaylistId,
fillerPreset.Expression,
fillerPreset.UseChaptersAsMediaItems);
new(fillerPreset.Id, fillerPreset.Name);
internal static FillerPresetViewModel ProjectToViewModel(FillerPreset fillerPreset) =>
new(
@@ -1,6 +1,5 @@
using ErsatzTV.Core.Api.Filler;
using ErsatzTV.Core.Domain.Filler;
namespace ErsatzTV.Application.Filler;
public record GetAllFillerPresetsForApi(FillerKind? FillerKind = null) : IRequest<List<FillerPresetResponseModel>>;
public record GetAllFillerPresetsForApi : IRequest<List<FillerPresetResponseModel>>;
@@ -14,13 +14,9 @@ public class GetAllFillerPresetsForApiHandler(IDbContextFactory<TvContext> dbCon
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
IQueryable<FillerPreset> query = dbContext.FillerPresets.AsNoTracking();
if (request.FillerKind is { } fillerKind)
{
query = query.Where(fp => fp.FillerKind == fillerKind);
}
List<FillerPreset> fillerPresets = await query.ToListAsync(cancellationToken);
List<FillerPreset> fillerPresets = await dbContext.FillerPresets
.AsNoTracking()
.ToListAsync(cancellationToken);
return fillerPresets.Map(ProjectToResponseModel).ToList();
}
}
@@ -1,5 +0,0 @@
using ErsatzTV.Core.Api.Filler;
namespace ErsatzTV.Application.Filler;
public record GetFillerPresetByIdForApi(int Id) : IRequest<Option<FillerPresetFullResponseModel>>;
@@ -1,22 +0,0 @@
using ErsatzTV.Core.Api.Filler;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
using static ErsatzTV.Application.Filler.Mapper;
namespace ErsatzTV.Application.Filler;
public class GetFillerPresetByIdForApiHandler(IDbContextFactory<TvContext> dbContextFactory)
: IRequestHandler<GetFillerPresetByIdForApi, Option<FillerPresetFullResponseModel>>
{
public async Task<Option<FillerPresetFullResponseModel>> Handle(
GetFillerPresetByIdForApi request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
return await dbContext.FillerPresets
.AsNoTracking()
.SelectOneAsync(fp => fp.Id, fp => fp.Id == request.Id, cancellationToken)
.MapT(ProjectToFullResponseModel);
}
}
+1 -16
View File
@@ -10,11 +10,7 @@ internal static class Mapper
result.Title,
GetStatus(result.Status),
result.Message,
string.IsNullOrWhiteSpace(result.BriefMessage) ? null : result.BriefMessage,
result.Link.MatchUnsafe(l => l.Target, () => (string)null),
result.Link.MatchUnsafe(
l => new HealthCheckRemediationResponseModel(GetLinkKind(l.Kind), l.Target),
() => (HealthCheckRemediationResponseModel)null));
result.Link.MatchUnsafe(l => l.Link, () => null));
private static string GetStatus(HealthCheckStatus status) =>
status switch
@@ -23,17 +19,6 @@ internal static class Mapper
HealthCheckStatus.Fail => "fail",
HealthCheckStatus.Warning => "warn",
HealthCheckStatus.Info => "info",
// NotApplicable is filtered out before mapping today; map it defensively rather
// than throwing, so a future caller that skips the filter can't 500 the endpoint.
HealthCheckStatus.NotApplicable => "notApplicable",
_ => throw new ArgumentOutOfRangeException(nameof(status), status, null)
};
private static string GetLinkKind(HealthCheckLinkKind kind) =>
kind switch
{
HealthCheckLinkKind.ExternalDoc => "ExternalDoc",
HealthCheckLinkKind.AppRoute => "AppRoute",
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, null)
};
}
@@ -2,4 +2,4 @@ using ErsatzTV.Core.Api.Health;
namespace ErsatzTV.Application.Health;
public record GetAllHealthCheckResultsForApi(bool Refresh = false) : IRequest<List<HealthCheckResponseModel>>;
public record GetAllHealthCheckResultsForApi : IRequest<List<HealthCheckResponseModel>>;
@@ -18,8 +18,7 @@ public class GetAllHealthCheckResultsForApiHandler
{
try
{
List<HealthCheckResult> results =
await _healthCheckService.PerformHealthChecks(request.Refresh, cancellationToken);
List<HealthCheckResult> results = await _healthCheckService.PerformHealthChecks(cancellationToken);
return results
.Filter(r => r.Status != HealthCheckStatus.NotApplicable)
.Map(ProjectToResponseModel)
@@ -1,4 +1,4 @@
using ErsatzTV.Core.Health;
using ErsatzTV.Core.Health;
namespace ErsatzTV.Application.Health;
@@ -15,7 +15,7 @@ public class GetAllHealthCheckResultsHandler : IRequestHandler<GetAllHealthCheck
{
try
{
List<HealthCheckResult> results = await _healthCheckService.PerformHealthChecks(false, cancellationToken);
List<HealthCheckResult> results = await _healthCheckService.PerformHealthChecks(cancellationToken);
return results.Filter(r => r.Status != HealthCheckStatus.NotApplicable).ToList();
}
catch (Exception ex) when (ex is TaskCanceledException or OperationCanceledException)

Some files were not shown because too many files have changed in this diff Show More