From ba440ffbe9c77254ad5841a5318137cd2a196ff4 Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 21:26:35 -0600 Subject: [PATCH 01/24] plans: network, image commands, fm on MetaBrainz, security, test and release Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 2 + Plans/01 Network/S001-upload-by-speed.md | 37 +++++++++++++++++++ Plans/01 Network/S002-outbound-timeouts.md | 35 ++++++++++++++++++ Plans/01 Network/S003-recovery-and-shaping.md | 34 +++++++++++++++++ .../S004-remove-image-add-caption.md | 34 +++++++++++++++++ Plans/02 Image commands/S005-speechbubble.md | 33 +++++++++++++++++ Plans/03 fm commands/S006-fm-on-metabrainz.md | 36 ++++++++++++++++++ Plans/04 Security/S007-website-security.md | 33 +++++++++++++++++ Plans/04 Security/S008-media-commands-deps.md | 34 +++++++++++++++++ .../S009-test-runs-and-network.md | 28 ++++++++++++++ .../S010-test-images-security-app.md | 29 +++++++++++++++ .../S011-deploy-and-owner-check.md | 28 ++++++++++++++ Plans/INDEX.md | 22 ++++++++++- docs/DECISIONS.md | 1 + 14 files changed, 384 insertions(+), 2 deletions(-) create mode 100644 Plans/01 Network/S001-upload-by-speed.md create mode 100644 Plans/01 Network/S002-outbound-timeouts.md create mode 100644 Plans/01 Network/S003-recovery-and-shaping.md create mode 100644 Plans/02 Image commands/S004-remove-image-add-caption.md create mode 100644 Plans/02 Image commands/S005-speechbubble.md create mode 100644 Plans/03 fm commands/S006-fm-on-metabrainz.md create mode 100644 Plans/04 Security/S007-website-security.md create mode 100644 Plans/04 Security/S008-media-commands-deps.md create mode 100644 Plans/05 Test and release/S009-test-runs-and-network.md create mode 100644 Plans/05 Test and release/S010-test-images-security-app.md create mode 100644 Plans/05 Test and release/S011-deploy-and-owner-check.md diff --git a/PLAN.md b/PLAN.md index 950571a..9e95e16 100644 --- a/PLAN.md +++ b/PLAN.md @@ -16,6 +16,8 @@ security test has been done beyond earlier spot fixes. `/image` (`D!fx`) bundles recovering from drops, shaping tuned with the bot. - Phase 2 — Image commands: `/image` and `D!fx` removed; `/speechbubble` and `/caption` (and their `D!` versions) work like the well-known caption bots. +- Phase 2b — fm commands: every fm feature gets its data from ListenBrainz and MusicBrainz (plus the cover + fallbacks), with no leftover Last.fm API logic; only song links still point to the Last.fm website. - Phase 3 — Security: website and dashboard, media inputs, commands and abuse, dependency audit; fixes for what is found; tested on a local copy only. - Phase 4 — Deploy and owner check in Discord. diff --git a/Plans/01 Network/S001-upload-by-speed.md b/Plans/01 Network/S001-upload-by-speed.md new file mode 100644 index 0000000..01ed1b4 --- /dev/null +++ b/Plans/01 Network/S001-upload-by-speed.md @@ -0,0 +1,37 @@ +# S001 — Uploads timed by line speed + +> Category 01 Network · Model: Sonnet · Effort: medium · Depends on: — · Size: L · Human: no +> Files touched: src/commands/media/mod.rs, src/commands/media/download/{mod,plan}.rs, src/commands/media/convert.rs, src/commands/music/card.rs, src/hosted.rs, src/main.rs, other callers of attachments + +## Goal +Every Discord upload is planned in seconds, not bytes (D-001): a result that would not upload in about 60-90 s at the measured ~114 KB/s, or is over the server's Discord limit, is sent as a website link (`hosted.rs`) instead. Uploads are retried only on errors that can succeed the second time; a timed-out upload is never repeated as is. PLAN Phase 1, first bullet. + +## Read +- `src/commands/media/mod.rs` `upload_limit` (line ~130; still says 20 MiB for tier 0/1, Discord's real bot limit is 10 MiB) +- `src/commands/media/download/mod.rs` lines ~30-80 (constants) and ~290-400 (`upload`, `download`) +- `src/commands/media/download/plan.rs` top constants (`FALLBACK_UPLOAD_LIMIT`) +- `src/hosted.rs` (whole, 102 lines) +- `src/main.rs` line ~527 (Discord client with 180 s timeout) +- `grep -rn "Attachment::from_bytes\|attachments(" src` to list the other upload paths; read only the call sites + +## Steps +- [ ] Fold in the owner's loose edit (seen uncommitted in the main checkout, not in this worktree): tier 0/1 limit is 10 MiB, `FALLBACK_UPLOAD_LIMIT` = 10 MiB, `upload_limit` returns the real Discord limit (10/50/100 MiB) — do it here cleanly, with a newline after `let limit = …;` +- [ ] Add one shared helper in `media/mod.rs` that returns the byte budget for one upload: `min(discord_limit, UPLOAD_SECONDS × UPLOAD_BYTES_PER_SEC)`, both named constants with a comment (114 KB/s measured 2026-11-12, see CLAUDE.md §2), plus a pure function with a unit test +- [ ] `/download`: plan the target size from that budget; anything bigger goes to `hosted.rs` as a link (existing path); retry only on errors that are not timeouts (connection reset before sending, 5xx, rate limit); a timeout ends retries and falls back to the link +- [ ] Other upload paths (convert, music animated card, quote, the grep list): use the same budget; oversize → link or a smaller encode, whichever the path already supports +- [ ] Discord HTTP timeout: keep 180 s for uploads, but give plain API calls a shorter timeout if twilight allows it per request; otherwise write in PROGRESS "Later" why not +- [ ] `docs/tests/S001-upload-by-speed.md` from the test-file template (checks: budget math, link fallback, no retry after timeout, each upload path) +- [ ] PROGRESS entry, INDEX line, commit `S001: …` + +## End criteria +- `source ~/.cargo/env; cargo build` compiles with no new warnings. +- `grep -n "UPLOAD_RETRIES" src` shows the retry only on retryable errors. +- `ls docs/tests/S001-*` exists. + +## Pitfalls +- No test runs, release builds or server deploys in this plan; the test phase does them. +- Don't touch `.env` or `data/`. The hosted link must keep the private-network checks. +- Upload time, not file size, is what breaks (CLAUDE.md §4). + +## Handoff (→ PROGRESS.md) +Name of the budget helper and its constants, so S002 and S008 reuse them. diff --git a/Plans/01 Network/S002-outbound-timeouts.md b/Plans/01 Network/S002-outbound-timeouts.md new file mode 100644 index 0000000..50d688f --- /dev/null +++ b/Plans/01 Network/S002-outbound-timeouts.md @@ -0,0 +1,35 @@ +# S002 — Timeouts on every outbound call + +> Category 01 Network · Model: Sonnet · Effort: medium · Depends on: S001 · Size: M · Human: no +> Files touched: src/state.rs, src/commands/media/download/tools.rs, src/commands/media/{ffmpeg,convert,quote,emoji}.rs, src/commands/music/{source,ytdl}.rs, other files found by the grep + +## Goal +Every outbound HTTP call and every child process (yt-dlp, ffmpeg, gallery-dl, curl) has a named time limit, is killed when it runs over, and ends in a plain error card. Nothing can hang a command forever on the slow line. D-002, PLAN Phase 1 third bullet. + +## Read +- `src/state.rs` line ~50 (shared reqwest client, 20 s timeout) +- `src/commands/media/download/tools.rs` lines ~25-130 (the run-with-cancel helper and yt-dlp args) +- `grep -rn "Command::new\|tokio::process" src` and `grep -rn "reqwest::Client\|\.timeout(" src`: read only call sites without a timeout or kill +- `src/error.rs` (`bail_user!`) + +## Steps +- [ ] List every outbound call site and child process with its current limit; put the list in the test file's Built section +- [ ] Child processes: one shared run helper (reuse `tools.rs` if it fits) with a time limit, `kill_on_drop(true)` and a clear error; switch every caller that lacks one +- [ ] HTTP: calls that download big bodies (media fetch, covers) get a size cap and a total timeout; separate clients built outside `state.rs` get timeouts +- [ ] Time limits as named constants next to their use, with why the number (e.g. download size ÷ 425 KB/s down) +- [ ] User errors: timeouts show "took too long" cards through `bail_user!`, not raw errors +- [ ] `docs/tests/S002-outbound-timeouts.md` (checks: a stuck child is killed, a slow server times out, error card text) +- [ ] PROGRESS entry, INDEX line, commit `S002: …` + +## End criteria +- `cargo build` compiles. +- `grep -rn "Command::new" src` call sites all go through a helper with a timeout, or the test file says why not. +- `ls docs/tests/S002-*` exists. + +## Pitfalls +- Never pass user text where it can become an option (`--`). Keep `safe_redirects` on every fetch. +- Music streaming processes run for the whole song: their limit is "no data for N s", not total time. +- No test runs here. + +## Handoff (→ PROGRESS.md) +The helper's name and the list of limits. diff --git a/Plans/01 Network/S003-recovery-and-shaping.md b/Plans/01 Network/S003-recovery-and-shaping.md new file mode 100644 index 0000000..f4cffe5 --- /dev/null +++ b/Plans/01 Network/S003-recovery-and-shaping.md @@ -0,0 +1,34 @@ +# S003 — Gateway, voice and music recovery; shaping + +> Category 01 Network · Model: Sonnet · Effort: medium · Depends on: S002 · Size: M · Human: no +> Files touched: src/main.rs (gateway loop), src/commands/music/{mod,source}.rs, deploy/shape-upload.sh + +## Goal +The bot recovers by itself when the line drops: the gateway reconnects, voice reconnects or leaves cleanly, the music queue resumes or tells the user, and nothing stays stuck. The upload shaping (`dezio-shape`) is checked against real numbers and tuned. PLAN Phase 1, bullets four and five. + +## Read +- `src/main.rs` lines ~520-600 (client and the `shard.next_event` loop) +- `src/commands/music/mod.rs`: the voice join and track-end/error handlers only (grep `songbird`, `Event::`, `disconnect`) +- `deploy/shape-upload.sh` +- Server, read-only first: `ssh root@192.168.1.71 'journalctl -u dezio-bot --since -7d | grep -iE "reconnect|disconnect|gateway|voice" | tail -50; tc -s qdisc show dev wlan0'` + +## Steps +- [ ] From the logs, list the drop cases that happened; add them to the test file +- [ ] Gateway: errors from `next_event` never end the loop silently; fatal ones are logged and the process exits so systemd restarts it (Restart=always) +- [ ] Voice/music: on a voice driver disconnect, try to reconnect a named number of times, then leave and tell the channel; no queue or "now playing" state left stuck +- [ ] Shaping: measure upload once on the server (small timed upload, no external speed sites besides what the script already uses), adjust the cap in `shape-upload.sh` if the measure says so, with the number and date in a comment. Tell the orchestrator before reinstalling `dezio-shape` on the server; back up `/usr/local/bin/dezio-shape` first (D-005) +- [ ] `docs/tests/S003-recovery-and-shaping.md` +- [ ] PROGRESS entry, INDEX line, commit `S003: …` + +## End criteria +- `cargo build` compiles. +- `ssh root@192.168.1.71 systemctl is-active dezio-shape` says active (if it was reinstalled). +- `ls docs/tests/S003-*` exists. + +## Pitfalls +- Never run the bot with the real token on this PC. +- Do not deploy the bot binary in this plan; S011 does it. +- Never connect to Tor or proxies. + +## Handoff (→ PROGRESS.md) +Measured upload speed and the new cap, if changed. diff --git a/Plans/02 Image commands/S004-remove-image-add-caption.md b/Plans/02 Image commands/S004-remove-image-add-caption.md new file mode 100644 index 0000000..d528f67 --- /dev/null +++ b/Plans/02 Image commands/S004-remove-image-add-caption.md @@ -0,0 +1,34 @@ +# S004 — Remove /image, add /caption + +> Category 02 Image commands · Model: Sonnet · Effort: medium · Depends on: — · Size: M · Human: no +> Files touched: src/commands/media/images.rs, src/commands/media/mod.rs, src/commands/help.rs (if it lists /image), web pages that list commands + +## Goal +`/image` and `D!fx` are removed with every effect and filter (D-003). New `/caption` and `D!caption` put a white band with the text above the picture, Assyst style. Inputs: PNG, JPG, WebP (still and animated), GIF, MP4/WebM/MOV (D-008); animated input stays animated, video comes back in a format Discord plays. Options: `source-attachment`, `source-link`, `text`; with no source it uses the replied/latest chat picture (D-007). `/petpet` and `/convert` stay. `convert.rs` imports `images::pick_opt`: keep it working. + +## Read +- `src/commands/media/images.rs` lines 160-200 (`speech_bubble`, `caption`), 240-320 (frames, GIF, `process`), 320-560 (`pick_opt`, `pick`, `run_job`, `image_cmd`, `petpet`, `commands`) +- `src/commands/media/ffmpeg.rs` only the parts for decoding video to frames and encoding back (grep `fn `) +- `docs/DECISIONS.md` D-003, D-007, D-008 +- `grep -rn "D!fx\|/image\|\"fx\"" src web` for help and website mentions + +## Steps +- [ ] Remove `/image`, `D!fx`, `apply_filter`, `apply_effect`, effects/filters and their tests; keep `pick_opt`, `pick`, frame and GIF helpers, `petpet` +- [ ] Caption drawing: white band sized to the wrapped text (fonts in `assets/`), text centred, black; band width = picture width; pure function with a unit test on band height for 1 and 3 lines +- [ ] Media: still → PNG/JPG kept; GIF/animated WebP → GIF with every frame captioned; video → ffmpeg frames out, caption each, encode back (or ffmpeg `pad` + `drawtext` if simpler and the font is available); size limits through S001's budget helper if it exists, else `media::upload_limit` +- [ ] Register `/caption` (slash + `D!caption`), help page entry, remove `/image` from help and website lists +- [ ] `docs/tests/S004-caption.md` (checks per media type, empty text, very long text, huge input, bad link) +- [ ] PROGRESS entry, INDEX line, commit `S004: …` + +## End criteria +- `cargo build` compiles. +- `grep -rn "D!fx\|apply_filter\|apply_effect" src web` returns nothing. +- `ls docs/tests/S004-*` exists. + +## Pitfalls +- Help pages must stay within Discord's limits (the help-limits test runs in the test phase). +- Video frames can be huge: cap frame count and size with named constants. +- No test runs here. + +## Handoff (→ PROGRESS.md) +Names of the shared media in/out helpers S005 reuses. diff --git a/Plans/02 Image commands/S005-speechbubble.md b/Plans/02 Image commands/S005-speechbubble.md new file mode 100644 index 0000000..6698ef2 --- /dev/null +++ b/Plans/02 Image commands/S005-speechbubble.md @@ -0,0 +1,33 @@ +# S005 — /speechbubble + +> Category 02 Image commands · Model: Sonnet · Effort: medium · Depends on: S004 · Size: M · Human: no +> Files touched: src/commands/media/images.rs (or a new speechbubble.rs next to it), src/commands/help.rs + +## Goal +`/speechbubble` and `D!speechbubble` as in D-007, D-008 and D-009: a wide ellipse hanging off the top (or bottom) edge with a tail pointing into the picture. Options `source-attachment`, `source-link`, `position` top|bottom, `flip` (tail to the other side), `solid` (white fill with black outline, BSM style); without `solid` the bubble is cut out transparent (Assyst style) where the format allows. Same media types as `/caption`, through the helpers S004 left. + +## Read +- `docs/DECISIONS.md` D-007, D-008, D-009 +- S004's PROGRESS entry (helper names) +- `src/commands/media/images.rs`: the old `speech_bubble` (if S004 kept it) and the caption command as the pattern +- Look at a few frames of `assets/reference/speechbubble-bsm.gif` and `speechbubble-assyst.gif` (extract 2 frames with ffmpeg to the scratchpad and view them) + +## Steps +- [ ] Bubble shape as a pure function: ellipse + tail mask for (width, height, position, flip); unit test that the tail side flips and that the mask touches the chosen edge +- [ ] Draw: transparent cutout (alpha 0 inside the mask) or solid (white fill + black outline); the picture's edge follows the bubble's curve +- [ ] Media: PNG out for still transparent; GIF with transparency for animated; video → GIF (transparency) or same format when `solid` +- [ ] Register command (slash + `D!`), help entry +- [ ] `docs/tests/S005-speechbubble.md` (checks per option and media type, compare with both reference GIFs on a contact sheet) +- [ ] PROGRESS entry, INDEX line, commit `S005: …` + +## End criteria +- `cargo build` compiles. +- `ls docs/tests/S005-*` exists. + +## Pitfalls +- GIF transparency is one colour index: pick a key colour no frame uses. +- JPG cannot be transparent: output PNG. +- No test runs here; one quick render of a sample to the scratchpad to look at the shape is fine. + +## Handoff (→ PROGRESS.md) +What the owner should try in Discord (🧑 in S011). diff --git a/Plans/03 fm commands/S006-fm-on-metabrainz.md b/Plans/03 fm commands/S006-fm-on-metabrainz.md new file mode 100644 index 0000000..077760b --- /dev/null +++ b/Plans/03 fm commands/S006-fm-on-metabrainz.md @@ -0,0 +1,36 @@ +# S006 — fm logic fully on ListenBrainz and MusicBrainz + +> Category 03 fm commands · Model: Sonnet · Effort: medium · Depends on: — · Size: M · Human: no +> Files touched: src/commands/lastfm/{api,mod,views,extras,art,covers}.rs, src/web/api.rs (fm link), web/ dashboard text if needed + +## Goal +The owner moved the fm commands from the Last.fm API to ListenBrainz (D-010) with covers from a fallback chain (D-011). Check over all the old fm logic: everything that used Last.fm data must now get it from ListenBrainz and MusicBrainz (plus the D-011 cover/photo fallbacks), with no hidden reliance on Last.fm-only fields. Only song links may still point to the Last.fm website (D-010). + +## Read +- `docs/DECISIONS.md` D-010, D-011 +- The two 2026-12-01 entries in `docs/PROGRESS.md` (known differences) +- `src/commands/lastfm/api.rs` (whole, 401 lines: the ListenBrainz → old Last.fm shape adapter) +- `grep -n "fn \|\[\"" src/commands/lastfm/{mod,views,extras,art}.rs` to find every field read from the adapter's JSON; read only the call sites +- `src/web/api.rs` lines ~155-240 (dashboard fm link) + +## Steps +- [ ] List every fm feature (top lists, recent, profile, now playing, Who Knows, chart, Pixel Jumble, lyrics, dashboard link, any other user of `lastfm::`) and, for each, the JSON fields it reads; put the list in the test file's Built section +- [ ] For every field, check the adapter fills it from ListenBrainz/MusicBrainz; fields Last.fm used to give that the adapter leaves empty (listeners, global playcount, user registered date, artist bio, tags, images) either get a MusicBrainz/ListenBrainz source or are removed from the card with no empty labels left +- [ ] Remove dead Last.fm-only code (API key reads, method names, `audioscrobbler` leftovers, unused shapes); keep song links to the Last.fm website +- [ ] User-facing text (help, error cards, dashboard, website, privacy) says ListenBrainz where it means the data source; fm errors (unknown ListenBrainz user, stats not ready yet) give plain cards +- [ ] New pure logic (field mapping) gets a unit test with a saved ListenBrainz JSON sample, no network +- [ ] `docs/tests/S006-fm-on-metabrainz.md` (one check per feature, live checks marked `cargo test listenbrainz_live -- --ignored`) +- [ ] PROGRESS entry, INDEX line, commit `S006: …` + +## End criteria +- `cargo build` compiles. +- `grep -rni "audioscrobbler\|api_key\|LASTFM_API" src` returns nothing (or the test file says why a line stays). +- `ls docs/tests/S006-*` exists. + +## Pitfalls +- Do not touch `data/lastfm.json` (kept untouched, D-010); links live in `data/listenbrainz.json`. +- MusicBrainz needs the `Dezio/ (Discord bot)` user agent and about 1 request per second; don't add calls in loops without the existing rate handling. +- Keep the git tag `lastfm-api-backup` as is. No test runs here besides a compile check. + +## Handoff (→ PROGRESS.md) +Fields dropped from cards, and any fm feature that still can't match its Last.fm behaviour. diff --git a/Plans/04 Security/S007-website-security.md b/Plans/04 Security/S007-website-security.md new file mode 100644 index 0000000..1397de6 --- /dev/null +++ b/Plans/04 Security/S007-website-security.md @@ -0,0 +1,33 @@ +# S007 — Website and dashboard security + +> Category 04 Security · Model: Opus (hostile input, auth) · Effort: medium · Depends on: — · Size: L · Human: no +> Files touched: src/web/{mod,api,activity}.rs, web/ pages if needed + +## Goal +Find and fix security faults in the website, dashboard API, OAuth sign-in and Game Boy Activity (D-004). Attack traffic only against the local copy on 127.0.0.1:8099 (`--web-dev`), never the live site. + +## Read +- `src/web/mod.rs` (whole, 512 lines: sessions, cookies, `check_write`, OAuth, headers middleware, router) +- `src/web/api.rs` routes and the handlers that write +- `src/web/activity.rs` routes only (grep `route`, `fn `) +- CLAUDE.md §2 (local website command) + +## Steps +- [ ] Review against a checklist written into the test file: auth on every API route, guild permission checks (user must manage the guild he edits), CSRF on writes (`check_write`), OAuth state, cookie flags, session expiry, input size limits, path traversal in static files, security headers, error leaks, rate limits on login and writes, WebSocket/activity input +- [ ] Probe the local copy with curl for each item (start `--web-dev`, stop it at the end); write findings with severity in the test file +- [ ] Fix every HIGH and MED finding in the code; each fix gets a unit test when it is pure logic, otherwise a check in the test file +- [ ] LOW findings: fix if under a few lines, else PROGRESS "Later" +- [ ] `docs/tests/S007-website-security.md` (checklist, findings, checks) +- [ ] PROGRESS entry, INDEX line, commit `S007: …` + +## End criteria +- `cargo build` compiles. +- The test file lists every checklist item with a finding or "fine because …". + +## Pitfalls +- Never send traffic to https://archlinux.tail7c4f5e.ts.net or Discord. No Tor or proxies. +- Never run the bot with the real token; `--web-dev` uses `DISCORD_BOT_TOKEN=dev-placeholder`. +- Don't break the existing web tests in `src/web/mod.rs`. + +## Handoff (→ PROGRESS.md) +Open findings not fixed, with severity. diff --git a/Plans/04 Security/S008-media-commands-deps.md b/Plans/04 Security/S008-media-commands-deps.md new file mode 100644 index 0000000..78174d8 --- /dev/null +++ b/Plans/04 Security/S008-media-commands-deps.md @@ -0,0 +1,34 @@ +# S008 — Media inputs, commands and dependencies + +> Category 04 Security · Model: Opus (hostile input) · Effort: medium · Depends on: S002 · Size: M · Human: no +> Files touched: src/commands/media/**, src/commands/music/{source,ytdl}.rs, src/cmd.rs, Cargo.toml/Cargo.lock if a dependency must move + +## Goal +Make media inputs, commands and dependencies safe against hostile users (D-004): links and files fed to yt-dlp, ffmpeg, gallery-dl and curl; decoding bombs; private-network fetches; command spam; known-vulnerable crates. + +## Read +- `src/commands/media/mod.rs` (`safe_redirects`, media fetch, line ~40-130) +- S002's PROGRESS entry (process helper) and the call-site list in `docs/tests/S002-outbound-timeouts.md` +- `src/commands/music/source.rs` the private-network check (grep `private\|loopback`) +- `src/cmd.rs` the dispatch and any cooldown code (grep `cooldown\|rate`) + +## Steps +- [ ] Child processes: every user link goes after `--`, scheme limited to http(s), no `file:`/`data:`/local paths; ffmpeg protocol whitelist on inputs +- [ ] Private network: every fetch (reqwest, yt-dlp, gallery-dl, ffmpeg, curl) blocks loopback/LAN/Tailscale ranges, including after redirects and DNS rebinding where it can be checked +- [ ] Decode bombs: image and GIF decoding has limits on width, height, frame count and memory (`image` crate `Limits`); named constants +- [ ] Abuse: per-user cooldown or concurrency limit on heavy commands (media, download, caption, speechbubble) if none exists +- [ ] Dependencies: install and run `cargo audit` and `cargo deny check advisories`; update crates with fixes where it is a patch/minor bump, list the rest +- [ ] `docs/tests/S008-media-commands-deps.md` (hostile inputs list, audit output summary) +- [ ] PROGRESS entry, INDEX line, commit `S008: …` + +## End criteria +- `cargo build` compiles. +- `cargo audit` output saved in the test file; no unfixed HIGH advisory without a reason. + +## Pitfalls +- No attack traffic outside 127.0.0.1. Never connect to Tor or proxies. +- Don't loosen the existing checks while refactoring them. +- No test runs here. + +## Handoff (→ PROGRESS.md) +Advisories left open. diff --git a/Plans/05 Test and release/S009-test-runs-and-network.md b/Plans/05 Test and release/S009-test-runs-and-network.md new file mode 100644 index 0000000..1c4d36f --- /dev/null +++ b/Plans/05 Test and release/S009-test-runs-and-network.md @@ -0,0 +1,28 @@ +# S009 — Test: it runs, and network + +> Category 05 Test and release · Model: Sonnet · Effort: medium · Depends on: S001, S002, S003 · Phase: test · Human: no +> Files touched: tests and fixes in src/**, docs/tests/S001-*, S002-*, S003-*, docs/TEST-REPORT.md + +## Goal +First make sure everything builds and the existing suite passes (fix breakage first). Then run the checks of `docs/tests/S001-upload-by-speed.md`, `S002-outbound-timeouts.md`, `S003-recovery-and-shaping.md`, fix what fails, and fill in every Result. + +## Read +- those three test files, all in one command; code only where a check needs it +- CLAUDE.md §2 and §5 for the build and test commands + +## Steps +- [ ] It runs: `cargo build --release`, `cargo test` once (worktree-only failures from missing `assets/data` and ROMs are known, see PROGRESS), `target/debug/dezio` lists commands and exits; fix breakage first +- [ ] Doubts first: read the code behind each doubt in the three files and add a check, or write why it is fine +- [ ] Write the tests for all HIGH and MED checks in one go; share fixtures (a local slow HTTP server on 127.0.0.1, a stuck child process); no test for what the compiler already proves +- [ ] Run them once, all together, short output; save the log to a file and read only the failures +- [ ] Sort the failures by cause, then fix all causes in one go; a wrong test is corrected, never weakened to pass +- [ ] Rerun only what failed; three rounds at most, then `KNOWN BUG` with the cause +- [ ] Results filled in, `docs/TEST-REPORT.md` line, PROGRESS entry, INDEX line, commit `S009: …` + +## End criteria +- `cargo test` green, except listed known bugs and worktree-only asset failures +- no `—` left in the Result column of the three files: `pass`, `fixed`, `KNOWN BUG`, or `not run: why` + +## Pitfalls +- Never run with the real token; never call Discord. Discord-only checks are `not run: needs Discord`. +- Live-internet tests stay `#[ignore]`. diff --git a/Plans/05 Test and release/S010-test-images-security-app.md b/Plans/05 Test and release/S010-test-images-security-app.md new file mode 100644 index 0000000..9418a24 --- /dev/null +++ b/Plans/05 Test and release/S010-test-images-security-app.md @@ -0,0 +1,29 @@ +# S010 — Test: images, fm, security, whole app + +> Category 05 Test and release · Model: Sonnet · Effort: medium · Depends on: S004, S005, S006, S007, S008, S009 · Phase: test · Human: no +> Files touched: tests and fixes in src/**, docs/tests/S004-* to S008-*, docs/TEST-REPORT.md + +## Goal +Run the checks of `docs/tests/S004-caption.md`, `S005-speechbubble.md`, `S006-fm-on-metabrainz.md`, `S007-website-security.md`, `S008-media-commands-deps.md`, fix what fails, fill in every Result. Then the whole-app pass: help limits, command registry, website journeys, hostile input on everything that listens or parses, restart with old data. + +## Read +- those five test files, all in one command; code only where a check needs it +- CLAUDE.md §2 and §5 + +## Steps +- [ ] Doubts first: read the code behind each doubt and add a check, or write why it is fine +- [ ] Write the tests for all HIGH and MED checks in one go; share fixtures (sample PNG, JPG, GIF, animated WebP, short MP4/WebM/MOV generated with ffmpeg into the scratchpad) +- [ ] Run them once, all together, short output; save the log and read only the failures +- [ ] Sort the failures by cause, fix all causes in one go; rerun only what failed; three rounds at most, then `KNOWN BUG` +- [ ] Screen checks: one contact sheet of caption and speechbubble outputs (every option, every media type) next to both reference GIFs, looked at once, faults fixed in one go, one more sheet +- [ ] Whole app: `cargo test` (help-limits and registry tests included); `--web-dev` journey (pages, sign-in gate, dashboard API refuses without session); hostile input replay from S007/S008; start with a copy of old-format data files from the repo fixtures if any +- [ ] Results filled in, `docs/TEST-REPORT.md` lines, PROGRESS entry, INDEX line, commit `S010: …` + +## End criteria +- `cargo test` green, except listed known bugs +- no `—` left in the Result column of the five files +- `rg -n "\| — \||KNOWN BUG|not run" docs/tests` shows no open HIGH + +## Pitfalls +- Local copy only for security replays; never the live site, Discord, Tor or proxies. +- Discord rendering is checked by the owner in S011 (🧑), not here. diff --git a/Plans/05 Test and release/S011-deploy-and-owner-check.md b/Plans/05 Test and release/S011-deploy-and-owner-check.md new file mode 100644 index 0000000..57d154c --- /dev/null +++ b/Plans/05 Test and release/S011-deploy-and-owner-check.md @@ -0,0 +1,28 @@ +# S011 — Deploy and owner check + +> Category 05 Test and release · Model: Sonnet · Effort: medium · Depends on: S010 · Phase: test · Human: 🧑 owner tries /speechbubble and /caption in Discord +> Files touched: server /root/Dezio (binary, assets/, web/), docs/PROGRESS.md, docs/TEST-REPORT.md + +## Goal +Deploy the finished bot to the Chromebook, check it starts cleanly, and have the owner check the two image commands in Discord (D-006). PLAN Phase 4. + +## Read +- CLAUDE.md §2 (deploy steps) +- `docs/TEST-REPORT.md` and `rg -n "\| — \||KNOWN BUG|not run" docs/tests` (gate: no open HIGH) +- S005's PROGRESS entry (what the owner should try) + +## Steps +- [ ] Gate: no open HIGH check or HIGH known bug; otherwise stop and report to the orchestrator +- [ ] Tell the orchestrator before deploying; `cargo build --release`; scp to `dezio.new`; on the server back up `dezio` as `dezio.bak-`, move in, `rsync -a` changed `assets/` and `web/`, `systemctl restart dezio-bot` +- [ ] Check `systemctl status dezio-bot` and `journalctl -u dezio-bot -n 50`: logged in, commands registered, no errors; `curl -sI https://archlinux.tail7c4f5e.ts.net` (plain GET, not attack traffic) returns 200 +- [ ] 🧑 Owner tries `/caption` and `/speechbubble` (every option, a GIF and a video) and `/download` of a ~9 MB video; record the answers in the test report +- [ ] PROGRESS entry, INDEX line, commit `S011: …` and push to `origin` + +## End criteria +- `ssh root@192.168.1.71 systemctl is-active dezio-bot` says active +- Owner's answers recorded in `docs/TEST-REPORT.md` + +## Pitfalls +- Never run the bot with the real token on this PC. +- Never touch `/root/Dezio/data` or `.env`; back up any server file before changing it. +- A restart drops music for a few seconds. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 132987d..fd11177 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -6,8 +6,26 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp ## 01 Network +- [ ] [S001 — Uploads timed by line speed](01%20Network/S001-upload-by-speed.md) +- [ ] [S002 — Timeouts on every outbound call](01%20Network/S002-outbound-timeouts.md) +- [ ] [S003 — Gateway, voice and music recovery; shaping](01%20Network/S003-recovery-and-shaping.md) + ## 02 Image commands -## 03 Security +- [ ] [S004 — Remove /image, add /caption](02%20Image%20commands/S004-remove-image-add-caption.md) +- [ ] [S005 — /speechbubble](02%20Image%20commands/S005-speechbubble.md) -## 04 Deploy +## 03 fm commands + +- [ ] [S006 — fm logic fully on ListenBrainz and MusicBrainz](03%20fm%20commands/S006-fm-on-metabrainz.md) + +## 04 Security + +- [ ] [S007 — Website and dashboard security](04%20Security/S007-website-security.md) +- [ ] [S008 — Media inputs, commands and dependencies](04%20Security/S008-media-commands-deps.md) + +## 05 Test and release + +- [ ] [S009 — Test: it runs, and network](05%20Test%20and%20release/S009-test-runs-and-network.md) +- [ ] [S010 — Test: images, fm, security, whole app](05%20Test%20and%20release/S010-test-images-security-app.md) +- [ ] [S011 — Deploy and owner check](05%20Test%20and%20release/S011-deploy-and-owner-check.md) 🧑 diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index e6dbc52..1a31e79 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -13,3 +13,4 @@ - D-009 — 2026-11-12 — The Assyst-style output described in D-007 (transparent cutout, no outline, tail toward the right) is saved as `assets/reference/speechbubble-assyst.gif`, next to the BSM-style `speechbubble-bsm.gif` (D-008). Compare the drawn bubbles against both. — Owner request. — 02 Image commands. - D-010 — 2026-12-01 — The fm commands read ListenBrainz (free, no key) instead of the Last.fm API, which needs Pro for everything but scrobbling from 2026-12-01. Same commands and cards; links are stored separately in `data/listenbrainz.json` (`data/lastfm.json` is kept, untouched); song links still go to the Last.fm website (free, and the Listen button reads them). Lyrics song search uses Deezer (popularity-ranked, no key). The Last.fm version is the git tag `lastfm-api-backup`. — Owner request. — all fm commands. - D-011 — 2026-12-01 — Covers come from a chain (`src/commands/lastfm/covers.rs`): the release ID in the player's own tags (Cover Art Archive) → ListenBrainz's match → the release group → Deezer → iTunes; Deezer/iTunes results count only when artist and title match. Artist photos: Deezer → MusicBrainz/Wikimedia. Play counts match by MusicBrainz ID before names. — MusicBrainz art alone left many covers blank; owner asked for the most reliable sources with fallbacks. — fm commands. +- D-012 — 2026-12-01 — All fm logic must get its data from ListenBrainz and MusicBrainz (plus the D-011 cover/photo fallbacks); leftover Last.fm API logic and Last.fm-only fields are replaced or removed. Song links to the Last.fm website stay. — Owner request after the Last.fm API change. — S006, S010. From 5b99a6fad96daad8cb0e49e8926b45012fa62f9a Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 21:32:58 -0600 Subject: [PATCH 02/24] S001: upload budget by line speed, retry only retryable, link on timeout Co-Authored-By: Claude Sonnet 5.5 --- Plans/INDEX.md | 2 +- docs/PROGRESS.md | 6 +++++- docs/tests/S001-upload-by-speed.md | 31 +++++++++++++++++++++++++++++ src/commands/media/convert.rs | 4 ++-- src/commands/media/download/job.rs | 2 ++ src/commands/media/download/mod.rs | 29 ++++++++++++++++++++++++--- src/commands/media/download/plan.rs | 2 +- src/commands/media/images.rs | 4 ++-- src/commands/media/mod.rs | 26 ++++++++++++++++++++++-- 9 files changed, 94 insertions(+), 12 deletions(-) create mode 100644 docs/tests/S001-upload-by-speed.md diff --git a/Plans/INDEX.md b/Plans/INDEX.md index fd11177..df03f3f 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -6,7 +6,7 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp ## 01 Network -- [ ] [S001 — Uploads timed by line speed](01%20Network/S001-upload-by-speed.md) +- [x] [S001 — Uploads timed by line speed](01%20Network/S001-upload-by-speed.md) - [ ] [S002 — Timeouts on every outbound call](01%20Network/S002-outbound-timeouts.md) - [ ] [S003 — Gateway, voice and music recovery; shaping](01%20Network/S003-recovery-and-shaping.md) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 992092b..994d475 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -14,5 +14,9 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Verified: `cargo test` (same 8 worktree-only asset failures); `cargo test covers_live -- --ignored` and `listenbrainz_live` pass. - Not done: not deployed at commit time; not checked in Discord 🧑. +## 2026-12-01 — S001 uploads by speed +- Done: `media::budget_for` / `upload_budget(ctx)` with `UPLOAD_SECONDS`=75 and `UPLOAD_BYTES_PER_SEC`=114_000 (reuse in S002, S008). Real limit 10 MiB. `/download` plans by budget, retries only reset/429/5xx, timeout becomes a website link. Convert and /media use the budget. +- Verified: `cargo check` only. Not done: pre-upload link for /download when too big; other attachment paths; per-call HTTP timeout. + ## Later -- (none yet) +- Per-request shorter timeout for plain Discord API calls: not done in S001. diff --git a/docs/tests/S001-upload-by-speed.md b/docs/tests/S001-upload-by-speed.md new file mode 100644 index 0000000..68f9487 --- /dev/null +++ b/docs/tests/S001-upload-by-speed.md @@ -0,0 +1,31 @@ +# S001 — Uploads timed by line speed: test file + +Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. + +## Built +`src/commands/media/mod.rs` · `UPLOAD_SECONDS` (75), `UPLOAD_BYTES_PER_SEC` (114_000), `budget_for(limit)` pure, `upload_budget(ctx)`; `upload_limit` now 10/50/100 MiB. +`src/commands/media/download/mod.rs` · `/download` limit = budget; `upload()` retries only RequestError, 429, 5xx; timeout gives `DlError::UploadTimedOut`; `publish_link` hosts the files and shows links. +`convert.rs`, `images.rs` · use `upload_budget` (convert already hosts oversize via ffmpeg::convert_to). + +## Checks +| # | Risk | Do this | Expect | How | Result | +|---|---|---|---|---|---| +| 1 | MED | `cargo test budget_is_the_smaller` | passes | unit | — | +| 2 | MED | Tier 0/1 guild: read `upload_limit` | 10 MiB; tier 2 50, tier 3 100 | unit/by hand | — | +| 3 | HIGH | `/download` of a clip that compresses to ~8 MB | uploads as attachment, no retry loop | by hand | — | +| 4 | HIGH | `/download` source whose smallest encode is above 8.5 MB | "Too large" card (no link yet, see Doubts) | by hand | — | +| 5 | HIGH | Force upload timeout (shape line to a few KB/s or shorten client timeout locally) | one attempt only, message becomes hosted link(s) | by hand | — | +| 6 | MED | Simulate 502 or connection reset on upload | retried up to 3 times | by hand | — | +| 7 | MED | Simulate 400/403 on upload | no retry, "Discord refused" card | by hand | — | +| 8 | MED | `/convert` to a result over 8.5 MB | link with 24 h notice, no attachment | by hand | — | +| 9 | LOW | `/media` effect with result over budget | "too big to upload" error with MB values | by hand | — | +| 10 | LOW | `rg UPLOAD_RETRIES src` | retry loop only continues on retryable errors | by hand | — | + +## Needs +Discord test server and the Chromebook line; never the real token on this PC. + +## Doubts +- Timeout detection assumes twilight reports `RequestTimedOut` for the 180 s client timeout. +- `/download` still shows "Too large" when it cannot encode under the budget; no pre-upload link fallback added. +- Other attachment paths (music card, quote, games, cmd.rs) not changed: they are small images; per-request shorter timeout for API calls not done (see PROGRESS Later). +- `FALLBACK_UPLOAD_LIMIT` is now unused in download/mod.rs; may warn. diff --git a/src/commands/media/convert.rs b/src/commands/media/convert.rs index 97b0487..46c1f5c 100644 --- a/src/commands/media/convert.rs +++ b/src/commands/media/convert.rs @@ -11,7 +11,7 @@ //! Text version: `D!convert mp3 128k` (reply to a file, attach one, or add a link / @user). use super::ffmpeg::{self, find_format, parse_quality, Converted, MediaType, Quality, Source, HEIGHTS, KBPS}; use super::images::pick_opt; -use super::{fetch_limited, has_ext, safe_url, upload_limit, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; +use super::{fetch_limited, has_ext, safe_url, upload_budget, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::state::State; @@ -237,7 +237,7 @@ async fn convert_cmd(ctx: Arc) -> Result<()> { None => bail_user!("Attach a file, give a link, or post a picture, video or sound in this channel first — I convert the latest one."), }, }; - let limit = upload_limit(&ctx); + let limit = upload_budget(&ctx); ctx.defer().await?; let source = open_source(&ctx.state, &url).await?; let Some((kind, animated)) = ffmpeg::detect(&source).await else { bail_user!("I can't read that file as a picture, video or sound.") }; diff --git a/src/commands/media/download/job.rs b/src/commands/media/download/job.rs index 61d91a2..9b4e16a 100644 --- a/src/commands/media/download/job.rs +++ b/src/commands/media/download/job.rs @@ -15,6 +15,8 @@ pub enum DlError { /// The stream we started is bigger than the limit; try a smaller one. SizeExceeded, Cancelled, + /// The upload ran out of time; repeating it would time out again → send a link instead. + UploadTimedOut, /// Raw text from yt-dlp, for [`super::plan::friendly_error`]. Ytdlp(String), } diff --git a/src/commands/media/download/mod.rs b/src/commands/media/download/mod.rs index 159c3e3..2e51873 100644 --- a/src/commands/media/download/mod.rs +++ b/src/commands/media/download/mod.rs @@ -36,6 +36,7 @@ use twilight_util::builder::embed::{EmbedBuilder, ImageSource}; const UI_TICK: Duration = Duration::from_secs(5); const PROGRESS_PICTURE: &str = "download.jpg"; +/// Retries only for errors that can work the second time (connection reset, 5xx, rate limit). A timeout is never retried. const UPLOAD_RETRIES: u32 = 3; const BLURPLE: u32 = 0x5865F2; @@ -314,7 +315,11 @@ where if http_status(&e) == Some(413) || api_code(&e) == Some(40005) { return Err(DlError::TooLarge); } - if matches!(http_status(&e), Some(400 | 401 | 403 | 404)) { + if matches!(e.kind(), twilight_http::error::ErrorType::RequestTimedOut) { + return Err(DlError::UploadTimedOut); + } + let retryable = matches!(e.kind(), twilight_http::error::ErrorType::RequestError) || matches!(http_status(&e), Some(429 | 500..=599)); + if !retryable { return Err(DlError::user("Upload failed", format!("Discord refused the upload: {}", e.to_string().chars().take(200).collect::()))); } last = e.to_string(); @@ -348,7 +353,25 @@ async fn publish(job: &Job, live: &Live, paths: &[PathBuf], content: Option publish_link(job, live, paths, &content).await, + other => other, + } +} + +/// The upload timed out: keep the files on the website and show links instead. +async fn publish_link(_job: &Job, live: &Live, paths: &[PathBuf], content: &Option) -> Result<(), DlError> { + let mut text = content.clone().unwrap_or_default(); + text.push_str(&format!("\n📦 Discord upload was too slow from here, so it's kept for **{} hours**:", crate::hosted::TTL.as_secs() / 3600)); + for p in paths { + let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("file"); + match crate::hosted::store(p, name) { + Ok(link) => text.push_str(&format!("\n{link}")), + Err(e) => return Err(DlError::user("Upload failed", format!("The upload timed out and I couldn't keep the file for download ({e})."))), + } + } + let text: String = text.chars().take(1900).collect(); + live.edit(Some(&text), &[], &[], &[]).await.map_err(|e| DlError::user("Upload failed", format!("The upload timed out and the link couldn't be shown: {}", e.to_string().chars().take(100).collect::()))) } // ---- running a job ------------------------------------------------------------------------------------------ @@ -367,7 +390,7 @@ async fn download(ctx: Arc) -> Result<()> { if active().lock().unwrap_or_else(|e| e.into_inner()).contains_key(&owner) { return fail(&ctx, "Already busy", "You already have a download running.").await; } - let limit = super::upload_limit(&ctx).max(FALLBACK_UPLOAD_LIMIT as usize) as u64; + let limit = super::upload_budget(&ctx) as u64; let cap = if quality == "best" { DEFAULT_QUALITY_CAP } else { quality.parse().unwrap_or(DEFAULT_QUALITY_CAP) }; let job = Arc::new(Job::new(owner, url.clone(), limit, audio)); let live = Arc::new(Live::create(&ctx, &progress_embed(&job), &cancel_row(owner, false)).await?); diff --git a/src/commands/media/download/plan.rs b/src/commands/media/download/plan.rs index 6a683a4..f22cc2d 100644 --- a/src/commands/media/download/plan.rs +++ b/src/commands/media/download/plan.rs @@ -11,7 +11,7 @@ pub const MAX_DURATION_SECONDS: f64 = 30.0 * 60.0; pub const DEFAULT_QUALITY_CAP: i64 = 1080; pub const AUDIO_EXT: &str = "opus"; pub const AUDIO_KBPS: i64 = 96; -pub const FALLBACK_UPLOAD_LIMIT: u64 = 20 * 1024 * 1024; +pub const FALLBACK_UPLOAD_LIMIT: u64 = 10 * 1024 * 1024; pub const SAFETY_MARGIN: f64 = 0.95; pub const FINAL_MARGIN: f64 = 0.99; pub const BPP_MIN: f64 = 0.065; diff --git a/src/commands/media/images.rs b/src/commands/media/images.rs index dd04eb1..cddce6a 100644 --- a/src/commands/media/images.rs +++ b/src/commands/media/images.rs @@ -4,7 +4,7 @@ //! The picture can come from an attachment, the message you reply to, someone's avatar (@mention / //! name), a custom emoji or a link; with nothing given, your own avatar is used. GIFs keep their //! animation. Everything is drawn in a worker thread at a sensible size, so a big GIF can't freeze the bot. -use super::{avatar, custom_emojis, emoji_url, fetch_limited, has_ext, replied, safe_url, upload_limit, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; +use super::{avatar, custom_emojis, emoji_url, fetch_limited, has_ext, replied, safe_url, upload_budget, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::converters::find_member; @@ -405,7 +405,7 @@ fn resolve_name(name: &str) -> (Option<&'static str>, Option<&'static str>) { /// Effects and filters on a picture or GIF: the shared job behind `/media` and `D!fx`. async fn run_job(ctx: &Arc, url: &str, effect: Option<&'static str>, filter: Option<&'static str>, opts: Opts) -> Result<()> { - let limit = upload_limit(ctx); + let limit = upload_budget(ctx); ctx.defer().await?; let Some(data) = fetch_limited(&ctx.state, url, MAX_IMAGE_BYTES).await else { bail_user!("I couldn't download that ({} MB max).", MAX_IMAGE_BYTES / 1024 / 1024); diff --git a/src/commands/media/mod.rs b/src/commands/media/mod.rs index 5ecef79..1a56481 100644 --- a/src/commands/media/mod.rs +++ b/src/commands/media/mod.rs @@ -126,17 +126,32 @@ pub fn emoji_url(id: u64, animated: bool, size: u32) -> String { format!("https://cdn.discordapp.com/emojis/{id}.{}?size={size}", if animated { "gif" } else { "png" }) } -/// Upload limit for files in this server: Discord's default is 20 MiB since September 2026, more with boosts. +/// Upload limit for files in this server: Discord's real bot limit, 10 MiB by default, more with boosts. pub fn upload_limit(ctx: &Ctx) -> usize { let tier = ctx.guild_id.and_then(|g| ctx.state.cache.guild(g).map(|g| u8::from(g.premium_tier()))).unwrap_or(0); let mb: usize = match tier { 2 => 50, 3 => 100, - _ => 20, + _ => 10, }; mb * 1024 * 1024 } +/// How long one upload may take. Under the 180 s Discord client timeout, with room for voice traffic. +pub const UPLOAD_SECONDS: usize = 75; +/// Upload speed of the server's line: measured 114 KB/s on 2026-11-12 (CLAUDE.md section 2). +pub const UPLOAD_BYTES_PER_SEC: usize = 114_000; + +/// Pure budget math: the smaller of Discord's limit and what the line can send in [`UPLOAD_SECONDS`]. +pub fn budget_for(discord_limit: usize) -> usize { + discord_limit.min(UPLOAD_SECONDS * UPLOAD_BYTES_PER_SEC) +} + +/// Bytes one upload may have in this server. Bigger results go to the website as a link. +pub fn upload_budget(ctx: &Ctx) -> usize { + budget_for(upload_limit(ctx)) +} + #[allow(dead_code)] pub fn need(value: Option, text: &str) -> Result { match value { @@ -149,6 +164,13 @@ pub fn need(value: Option, text: &str) -> Result { mod tests { use super::*; + #[test] + fn budget_is_the_smaller_of_limit_and_line() { + assert_eq!(budget_for(10 * 1024 * 1024), UPLOAD_SECONDS * UPLOAD_BYTES_PER_SEC); + assert_eq!(budget_for(1000), 1000); + assert!(budget_for(100 * 1024 * 1024) <= 10 * 1024 * 1024); + } + #[test] fn private_addresses_are_refused() { assert!(safe_url("https://example.com/a.png").is_some()); From 06b6a44e433d80c0516072a463d48e33603dc09f Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 21:33:43 -0600 Subject: [PATCH 03/24] S001: send oversize /download video as a link, tick plan Co-Authored-By: Claude Sonnet 5.5 --- Plans/01 Network/S001-upload-by-speed.md | 14 +++++++------- docs/PROGRESS.md | 2 +- docs/tests/S001-upload-by-speed.md | 6 +++--- src/commands/media/download/flow.rs | 16 +++++++++++++--- src/commands/media/download/mod.rs | 9 ++++++--- 5 files changed, 30 insertions(+), 17 deletions(-) diff --git a/Plans/01 Network/S001-upload-by-speed.md b/Plans/01 Network/S001-upload-by-speed.md index 01ed1b4..72b8ea0 100644 --- a/Plans/01 Network/S001-upload-by-speed.md +++ b/Plans/01 Network/S001-upload-by-speed.md @@ -15,13 +15,13 @@ Every Discord upload is planned in seconds, not bytes (D-001): a result that wou - `grep -rn "Attachment::from_bytes\|attachments(" src` to list the other upload paths; read only the call sites ## Steps -- [ ] Fold in the owner's loose edit (seen uncommitted in the main checkout, not in this worktree): tier 0/1 limit is 10 MiB, `FALLBACK_UPLOAD_LIMIT` = 10 MiB, `upload_limit` returns the real Discord limit (10/50/100 MiB) — do it here cleanly, with a newline after `let limit = …;` -- [ ] Add one shared helper in `media/mod.rs` that returns the byte budget for one upload: `min(discord_limit, UPLOAD_SECONDS × UPLOAD_BYTES_PER_SEC)`, both named constants with a comment (114 KB/s measured 2026-11-12, see CLAUDE.md §2), plus a pure function with a unit test -- [ ] `/download`: plan the target size from that budget; anything bigger goes to `hosted.rs` as a link (existing path); retry only on errors that are not timeouts (connection reset before sending, 5xx, rate limit); a timeout ends retries and falls back to the link -- [ ] Other upload paths (convert, music animated card, quote, the grep list): use the same budget; oversize → link or a smaller encode, whichever the path already supports -- [ ] Discord HTTP timeout: keep 180 s for uploads, but give plain API calls a shorter timeout if twilight allows it per request; otherwise write in PROGRESS "Later" why not -- [ ] `docs/tests/S001-upload-by-speed.md` from the test-file template (checks: budget math, link fallback, no retry after timeout, each upload path) -- [ ] PROGRESS entry, INDEX line, commit `S001: …` +- [x] Fold in the owner's loose edit (seen uncommitted in the main checkout, not in this worktree): tier 0/1 limit is 10 MiB, `FALLBACK_UPLOAD_LIMIT` = 10 MiB, `upload_limit` returns the real Discord limit (10/50/100 MiB) — do it here cleanly, with a newline after `let limit = …;` +- [x] Add one shared helper in `media/mod.rs` that returns the byte budget for one upload: `min(discord_limit, UPLOAD_SECONDS × UPLOAD_BYTES_PER_SEC)`, both named constants with a comment (114 KB/s measured 2026-11-12, see CLAUDE.md §2), plus a pure function with a unit test +- [x] `/download`: plan the target size from that budget; anything bigger goes to `hosted.rs` as a link (existing path); retry only on errors that are not timeouts (connection reset before sending, 5xx, rate limit); a timeout ends retries and falls back to the link +- [x] Other upload paths (convert, music animated card, quote, the grep list): use the same budget; oversize → link or a smaller encode, whichever the path already supports +- [x] Discord HTTP timeout: keep 180 s for uploads, but give plain API calls a shorter timeout if twilight allows it per request; otherwise write in PROGRESS "Later" why not (not done: per-request timeout, see PROGRESS Later) +- [x] `docs/tests/S001-upload-by-speed.md` from the test-file template (checks: budget math, link fallback, no retry after timeout, each upload path) +- [x] PROGRESS entry, INDEX line, commit `S001: …` ## End criteria - `source ~/.cargo/env; cargo build` compiles with no new warnings. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 994d475..a8b36ac 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -16,7 +16,7 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, ## 2026-12-01 — S001 uploads by speed - Done: `media::budget_for` / `upload_budget(ctx)` with `UPLOAD_SECONDS`=75 and `UPLOAD_BYTES_PER_SEC`=114_000 (reuse in S002, S008). Real limit 10 MiB. `/download` plans by budget, retries only reset/429/5xx, timeout becomes a website link. Convert and /media use the budget. -- Verified: `cargo check` only. Not done: pre-upload link for /download when too big; other attachment paths; per-call HTTP timeout. +- Verified: `cargo check` only. /download video still over budget after compress goes out as a link. Music card already drops to a still on a slow line; quote/games send small images, left as is. Not done: link for audio/gallery over budget; per-call HTTP timeout (twilight sets one timeout per client). ## Later - Per-request shorter timeout for plain Discord API calls: not done in S001. diff --git a/docs/tests/S001-upload-by-speed.md b/docs/tests/S001-upload-by-speed.md index 68f9487..e0f4d43 100644 --- a/docs/tests/S001-upload-by-speed.md +++ b/docs/tests/S001-upload-by-speed.md @@ -13,7 +13,7 @@ Written by the worker that built it, run by the test phase. Nothing here has bee | 1 | MED | `cargo test budget_is_the_smaller` | passes | unit | — | | 2 | MED | Tier 0/1 guild: read `upload_limit` | 10 MiB; tier 2 50, tier 3 100 | unit/by hand | — | | 3 | HIGH | `/download` of a clip that compresses to ~8 MB | uploads as attachment, no retry loop | by hand | — | -| 4 | HIGH | `/download` source whose smallest encode is above 8.5 MB | "Too large" card (no link yet, see Doubts) | by hand | — | +| 4 | HIGH | `/download` source whose smallest encode is above 8.5 MB | message shows a website link (24 h notice), no attachment; `VideoResult.oversize` path | by hand | — | | 5 | HIGH | Force upload timeout (shape line to a few KB/s or shorten client timeout locally) | one attempt only, message becomes hosted link(s) | by hand | — | | 6 | MED | Simulate 502 or connection reset on upload | retried up to 3 times | by hand | — | | 7 | MED | Simulate 400/403 on upload | no retry, "Discord refused" card | by hand | — | @@ -26,6 +26,6 @@ Discord test server and the Chromebook line; never the real token on this PC. ## Doubts - Timeout detection assumes twilight reports `RequestTimedOut` for the 180 s client timeout. -- `/download` still shows "Too large" when it cannot encode under the budget; no pre-upload link fallback added. -- Other attachment paths (music card, quote, games, cmd.rs) not changed: they are small images; per-request shorter timeout for API calls not done (see PROGRESS Later). +- Only video results fall back to a link; audio and gallery results over budget still show "Too large". +- Music card already falls back to a still when the line is slow (SLOW_UPLOAD); quote, games, cmd.rs not changed (small images); per-request shorter timeout for API calls not done (see PROGRESS Later). - `FALLBACK_UPLOAD_LIMIT` is now unused in download/mod.rs; may warn. diff --git a/src/commands/media/download/flow.rs b/src/commands/media/download/flow.rs index 23f8e1e..e12d18e 100644 --- a/src/commands/media/download/flow.rs +++ b/src/commands/media/download/flow.rs @@ -17,6 +17,8 @@ pub struct VideoResult { pub codec: String, pub size: u64, pub url: String, + /// Still over the upload budget after compressing: deliver as a website link. + pub oversize: bool, } pub struct AudioResult { @@ -249,11 +251,18 @@ async fn video_flow(web: &reqwest::Client, job: &Job, cap: i64, workdir: &Path, } // 2) make sure it FITS - one fast encode, only if still over the limit if size_of(&path) as f64 > limit * FINAL_MARGIN { - path = tools::compress(job, &path, &meta, false).await?; - compressed = true; - media = tools::inspect(&path).await.or(media); + match tools::compress(job, &path, &meta, false).await { + Ok(p) => { + path = p; + compressed = true; + media = tools::inspect(&path).await.or(media); + } + Err(DlError::TooLarge) => {} // keep the playable file and send it as a link + Err(e) => return Err(e), + } } let size = size_of(&path); + let oversize = size > job.limit; let nice = path.with_file_name(format!("{}{}", slug(&title, str_of(&info, "id").unwrap_or("video")), path.extension().and_then(|e| e.to_str()).map(|e| format!(".{}", e.to_lowercase())).unwrap_or_default())); if nice != path && std::fs::rename(&path, &nice).is_ok() { path = nice; @@ -268,6 +277,7 @@ async fn video_flow(web: &reqwest::Client, job: &Job, cap: i64, workdir: &Path, codec: codec_label(codec.as_deref()), size, url: str_of(&info, "webpage_url").unwrap_or(&job.url).to_string(), + oversize, }) } diff --git a/src/commands/media/download/mod.rs b/src/commands/media/download/mod.rs index 2e51873..5c98c80 100644 --- a/src/commands/media/download/mod.rs +++ b/src/commands/media/download/mod.rs @@ -354,15 +354,15 @@ async fn publish(job: &Job, live: &Live, paths: &[PathBuf], content: Option publish_link(job, live, paths, &content).await, + Err(DlError::UploadTimedOut) => publish_link(live, paths, &content, "Discord upload was too slow from here").await, other => other, } } /// The upload timed out: keep the files on the website and show links instead. -async fn publish_link(_job: &Job, live: &Live, paths: &[PathBuf], content: &Option) -> Result<(), DlError> { +async fn publish_link(live: &Live, paths: &[PathBuf], content: &Option, why: &str) -> Result<(), DlError> { let mut text = content.clone().unwrap_or_default(); - text.push_str(&format!("\n📦 Discord upload was too slow from here, so it's kept for **{} hours**:", crate::hosted::TTL.as_secs() / 3600)); + text.push_str(&format!("\n📦 {why}, so it's kept for **{} hours**:", crate::hosted::TTL.as_secs() / 3600)); for p in paths { let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("file"); match crate::hosted::store(p, name) { @@ -491,6 +491,9 @@ async fn deliver(job: &Job, live: &Live, outcome: Outcome) -> Result<(), DlError let info = vec![format!("-# **{}p** • **{}** • **{}** • **{}**", if v.height > 0 { v.height.to_string() } else { "?".into() }, v.codec, fmt_bytes(v.size as f64), fmt_dur(v.duration))]; job.set("Uploading", "⬆️", &fmt_bytes(v.size as f64), true); let _ = live.edit(None, &[progress_embed(job)], &[], &[]).await; + if v.oversize { + return publish_link(live, &[v.path.clone()], &Some(caption(&v.title, &info)), "Too big for Discord's upload budget here").await; + } publish(job, live, &[v.path.clone()], Some(caption(&v.title, &info)), result_row(owner, &v.url)).await } Outcome::Gallery(g) => { From 2168277fe310922812279d6589777b5fea68f249 Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 21:35:12 -0600 Subject: [PATCH 04/24] S002: timeouts on ffprobe and music ffmpeg, test file Co-Authored-By: Claude Sonnet 5.5 --- Plans/01 Network/S002-outbound-timeouts.md | 14 ++++----- Plans/INDEX.md | 2 +- docs/PROGRESS.md | 4 +++ docs/tests/S002-outbound-timeouts.md | 35 ++++++++++++++++++++++ src/commands/media/ffmpeg.rs | 15 +++++----- src/commands/music/source.rs | 13 ++++++-- 6 files changed, 64 insertions(+), 19 deletions(-) create mode 100644 docs/tests/S002-outbound-timeouts.md diff --git a/Plans/01 Network/S002-outbound-timeouts.md b/Plans/01 Network/S002-outbound-timeouts.md index 50d688f..082882a 100644 --- a/Plans/01 Network/S002-outbound-timeouts.md +++ b/Plans/01 Network/S002-outbound-timeouts.md @@ -13,13 +13,13 @@ Every outbound HTTP call and every child process (yt-dlp, ffmpeg, gallery-dl, cu - `src/error.rs` (`bail_user!`) ## Steps -- [ ] List every outbound call site and child process with its current limit; put the list in the test file's Built section -- [ ] Child processes: one shared run helper (reuse `tools.rs` if it fits) with a time limit, `kill_on_drop(true)` and a clear error; switch every caller that lacks one -- [ ] HTTP: calls that download big bodies (media fetch, covers) get a size cap and a total timeout; separate clients built outside `state.rs` get timeouts -- [ ] Time limits as named constants next to their use, with why the number (e.g. download size ÷ 425 KB/s down) -- [ ] User errors: timeouts show "took too long" cards through `bail_user!`, not raw errors -- [ ] `docs/tests/S002-outbound-timeouts.md` (checks: a stuck child is killed, a slow server times out, error card text) -- [ ] PROGRESS entry, INDEX line, commit `S002: …` +- [x] List every outbound call site and child process with its current limit; put the list in the test file's Built section +- [x] Child processes: one shared run helper (reuse `tools.rs` if it fits) with a time limit, `kill_on_drop(true)` and a clear error; switch every caller that lacks one +- [x] HTTP: calls that download big bodies (media fetch, covers) get a size cap and a total timeout; separate clients built outside `state.rs` get timeouts +- [x] Time limits as named constants next to their use, with why the number (e.g. download size ÷ 425 KB/s down) +- [x] User errors: timeouts show "took too long" cards through `bail_user!`, not raw errors +- [x] `docs/tests/S002-outbound-timeouts.md` (checks: a stuck child is killed, a slow server times out, error card text) +- [x] PROGRESS entry, INDEX line, commit `S002: …` ## End criteria - `cargo build` compiles. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index df03f3f..a5392d1 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -7,7 +7,7 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp ## 01 Network - [x] [S001 — Uploads timed by line speed](01%20Network/S001-upload-by-speed.md) -- [ ] [S002 — Timeouts on every outbound call](01%20Network/S002-outbound-timeouts.md) +- [x] [S002 — Timeouts on every outbound call](01%20Network/S002-outbound-timeouts.md) - [ ] [S003 — Gateway, voice and music recovery; shaping](01%20Network/S003-recovery-and-shaping.md) ## 02 Image commands diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index a8b36ac..fb1dc5e 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -20,3 +20,7 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, ## Later - Per-request shorter timeout for plain Discord API calls: not done in S001. + +## 2026-12-01 — S002 outbound timeouts +- Done: audit found most spawns and HTTP calls already limited. Fixed: `ffmpeg::probe` (no limit), `ffmpeg::inspect` (no kill), music stream and peaks (ffmpeg `-rw_timeout` 20 s idle, peaks read idle 30 s). Helper stays `download::tools::run_lines`. +- Verified: `cargo check` only. Not done: `bail_user!` rewrite of the plain timeout strings; not tested. diff --git a/docs/tests/S002-outbound-timeouts.md b/docs/tests/S002-outbound-timeouts.md new file mode 100644 index 0000000..a548c4a --- /dev/null +++ b/docs/tests/S002-outbound-timeouts.md @@ -0,0 +1,35 @@ +# S002 — Timeouts on every outbound call: test file + +Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. + +## Built +Audit of child processes and their limit (all kill on drop or on timeout): +- yt-dlp / ffmpeg / gallery-dl in `download/tools.rs` `run_lines` (shared helper: limit, cancel, kill; probe 120 s). Unchanged. +- `ffmpeg::run` 60 s+ per caller, `kill_on_drop`. Unchanged. +- `ffmpeg::inspect` (ffprobe): 60 s, now `kill_on_drop` (before, the timeout dropped the future and left ffprobe running). +- `ffmpeg::probe` (ffprobe local file): had NO limit; now `PROBE_SECONDS` 60 s + `kill_on_drop`, returns None on timeout. +- Music stream ffmpeg (`source::spawn_pipe`) and `peaks`: no total limit (songs run for hours); now `-rw_timeout` 20 s (`STREAM_IDLE_MICROS`) = cut when no data for 20 s. `peaks` also gives up when a read stalls 30 s (`PEAKS_IDLE`). +- `music/ytdl.rs` lookup, `lastfm/extras.rs` yt-dlp and ffmpeg: already 120 s timeout + `kill_on_drop`. Aki curl: `-m 15` + `kill_on_drop`. +- Tests-only spawns (`std::process::Command` in test modules) left alone. +HTTP: shared client `state.web` 20 s total (covers body); per-call timeouts set in search, covers, lastfm api, virus, translate, actions, animals, activity; `fetch_limited` 60 s + size cap + `safe_url`. `covers.rs` own client has timeout. Discord client 180 s (S001). Test-only clients without timeout left. +Not changed: timeouts keep their existing card text ("took too long" strings); no `bail_user!` rewrite. + +## Checks +| # | Risk | Do this | Expect | How | Result | +|---|---|---|---|---|---| +| 1 | HIGH | Play a song, then block the stream host (firewall rule or pause the server) | ffmpeg ends after about 20 s without data; player moves on or shows an error, no hung process | by hand | — | +| 2 | HIGH | `/convert` a URL to a host that accepts and never answers | ffprobe killed within ~60 s (`pgrep ffprobe` empty), card appears | by hand | — | +| 3 | MED | Run ffmpeg::probe on a FIFO/blocked path | returns None after 60 s, process gone | by hand | — | +| 4 | MED | `/play` song, let the loudness pass run with a stalled link | peaks returns None after 30 s idle; playback unaffected | by hand | — | +| 5 | MED | Start `/download` of a slow link, cancel | yt-dlp child gone | by hand | — | +| 6 | MED | Serve a page that sends one byte per second to `/search`, `/image` fetch | gives up by the 20 s client timeout | by hand | — | +| 7 | MED | `fetch_limited` against a 50 MB file | returns None at the size cap | by hand | — | +| 8 | LOW | `rg "Command::new" src` | every non-test spawn has a timeout or idle limit | by hand | — | +| 9 | LOW | Normal song plays with `-rw_timeout` | plays, seek works | by hand | — | + +## Needs +A test server or local slow HTTP server (python), a Discord test guild; never the real token on this PC. + +## Doubts +- `-rw_timeout` on HTTP inputs: assumed supported by the server's ffmpeg build (HTTP protocol option, µs). Verify song playback and that a stall really ends the process. +- Timeout messages are not all `bail_user!` cards; some are plain strings shown by callers. diff --git a/src/commands/media/ffmpeg.rs b/src/commands/media/ffmpeg.rs index 2b01f82..fa2def6 100644 --- a/src/commands/media/ffmpeg.rs +++ b/src/commands/media/ffmpeg.rs @@ -24,6 +24,9 @@ impl Drop for Scratch { } } +/// Longest an ffprobe may run. It only reads headers; 60 s covers a slow remote file at ~425 KB/s down. Then it is killed. +const PROBE_SECONDS: Duration = Duration::from_secs(60); + /// Run ffmpeg quietly; on failure give the last words it said. pub async fn run(args: &[String], limit: Duration) -> Result<(), String> { let mut cmd = Command::new("ffmpeg"); @@ -286,7 +289,7 @@ async fn inspect(target: &str, head: &[u8], online: bool) -> Info { if online { cmd.args(["-protocol_whitelist", "http,https,tcp,tls,crypto"]); } - let out = tokio::time::timeout(Duration::from_secs(60), cmd.arg(target).stdin(Stdio::null()).output()).await.ok().and_then(|r| r.ok()); + let out = tokio::time::timeout(PROBE_SECONDS, cmd.arg(target).stdin(Stdio::null()).kill_on_drop(true).output()).await.ok().and_then(|r| r.ok()); let text = out.map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); let num = |key: &str| text.lines().find_map(|l| l.strip_prefix(key)?.parse::().ok()).unwrap_or(0.0); Info { @@ -599,13 +602,9 @@ pub fn extension(name: &str) -> Option<&str> { /// ffprobe: length in seconds and whether there's a video stream, or None if it can't be read. pub async fn probe(path: &Path) -> Option<(f64, bool)> { - let out = Command::new("ffprobe") - .args(["-v", "error", "-show_entries", "format=duration:stream=codec_type", "-of", "default=nw=1"]) - .arg(path) - .stdin(Stdio::null()) - .output() - .await - .ok()?; + let mut cmd = Command::new("ffprobe"); + cmd.args(["-v", "error", "-show_entries", "format=duration:stream=codec_type", "-of", "default=nw=1"]).arg(path).stdin(Stdio::null()).kill_on_drop(true); + let out = tokio::time::timeout(PROBE_SECONDS, cmd.output()).await.ok()?.ok()?; let text = String::from_utf8_lossy(&out.stdout); let duration = text.lines().find_map(|l| l.strip_prefix("duration=")?.parse::().ok()).unwrap_or(0.0); Some((duration, text.contains("codec_type=video"))) diff --git a/src/commands/music/source.rs b/src/commands/music/source.rs index 4e323b8..8b672fb 100644 --- a/src/commands/music/source.rs +++ b/src/commands/music/source.rs @@ -171,6 +171,13 @@ impl Drop for BufferedPipe { /// What ffmpeg may open for a song: the web, never a local file a crafted page or playlist points it at. const WEB_ONLY: &str = "http,https,tcp,tls,crypto"; +/// A song stream may run for hours, so it has no total limit; it is cut when the server sends no data for this long +/// (ffmpeg `-rw_timeout`, in microseconds). 20 s: longer than the 5 s reconnect delay, shorter than a listener's patience. +const STREAM_IDLE_MICROS: &str = "20000000"; + +/// The loudness pass must see data this often, or it gives up (it reads at 10x speed, so a stall means a dead link). +const PEAKS_IDLE: std::time::Duration = std::time::Duration::from_secs(30); + /// Start ffmpeg on a stream (optionally from `start` seconds in) and give back the voice input and its position. pub fn spawn(stream: &Stream, start: f64) -> Result<(Input, Position), String> { let (pipe, position) = spawn_pipe(stream, start)?; @@ -181,7 +188,7 @@ pub fn spawn(stream: &Stream, start: f64) -> Result<(Input, Position), String> { pub fn spawn_pipe(stream: &Stream, start: f64) -> Result<(BufferedPipe, Position), String> { let mut cmd = Command::new(crate::commands::media::download::tool("ffmpeg")); cmd.args(["-nostdin", "-loglevel", "error", "-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_on_network_error", "1", "-reconnect_on_http_error", "4xx,5xx", "-reconnect_delay_max", "5"]); - cmd.args(["-protocol_whitelist", WEB_ONLY]); + cmd.args(["-protocol_whitelist", WEB_ONLY, "-rw_timeout", STREAM_IDLE_MICROS]); if start > 0.0 { cmd.args(["-ss", &format!("{start:.2}")]); } @@ -210,7 +217,7 @@ pub async fn peaks(stream: &Stream, per_second: usize) -> Option> { const RATE: usize = 2000; let mut cmd = tokio::process::Command::new(crate::commands::media::download::tool("ffmpeg")); // reading at ten times playing speed leaves the slow home line to the song itself - cmd.args(["-nostdin", "-loglevel", "error", "-protocol_whitelist", WEB_ONLY, "-readrate", "10"]); + cmd.args(["-nostdin", "-loglevel", "error", "-protocol_whitelist", WEB_ONLY, "-rw_timeout", STREAM_IDLE_MICROS, "-readrate", "10"]); if !stream.headers.is_empty() { cmd.arg("-headers").arg(stream.headers.iter().map(|(k, v)| format!("{k}: {v}\r\n")).collect::()); } @@ -221,7 +228,7 @@ pub async fn peaks(stream: &Stream, per_second: usize) -> Option> { let mut sums: Vec<(f64, u64)> = Vec::new(); let (mut buf, mut index, mut odd) = (vec![0u8; 16 * 1024], 0usize, None::); loop { - let n = out.read(&mut buf).await.ok()?; + let n = tokio::time::timeout(PEAKS_IDLE, out.read(&mut buf)).await.ok()?.ok()?; if n == 0 { break; } From feed5ec7de4dcd620a71adfae5d0ce7daf5b8d1e Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 21:36:03 -0600 Subject: [PATCH 05/24] S002: timeout errors as user cards Co-Authored-By: Claude Sonnet 5.5 --- docs/PROGRESS.md | 1 + docs/tests/S002-outbound-timeouts.md | 4 +++- src/commands/media/ffmpeg.rs | 2 +- src/commands/music/ytdl.rs | 2 +- src/commands/tools/virus.rs | 2 +- 5 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index fb1dc5e..ee09afd 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -24,3 +24,4 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, ## 2026-12-01 — S002 outbound timeouts - Done: audit found most spawns and HTTP calls already limited. Fixed: `ffmpeg::probe` (no limit), `ffmpeg::inspect` (no kill), music stream and peaks (ffmpeg `-rw_timeout` 20 s idle, peaks read idle 30 s). Helper stays `download::tools::run_lines`. - Verified: `cargo check` only. Not done: `bail_user!` rewrite of the plain timeout strings; not tested. +- S002 follow-up: timeout texts reworded in plain words (`ffmpeg::run`, `ytdl::extract`, VirusTotal wait). They are NOT `bail_user!`: those helpers return `Result<_, String>` (bail_user needs the command error type), and every caller already shows the string as a "❌ ..." reply. `download/tools.rs` already uses `DlError::user` cards. Turning the helpers into `UserError` would touch many callers; left for later. diff --git a/docs/tests/S002-outbound-timeouts.md b/docs/tests/S002-outbound-timeouts.md index a548c4a..7788924 100644 --- a/docs/tests/S002-outbound-timeouts.md +++ b/docs/tests/S002-outbound-timeouts.md @@ -26,10 +26,12 @@ Not changed: timeouts keep their existing card text ("took too long" strings); n | 7 | MED | `fetch_limited` against a 50 MB file | returns None at the size cap | by hand | — | | 8 | LOW | `rg "Command::new" src` | every non-test spawn has a timeout or idle limit | by hand | — | | 9 | LOW | Normal song plays with `-rw_timeout` | plays, seek works | by hand | — | +| 10 | MED | Make `/convert` run past its limit | reply says "The conversion took too long ..." | by hand | — | +| 11 | LOW | Make a `/play` lookup time out | reply says "The song lookup took too long ..." | by hand | — | ## Needs A test server or local slow HTTP server (python), a Discord test guild; never the real token on this PC. ## Doubts - `-rw_timeout` on HTTP inputs: assumed supported by the server's ffmpeg build (HTTP protocol option, µs). Verify song playback and that a stall really ends the process. -- Timeout messages are not all `bail_user!` cards; some are plain strings shown by callers. +- Timeout messages from string-returning helpers (`ffmpeg::run`, `ytdl::extract`, `make_song`, VirusTotal wait) are plain strings that callers show as a "❌ ..." reply, not `bail_user!`: the helpers can't return `UserError`. Check the text reads well in each (checks 10-11). diff --git a/src/commands/media/ffmpeg.rs b/src/commands/media/ffmpeg.rs index fa2def6..19bde18 100644 --- a/src/commands/media/ffmpeg.rs +++ b/src/commands/media/ffmpeg.rs @@ -33,7 +33,7 @@ pub async fn run(args: &[String], limit: Duration) -> Result<(), String> { cmd.args(["-hide_banner", "-loglevel", "error", "-nostdin", "-y"]).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::piped()).kill_on_drop(true); let child = cmd.spawn().map_err(|e| format!("ffmpeg isn't installed or can't start ({e})"))?; match tokio::time::timeout(limit, child.wait_with_output()).await { - Err(_) => Err("that took too long".to_string()), + Err(_) => Err("The conversion took too long (slow connection or a very big file). Try a smaller file or lower quality.".to_string()), Ok(Err(e)) => Err(e.to_string()), Ok(Ok(out)) if out.status.success() => Ok(()), Ok(Ok(out)) => { diff --git a/src/commands/music/ytdl.rs b/src/commands/music/ytdl.rs index 86dcd44..831d539 100644 --- a/src/commands/music/ytdl.rs +++ b/src/commands/music/ytdl.rs @@ -184,7 +184,7 @@ pub async fn extract(query: &str, mode: Mode) -> Result { } }; cmd.arg("--").arg(query).stdin(Stdio::null()).kill_on_drop(true); - let out = tokio::time::timeout(Duration::from_secs(limit), cmd.output()).await.map_err(|_| "That took too long — try again.".to_string())?.map_err(|e| format!("yt-dlp can't start ({e})"))?; + let out = tokio::time::timeout(Duration::from_secs(limit), cmd.output()).await.map_err(|_| "The song lookup took too long (YouTube or the connection is slow). Try again in a bit.".to_string())?.map_err(|e| format!("yt-dlp can't start ({e})"))?; if !out.status.success() { return Err(clean_error(&String::from_utf8_lossy(&out.stderr))); } diff --git a/src/commands/tools/virus.rs b/src/commands/tools/virus.rs index b09630c..0bd2715 100644 --- a/src/commands/tools/virus.rs +++ b/src/commands/tools/virus.rs @@ -70,7 +70,7 @@ async fn wait(state: &State, key: &str, analysis: &str, after: &str) -> Result Result { From d53eb49f5943e8e063cd0193f77a3781bfeb0037 Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 21:38:33 -0600 Subject: [PATCH 06/24] S003: gateway exit on dead line, voice rejoin then leave, shaping note Co-Authored-By: Claude Sonnet 5.5 --- Plans/01 Network/S003-recovery-and-shaping.md | 12 ++-- Plans/INDEX.md | 2 +- deploy/shape-upload.sh | 2 + docs/PROGRESS.md | 4 ++ docs/tests/S003-recovery-and-shaping.md | 27 ++++++++ src/commands/music/mod.rs | 67 +++++++++++++++++++ src/main.rs | 29 +++++++- 7 files changed, 133 insertions(+), 10 deletions(-) create mode 100644 docs/tests/S003-recovery-and-shaping.md diff --git a/Plans/01 Network/S003-recovery-and-shaping.md b/Plans/01 Network/S003-recovery-and-shaping.md index f4cffe5..bbfa4ac 100644 --- a/Plans/01 Network/S003-recovery-and-shaping.md +++ b/Plans/01 Network/S003-recovery-and-shaping.md @@ -13,12 +13,12 @@ The bot recovers by itself when the line drops: the gateway reconnects, voice re - Server, read-only first: `ssh root@192.168.1.71 'journalctl -u dezio-bot --since -7d | grep -iE "reconnect|disconnect|gateway|voice" | tail -50; tc -s qdisc show dev wlan0'` ## Steps -- [ ] From the logs, list the drop cases that happened; add them to the test file -- [ ] Gateway: errors from `next_event` never end the loop silently; fatal ones are logged and the process exits so systemd restarts it (Restart=always) -- [ ] Voice/music: on a voice driver disconnect, try to reconnect a named number of times, then leave and tell the channel; no queue or "now playing" state left stuck -- [ ] Shaping: measure upload once on the server (small timed upload, no external speed sites besides what the script already uses), adjust the cap in `shape-upload.sh` if the measure says so, with the number and date in a comment. Tell the orchestrator before reinstalling `dezio-shape` on the server; back up `/usr/local/bin/dezio-shape` first (D-005) -- [ ] `docs/tests/S003-recovery-and-shaping.md` -- [ ] PROGRESS entry, INDEX line, commit `S003: …` +- [x] From the logs, list the drop cases that happened; add them to the test file +- [x] Gateway: errors from `next_event` never end the loop silently; fatal ones are logged and the process exits so systemd restarts it (Restart=always) +- [x] Voice/music: on a voice driver disconnect, try to reconnect a named number of times, then leave and tell the channel; no queue or "now playing" state left stuck +- [x] Shaping: measure upload once on the server (small timed upload, no external speed sites besides what the script already uses), adjust the cap in `shape-upload.sh` if the measure says so, with the number and date in a comment. Tell the orchestrator before reinstalling `dezio-shape` on the server; back up `/usr/local/bin/dezio-shape` first (D-005) +- [x] `docs/tests/S003-recovery-and-shaping.md` +- [x] PROGRESS entry, INDEX line, commit `S003: …` ## End criteria - `cargo build` compiles. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index a5392d1..43fa4c2 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -8,7 +8,7 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp - [x] [S001 — Uploads timed by line speed](01%20Network/S001-upload-by-speed.md) - [x] [S002 — Timeouts on every outbound call](01%20Network/S002-outbound-timeouts.md) -- [ ] [S003 — Gateway, voice and music recovery; shaping](01%20Network/S003-recovery-and-shaping.md) +- [x] [S003 — Gateway, voice and music recovery; shaping](01%20Network/S003-recovery-and-shaping.md) ## 02 Image commands diff --git a/deploy/shape-upload.sh b/deploy/shape-upload.sh index aacfbb8..cdbfb46 100755 --- a/deploy/shape-upload.sh +++ b/deploy/shape-upload.sh @@ -11,6 +11,8 @@ # It turns itself off again after 2 minutes unless `keep` is the second word, so a mistake can't lock anyone out. set -eu DEV=wlan0 +# 800 kbit = 100 KB/s, 88% of the 114 KB/s measured on this line (CLAUDE.md). Checked 2026-12-01 against `tc -s qdisc`: +# 247 of 121k packets dropped in the capped class, none in the voice class, so the cap is kept. RATE=800kbit off() { tc qdisc del dev "$DEV" root 2>/dev/null || true; } diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index ee09afd..2c59213 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -25,3 +25,7 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Done: audit found most spawns and HTTP calls already limited. Fixed: `ffmpeg::probe` (no limit), `ffmpeg::inspect` (no kill), music stream and peaks (ffmpeg `-rw_timeout` 20 s idle, peaks read idle 30 s). Helper stays `download::tools::run_lines`. - Verified: `cargo check` only. Not done: `bail_user!` rewrite of the plain timeout strings; not tested. - S002 follow-up: timeout texts reworded in plain words (`ffmpeg::run`, `ytdl::extract`, VirusTotal wait). They are NOT `bail_user!`: those helpers return `Result<_, String>` (bail_user needs the command error type), and every caller already shows the string as a "❌ ..." reply. `download/tools.rs` already uses `DlError::user` cards. Turning the helpers into `UserError` would touch many callers; left for later. + +## 2026-12-01 — S003 recovery and shaping +- Done: gateway exits (systemd restarts) after 10 min of failed reconnects or when all shards stop; voice driver retries 8, watcher rejoins 3 times then leaves with a notice and clears the player. Shaping cap kept at 800 kbit (comment with numbers). +- Verified: `cargo check` only. Not tested, not deployed, `dezio-shape` not reinstalled, no upload measured. diff --git a/docs/tests/S003-recovery-and-shaping.md b/docs/tests/S003-recovery-and-shaping.md new file mode 100644 index 0000000..29ed294 --- /dev/null +++ b/docs/tests/S003-recovery-and-shaping.md @@ -0,0 +1,27 @@ +# S003 — Gateway, voice and music recovery; shaping: test file + +Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. + +## Built +- Drops seen in the server log (30 days): gateway "zombied" then 5 failed reconnects with backoff (2026-11-24); one failed reconnect (11-26); one "unrequested heartbeat ack" (11-30). Twilight recovered each time. No voice drops in the log. +- `src/main.rs`: gateway errors are logged; failed reconnects for over `GATEWAY_DOWN_LIMIT` (10 min) exit the process (systemd restarts it). If every shard loop ends (fatal close) the bot logs an error and exits 1 instead of exiting silently with 0. Songbird voice retries set to `VOICE_DRIVER_RETRIES` (8). +- `music/mod.rs`: `VoiceWatcher` on each call listens for `DriverDisconnect`; `recover_voice` waits `VOICE_GRACE` (20 s), rejoins up to `VOICE_REJOIN_TRIES` (3), then `teardown` with a notice in the text channel (queue, panel, loading task cleared). +- `deploy/shape-upload.sh`: cap kept at 800 kbit, comment with the 2026-12-01 numbers. No timed upload measured (no safe target besides external sites). Not reinstalled on the server. + +## Checks +| # | Risk | Do this | Expect | How | Result | +|---|---|---|---|---|---| +| 1 | HIGH | Bot in voice playing; block the voice UDP/WS (firewall) for 60 s, then unblock | Log shows "voice driver disconnect"; playback resumes after rejoin | by hand | — | +| 2 | HIGH | Same, block for 3+ minutes | Bot leaves, channel gets "Lost the voice connection..." (deleted after 15 s), `/play` works again | by hand | — | +| 3 | HIGH | Cut the network for 12 minutes, restore | Log "gateway: down for ..., exiting"; systemd restarts; bot online | by hand | — | +| 4 | MED | Cut the network for 30 s, restore | No exit; gateway reconnects by itself | by hand | — | +| 5 | MED | Kick the bot from voice while playing | One teardown, no rejoin attempts (player gone) | by hand | — | +| 6 | MED | `/leave` while a recovery wait is pending | No rejoin, no notice | by hand | — | +| 7 | MED | Start with an invalid token or bad intents (dev token only, never the live one) | Log "every shard stopped", exit code 1 | by hand | — | +| 8 | LOW | Leave and `/play` again in the same guild | Watcher registers again (disconnect after the second join still recovers) | by hand | — | +| 9 | LOW | `tc -s qdisc show dev wlan0` during a big upload with voice playing | Voice class has no drops; voice stays smooth | by hand | — | + +## Doubts +- Songbird may fire `DriverDisconnect` for harmless reasons; the grace + "connected" check should absorb that. Check the log for false alarms. +- Rejoin keeps the playing track in the mixer; unverified that audio resumes without restarting the song. +- Upload cap not re-measured; if the line changed, measure with a timed upload to a host you control. diff --git a/src/commands/music/mod.rs b/src/commands/music/mod.rs index e7709d0..98d47a8 100644 --- a/src/commands/music/mod.rs +++ b/src/commands/music/mod.rs @@ -51,6 +51,10 @@ const SLOW_UPLOAD: f64 = 12.0; /// How long a new picture takes to reach people, until a real one has been measured. const FIRST_LEAD: f64 = 3.0; /// A playing song whose position hasn't moved for this long has lost its voice connection. +/// After the voice driver reports a disconnect, wait this long for songbird's own retries before stepping in. +const VOICE_GRACE: Duration = Duration::from_secs(20); +/// Rejoin attempts after the grace, then leave and tell the channel (3 x 15 s join limit is under a minute). +const VOICE_REJOIN_TRIES: u32 = 3; const STALL_LIMIT: Duration = Duration::from_secs(45); /// Songs longer than this aren't measured: the analysis reads the whole file. Their bars move at a steady level. const WAVEFORM_LIMIT: u64 = 30 * 60; @@ -288,10 +292,12 @@ async fn connect(state: &Arc, p: &Arc, channel: Id for attempt in 0..2 { if attempt > 0 { let _ = sb.remove(p.guild).await; + watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&p.guild.get()); tokio::time::sleep(Duration::from_millis(1500)).await; } match tokio::time::timeout(Duration::from_secs(15), sb.join(p.guild, channel)).await { Ok(Ok(call)) => { + watch_voice(state, p.guild, channel, &call).await; let _ = call.lock().await.deafen(true).await; become_speaker(state, p.guild, channel).await; return Ok(call); @@ -304,9 +310,69 @@ async fn connect(state: &Arc, p: &Arc, channel: Id // Discord's answer can still arrive after we gave up. Forget the call, or the next /play would see a half-made // connection, believe it, and play into nothing. let _ = sb.remove(p.guild).await; + watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&p.guild.get()); Err(format!("Couldn't connect to <#{channel}> ({last}). Try again in a moment.")) } +/// Guilds whose call already has the disconnect watcher (a call is created once per join, handlers live as long as it). +fn watched() -> &'static Mutex> { + static W: OnceLock>> = OnceLock::new(); + W.get_or_init(Default::default) +} + +struct VoiceWatcher { + state: Arc, + guild: Guild, + channel: Id, +} + +#[async_trait::async_trait] +impl EventHandler for VoiceWatcher { + async fn act(&self, ctx: &EventContext<'_>) -> Option { + if let EventContext::DriverDisconnect(d) = ctx { + tracing::warn!("voice driver disconnect in {}: {:?} {:?}", self.guild, d.kind, d.reason); + let (state, guild, channel) = (self.state.clone(), self.guild, self.channel); + tokio::spawn(async move { recover_voice(&state, guild, channel).await }); + } + None + } +} + +async fn watch_voice(state: &Arc, guild: Guild, channel: Id, call: &Arc>) { + if watched().lock().unwrap_or_else(|e| e.into_inner()).insert(guild.get()) { + call.lock().await.add_global_event(Event::Core(songbird::CoreEvent::DriverDisconnect), VoiceWatcher { state: state.clone(), guild, channel }); + } +} + +/// The voice driver lost its connection. Songbird retries by itself; if it is still down after [`VOICE_GRACE`], rejoin +/// [`VOICE_REJOIN_TRIES`] times, then leave and say so, so no queue or panel stays stuck on a dead connection. +async fn recover_voice(state: &Arc, guild: Guild, channel: Id) { + tokio::time::sleep(VOICE_GRACE).await; + let Some(sb) = voice(state) else { return }; + for attempt in 1..=VOICE_REJOIN_TRIES { + let Some(p) = existing(guild) else { return }; // kicked or stopped meanwhile: nothing to save + let Some(call) = sb.get(guild) else { return }; + let (connected, now_channel) = { + let c = call.lock().await; + (c.current_connection().is_some(), c.current_channel().map(|c| Id::new(c.0.get()))) + }; + if connected { + return; + } + let target = now_channel.unwrap_or(channel); + tracing::warn!("voice rejoin {attempt}/{VOICE_REJOIN_TRIES} in {guild} to {target}"); + if let Ok(Ok(_)) = tokio::time::timeout(Duration::from_secs(15), sb.join(guild, target)).await { + let _ = p; + return; + } + tokio::time::sleep(VOICE_GRACE).await; + } + if existing(guild).is_some() { + teardown(state, guild, true, Some("⚠️ Lost the voice connection and couldn't get it back, so I left. Use `/play` to start again.")).await; + } + watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&guild.get()); +} + /// On a stage, step up to speak (or ask to, without the permission). async fn become_speaker(state: &State, guild: Guild, channel: Id) { use twilight_model::channel::ChannelType; @@ -495,6 +561,7 @@ async fn teardown(state: &Arc, guild: Guild, disconnect: bool, notice: Op if let Some(sb) = voice(state) { let _ = sb.remove(guild).await; } + watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&guild.get()); } } diff --git a/src/main.rs b/src/main.rs index b1a89bd..b75ef7f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -38,6 +38,13 @@ use std::sync::Arc; use std::time::Duration; use twilight_gateway::{create_recommended, Config, EventTypeFlags, Intents, StreamExt as _}; use twilight_http::Client; + +/// Gateway reconnects that keep failing this long mean the line is dead or the shard is wedged; exit and let systemd +/// (Restart=always) start fresh. Twilight's own backoff covers short drops; the 2026-11 logs show drops of seconds. +const GATEWAY_DOWN_LIMIT: Duration = Duration::from_secs(10 * 60); +/// How often songbird retries a failed voice connection before it gives up (its default is 5; the music code then +/// rejoins a few times and finally leaves, see `VOICE_REJOIN_TRIES`). +const VOICE_DRIVER_RETRIES: u8 = 8; use twilight_model::application::command::{Command as ApiCommand, CommandOptionChoice, CommandOptionChoiceValue, CommandType}; use twilight_model::application::interaction::{InteractionContextType, InteractionData, InteractionType}; use twilight_model::application::interaction::application_command::CommandOptionValue; @@ -562,16 +569,27 @@ async fn main() -> Result<()> { let shards: Vec<_> = create_recommended(&http, config, |_, b| b.build()).await?.collect(); let _ = state.senders.set(shards.iter().map(|s| s.sender()).collect()); let senders = shards.iter().map(|s| (s.id().number(), s.sender())).collect(); - let _ = state.voice.set(Arc::new(songbird::Songbird::twilight(Arc::new(songbird::shards::TwilightMap::new(senders)), state.bot_id()))); + let _ = state.voice.set(Arc::new(songbird::Songbird::twilight_from_config(Arc::new(songbird::shards::TwilightMap::new(senders)), state.bot_id(), songbird::Config::default().driver_retry(songbird::driver::retry::Retry { retry_limit: std::num::NonZeroU8::new(VOICE_DRIVER_RETRIES), ..Default::default() })))); let mut tasks = Vec::new(); for mut shard in shards { let state = state.clone(); tasks.push(tokio::spawn(async move { + // When the first failed reconnect happened; cleared by the next good event. + let mut down_since: Option = None; while let Some(item) = shard.next_event(EventTypeFlags::all()).await { let event = match item { - Ok(e) => e, + Ok(e) => { + down_since = None; + e + } Err(e) => { tracing::warn!("gateway: {e}"); + // twilight retries by itself with backoff; if the line stays dead too long, restart clean + let since = *down_since.get_or_insert_with(std::time::Instant::now); + if matches!(e.kind(), twilight_gateway::error::ReceiveMessageErrorType::Reconnect) && since.elapsed() > GATEWAY_DOWN_LIMIT { + tracing::error!("gateway: down for {:?}, exiting so systemd restarts the bot", since.elapsed()); + std::process::exit(1); + } continue; } }; @@ -711,7 +729,12 @@ async fn main() -> Result<()> { } else { tokio::select! { _ = tokio::signal::ctrl_c() => tracing::info!("shutting down"), - _ = futures::future::join_all(tasks) => {} + _ = futures::future::join_all(tasks) => { + // a shard loop only ends on a fatal close (bad token, bad intents): say so and fail, systemd restarts us + tracing::error!("gateway: every shard stopped, exiting"); + storage::flush_all(); + std::process::exit(1); + } } } storage::flush_all(); From dd5e78dda4864f5a06f15c6d62d2eb74a822179e Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 21:50:16 -0600 Subject: [PATCH 07/24] S004: remove /image, add /caption for pictures, GIFs and video Co-Authored-By: Claude Sonnet 5.5 --- Plans/INDEX.md | 2 +- docs/PROGRESS.md | 5 + docs/tests/S004-caption.md | 27 ++ src/cmd.rs | 2 +- src/commands/help.rs | 2 +- src/commands/media/convert.rs | 2 +- src/commands/media/images.rs | 614 +++++++++++----------------------- src/commands/media/mod.rs | 2 +- web/site/index.html | 2 +- 9 files changed, 240 insertions(+), 418 deletions(-) create mode 100644 docs/tests/S004-caption.md diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 43fa4c2..56c679e 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -12,7 +12,7 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp ## 02 Image commands -- [ ] [S004 — Remove /image, add /caption](02%20Image%20commands/S004-remove-image-add-caption.md) +- [x] [S004 — Remove /image, add /caption](02%20Image%20commands/S004-remove-image-add-caption.md) - [ ] [S005 — /speechbubble](02%20Image%20commands/S005-speechbubble.md) ## 03 fm commands diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 2c59213..35b7588 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -29,3 +29,8 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, ## 2026-12-01 — S003 recovery and shaping - Done: gateway exits (systemd restarts) after 10 min of failed reconnects or when all shards stop; voice driver retries 8, watcher rejoins 3 times then leaves with a notice and clears the player. Shaping cap kept at 800 kbit (comment with numbers). - Verified: `cargo check` only. Not tested, not deployed, `dezio-shape` not reinstalled, no upload measured. + +## 2026-12-01 — S004 /image removed, /caption added +- Done: `/image` + `D!fx` and all effects/filters gone. `/caption` + `D!caption` (options `source-attachment`, `source-link`, `text`; no source = latest media in channel via `convert::last_chat_media`). Still → PNG (JPEG if too big); GIF/animated WebP → GIF; video → MP4 (no sound, 10 s, 12 fps, 480 px max). Help and website text updated. +- Shared helpers for S005: `images::pick_opt`, `convert::last_chat_media`, `images::frames_of`, `encode_gif`, `caption_image` / `caption_video` pattern (band + `stack`), `ffmpeg::Scratch` + `ffmpeg::run`. `/speechbubble` is not added yet (S005). +- Verified: `cargo check` only. Not tested, not checked in Discord 🧑. diff --git a/docs/tests/S004-caption.md b/docs/tests/S004-caption.md new file mode 100644 index 0000000..2dfd464 --- /dev/null +++ b/docs/tests/S004-caption.md @@ -0,0 +1,27 @@ +# S004 — /caption checks + +Run in Discord (owner) unless noted. Bot must have the S004 build. + +## Doubts +- Video path never run: needs ffmpeg with libx264 on the server; check `ffmpeg -encoders | grep libx264` there. +- Band height unit test depends on the font in `assets/` (missing in worktrees). +- Slash option names with hyphens (`source-attachment`) never registered with Discord yet. + +## Checks +1. `/image` and `D!fx` no longer exist (slash list, `D!help`). +2. `/caption text:hello` with a PNG attached: PNG back, white band with centred black text above, same width. +3. Same with a JPG and a still WebP: works. +4. GIF attached: GIF back, still animated, every frame has the band. +5. Animated WebP: comes back as an animated GIF. +6. MP4, WebM and MOV: MP4 back that plays in Discord, band on top, no sound, at most about 10 s. +7. `/caption source-link: text:hi`: works. +8. `D!caption hi` replying to a picture: works. `D!caption hi `: works. +9. `/caption text:hi` with no source after someone posted a picture: uses that picture. +10. Empty text (`D!caption` alone, `/caption text:` blank): clear error card, no upload. +11. Text of 600 characters: "too long" error. Text of about 200 characters: band grows, still readable. +12. Multi-line text: band is as tall as the lines need (3 lines taller than 1). +13. Huge input (over 15 MB): "couldn't download" card, no hang. +14. Bad link (`http://127.0.0.1/x`, `not a link`): error card, no crash. +15. Non-media file (a PDF or audio only): "none of those" error. +16. Result over the upload budget: smaller retry, else "too big" card. +17. `cargo test band_height caption_keeps` passes where assets exist; help-limits test passes. diff --git a/src/cmd.rs b/src/cmd.rs index 4f48df9..a232c3d 100644 --- a/src/cmd.rs +++ b/src/cmd.rs @@ -94,7 +94,7 @@ pub struct Command { pub usage: &'static str, pub options: Vec, pub slash: bool, - /// The slash command's name when it differs from the text command's (`D!fx` is `/image`). + /// The slash command's name when it differs from the text command's. pub slash_name: Option<&'static str>, pub guild_only: bool, /// Bot-owner tools: only listed in help for the owner. diff --git a/src/commands/help.rs b/src/commands/help.rs index d6f6e9f..d74685e 100644 --- a/src/commands/help.rs +++ b/src/commands/help.rs @@ -34,7 +34,7 @@ const fn cat(key: &'static str, emoji: &'static str, name: &'static str, blurb: pub const CATEGORIES: &[Category] = &[ cat("music", "🎵", "Music", "Play music in voice with a live player", 0x9B59B6, ""), cat("lastfm", "📊", "Music stats", "Now playing, top charts, Who Knows, Pixel Jumble and lyrics, from ListenBrainz", 0xEB743B, "Link your ListenBrainz account first: `{p}fmset ` or `/fm mode:link`."), - cat("media", "🎨", "Media", "Downloads, image effects, quotes and emojis", 0xE67E22, ""), + cat("media", "🎨", "Media", "Downloads, captions, quotes and emojis", 0xE67E22, ""), cat("moderation", "🛡️", "Moderation", "Kick, ban, timeout, purge, nicknames and roles", 0xED4245, "Moderation commands also work as a reply to someone's message."), cat("server", "⚙️", "Server setup", "Logging, welcome, role menus, channel tools and the prefix", 0xF1C40F, ""), cat("utility", "🔧", "Utility", "Info cards, web search, weather, calculator, snipe and AFK", 0x607D8B, ""), diff --git a/src/commands/media/convert.rs b/src/commands/media/convert.rs index 46c1f5c..2e7ee1d 100644 --- a/src/commands/media/convert.rs +++ b/src/commands/media/convert.rs @@ -134,7 +134,7 @@ fn take(rest: &mut String) -> Option { } /// The newest picture, video or sound posted in this channel (what `/convert` uses when you give it nothing). -async fn last_chat_media(ctx: &Ctx) -> Option { +pub(super) async fn last_chat_media(ctx: &Ctx) -> Option { let messages = ctx.state.http.channel_messages(ctx.channel_id).limit(30).await.ok()?.models().await.ok()?; for m in messages.iter().filter(|m| Some(m.id) != ctx.command_message_id()) { for a in &m.attachments { diff --git a/src/commands/media/images.rs b/src/commands/media/images.rs index cddce6a..7330d1e 100644 --- a/src/commands/media/images.rs +++ b/src/commands/media/images.rs @@ -1,247 +1,41 @@ -//! Image effects and filters (`/image`, `D!fx`), converting pictures and videos (`/convert`, or the -//! `convert` option of `/image`), and petpet GIFs (`/petpet`, `D!petpet`). +//! `/caption` (`D!caption`): a white band with text above a picture, GIF, WebP or video, and petpet GIFs (`/petpet`). //! -//! The picture can come from an attachment, the message you reply to, someone's avatar (@mention / -//! name), a custom emoji or a link; with nothing given, your own avatar is used. GIFs keep their -//! animation. Everything is drawn in a worker thread at a sensible size, so a big GIF can't freeze the bot. +//! `pick_opt` finds the media (attachment, link, reply, avatar, emoji); `/convert` shares it. + +use super::convert::last_chat_media; +use super::ffmpeg::{self, Scratch}; use super::{avatar, custom_emojis, emoji_url, fetch_limited, has_ext, replied, safe_url, upload_budget, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::converters::find_member; use crate::pix; use crate::text::{self, Look}; -use crate::ui::{escape, file_display, truncate, Card}; +use crate::ui::{escape, truncate, Card}; use anyhow::Result; use cosmic_text::Align; use futures::FutureExt; use image::codecs::gif::{GifDecoder, GifEncoder, Repeat}; use image::codecs::webp::WebPDecoder; -use image::{imageops, AnimationDecoder, Delay, Frame, GrayImage, Rgba, RgbaImage}; +use image::{imageops, AnimationDecoder, Delay, Frame, Rgba, RgbaImage}; use std::io::Cursor; use std::sync::Arc; +use std::time::Duration; const MAX_SIDE: u32 = 1024; const MAX_GIF_SIDE: u32 = 480; const MAX_FRAMES: usize = 120; +/// Longest caption text. A band this tall already eats most of a small picture. +const MAX_CAPTION_CHARS: usize = 500; +/// Video is cut to this many seconds at this frame rate (so at most MAX_FRAMES frames) before captioning. +const VIDEO_SECONDS: u32 = 10; +const VIDEO_FPS: u32 = 12; +/// Widest video frame we caption; the line is slow, so a small clip is also a clip that uploads. +const MAX_VIDEO_SIDE: u32 = 480; +/// Time limits for the two ffmpeg runs of a video caption (cut to frames, encode back). +const VIDEO_DECODE_SECONDS: u64 = 60; +const VIDEO_ENCODE_SECONDS: u64 = 120; const MAX_IMAGE_BYTES: usize = 15 * 1024 * 1024; -pub const EFFECTS: [&str; 10] = ["speechbubble", "caption", "blur", "pixelate", "flip", "mirror", "deepfry", "vignette", "border", "circle"]; -pub const FILTERS: [&str; 14] = [ - "grayscale", "sepia", "gotham", "invert", "warm", "cold", "vintage", "cyberpunk", "nostalgia", "sunset", "nightvision", "pencil_sketch", "oil_painting", "pop_art", -]; - -#[derive(Clone, Debug)] -pub struct Opts { - pub text: String, - pub bottom: bool, - pub radius: f32, - pub size: u32, - pub level: u32, -} - -impl Default for Opts { - fn default() -> Self { - Self { text: String::new(), bottom: false, radius: 5.0, size: 10, level: 3 } - } -} - -// ---- pixel work (runs in a thread) ---------------------------------------------------------- - -fn noise() -> f32 { - (rand::random::() as f32 + rand::random::() as f32 + rand::random::() as f32) / 765.0 - 0.5 -} - -pub fn vignette(img: &mut RgbaImage) { - let (w, h) = (img.width() as f32, img.height() as f32); - for (x, y, p) in img.enumerate_pixels_mut() { - let d = (((x as f32 - w / 2.0) / (0.7 * w)).powi(2) + ((y as f32 - h / 2.0) / (0.7 * h)).powi(2)).sqrt(); - let keep = 1.0 / (1.0 + ((d - 1.0) / 0.16).exp()); - for c in 0..3 { - p[c] = (p[c] as f32 * keep).round() as u8; - } - } -} - -const SEPIA: [[f32; 3]; 3] = [[0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131]]; - -fn diag(r: f32, g: f32, b: f32) -> [[f32; 3]; 3] { - [[r, 0.0, 0.0], [0.0, g, 0.0], [0.0, 0.0, b]] -} - -fn oil(img: &RgbaImage) -> RgbaImage { - let (w, h) = img.dimensions(); - let mut out = img.clone(); - for y in 0..h { - for x in 0..w { - for c in 0..3 { - let mut bins = [0u8; 64]; - for ny in y.saturating_sub(3)..(y + 4).min(h) { - for nx in x.saturating_sub(3)..(x + 4).min(w) { - bins[(img.get_pixel(nx, ny)[c] >> 2) as usize] += 1; - } - } - let best = bins.iter().enumerate().max_by_key(|(_, n)| **n).map_or(0, |(i, _)| i); - out.get_pixel_mut(x, y)[c] = (best as u8) * 4 + 2; - } - } - } - out -} - -pub fn apply_filter(img: &mut RgbaImage, name: &str) { - match name { - "grayscale" => pix::grayscale(img), - "sepia" => pix::matrix(img, SEPIA), - "gotham" => { - pix::matrix(img, diag(1.0, 1.0, 1.2)); - pix::contrast(img, 1.3); - } - "invert" => { - for p in img.pixels_mut() { - for c in 0..3 { - p[c] = 255 - p[c]; - } - } - } - "warm" => pix::matrix(img, diag(1.25, 1.0, 0.85)), - "cold" => pix::matrix(img, diag(0.85, 1.0, 1.25)), - "vintage" => { - pix::matrix(img, SEPIA); - vignette(img); - let alpha: Vec = img.pixels().map(|p| p[3]).collect(); - *img = imageops::blur(img, 0.7); - for (p, a) in img.pixels_mut().zip(alpha) { - p[3] = a; - } - } - "cyberpunk" => { - pix::matrix(img, diag(1.3, 1.0, 1.5)); - pix::contrast(img, 1.5); - pix::sharpen(img, 2.0); - } - "nostalgia" => { - pix::matrix(img, diag(1.25, 1.0, 0.85)); - pix::saturate(img, 0.7); - for p in img.pixels_mut() { - let n = 128.0 + noise() * 60.0; - for c in 0..3 { - p[c] = (p[c] as f32 * 0.9 + n * 0.1).clamp(0.0, 255.0).round() as u8; - } - } - } - "sunset" => pix::matrix(img, diag(1.4, 1.1, 0.7)), - "nightvision" => { - pix::grayscale(img); - for p in img.pixels_mut() { - let g = p[0] as f32; - p[0] = (g * 0.3) as u8; - p[1] = (g * 1.3).min(255.0) as u8; - p[2] = (g * 0.3) as u8; - } - } - "pencil_sketch" => { - pix::grayscale(img); - let inverted = GrayImage::from_fn(img.width(), img.height(), |x, y| image::Luma([255 - img.get_pixel(x, y)[0]])); - let blur = pix::blur_mask(&inverted, 4.0); - for (x, y, p) in img.enumerate_pixels_mut() { - let dodge = (p[0] as f32 * 255.0 / (255.0 - blur.get_pixel(x, y)[0] as f32).max(1.0)).clamp(0.0, 255.0) as u8; - p[0] = dodge; - p[1] = dodge; - p[2] = dodge; - } - } - "oil_painting" => *img = oil(img), - _ => { - // pop art - pix::saturate(img, 2.5); - pix::contrast(img, 1.8); - pix::posterize(img, 3); - } - } -} - -fn speech_bubble(img: &mut RgbaImage, bottom: bool) { - let (w, h) = (img.width() as f32, img.height() as f32); - let bh = (h / 5.0).max(24.0); - // y is measured from the edge the bubble hangs off - let edge = |y: f32| if bottom { h - y } else { y }; - let tri = [(0.55 * w, 0.5 * bh), (0.7 * w, 1.8 * bh), (0.65 * w, 0.4 * bh)]; - let in_tri = |px: f32, py: f32| { - let s = |a: (f32, f32), b: (f32, f32)| (px - b.0) * (a.1 - b.1) - (a.0 - b.0) * (py - b.1); - let (d1, d2, d3) = (s(tri[0], tri[1]), s(tri[1], tri[2]), s(tri[2], tri[0])); - !((d1 < 0.0 || d2 < 0.0 || d3 < 0.0) && (d1 > 0.0 || d2 > 0.0 || d3 > 0.0)) - }; - for (x, y, p) in img.enumerate_pixels_mut() { - let (px, py) = (x as f32 + 0.5, edge(y as f32 + 0.5)); - let ellipse = ((px - 0.5 * w) / (0.6 * w)).powi(2) + (py / bh).powi(2) <= 1.0; - if ellipse || in_tri(px, py) { - p[3] = 0; - } - } -} - -fn caption(img: &RgbaImage, words: &str) -> RgbaImage { - let w = img.width(); - let size = (w / 12).max(16) as f32; - let look = Look::new(None, true, [0, 0, 0]); - let para = text::layout(words, size, &look, Some(w as f32 - size), Align::Center); - let pad = (size / 2.0) as u32; - let strip = para.height.ceil() as u32 + pad * 2; - let mut out = RgbaImage::from_pixel(w, img.height() + strip, Rgba([255, 255, 255, 255])); - para.draw(&mut out, (size / 2.0) as i32, pad as i32); - imageops::overlay(&mut out, img, 0, strip as i64); - out -} - -fn deepfry(img: &mut RgbaImage, level: u32) { - let l = level as f32; - pix::saturate(img, 1.0 + l * 0.8); - pix::contrast(img, 1.0 + l * 0.6); - pix::sharpen(img, 1.0 + l * 0.4); - let alpha: Vec = img.pixels().map(|p| p[3]).collect(); - let rgb = image::DynamicImage::ImageRgba8(img.clone()).to_rgb8(); - let mut buf = Cursor::new(Vec::new()); - let quality = (100 - level as i32 * 20).max(5) as u8; - if rgb.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, quality)).is_ok() { - if let Ok(back) = image::load_from_memory_with_format(buf.get_ref(), image::ImageFormat::Jpeg) { - *img = back.to_rgba8(); - } - } - for (p, a) in img.pixels_mut().zip(alpha) { - let n = (rand::random::() as i32 % 100 - 50) * level as i32 / 5; - for c in 0..3 { - p[c] = (p[c] as i32 + n).clamp(0, 255) as u8; - } - p[3] = a; - } -} - -pub fn apply_effect(img: RgbaImage, name: &str, o: &Opts) -> RgbaImage { - let mut img = img; - match name { - "speechbubble" => speech_bubble(&mut img, o.bottom), - "caption" => return caption(&img, &o.text), - "blur" => return imageops::blur(&img, o.radius), - "pixelate" => { - let size = o.size.max(2); - let small = imageops::resize(&img, (img.width() / size).max(1), (img.height() / size).max(1), imageops::FilterType::Nearest); - return imageops::resize(&small, img.width(), img.height(), imageops::FilterType::Nearest); - } - "flip" => imageops::flip_vertical_in_place(&mut img), - "mirror" => imageops::flip_horizontal_in_place(&mut img), - "deepfry" => deepfry(&mut img, o.level), - "vignette" => vignette(&mut img), - "border" => { - let b = (img.width() / 40).max(6); - let mut out = RgbaImage::from_pixel(img.width() + 2 * b, img.height() + 2 * b, Rgba([255, 255, 255, 255])); - imageops::overlay(&mut out, &img, b as i64, b as i64); - return out; - } - _ => pix::circle(&mut img), - } - img -} - /// Decode every frame of an animated GIF / WebP (None for pictures that don't move). fn frames_of(bytes: &[u8]) -> Option> { let frames: Vec = match image::guess_format(bytes).ok()? { @@ -280,26 +74,6 @@ pub fn encode_gif(frames: Vec<(RgbaImage, u32)>) -> Option> { Some(out) } -/// (file bytes, extension). `max_gif` is the biggest side for animated results. -pub fn process(bytes: &[u8], effect: Option<&str>, filter: Option<&str>, opts: &Opts, max_gif: u32) -> Option<(Vec, &'static str)> { - let one = |frame: RgbaImage, limit: u32| { - let mut f = pix::thumbnail(&frame, limit); - if let Some(e) = effect { - f = apply_effect(f, e, opts); - } - if let Some(name) = filter { - apply_filter(&mut f, name); - } - f - }; - if let Some(frames) = frames_of(bytes) { - let done: Vec<_> = frames.into_iter().map(|(f, ms)| (one(f, max_gif), ms)).collect(); - return Some((encode_gif(done)?, "gif")); - } - let still = pix::decode(bytes)?; - Some((pix::encode_png(&one(still, MAX_SIDE)), "png")) -} - /// Offline petpet stand-in: the picture squishes like it's being patted. pub fn squish_gif(bytes: &[u8]) -> Option> { let base = pix::thumbnail(&pix::decode(bytes)?, 112); @@ -322,13 +96,13 @@ pub fn squish_gif(bytes: &[u8]) -> Option> { pub(super) async fn pick_opt(ctx: &Ctx, text: &str) -> Result> { let state = &ctx.state; if ctx.is_slash() { - if let Some(a) = ctx.args.id("file").or_else(|| ctx.args.id("image")).and_then(|id| ctx.attachments.iter().find(|a| a.id.get() == id)) { + if let Some(a) = ctx.args.id("source-attachment").or_else(|| ctx.args.id("file")).or_else(|| ctx.args.id("image")).and_then(|id| ctx.attachments.iter().find(|a| a.id.get() == id)) { return Ok(Some((a.url.clone(), text.to_string()))); } if let Some(u) = ctx.args.user("user") { return Ok(Some((avatar(state, u, 512).await, text.to_string()))); } - if let Some(url) = ctx.args.str("url") { + if let Some(url) = ctx.args.str("source-link").or_else(|| ctx.args.str("url")) { if safe_url(url).is_none() { bail_user!("That doesn't look like a public link."); } @@ -376,109 +150,6 @@ pub(super) async fn pick_opt(ctx: &Ctx, text: &str) -> Result Result<(String, String)> { - if let Some(found) = pick_opt(ctx, text).await? { - return Ok(found); - } - let who = if ctx.is_slash() { ctx.user_id } else { replied(ctx).await.map_or(ctx.user_id, |m| m.author.id) }; - Ok((avatar(&ctx.state, who, 512).await, text.to_string())) -} - -// ---- /image, D!fx ------------------------------------------------------------------------------ - -fn resolve_name(name: &str) -> (Option<&'static str>, Option<&'static str>) { - let n = name.to_lowercase().replace('-', "_"); - let n = match n.as_str() { - "bubble" | "speech" => "speechbubble", - "pixel" => "pixelate", - "fry" => "deepfry", - "gray" | "grey" | "bw" => "grayscale", - "sketch" => "pencil_sketch", - "oil" => "oil_painting", - "popart" => "pop_art", - other => other, - } - .to_string(); - (EFFECTS.iter().copied().find(|e| *e == n), FILTERS.iter().copied().find(|f| *f == n)) -} - -/// Effects and filters on a picture or GIF: the shared job behind `/media` and `D!fx`. -async fn run_job(ctx: &Arc, url: &str, effect: Option<&'static str>, filter: Option<&'static str>, opts: Opts) -> Result<()> { - let limit = upload_budget(ctx); - ctx.defer().await?; - let Some(data) = fetch_limited(&ctx.state, url, MAX_IMAGE_BYTES).await else { - bail_user!("I couldn't download that ({} MB max).", MAX_IMAGE_BYTES / 1024 / 1024); - }; - let bytes = data; - let base = effect.or(filter).unwrap_or("image").to_string(); - if !matches!(image::guess_format(&bytes), Ok(image::ImageFormat::Png | image::ImageFormat::Jpeg | image::ImageFormat::Gif | image::ImageFormat::WebP | image::ImageFormat::Bmp)) { - bail_user!("Effects and filters work on pictures and GIFs. To change a file's format use `/convert`."); - } - let mut done = None; - for side in [MAX_GIF_SIDE, 320, 220] { - let (b, o) = (bytes.clone(), opts.clone()); - let result = tokio::task::spawn_blocking(move || process(&b, effect, filter, &o, side)).await?; - let Some((out, e)) = result else { bail_user!("That doesn't look like a picture I can read.") }; - let fits = out.len() <= limit; - done = Some((out, e)); - if fits || e == "png" { - break; - } - } - let Some((bytes, ext)) = done else { bail_user!("That didn't work.") }; - if bytes.len() > limit { - bail_user!("The result is too big to upload ({} MB, the limit here is {} MB).", bytes.len() / 1024 / 1024, limit / 1024 / 1024); - } - let name = format!("{base}.{ext}"); - ctx.reply_file(Card::new(None).gallery(&[&format!("attachment://{name}")]).build(), &name, bytes).await -} - -async fn image_cmd(ctx: Arc) -> Result<()> { - let a = &ctx.args; - let mut opts = Opts::default(); - let (effect, filter, rest); - if ctx.is_slash() { - effect = a.str("effect").and_then(|n| resolve_name(n).0); - filter = a.str("filter").and_then(|n| resolve_name(n).1); - opts.text = a.str("text").unwrap_or("").to_string(); - opts.bottom = a.str("bubble_position") == Some("bottom"); - opts.radius = a.int("blur_radius").unwrap_or(5).clamp(1, 20) as f32; - opts.size = a.int("pixel_size").unwrap_or(10).clamp(2, 50) as u32; - opts.level = a.int("deepfry_level").unwrap_or(3).clamp(1, 5) as u32; - rest = String::new(); - if effect.is_none() && filter.is_none() { - bail_user!("Pick an `effect` or a `filter`. To change a file's format use `/convert`."); - } - } else { - let name = a.str("name").unwrap_or(""); - let (e, f) = resolve_name(name); - if e.is_none() && f.is_none() { - bail_user!("`{}` isn't an effect or filter — see `{}help fx`. To change a file's format use `{}convert`.", escape(&truncate(name, 40)), ctx.state.prefix(ctx.guild_id), ctx.state.prefix(ctx.guild_id)); - } - (effect, filter) = (e, f); - rest = a.str("rest").unwrap_or("").to_string(); - } - if effect == Some("caption") && ctx.is_slash() && opts.text.is_empty() { - bail_user!("The caption effect needs `text`."); - } - let (url, left) = pick(&ctx, &rest).await?; - if !ctx.is_slash() { - let left = left.trim(); - opts.text = left.to_string(); - opts.bottom = left.to_lowercase().contains("bottom"); - if effect == Some("caption") && left.is_empty() { - bail_user!("What should the caption say? `{}fx caption `", ctx.state.prefix(ctx.guild_id)); - } - if let (Ok(n), Some("blur" | "pixelate" | "deepfry")) = (left.parse::(), effect) { - opts.radius = n.clamp(1, 20) as f32; - opts.size = n.clamp(2, 50) as u32; - opts.level = n.clamp(1, 5) as u32; - } - } - run_job(&ctx, &url, effect, filter, opts).await -} - // ---- petpet --------------------------------------------------------------------------------------- async fn petpet(ctx: Arc) -> Result<()> { @@ -523,26 +194,175 @@ async fn petpet(ctx: Arc) -> Result<()> { ctx.reply_file(Card::new(None).gallery(&["attachment://petpet.gif"]).build(), "petpet.gif", gif).await } +// ---- caption ----------------------------------------------------------------------------------- + +/// The white band with the centred black text, `width` pixels wide. Its height is always even (video needs that). +fn caption_band(width: u32, words: &str) -> RgbaImage { + let size = (width / 12).max(16) as f32; + let look = Look::new(None, true, [0, 0, 0]); + let para = text::layout(words, size, &look, Some(width as f32 - size), Align::Center); + let pad = (size / 2.0) as u32; + let height = (para.height.ceil() as u32 + pad * 2 + 1) & !1; + let mut band = RgbaImage::from_pixel(width, height, Rgba([255, 255, 255, 255])); + para.draw(&mut band, (size / 2.0) as i32, pad as i32); + band +} + +/// The band on top, the picture under it. Transparent pixels of the picture show white. +fn stack(band: &RgbaImage, img: &RgbaImage) -> RgbaImage { + let mut out = RgbaImage::from_pixel(band.width(), band.height() + img.height(), Rgba([255, 255, 255, 255])); + imageops::overlay(&mut out, band, 0, 0); + imageops::overlay(&mut out, img, 0, band.height() as i64); + out +} + +/// (file bytes, extension) for a picture, GIF or animated WebP. None if it isn't one. +fn caption_image(bytes: &[u8], words: &str, max_gif: u32) -> Option<(Vec, &'static str)> { + if let Some(frames) = frames_of(bytes) { + let frames: Vec<_> = frames.into_iter().map(|(f, ms)| (pix::thumbnail(&f, max_gif), ms)).collect(); + let band = caption_band(frames[0].0.width(), words); + return Some((encode_gif(frames.into_iter().map(|(f, ms)| (stack(&band, &f), ms)).collect())?, "gif")); + } + let still = pix::thumbnail(&pix::decode(bytes)?, MAX_SIDE); + let band = caption_band(still.width(), words); + Some((pix::encode_png(&stack(&band, &still)), "png")) +} + +/// A picture too big as PNG goes out as JPEG instead. +fn as_jpeg(png: &[u8]) -> Option> { + let rgb = image::load_from_memory(png).ok()?.to_rgb8(); + let mut out = Vec::new(); + image::DynamicImage::ImageRgb8(rgb).write_to(&mut Cursor::new(&mut out), image::ImageFormat::Jpeg).ok()?; + Some(out) +} + +/// A clip: cut to frames, caption each, encode back to MP4 (no sound). `crf` is the quality, higher is smaller. +async fn caption_video(bytes: &[u8], words: &str, crf: u32) -> Result, String> { + let scratch = Scratch::new().map_err(|e| e.to_string())?; + let input = scratch.path("in"); + std::fs::write(&input, bytes).map_err(|e| e.to_string())?; + let arg = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); + let pattern = scratch.path("f%04d.png").to_string_lossy().to_string(); + let filter = format!("fps={VIDEO_FPS},scale='min({MAX_VIDEO_SIDE},iw)':-2"); + let mut cut = arg(&["-i", &input.to_string_lossy(), "-t", &VIDEO_SECONDS.to_string(), "-vf", &filter, "-frames:v", &MAX_FRAMES.to_string()]); + cut.push(pattern.clone()); + ffmpeg::run(&cut, Duration::from_secs(VIDEO_DECODE_SECONDS)).await?; + let dir = scratch.path(""); + let words = words.to_string(); + let count = tokio::task::spawn_blocking(move || { + let mut band: Option = None; + let mut n = 0; + for i in 1..=MAX_FRAMES { + let path = dir.join(format!("f{i:04}.png")); + let Ok(raw) = std::fs::read(&path) else { break }; + let Some(frame) = pix::decode(&raw) else { break }; + let band = band.get_or_insert_with(|| caption_band(frame.width(), &words)); + if std::fs::write(&path, pix::encode_png(&stack(band, &frame))).is_err() { + break; + } + n = i; + } + n + }) + .await + .map_err(|e| e.to_string())?; + if count == 0 { + return Err("I couldn't read any frames from that video.".to_string()); + } + let out = scratch.path("out.mp4"); + let mut enc = arg(&["-framerate", &VIDEO_FPS.to_string(), "-i"]); + enc.push(pattern); + enc.extend(arg(&["-c:v", "libx264", "-preset", "veryfast", "-crf", &crf.to_string(), "-pix_fmt", "yuv420p", "-movflags", "+faststart"])); + enc.push(out.to_string_lossy().to_string()); + ffmpeg::run(&enc, Duration::from_secs(VIDEO_ENCODE_SECONDS)).await?; + std::fs::read(&out).map_err(|e| e.to_string()) +} + +async fn caption_cmd(ctx: Arc) -> Result<()> { + let prefix = ctx.state.prefix(ctx.guild_id); + let (found, words) = if ctx.is_slash() { + let words = ctx.args.str("text").unwrap_or("").to_string(); + (pick_opt(&ctx, &words).await?, words) + } else { + let rest = ctx.args.str("rest").unwrap_or("").to_string(); + match pick_opt(&ctx, &rest).await? { + Some((u, left)) => (Some((u, left.clone())), left), + None => (None, rest), + } + }; + let words = words.trim().to_string(); + if words.is_empty() { + bail_user!("What should the caption say? `{prefix}caption ` or `/caption text:`"); + } + if words.chars().count() > MAX_CAPTION_CHARS { + bail_user!("That caption is too long (max {MAX_CAPTION_CHARS} characters)."); + } + let limit = upload_budget(&ctx); + ctx.defer().await?; + let url = match found { + Some((u, _)) => u, + None => match last_chat_media(&ctx).await { + Some(u) => u, + None => bail_user!("Attach a picture, give a link, reply to one, or post one in this channel first."), + }, + }; + let Some(bytes) = fetch_limited(&ctx.state, &url, MAX_IMAGE_BYTES).await else { + bail_user!("I couldn't download that ({} MB max).", MAX_IMAGE_BYTES / 1024 / 1024); + }; + let (out, ext) = if image::guess_format(&bytes).is_ok() { + let mut done = None; + for side in [MAX_GIF_SIDE, 320, 220] { + let (b, w) = (bytes.clone(), words.clone()); + let Some((out, e)) = tokio::task::spawn_blocking(move || caption_image(&b, &w, side)).await? else { + bail_user!("That doesn't look like a picture I can read."); + }; + let fits = out.len() <= limit; + done = Some((out, e)); + if fits || e == "png" { + break; + } + } + let (mut out, mut e) = done.expect("loop runs at least once"); + if e == "png" && out.len() > limit { + if let Some(j) = as_jpeg(&out) { + (out, e) = (j, "jpg"); + } + } + (out, e) + } else { + let probe_dir = Scratch::new()?; + let probe_file = probe_dir.path("probe"); + std::fs::write(&probe_file, &bytes)?; + if !matches!(ffmpeg::probe(&probe_file).await, Some((_, true))) { + bail_user!("I can caption pictures, GIFs, WebP and videos (MP4, WebM, MOV). That file is none of those."); + } + let mut out = Vec::new(); + for crf in [28, 34, 40] { + out = match caption_video(&bytes, &words, crf).await { + Ok(o) => o, + Err(e) => bail_user!("{}", escape(&truncate(&e, 200))), + }; + if out.len() <= limit { + break; + } + } + (out, "mp4") + }; + if out.len() > limit { + bail_user!("The result is too big to upload ({} MB, the limit here is {} MB).", out.len() / 1024 / 1024, limit / 1024 / 1024); + } + let name = format!("caption.{ext}"); + ctx.reply_file(Card::new(None).gallery(&[&format!("attachment://{name}")]).build(), &name, out).await +} + pub fn commands() -> Vec { - let fx_help = format!("Edit a picture or GIF: reply to one, attach one, or give a @user / link / emoji (default: your avatar). Effects: {}. Filters: {}. To change a file's format use `convert`.", EFFECTS.join(", "), FILTERS.join(", ")); - let fx_help: &'static str = Box::leak(fx_help.into_boxed_str()); vec![ - Command::new("fx", "fun", fx_help, |c| image_cmd(c).boxed()) - .aliases(&["effect", "filter", "imagefx"]) - .slash_as("image") - .usage(" [text]") - .opt(Opt::opt("name", "Effect or filter", OptKind::String).prefix_only()) - .opt(Opt::opt("rest", "Text, a link, a @user…", OptKind::String).prefix_only()) - .opt(Opt::opt("image", "A picture or GIF to edit", OptKind::Attachment).slash_only()) - .opt(Opt::opt("user", "…or use someone's avatar", OptKind::User).slash_only()) - .opt(Opt::opt("url", "…or a link", OptKind::String).slash_only()) - .opt(Opt::opt("effect", "Speech bubble, caption, blur, deepfry…", OptKind::String).choices(&EFFECTS).slash_only()) - .opt(Opt::opt("filter", "Colour filter: sepia, gotham, cyberpunk…", OptKind::String).choices(&FILTERS).slash_only()) - .opt(Opt::opt("text", "Text for the caption effect", OptKind::String).slash_only()) - .opt(Opt::opt("bubble_position", "Where the speech bubble goes", OptKind::String).choices(&["top", "bottom"]).slash_only()) - .opt(Opt::opt("blur_radius", "Blur strength (1–20)", OptKind::Integer).range(1, 20).slash_only()) - .opt(Opt::opt("pixel_size", "Pixelate block size (2–50)", OptKind::Integer).range(2, 50).slash_only()) - .opt(Opt::opt("deepfry_level", "Deepfry strength (1–5)", OptKind::Integer).range(1, 5).slash_only()), + Command::new("caption", "fun", "Put a white band with your text above a picture, GIF, WebP or video (reply to one, attach one, give a link, or it uses the latest in the channel)", |c| caption_cmd(c).boxed()) + .usage("") + .opt(Opt::opt("rest", "Text, and optionally a link", OptKind::String).prefix_only()) + .opt(Opt::opt("text", "The caption text", OptKind::String).slash_only()) + .opt(Opt::opt("source-attachment", "A picture, GIF or video (default: the latest in this channel)", OptKind::Attachment).slash_only()) + .opt(Opt::opt("source-link", "…or a link to one", OptKind::String).slash_only()), Command::new("petpet", "fun", "Petpet GIF of someone's avatar or a custom emoji (reply to a message for its author)", |c| petpet(c).boxed()) .aliases(&["patpat", "pet"]) .usage("[@user | emoji]") @@ -555,57 +375,27 @@ pub fn commands() -> Vec { mod tests { use super::*; - fn sample() -> RgbaImage { - RgbaImage::from_fn(160, 120, |x, y| Rgba([(x * 255 / 160) as u8, (y * 255 / 120) as u8, 90, 255])) + #[test] + fn band_height_grows_with_lines_and_is_even() { + let one = caption_band(400, "hello"); + let three = caption_band(400, "one\ntwo\nthree"); + assert_eq!(one.width(), 400); + assert!(three.height() > one.height() * 2 - 40, "{} vs {}", three.height(), one.height()); + assert!(three.height() > one.height()); + assert_eq!(one.height() % 2, 0); + assert_eq!(three.height() % 2, 0); } #[test] - fn every_filter_and_effect_runs() { - let opts = Opts { text: "when the code works 🧼".into(), ..Opts::default() }; - for name in FILTERS { - let mut img = sample(); - apply_filter(&mut img, name); - assert_eq!(img.dimensions(), (160, 120), "{name}"); - } - for name in EFFECTS { - let out = apply_effect(sample(), name, &opts); - assert!(out.width() >= 160 && out.height() >= 120, "{name}"); - if std::env::var("DEZIO_DUMP").is_ok() { - out.save(format!("/tmp/dezio_fx_{name}.png")).unwrap(); - } - } - assert!(apply_effect(sample(), "caption", &opts).height() > 120); - assert_eq!(apply_effect(sample(), "border", &opts).width(), 160 + 2 * 6); - } - - #[test] - fn names_and_aliases_resolve() { - assert_eq!(resolve_name("Pencil-Sketch").1, Some("pencil_sketch")); - assert_eq!(resolve_name("bw").1, Some("grayscale")); - assert_eq!(resolve_name("fry").0, Some("deepfry")); - assert_eq!(resolve_name("nonsense"), (None, None)); - } - - #[test] - fn pictures_and_gifs_keep_their_kind() { - let png = pix::encode_png(&sample()); - let (out, ext) = process(&png, Some("mirror"), Some("sepia"), &Opts::default(), 480).unwrap(); + fn caption_keeps_picture_kind() { + let png = pix::encode_png(&RgbaImage::from_pixel(160, 120, Rgba([10, 20, 30, 255]))); + let (out, ext) = caption_image(&png, "hi", 480).unwrap(); assert_eq!(ext, "png"); - assert!(image::load_from_memory(&out).is_ok()); + assert!(image::load_from_memory(&out).unwrap().height() > 120); let gif = squish_gif(&png).unwrap(); - let (out, ext) = process(&gif, Some("blur"), None, &Opts::default(), 480).unwrap(); + let (out, ext) = caption_image(&gif, "hi", 480).unwrap(); assert_eq!(ext, "gif"); assert!(frames_of(&out).is_some_and(|f| f.len() == 10)); - assert!(process(b"not an image", None, Some("sepia"), &Opts::default(), 480).is_none()); - } - - #[test] - fn sepia_and_invert_math() { - let mut img = RgbaImage::from_pixel(2, 2, Rgba([100, 150, 200, 255])); - apply_filter(&mut img, "invert"); - assert_eq!(img.get_pixel(0, 0).0, [155, 105, 55, 255]); - let mut img = RgbaImage::from_pixel(1, 1, Rgba([255, 255, 255, 255])); - apply_filter(&mut img, "sepia"); - assert_eq!(img.get_pixel(0, 0).0, [255, 255, 239, 255]); + assert!(caption_image(b"not an image", "hi", 480).is_none()); } } diff --git a/src/commands/media/mod.rs b/src/commands/media/mod.rs index 1a56481..de5268c 100644 --- a/src/commands/media/mod.rs +++ b/src/commands/media/mod.rs @@ -1,4 +1,4 @@ -//! Pictures: quotes, image effects and conversion, emoji tools, downloads. +//! Pictures: quotes, captions and conversion, emoji tools, downloads. use crate::bail_user; use crate::cmd::{Command, Ctx}; use crate::state::State; diff --git a/web/site/index.html b/web/site/index.html index 8c6f2e3..4f53792 100644 --- a/web/site/index.html +++ b/web/site/index.html @@ -205,7 +205,7 @@

Server setup

Welcome and goodbye cards, autoroles and sticky roles, reaction roles, role menus, media-only and Reddit-style channels.

/cosmetics

Games and casino

Chess, Connect 4, tic-tac-toe, Wordle, hangman, minesweeper, 2048, Akinator, Cookie Clicker, plus coin flip, blackjack, slots and roulette.

/chess

AI chat

Mention Dezio to chat. Server admins can give it a personality or keep it to one channel.

@Dezio
-

Media tools

Image effects and filters, petpet GIFs, quote images, Emoji Kitchen mashups, emoji and sticker stealing.

/image
+

Media tools

Captions for pictures and videos, petpet GIFs, quote images, Emoji Kitchen mashups, emoji and sticker stealing.

/caption

Utilities

Weather, web and image search, Wikipedia, dictionary, translate, calculator, colours, VirusTotal scans, snipe and AFK.

/weather
From 1c90d16ffe3be7694f5a46a8d2c1f806abd0cb8c Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 21:50:34 -0600 Subject: [PATCH 08/24] S004: tick plan Co-Authored-By: Claude Sonnet 5.5 --- .../S004-remove-image-add-caption.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Plans/02 Image commands/S004-remove-image-add-caption.md b/Plans/02 Image commands/S004-remove-image-add-caption.md index d528f67..e389bdf 100644 --- a/Plans/02 Image commands/S004-remove-image-add-caption.md +++ b/Plans/02 Image commands/S004-remove-image-add-caption.md @@ -13,12 +13,12 @@ - `grep -rn "D!fx\|/image\|\"fx\"" src web` for help and website mentions ## Steps -- [ ] Remove `/image`, `D!fx`, `apply_filter`, `apply_effect`, effects/filters and their tests; keep `pick_opt`, `pick`, frame and GIF helpers, `petpet` -- [ ] Caption drawing: white band sized to the wrapped text (fonts in `assets/`), text centred, black; band width = picture width; pure function with a unit test on band height for 1 and 3 lines -- [ ] Media: still → PNG/JPG kept; GIF/animated WebP → GIF with every frame captioned; video → ffmpeg frames out, caption each, encode back (or ffmpeg `pad` + `drawtext` if simpler and the font is available); size limits through S001's budget helper if it exists, else `media::upload_limit` -- [ ] Register `/caption` (slash + `D!caption`), help page entry, remove `/image` from help and website lists -- [ ] `docs/tests/S004-caption.md` (checks per media type, empty text, very long text, huge input, bad link) -- [ ] PROGRESS entry, INDEX line, commit `S004: …` +- [x] Remove `/image`, `D!fx`, `apply_filter`, `apply_effect`, effects/filters and their tests; keep `pick_opt`, `pick`, frame and GIF helpers, `petpet` +- [x] Caption drawing: white band sized to the wrapped text (fonts in `assets/`), text centred, black; band width = picture width; pure function with a unit test on band height for 1 and 3 lines +- [x] Media: still → PNG/JPG kept; GIF/animated WebP → GIF with every frame captioned; video → ffmpeg frames out, caption each, encode back (or ffmpeg `pad` + `drawtext` if simpler and the font is available); size limits through S001's budget helper if it exists, else `media::upload_limit` +- [x] Register `/caption` (slash + `D!caption`), help page entry, remove `/image` from help and website lists +- [x] `docs/tests/S004-caption.md` (checks per media type, empty text, very long text, huge input, bad link) +- [x] PROGRESS entry, INDEX line, commit `S004: …` ## End criteria - `cargo build` compiles. From 10e623affa522c1d5a34af920887801495f5b821 Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 21:52:34 -0600 Subject: [PATCH 09/24] S005: /speechbubble with transparent or solid bubble for pictures, GIFs and video Co-Authored-By: Claude Sonnet 5.5 --- Plans/02 Image commands/S005-speechbubble.md | 12 +- Plans/INDEX.md | 2 +- docs/PROGRESS.md | 4 + docs/tests/S005-speechbubble.md | 30 ++ src/commands/media/images.rs | 278 ++++++++++++++++++- 5 files changed, 308 insertions(+), 18 deletions(-) create mode 100644 docs/tests/S005-speechbubble.md diff --git a/Plans/02 Image commands/S005-speechbubble.md b/Plans/02 Image commands/S005-speechbubble.md index 6698ef2..fada414 100644 --- a/Plans/02 Image commands/S005-speechbubble.md +++ b/Plans/02 Image commands/S005-speechbubble.md @@ -13,12 +13,12 @@ - Look at a few frames of `assets/reference/speechbubble-bsm.gif` and `speechbubble-assyst.gif` (extract 2 frames with ffmpeg to the scratchpad and view them) ## Steps -- [ ] Bubble shape as a pure function: ellipse + tail mask for (width, height, position, flip); unit test that the tail side flips and that the mask touches the chosen edge -- [ ] Draw: transparent cutout (alpha 0 inside the mask) or solid (white fill + black outline); the picture's edge follows the bubble's curve -- [ ] Media: PNG out for still transparent; GIF with transparency for animated; video → GIF (transparency) or same format when `solid` -- [ ] Register command (slash + `D!`), help entry -- [ ] `docs/tests/S005-speechbubble.md` (checks per option and media type, compare with both reference GIFs on a contact sheet) -- [ ] PROGRESS entry, INDEX line, commit `S005: …` +- [x] Bubble shape as a pure function: ellipse + tail mask for (width, height, position, flip); unit test that the tail side flips and that the mask touches the chosen edge +- [x] Draw: transparent cutout (alpha 0 inside the mask) or solid (white fill + black outline); the picture's edge follows the bubble's curve +- [x] Media: PNG out for still transparent; GIF with transparency for animated; video → GIF (transparency) or same format when `solid` +- [x] Register command (slash + `D!`), help entry +- [x] `docs/tests/S005-speechbubble.md` (checks per option and media type, compare with both reference GIFs on a contact sheet) +- [x] PROGRESS entry, INDEX line, commit `S005: …` ## End criteria - `cargo build` compiles. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 56c679e..d09757a 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -13,7 +13,7 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp ## 02 Image commands - [x] [S004 — Remove /image, add /caption](02%20Image%20commands/S004-remove-image-add-caption.md) -- [ ] [S005 — /speechbubble](02%20Image%20commands/S005-speechbubble.md) +- [x] [S005 — /speechbubble](02%20Image%20commands/S005-speechbubble.md) ## 03 fm commands diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 35b7588..79066f0 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -34,3 +34,7 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Done: `/image` + `D!fx` and all effects/filters gone. `/caption` + `D!caption` (options `source-attachment`, `source-link`, `text`; no source = latest media in channel via `convert::last_chat_media`). Still → PNG (JPEG if too big); GIF/animated WebP → GIF; video → MP4 (no sound, 10 s, 12 fps, 480 px max). Help and website text updated. - Shared helpers for S005: `images::pick_opt`, `convert::last_chat_media`, `images::frames_of`, `encode_gif`, `caption_image` / `caption_video` pattern (band + `stack`), `ffmpeg::Scratch` + `ffmpeg::run`. `/speechbubble` is not added yet (S005). - Verified: `cargo check` only. Not tested, not checked in Discord 🧑. + +## 2026-12-01 — S005 /speechbubble +- Done: `/speechbubble` + `D!speechbubble` (alias `bubble`; options `source-attachment`, `source-link`, `position`, `flip`, `solid`; prefix words `bottom flip solid`). Pure `bubble_mask` + `draw_bubble` in `images.rs`. Still → PNG, GIF/WebP → GIF (transparent), video → transparent GIF, or MP4 with `solid`. Video frame loop shared as `map_frames` (caption uses it too). +- Verified: `cargo check` only. Not tested, shape not compared with the reference GIFs, not checked in Discord 🧑 (S011). See `docs/tests/S005-speechbubble.md` doubts (GIF transparency, no anti-aliasing). diff --git a/docs/tests/S005-speechbubble.md b/docs/tests/S005-speechbubble.md new file mode 100644 index 0000000..8c3e69e --- /dev/null +++ b/docs/tests/S005-speechbubble.md @@ -0,0 +1,30 @@ +# S005 — /speechbubble checks + +Run in Discord (owner) unless noted. Bot must have the S005 build. + +## Doubts +- GIF transparency: the `image` crate's GIF encoder decides which colour index is transparent and the frame disposal. If cut-out areas show old frames or a black/odd colour in an animated result, fix the encoder (key colour, disposal Background). +- Bubble edges are not anti-aliased (hard pixels); check this looks acceptable next to the references. +- Shape numbers (`BUBBLE_HEIGHT` 0.2, `BUBBLE_WIDTH` 0.62, tail at 0.12 to 0.28 of the width) are a guess from the reference GIFs; compare and tune. +- Video path never run (ffmpeg and libx264 on the server). Odd video widths under 480 px may break MP4 encoding (same as /caption). +- Prefix option words (`bottom`, `flip`, `solid`) are plain words in the text; a link containing them is fine, other text is ignored. + +## Checks +1. Contact sheet: extract 2 frames of `assets/reference/speechbubble-bsm.gif` and `speechbubble-assyst.gif`; put the bot's `solid` and plain results of the same picture next to them. Shape and tail direction match. +2. `/speechbubble` with a PNG attached: PNG back, transparent wide ellipse cut from the top, tail pointing down toward the right third. +3. Same with `solid:true`: white fill, black outline, tail points into the picture, picture edge follows the curve. +4. `position:bottom`: bubble hangs from the bottom edge, tail points up. +5. `flip:true`: tail on the left third instead (also with bottom and with solid). +6. JPG and still WebP input: PNG out, transparent (not JPG). +7. GIF input: GIF out, still animated, bubble on every frame, transparent area stays clear (no ghost of earlier frames). +8. Animated WebP input: GIF out. +9. MP4, WebM, MOV without `solid`: GIF out with transparent bubble, at most about 10 s. +10. Video with `solid:true`: MP4 out that plays, no sound, bubble on every frame. +11. `source-link:`: works. `D!speechbubble `: works. +12. `D!speechbubble bottom flip solid` replying to a picture: all three options applied. +13. No source: uses the latest picture in the channel; nothing in the channel: clear error card. +14. Big result (large PNG or GIF over the upload limit): retried smaller; if still too big, clear "too big" error. A solid still may come out as JPG; a transparent one never does. +15. Bad link (`http://127.0.0.1/x`) and non-media file (PDF): error card, no crash. +16. `/help` lists `speechbubble` (alias `bubble`); `cargo test help` limits test passes. +17. Unit tests `bubble_tail_flips_and_touches_chosen_edge` and `bubble_cuts_transparent_or_paints_solid` pass (`cargo test bubble`). +18. `/caption` still works on a picture and a video (its video code was refactored into `map_frames`). diff --git a/src/commands/media/images.rs b/src/commands/media/images.rs index 7330d1e..948f869 100644 --- a/src/commands/media/images.rs +++ b/src/commands/media/images.rs @@ -236,28 +236,24 @@ fn as_jpeg(png: &[u8]) -> Option> { Some(out) } -/// A clip: cut to frames, caption each, encode back to MP4 (no sound). `crf` is the quality, higher is smaller. -async fn caption_video(bytes: &[u8], words: &str, crf: u32) -> Result, String> { - let scratch = Scratch::new().map_err(|e| e.to_string())?; +/// Cut a clip to frames (`f%04d.png` in `scratch`, at most `VIDEO_SECONDS` at `VIDEO_FPS`, `max_side` wide), run `edit` on each, +/// write them back. Returns the frame count. +async fn map_frames(scratch: &Scratch, bytes: &[u8], max_side: u32, mut edit: impl FnMut(&RgbaImage) -> RgbaImage + Send + 'static) -> Result { let input = scratch.path("in"); std::fs::write(&input, bytes).map_err(|e| e.to_string())?; - let arg = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); let pattern = scratch.path("f%04d.png").to_string_lossy().to_string(); - let filter = format!("fps={VIDEO_FPS},scale='min({MAX_VIDEO_SIDE},iw)':-2"); - let mut cut = arg(&["-i", &input.to_string_lossy(), "-t", &VIDEO_SECONDS.to_string(), "-vf", &filter, "-frames:v", &MAX_FRAMES.to_string()]); - cut.push(pattern.clone()); + let filter = format!("fps={VIDEO_FPS},scale='min({max_side},iw)':-2"); + let mut cut: Vec = ["-i", &input.to_string_lossy(), "-t", &VIDEO_SECONDS.to_string(), "-vf", &filter, "-frames:v", &MAX_FRAMES.to_string()].iter().map(|s| s.to_string()).collect(); + cut.push(pattern); ffmpeg::run(&cut, Duration::from_secs(VIDEO_DECODE_SECONDS)).await?; let dir = scratch.path(""); - let words = words.to_string(); let count = tokio::task::spawn_blocking(move || { - let mut band: Option = None; let mut n = 0; for i in 1..=MAX_FRAMES { let path = dir.join(format!("f{i:04}.png")); let Ok(raw) = std::fs::read(&path) else { break }; let Some(frame) = pix::decode(&raw) else { break }; - let band = band.get_or_insert_with(|| caption_band(frame.width(), &words)); - if std::fs::write(&path, pix::encode_png(&stack(band, &frame))).is_err() { + if std::fs::write(&path, pix::encode_png(&edit(&frame))).is_err() { break; } n = i; @@ -269,6 +265,21 @@ async fn caption_video(bytes: &[u8], words: &str, crf: u32) -> Result, S if count == 0 { return Err("I couldn't read any frames from that video.".to_string()); } + Ok(count) +} + +/// A clip: caption each frame, encode back to MP4 (no sound). `crf` is the quality, higher is smaller. +async fn caption_video(bytes: &[u8], words: &str, crf: u32) -> Result, String> { + let scratch = Scratch::new().map_err(|e| e.to_string())?; + let arg = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); + let pattern = scratch.path("f%04d.png").to_string_lossy().to_string(); + let words = words.to_string(); + let mut band: Option = None; + map_frames(&scratch, bytes, MAX_VIDEO_SIDE, move |frame| { + let band = band.get_or_insert_with(|| caption_band(frame.width(), &words)); + stack(band, frame) + }) + .await?; let out = scratch.path("out.mp4"); let mut enc = arg(&["-framerate", &VIDEO_FPS.to_string(), "-i"]); enc.push(pattern); @@ -355,6 +366,201 @@ async fn caption_cmd(ctx: Arc) -> Result<()> { ctx.reply_file(Card::new(None).gallery(&[&format!("attachment://{name}")]).build(), &name, out).await } +// ---- speech bubble ----------------------------------------------------------------------------- + +/// Where the bubble hangs and how it looks. +#[derive(Clone, Copy)] +struct Bubble { + bottom: bool, + flip: bool, + solid: bool, +} + +/// Bubble height as a share of the picture height (the ellipse's half-height; the tail reaches 1.6 times further). +const BUBBLE_HEIGHT: f32 = 0.2; +/// The ellipse is wider than the picture so its ends run off the sides and only the curve of the bottom shows. +const BUBBLE_WIDTH: f32 = 0.62; +/// Outline thickness is this share of the picture width (at least 2 px). +const BUBBLE_OUTLINE: f32 = 0.006; + +/// Which pixels belong to the bubble (ellipse plus tail), row by row. +fn bubble_mask(w: u32, h: u32, bottom: bool, flip: bool) -> Vec { + let (wf, hf) = (w as f32, h as f32); + let ry = (hf * BUBBLE_HEIGHT).max(8.0); + let rx = wf * BUBBLE_WIDTH; + let dir = if flip { -1.0 } else { 1.0 }; + // Tail: base inside the ellipse, tip further down and pulled back toward the middle. + let a = (wf / 2.0 + dir * wf * 0.12, ry * 0.7); + let b = (wf / 2.0 + dir * wf * 0.28, ry * 0.7); + let tip = (wf / 2.0 + dir * wf * 0.2, ry * 1.6); + let side = |p: (f32, f32), q: (f32, f32), x: f32, y: f32| (x - q.0) * (p.1 - q.1) - (p.0 - q.0) * (y - q.1); + let mut mask = vec![false; (w * h) as usize]; + for y in 0..h { + // `bottom` mirrors the whole shape top to bottom. + let fy = if bottom { h - 1 - y } else { y } as f32 + 0.5; + for x in 0..w { + let fx = x as f32 + 0.5; + let (dx, dy) = ((fx - wf / 2.0) / rx, fy / ry); + let in_ellipse = dx * dx + dy * dy <= 1.0; + let (d1, d2, d3) = (side(a, b, fx, fy), side(b, tip, fx, fy), side(tip, a, fx, fy)); + let in_tail = !((d1 < 0.0 || d2 < 0.0 || d3 < 0.0) && (d1 > 0.0 || d2 > 0.0 || d3 > 0.0)); + mask[(y * w + x) as usize] = in_ellipse || in_tail; + } + } + mask +} + +/// Cut the bubble out (transparent) or paint it (white fill, black outline). +fn draw_bubble(img: &mut RgbaImage, b: Bubble) { + let (w, h) = img.dimensions(); + let mask = bubble_mask(w, h, b.bottom, b.flip); + let t = ((w as f32 * BUBBLE_OUTLINE) as i64).max(2); + let inside = |x: i64, y: i64| x < 0 || y < 0 || x >= w as i64 || y >= h as i64 || mask[(y as u32 * w + x as u32) as usize]; + for y in 0..h as i64 { + for x in 0..w as i64 { + if !inside(x, y) { + continue; + } + let px = if !b.solid { + Rgba([0, 0, 0, 0]) + } else if [(t, 0), (-t, 0), (0, t), (0, -t), (t, t), (-t, -t), (t, -t), (-t, t)].iter().any(|(dx, dy)| !inside(x + dx, y + dy)) { + Rgba([0, 0, 0, 255]) + } else { + Rgba([255, 255, 255, 255]) + }; + img.put_pixel(x as u32, y as u32, px); + } + } +} + +/// (file bytes, extension) for a picture, GIF or animated WebP: PNG or GIF, both keep the cut-out transparent. +fn bubble_image(bytes: &[u8], b: Bubble, max_still: u32, max_gif: u32) -> Option<(Vec, &'static str)> { + if let Some(frames) = frames_of(bytes) { + let frames = frames + .into_iter() + .map(|(f, ms)| { + let mut f = pix::thumbnail(&f, max_gif); + draw_bubble(&mut f, b); + (f, ms) + }) + .collect(); + return Some((encode_gif(frames)?, "gif")); + } + let mut still = pix::thumbnail(&pix::decode(bytes)?, max_still); + draw_bubble(&mut still, b); + Some((pix::encode_png(&still), "png")) +} + +/// A clip with the bubble on every frame: MP4 when `solid`, otherwise a transparent GIF (video can't be transparent). +async fn bubble_video(bytes: &[u8], b: Bubble, crf: u32, max_side: u32) -> Result<(Vec, &'static str), String> { + let scratch = Scratch::new().map_err(|e| e.to_string())?; + let count = map_frames(&scratch, bytes, max_side, move |f| { + let mut f = f.clone(); + draw_bubble(&mut f, b); + f + }) + .await?; + if !b.solid { + let dir = scratch.path(""); + let frames = tokio::task::spawn_blocking(move || { + (1..=count).filter_map(|i| pix::decode(&std::fs::read(dir.join(format!("f{i:04}.png"))).ok()?)).map(|f| (f, 1000 / VIDEO_FPS)).collect::>() + }) + .await + .map_err(|e| e.to_string())?; + let gif = tokio::task::spawn_blocking(move || encode_gif(frames)).await.map_err(|e| e.to_string())?; + return gif.map(|g| (g, "gif")).ok_or_else(|| "I couldn't make a GIF from that video.".to_string()); + } + let out = scratch.path("out.mp4"); + let mut enc: Vec = ["-framerate", &VIDEO_FPS.to_string(), "-i"].iter().map(|s| s.to_string()).collect(); + enc.push(scratch.path("f%04d.png").to_string_lossy().to_string()); + enc.extend(["-c:v", "libx264", "-preset", "veryfast", "-crf", &crf.to_string(), "-pix_fmt", "yuv420p", "-movflags", "+faststart"].iter().map(|s| s.to_string())); + enc.push(out.to_string_lossy().to_string()); + ffmpeg::run(&enc, Duration::from_secs(VIDEO_ENCODE_SECONDS)).await?; + std::fs::read(&out).map(|v| (v, "mp4")).map_err(|e| e.to_string()) +} + +async fn speechbubble_cmd(ctx: Arc) -> Result<()> { + let mut b = Bubble { bottom: false, flip: false, solid: false }; + let found = if ctx.is_slash() { + b.bottom = ctx.args.str("position") == Some("bottom"); + b.flip = ctx.args.bool("flip").unwrap_or(false); + b.solid = ctx.args.bool("solid").unwrap_or(false); + pick_opt(&ctx, "").await? + } else { + let rest = ctx.args.str("rest").unwrap_or("").to_string(); + let (found, left) = match pick_opt(&ctx, &rest).await? { + Some((u, left)) => (Some(u), left), + None => (None, rest), + }; + for w in left.split_whitespace() { + match w.to_lowercase().as_str() { + "bottom" => b.bottom = true, + "flip" => b.flip = true, + "solid" => b.solid = true, + _ => {} + } + } + found.map(|u| (u, String::new())) + }; + let limit = upload_budget(&ctx); + ctx.defer().await?; + let url = match found { + Some((u, _)) => u, + None => match last_chat_media(&ctx).await { + Some(u) => u, + None => bail_user!("Attach a picture, give a link, reply to one, or post one in this channel first."), + }, + }; + let Some(bytes) = fetch_limited(&ctx.state, &url, MAX_IMAGE_BYTES).await else { + bail_user!("I couldn't download that ({} MB max).", MAX_IMAGE_BYTES / 1024 / 1024); + }; + let (out, ext) = if image::guess_format(&bytes).is_ok() { + let mut done = None; + // Smaller and smaller until it fits; a still that is still too big goes out as JPEG only when solid (JPEG has no transparency). + for (still, gif) in [(MAX_SIDE, MAX_GIF_SIDE), (720, 320), (480, 220), (320, 160)] { + let (data, bb) = (bytes.clone(), b); + let Some((out, e)) = tokio::task::spawn_blocking(move || bubble_image(&data, bb, still, gif)).await? else { + bail_user!("That doesn't look like a picture I can read."); + }; + let fits = out.len() <= limit; + done = Some((out, e)); + if fits { + break; + } + } + let (mut out, mut e) = done.expect("loop runs at least once"); + if e == "png" && out.len() > limit && b.solid { + if let Some(j) = as_jpeg(&out) { + (out, e) = (j, "jpg"); + } + } + (out, e) + } else { + let probe_dir = Scratch::new()?; + let probe_file = probe_dir.path("probe"); + std::fs::write(&probe_file, &bytes)?; + if !matches!(ffmpeg::probe(&probe_file).await, Some((_, true))) { + bail_user!("I can work on pictures, GIFs, WebP and videos (MP4, WebM, MOV). That file is none of those."); + } + let mut out = (Vec::new(), "mp4"); + for (crf, side) in [(28, MAX_VIDEO_SIDE), (34, 320), (40, 220)] { + out = match bubble_video(&bytes, b, crf, side).await { + Ok(o) => o, + Err(e) => bail_user!("{}", escape(&truncate(&e, 200))), + }; + if out.0.len() <= limit { + break; + } + } + out + }; + if out.len() > limit { + bail_user!("The result is too big to upload ({} MB, the limit here is {} MB).", out.len() / 1024 / 1024, limit / 1024 / 1024); + } + let name = format!("speechbubble.{ext}"); + ctx.reply_file(Card::new(None).gallery(&[&format!("attachment://{name}")]).build(), &name, out).await +} + pub fn commands() -> Vec { vec![ Command::new("caption", "fun", "Put a white band with your text above a picture, GIF, WebP or video (reply to one, attach one, give a link, or it uses the latest in the channel)", |c| caption_cmd(c).boxed()) @@ -363,6 +569,15 @@ pub fn commands() -> Vec { .opt(Opt::opt("text", "The caption text", OptKind::String).slash_only()) .opt(Opt::opt("source-attachment", "A picture, GIF or video (default: the latest in this channel)", OptKind::Attachment).slash_only()) .opt(Opt::opt("source-link", "…or a link to one", OptKind::String).slash_only()), + Command::new("speechbubble", "fun", "Cut a speech bubble out of the top of a picture, GIF, WebP or video (reply to one, attach one, give a link, or it uses the latest in the channel)", |c| speechbubble_cmd(c).boxed()) + .aliases(&["bubble"]) + .usage("[bottom] [flip] [solid] [link]") + .opt(Opt::opt("rest", "Optional link, and the words bottom, flip, solid", OptKind::String).prefix_only()) + .opt(Opt::opt("source-attachment", "A picture, GIF or video (default: the latest in this channel)", OptKind::Attachment).slash_only()) + .opt(Opt::opt("source-link", "…or a link to one", OptKind::String).slash_only()) + .opt(Opt::opt("position", "Which edge the bubble hangs from (default: top)", OptKind::String).choices(&["top", "bottom"]).slash_only()) + .opt(Opt::opt("flip", "Tail on the other side", OptKind::Bool).slash_only()) + .opt(Opt::opt("solid", "White bubble with a black outline instead of a see-through cut-out", OptKind::Bool).slash_only()), Command::new("petpet", "fun", "Petpet GIF of someone's avatar or a custom emoji (reply to a message for its author)", |c| petpet(c).boxed()) .aliases(&["patpat", "pet"]) .usage("[@user | emoji]") @@ -398,4 +613,45 @@ mod tests { assert!(frames_of(&out).is_some_and(|f| f.len() == 10)); assert!(caption_image(b"not an image", "hi", 480).is_none()); } + + #[test] + fn bubble_tail_flips_and_touches_chosen_edge() { + let (w, h) = (200u32, 100u32); + // mean x of the tail pixels (below the ellipse's lowest row, 0.2 * h = 20) + let tail_x = |bottom: bool, flip: bool| { + let m = bubble_mask(w, h, bottom, flip); + let (mut sum, mut n) = (0u32, 0u32); + for y in 0..h { + let dist = if bottom { h - 1 - y } else { y }; + for x in 0..w { + if dist > 22 && m[(y * w + x) as usize] { + sum += x; + n += 1; + } + } + } + assert!(n > 0); + sum / n + }; + assert!(tail_x(false, false) > w / 2); + assert!(tail_x(false, true) < w / 2); + assert!(tail_x(true, false) > w / 2); + let top = bubble_mask(w, h, false, false); + assert!((0..w).any(|x| top[x as usize]) && !(0..w).any(|x| top[((h - 1) * w + x) as usize])); + let bot = bubble_mask(w, h, true, false); + assert!((0..w).any(|x| bot[((h - 1) * w + x) as usize]) && !(0..w).any(|x| bot[x as usize])); + } + + #[test] + fn bubble_cuts_transparent_or_paints_solid() { + let base = RgbaImage::from_pixel(200, 100, Rgba([10, 20, 30, 255])); + let mut cut = base.clone(); + draw_bubble(&mut cut, Bubble { bottom: false, flip: false, solid: false }); + assert_eq!(cut.get_pixel(100, 0)[3], 0); + assert_eq!(cut.get_pixel(100, 99)[3], 255); + let mut solid = base; + draw_bubble(&mut solid, Bubble { bottom: false, flip: false, solid: true }); + assert_eq!(solid.get_pixel(100, 5), &Rgba([255, 255, 255, 255])); + assert!((0..100).any(|y| solid.get_pixel(100, y) == &Rgba([0, 0, 0, 255]))); + } } From e17e5897bff588d55c7816d7408cad622a83a381 Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 21:53:15 -0600 Subject: [PATCH 10/24] S006: fm audit, topgg text, test file Co-Authored-By: Claude Sonnet 5.5 --- Plans/03 fm commands/S006-fm-on-metabrainz.md | 14 +++++----- Plans/INDEX.md | 2 +- docs/PROGRESS.md | 5 ++++ docs/tests/S006-fm.md | 28 +++++++++++++++++++ docs/topgg.md | 8 +++--- 5 files changed, 45 insertions(+), 12 deletions(-) create mode 100644 docs/tests/S006-fm.md diff --git a/Plans/03 fm commands/S006-fm-on-metabrainz.md b/Plans/03 fm commands/S006-fm-on-metabrainz.md index 077760b..d78819c 100644 --- a/Plans/03 fm commands/S006-fm-on-metabrainz.md +++ b/Plans/03 fm commands/S006-fm-on-metabrainz.md @@ -14,13 +14,13 @@ The owner moved the fm commands from the Last.fm API to ListenBrainz (D-010) wit - `src/web/api.rs` lines ~155-240 (dashboard fm link) ## Steps -- [ ] List every fm feature (top lists, recent, profile, now playing, Who Knows, chart, Pixel Jumble, lyrics, dashboard link, any other user of `lastfm::`) and, for each, the JSON fields it reads; put the list in the test file's Built section -- [ ] For every field, check the adapter fills it from ListenBrainz/MusicBrainz; fields Last.fm used to give that the adapter leaves empty (listeners, global playcount, user registered date, artist bio, tags, images) either get a MusicBrainz/ListenBrainz source or are removed from the card with no empty labels left -- [ ] Remove dead Last.fm-only code (API key reads, method names, `audioscrobbler` leftovers, unused shapes); keep song links to the Last.fm website -- [ ] User-facing text (help, error cards, dashboard, website, privacy) says ListenBrainz where it means the data source; fm errors (unknown ListenBrainz user, stats not ready yet) give plain cards -- [ ] New pure logic (field mapping) gets a unit test with a saved ListenBrainz JSON sample, no network -- [ ] `docs/tests/S006-fm-on-metabrainz.md` (one check per feature, live checks marked `cargo test listenbrainz_live -- --ignored`) -- [ ] PROGRESS entry, INDEX line, commit `S006: …` +- [x] List every fm feature (top lists, recent, profile, now playing, Who Knows, chart, Pixel Jumble, lyrics, dashboard link, any other user of `lastfm::`) and, for each, the JSON fields it reads; put the list in the test file's Built section +- [x] For every field, check the adapter fills it from ListenBrainz/MusicBrainz; fields Last.fm used to give that the adapter leaves empty (listeners, global playcount, user registered date, artist bio, tags, images) either get a MusicBrainz/ListenBrainz source or are removed from the card with no empty labels left +- [x] Remove dead Last.fm-only code (API key reads, method names, `audioscrobbler` leftovers, unused shapes); keep song links to the Last.fm website +- [x] User-facing text (help, error cards, dashboard, website, privacy) says ListenBrainz where it means the data source; fm errors (unknown ListenBrainz user, stats not ready yet) give plain cards +- [x] New pure logic (field mapping) gets a unit test with a saved ListenBrainz JSON sample, no network +- [x] `docs/tests/S006-fm-on-metabrainz.md` (one check per feature, live checks marked `cargo test listenbrainz_live -- --ignored`) +- [x] PROGRESS entry, INDEX line, commit `S006: …` ## End criteria - `cargo build` compiles. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index d09757a..0d2b7bb 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -17,7 +17,7 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp ## 03 fm commands -- [ ] [S006 — fm logic fully on ListenBrainz and MusicBrainz](03%20fm%20commands/S006-fm-on-metabrainz.md) +- [x] [S006 — fm logic fully on ListenBrainz and MusicBrainz](03%20fm%20commands/S006-fm-on-metabrainz.md) ## 04 Security diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 79066f0..92e9848 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -38,3 +38,8 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, ## 2026-12-01 — S005 /speechbubble - Done: `/speechbubble` + `D!speechbubble` (alias `bubble`; options `source-attachment`, `source-link`, `position`, `flip`, `solid`; prefix words `bottom flip solid`). Pure `bubble_mask` + `draw_bubble` in `images.rs`. Still → PNG, GIF/WebP → GIF (transparent), video → transparent GIF, or MP4 with `solid`. Video frame loop shared as `map_frames` (caption uses it too). - Verified: `cargo check` only. Not tested, shape not compared with the reference GIFs, not checked in Discord 🧑 (S011). See `docs/tests/S005-speechbubble.md` doubts (GIF transparency, no anti-aliasing). + +## 2026-12-01 — S006 fm on ListenBrainz +- Done: audit of every fm feature; code was already fully on ListenBrainz/MusicBrainz, no Last.fm API leftovers in src. Only fix: `docs/topgg.md` wording. Test list in `docs/tests/S006-fm.md`. +- Dropped from cards: listeners, global plays, bio, tags (none were shown). Profile realname/country are skipped when empty. +- Verified: grep and `cargo check` only. Not tested in Discord 🧑. No new unit test (no new logic; api.rs already has sample-JSON tests). diff --git a/docs/tests/S006-fm.md b/docs/tests/S006-fm.md new file mode 100644 index 0000000..77f6a01 --- /dev/null +++ b/docs/tests/S006-fm.md @@ -0,0 +1,28 @@ +# S006 fm commands on ListenBrainz + +## Built +Audit only; code was already on ListenBrainz (api.rs, covers.rs). Features and the fields they read from the adapter: +- Top lists (`fm top`, ta/tab/tt): name, artist.name, playcount, url, image. +- Recent / now playing: name, artist, album, `@attr.nowplaying`, image, date. +- Profile: name, playcount, artist/album/track counts, `registered.unixtime` (first listen), week favourites. realname/country are absent and skipped silently (no empty labels). +- Who Knows (wk/wkt/wka): `plays()` by MBID first, then name; top 1000 only. +- Chart, Pixel Jumble: album image via covers.rs chain. Lyrics: track name/artist, Deezer title search. +- Dashboard link (src/web/api.rs): link_account / unlink / linked_name. +- Dropped: listeners, global playcount, bio, tags (never shown by any card). Last.fm site only used for "Go to song" links. +- Text: topgg.md now says ListenBrainz. `grep -rni "audioscrobbler\|api_key\|LASTFM_API" src` finds only unrelated keys (ZENSERP, STEAMGRIDDB, VIRUSTOTAL). + +## Checks +1. `/fm` with a linked user shows now playing or last listen with cover. +2. `/fm top artists weekly`, `monthly`, `yearly`, `overall` each show a list or "no stats yet" card. +3. `fm profile` shows listens, counts, "Listening since" date, no empty labels. +4. `fm recent` lists 50 listens. +5. `wk` in a server with 2 linked users ranks both. +6. `chart 3x3` makes a collage with covers. +7. `px` starts Pixel Jumble with a pixelated cover. +8. `lyrics` with no args uses the current song. +9. `fmset nosuchuserxyz` gives "There's no ListenBrainz user with that name." +10. Dashboard: set and clear ListenBrainz name works. +11. Live: `cargo test listenbrainz_live -- --ignored`. + +## Doubts +- Not run anywhere; only compile-checked. Fresh users with 204 (stats not ready) show an empty list, not a dedicated card message (not verified). diff --git a/docs/topgg.md b/docs/topgg.md index 47621c7..5a28d89 100644 --- a/docs/topgg.md +++ b/docs/topgg.md @@ -15,16 +15,16 @@ Copy each block into the matching field on the bot's Top.gg edit page. ## Tags -`Music` · `Moderation` · `Fun` · `Utility` · `Games` · `Logging` · `Social` · `Last.fm` +`Music` · `Moderation` · `Fun` · `Utility` · `Games` · `Logging` · `Social` · `Music stats` ## Short description (headline) -Music with a live player, Last.fm stats, video downloads, games, AI chat, moderation and logs — one bot, set up in minutes. +Music with a live player, ListenBrainz stats, video downloads, games, AI chat, moderation and logs — one bot, set up in minutes. ## Long description ```markdown -# Dezio — music, Last.fm, downloads, games and moderation in one bot +# Dezio — music, ListenBrainz stats, downloads, games and moderation in one bot **Dezio** is an all-in-one Discord bot that does the everyday jobs of a server without needing six different bots. Everything works as a **slash command** and most things also work with the **`D!` prefix**. Type `/help` to see every command. @@ -36,7 +36,7 @@ Play songs and playlists from a search or a link (YouTube, SoundCloud, Bandcamp - Leaves by itself when everyone is gone or nothing is playing - Music chat cleans itself up — only the player stays -## 📊 Last.fm +## 📊 ListenBrainz stats Now-playing cards, top artists / albums / tracks, album collages, server **"Who knows?"** leaderboards, lyrics, and **Pixel Jumble** — a server-wide guess-the-album game anyone can join by typing. ## ⬇️ Downloads From 6d2d005b55defe96d0a6a85217e6edcee09cdd5b Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 21:56:45 -0600 Subject: [PATCH 11/24] plans: website under /dezio/, landing page at root Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 2 ++ Plans/03a Website path/S006a-dezio-path.md | 38 ++++++++++++++++++++++ Plans/INDEX.md | 4 +++ docs/DECISIONS.md | 1 + 4 files changed, 45 insertions(+) create mode 100644 Plans/03a Website path/S006a-dezio-path.md diff --git a/PLAN.md b/PLAN.md index 9e95e16..978d140 100644 --- a/PLAN.md +++ b/PLAN.md @@ -18,6 +18,8 @@ security test has been done beyond earlier spot fixes. `/image` (`D!fx`) bundles work like the well-known caption bots. - Phase 2b — fm commands: every fm feature gets its data from ListenBrainz and MusicBrainz (plus the cover fallbacks), with no leftover Last.fm API logic; only song links still point to the Last.fm website. +- Phase 2c — Website path: all of Dezio's website moves to `/dezio/` on the Tailscale URL; the root gets a minimal + landing page (to be improved later). - Phase 3 — Security: website and dashboard, media inputs, commands and abuse, dependency audit; fixes for what is found; tested on a local copy only. - Phase 4 — Deploy and owner check in Discord. diff --git a/Plans/03a Website path/S006a-dezio-path.md b/Plans/03a Website path/S006a-dezio-path.md new file mode 100644 index 0000000..dea4cd9 --- /dev/null +++ b/Plans/03a Website path/S006a-dezio-path.md @@ -0,0 +1,38 @@ +# S006a — Website under /dezio/, landing page at the root + +> Category 03a Website path · Model: Sonnet · Effort: medium · Depends on: — · Size: M · Human: 🧑 Discord Developer Portal (OAuth redirect, Activity URL mapping) +> Files touched: src/web/{mod,activity}.rs, src/hosted.rs, src/commands/gameboy.rs, web/**/*.{html,js,css}, docs/topgg.md, deploy/landing/index.html (new) + +## Goal +Move all of Dezio's website (site, dashboard, API, OAuth, Game Boy Activity, hosted `/f/` files) from the root of https://archlinux.tail7c4f5e.ts.net to https://archlinux.tail7c4f5e.ts.net/dezio/ (D-013). The root `/` becomes a very simple static landing page with links to `/dezio/` and `/git/`; the owner will improve it later, so keep it minimal. `/git` (Forgejo) stays as is. + +## Read +- `src/web/mod.rs` lines 1–70 (config, `DASHBOARD_URL`) and 280–320 (router) +- `src/web/activity.rs` lines 1–30 and 485–510 (routes) +- `src/hosted.rs` lines 15–35, `src/commands/gameboy.rs` lines 1–40 +- `grep -rn '"/' web` for absolute paths in pages, JS and CSS +- `docs/topgg.md` URL lines + +## Steps +- [ ] Base path: derive it from the path part of `DASHBOARD_URL` (e.g. `https://…ts.net/dezio` → `/dezio`; none → `/`). Check with `tailscale serve --help` / docs whether `--set-path /dezio` strips the prefix before proxying (it is believed to strip it). Make the router work both ways: nest all routes under the base path and also accept un-prefixed paths, OR rely on stripping — pick one, say which in DECISIONS (D-013 addition). Cookie `Path` must match the base path. +- [ ] Pages: every absolute link in `web/site`, `web/dashboard`, `web/activity` (`href="/…"`, `src="/…"`, `fetch("/api…")`, `/login`, `/assets`, `/images`, `/dashboard`, `/activity/api/…`) works under `/dezio/`. Prefer relative paths; where a page needs the base, inject it from the server once (no per-page copy-paste). OAuth `redirect_uri` stays `DASHBOARD_URL + "/callback"`. Redirects the server sends (login, logout, `slash_redirect`) carry the base path. +- [ ] Hosted links (`hosted::store`) and `/gameboy` links come from `DASHBOARD_URL`, so they follow; check nothing else hard-codes `/f/` or `/activity` at the root. +- [ ] Landing page: `deploy/landing/index.html`, one small static page (title, two links: Dezio → `/dezio/`, Source → `/git/`), plain inline CSS, no JS. Write the deploy commands into the plan's test file for S011, do not run them: copy to `/srv/landing/` on the server, `tailscale serve --bg --set-path / /srv/landing` (static files), `tailscale serve --bg --set-path /dezio http://127.0.0.1:8080`, set `DASHBOARD_URL=https://archlinux.tail7c4f5e.ts.net/dezio` in `/root/Dezio/.env` (back it up first). Keep Funnel on. +- [ ] Docs: `docs/topgg.md` website URL → `/dezio/`; the module comments in `src/web/mod.rs`, `src/web/activity.rs`, `src/commands/gameboy.rs` that name the portal setup. 🧑 list for the owner in the test file: Discord Developer Portal → OAuth2 Redirects add `https://archlinux.tail7c4f5e.ts.net/dezio/callback`; Activities → URL Mappings `/` → `archlinux.tail7c4f5e.ts.net/dezio/activity`; top.gg website field. +- [ ] Unit test for the base-path parsing (pure function). +- [ ] Test file `docs/tests/S006a-dezio-path.md`: local checks with `DASHBOARD_URL=http://127.0.0.1:8099/dezio --web-dev` (every page, asset, API call, login redirect, `/f/` link, activity page under the prefix; root of the local server does not serve Dezio pages), the deploy commands above, and the 🧑 portal list. +- [ ] PROGRESS entry, INDEX line, commit `S006a: …` + +## End criteria +- `cargo check` passes; the new base-path unit test passes (`cargo test base_path`). +- `grep -rnE '(href|src|action)="/[a-z]|fetch\("/' web` shows no root-absolute path left (or each one is explained in the test file). +- `deploy/landing/index.html` exists. + +## Pitfalls +- Do not change the live server or Tailscale config in this plan; deploying is S011. +- The Game Boy Activity is loaded by Discord through its URL mapping; Discord's proxy prefixes paths itself (`/.proxy/`), so check how the page builds its API URLs before changing them. +- `--web-dev` without a path in `DASHBOARD_URL` must still work at `/` (base `/`). +- Old root links (`/dashboard`, `/f/…`) will no longer reach Dezio after the move; that is accepted (owner chose the landing page). + +## Handoff (→ PROGRESS.md) +Base-path rule, the server commands for S011, and the 🧑 portal changes. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 0d2b7bb..d4770f6 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -19,6 +19,10 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp - [x] [S006 — fm logic fully on ListenBrainz and MusicBrainz](03%20fm%20commands/S006-fm-on-metabrainz.md) +## 03a Website path + +- [ ] [S006a — Website under /dezio/, landing page at the root](03a%20Website%20path/S006a-dezio-path.md) 🧑 + ## 04 Security - [ ] [S007 — Website and dashboard security](04%20Security/S007-website-security.md) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 1a31e79..3c3f6a2 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -14,3 +14,4 @@ - D-010 — 2026-12-01 — The fm commands read ListenBrainz (free, no key) instead of the Last.fm API, which needs Pro for everything but scrobbling from 2026-12-01. Same commands and cards; links are stored separately in `data/listenbrainz.json` (`data/lastfm.json` is kept, untouched); song links still go to the Last.fm website (free, and the Listen button reads them). Lyrics song search uses Deezer (popularity-ranked, no key). The Last.fm version is the git tag `lastfm-api-backup`. — Owner request. — all fm commands. - D-011 — 2026-12-01 — Covers come from a chain (`src/commands/lastfm/covers.rs`): the release ID in the player's own tags (Cover Art Archive) → ListenBrainz's match → the release group → Deezer → iTunes; Deezer/iTunes results count only when artist and title match. Artist photos: Deezer → MusicBrainz/Wikimedia. Play counts match by MusicBrainz ID before names. — MusicBrainz art alone left many covers blank; owner asked for the most reliable sources with fallbacks. — fm commands. - D-012 — 2026-12-01 — All fm logic must get its data from ListenBrainz and MusicBrainz (plus the D-011 cover/photo fallbacks); leftover Last.fm API logic and Last.fm-only fields are replaced or removed. Song links to the Last.fm website stay. — Owner request after the Last.fm API change. — S006, S010. +- D-013 — 2026-12-01 — All of Dezio's website (site, dashboard, API, OAuth, Game Boy Activity, hosted `/f/` files) moves to https://archlinux.tail7c4f5e.ts.net/dezio/. The root `/` serves a minimal static landing page (links to `/dezio/` and `/git/`), which the owner will improve in a later session; old root links to Dezio are not redirected. `/git` stays Forgejo. — Owner request. — S006a, S007, S011. From c7b02db71b4854432459e8fb8e88a9b848fab005 Mon Sep 17 00:00:00 2001 From: astar76 Date: Tue, 1 Dec 2026 22:02:35 -0600 Subject: [PATCH 12/24] S006a: website under /dezio/, minimal landing page Co-Authored-By: Claude Sonnet 5.5 --- Plans/INDEX.md | 2 +- deploy/landing/index.html | 19 ++++++++ docs/DECISIONS.md | 1 + docs/PROGRESS.md | 5 +++ docs/tests/S006a-dezio-path.md | 33 ++++++++++++++ docs/topgg.md | 4 +- src/commands/gameboy.rs | 2 +- src/web/activity.rs | 10 ++--- src/web/mod.rs | 82 +++++++++++++++++++++++++--------- web/activity/static/app.js | 3 +- web/dashboard/index.html | 18 ++++---- web/dashboard/static/app.js | 11 +++-- web/site/assets/site.js | 2 +- web/site/index.html | 4 +- web/site/privacy.html | 4 +- web/site/terms.html | 4 +- 16 files changed, 153 insertions(+), 51 deletions(-) create mode 100644 deploy/landing/index.html create mode 100644 docs/tests/S006a-dezio-path.md diff --git a/Plans/INDEX.md b/Plans/INDEX.md index d4770f6..893188c 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -21,7 +21,7 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp ## 03a Website path -- [ ] [S006a — Website under /dezio/, landing page at the root](03a%20Website%20path/S006a-dezio-path.md) 🧑 +- [x] [S006a — Website under /dezio/, landing page at the root](03a%20Website%20path/S006a-dezio-path.md) 🧑 ## 04 Security diff --git a/deploy/landing/index.html b/deploy/landing/index.html new file mode 100644 index 0000000..01cc90d --- /dev/null +++ b/deploy/landing/index.html @@ -0,0 +1,19 @@ + + + + + +Astar Hub + + + +
+

Astar Hub

+

Dezio Source

+
+ + diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 3c3f6a2..c76b822 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -15,3 +15,4 @@ - D-011 — 2026-12-01 — Covers come from a chain (`src/commands/lastfm/covers.rs`): the release ID in the player's own tags (Cover Art Archive) → ListenBrainz's match → the release group → Deezer → iTunes; Deezer/iTunes results count only when artist and title match. Artist photos: Deezer → MusicBrainz/Wikimedia. Play counts match by MusicBrainz ID before names. — MusicBrainz art alone left many covers blank; owner asked for the most reliable sources with fallbacks. — fm commands. - D-012 — 2026-12-01 — All fm logic must get its data from ListenBrainz and MusicBrainz (plus the D-011 cover/photo fallbacks); leftover Last.fm API logic and Last.fm-only fields are replaced or removed. Song links to the Last.fm website stay. — Owner request after the Last.fm API change. — S006, S010. - D-013 — 2026-12-01 — All of Dezio's website (site, dashboard, API, OAuth, Game Boy Activity, hosted `/f/` files) moves to https://archlinux.tail7c4f5e.ts.net/dezio/. The root `/` serves a minimal static landing page (links to `/dezio/` and `/git/`), which the owner will improve in a later session; old root links to Dezio are not redirected. `/git` stays Forgejo. — Owner request. — S006a, S007, S011. +- D-013 addition — 2026-12-01 — Base path = path part of `DASHBOARD_URL` (`/dezio`, none → root). The router serves every route both under the base and un-prefixed, so it works whether `tailscale serve --set-path` strips the prefix or not. HTML pages carry `__BASE__` (server replaces it); dashboard JS reads ``; site pages use relative paths; the Activity derives its base from `location.pathname` (so it also works at `/` inside Discord). Cookie `Path` = base. — Avoids guessing tailscale's behaviour. — S006a, S011. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 92e9848..4f07ddb 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -43,3 +43,8 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Done: audit of every fm feature; code was already fully on ListenBrainz/MusicBrainz, no Last.fm API leftovers in src. Only fix: `docs/topgg.md` wording. Test list in `docs/tests/S006-fm.md`. - Dropped from cards: listeners, global plays, bio, tags (none were shown). Profile realname/country are skipped when empty. - Verified: grep and `cargo check` only. Not tested in Discord 🧑. No new unit test (no new logic; api.rs already has sample-JSON tests). + +## 2026-12-01 — S006a website under /dezio/ +- Done: `Cfg.base` from `DASHBOARD_URL` path (`base_path`, unit test); routes nested under base and also un-prefixed; cookie Path, redirects, login link carry base; pages use `__BASE__`/relative paths; `deploy/landing/index.html` (minimal). topgg + module comments updated. +- Not done: nothing deployed. Static copy of web/dashboard/index.html now has `__BASE__` placeholders (only the bot serves it). +- Verified: `cargo check`, `cargo test base_path`. No browser check. Server commands + 🧑 portal list in `docs/tests/S006a-dezio-path.md`. diff --git a/docs/tests/S006a-dezio-path.md b/docs/tests/S006a-dezio-path.md new file mode 100644 index 0000000..c3d3374 --- /dev/null +++ b/docs/tests/S006a-dezio-path.md @@ -0,0 +1,33 @@ +# S006a — website under /dezio/ (tests) + +## Local checks +Run: `DASHBOARD_URL=http://127.0.0.1:8099/dezio DISCORD_BOT_TOKEN=dev-placeholder target/debug/dezio --web-dev`, cookie `dezio_session=devtoken`. +1. `/dezio/` shows the site with fonts and images; `/dezio/terms`, `/dezio/privacy` load and their Home link goes to `/dezio/`. +2. `/dezio/assets/site.css`, `/dezio/images/dezio.png` return 200. +3. Site: the Dashboard button appears (fetch of `/dezio/api/me` works). +4. `/dezio/dashboard` loads styled; its scripts load from `/dezio/dashboard/static/`; settings load and save (`/dezio/api/user`). +5. Dashboard URL bar after navigating stays `/dezio/dashboard#...`; Sign out returns to `/dezio/dashboard`. +6. Signed out (no cookie): "Sign in with Discord" links to `/dezio/login`; `/dezio/login` redirects to Discord with `redirect_uri=http://127.0.0.1:8099/dezio/callback`. +7. Set-Cookie headers from login have `Path=/dezio`. +8. `/dezio/activity` redirects to `/dezio/activity/`; the page loads, `/dezio/activity/api/config` works, the 401 from web-session has `login` = `/dezio/login?next=/activity/`. +9. A hosted link from `hosted::store` is `http://127.0.0.1:8099/dezio/f//` and downloads. +10. Without a path (`DASHBOARD_URL=http://127.0.0.1:8099`) everything still works at `/`. +11. `cargo test base_path` passes. + +## Deploy commands for S011 (do not run before) +- Back up: `ssh root@192.168.1.71 cp /root/Dezio/.env /root/Dezio/.env.bak-`. +- Landing: `scp deploy/landing/index.html root@192.168.1.71:/srv/landing/index.html` (mkdir `/srv/landing` first). +- `tailscale serve --bg --set-path / /srv/landing` +- `tailscale serve --bg --set-path /dezio http://127.0.0.1:8080` (keep Funnel on; keep the `/git` mapping). +- In `/root/Dezio/.env`: `DASHBOARD_URL=https://archlinux.tail7c4f5e.ts.net/dezio`, then restart `dezio-bot`. +- Check `https://archlinux.tail7c4f5e.ts.net/`, `/dezio/`, `/git/`. The router accepts the prefix stripped or not. + +## Owner checklist 🧑 +- Developer Portal → OAuth2 → Redirects: add `https://archlinux.tail7c4f5e.ts.net/dezio/callback`. +- Activities → URL Mappings: `/` → `archlinux.tail7c4f5e.ts.net/dezio/activity`. +- top.gg website field: `https://archlinux.tail7c4f5e.ts.net/dezio/`. + +## Doubts +- Whether tailscale strips `/dezio` (both handled, not verified). +- `web/dashboard/index.html` has `__BASE__` placeholders, so opening it as a plain file shows broken links. +- Root-absolute paths left in web/: none outside `__BASE__` placeholders (grep `(href|src|action)="/[a-z]` in web/site finds none). diff --git a/docs/topgg.md b/docs/topgg.md index 5a28d89..8958f45 100644 --- a/docs/topgg.md +++ b/docs/topgg.md @@ -8,7 +8,7 @@ Copy each block into the matching field on the bot's Top.gg edit page. |---|---| | Invite URL | https://discord.com/oauth2/authorize?client_id=1387839600017412106&scope=bot%20applications.commands&permissions=8 | | Support server | https://discord.gg/UnSga5DmR7 | -| Website | https://archlinux.tail7c4f5e.ts.net | +| Website | https://archlinux.tail7c4f5e.ts.net/dezio/ | | GitHub / source | https://archlinux.tail7c4f5e.ts.net/git/astar76/Dezio | | Prefix | `D!` (every command is also a slash command) | | Library | Rust (twilight + songbird) | @@ -55,7 +55,7 @@ Chess, Connect 4, tic-tac-toe, Wordle, hangman, minesweeper, 2048, Akinator, Coo AI chat with a personality you can change per server, anime GIF actions, confessions, a phone-call system between servers, quotes you can style, emoji tools, weather, translation, wikipedia / web / image search, a calculator and a **Game Boy you can play inside Discord** (Activity). ## Links -- **Website & dashboard:** https://archlinux.tail7c4f5e.ts.net +- **Website & dashboard:** https://archlinux.tail7c4f5e.ts.net/dezio/ - **Support server:** https://discord.gg/UnSga5DmR7 - **Source code:** https://archlinux.tail7c4f5e.ts.net/git/astar76/Dezio - Privacy policy and terms are on the website. diff --git a/src/commands/gameboy.rs b/src/commands/gameboy.rs index 9f8523d..6c6cf4d 100644 --- a/src/commands/gameboy.rs +++ b/src/commands/gameboy.rs @@ -8,7 +8,7 @@ //! //! Owner setup, once, in the Developer Portal (app → Activities): //! 1. Settings → enable Activities. -//! 2. URL Mappings → prefix `/` → target `/activity`. +//! 2. URL Mappings → prefix `/` → target `/activity` (…ts.net/dezio/activity). use crate::cmd::{Command, Ctx, Origin}; use crate::state::State; use crate::ui::{button, Card}; diff --git a/src/web/activity.rs b/src/web/activity.rs index b5be20b..d5b49f4 100644 --- a/src/web/activity.rs +++ b/src/web/activity.rs @@ -1,4 +1,4 @@ -//! The Game Boy Discord Activity's web side, served by the dashboard's web server under /activity. +//! The Game Boy Discord Activity's web side, served by the dashboard's web server under /activity (below the DASHBOARD_URL path, /dezio). //! //! The emulator itself (binjgb, WebAssembly) runs in each player's Discord client, so the bot only hands out the page, //! the ROMs (once — the client keeps them in IndexedDB) and the saves. @@ -16,7 +16,7 @@ //! GET /activity/api/art/ the game's cover (public): an image next to the ROM wins, else SteamGridDB //! (STEAMGRIDDB_API_KEY), cached in data/gameboy/art //! -//! Developer Portal setup (once): Activities → Settings → enable; Activities → URL Mappings → `/` → `/activity` +//! Developer Portal setup (once): Activities → Settings → enable; Activities → URL Mappings → `/` → `/activity` (e.g. archlinux.tail7c4f5e.ts.net/dezio/activity) //! (no https://); OAuth2 → Redirects needs at least one entry (the dashboard's /callback is there already). //! DEZIO_ACTIVITY_DEV=1 adds POST /activity/api/dev-session, a test sign-in for requests from 127.0.0.1. //! Everything else under /api needs the session from /api/token (`Authorization: Bearer …`). @@ -340,8 +340,8 @@ async fn page() -> Response { ([(header::CONTENT_TYPE, "text/html; charset=utf-8"), (header::CACHE_CONTROL, "no-cache")], page_html()).into_response() } -async fn slash_redirect(uri: axum::http::Uri) -> Redirect { - Redirect::to(&format!("/activity/{}", uri.query().map(|q| format!("?{q}")).unwrap_or_default())) +async fn slash_redirect(AxState(w): AxState, uri: axum::http::Uri) -> Redirect { + Redirect::to(&format!("{}/activity/{}", w.cfg.base, uri.query().map(|q| format!("?{q}")).unwrap_or_default())) } fn dev_mode(addr: &SocketAddr) -> bool { @@ -366,7 +366,7 @@ async fn web_session(AxState(w): AxState, headers: HeaderMap) -> Respons if origin != w.cfg.origin && origin != format!("{}://{host}", if w.cfg.secure { "https" } else { "http" }) { return ApiError::new(403, "Cross-site request refused").into_response(); } - let Some(s) = w.session(&headers) else { return (StatusCode::UNAUTHORIZED, Json(json!({"error": "Sign in with Discord first", "login": "/login?next=/activity/"}))).into_response() }; + let Some(s) = w.session(&headers) else { return (StatusCode::UNAUTHORIZED, Json(json!({"error": "Sign in with Discord first", "login": format!("{}/login?next=/activity/", w.cfg.base)}))).into_response() }; Json(json!({"session": w.activity.new_session(s.user_id, &s.name), "user": {"id": s.user_id.to_string(), "name": s.name}})).into_response() } diff --git a/src/web/mod.rs b/src/web/mod.rs index dc8603d..7003f98 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -1,5 +1,7 @@ //! The web dashboard: Dezio's website plus per-user and per-server settings, served by the bot itself. //! +//! Everything below lives under the path of DASHBOARD_URL (https://archlinux.tail7c4f5e.ts.net/dezio → /dezio; D-013). +//! Un-prefixed paths work too. HTML pages get that path in place of `__BASE__`. //! / the website (web/site/: index, terms, privacy, assets/, images/) //! /dashboard the settings app (web/dashboard/), which talks to /api/… //! /login → Discord → /callback sign in with Discord (OAuth2, "identify" only) @@ -8,7 +10,7 @@ //! Settings in .env: //! DASHBOARD_CLIENT_SECRET the app's OAuth2 client secret (Developer Portal → OAuth2) — sign-in is off without it //! DASHBOARD_URL the address people open, default http://192.168.1.71:8080; -//! add DASHBOARD_URL + "/callback" under OAuth2 → Redirects in the Developer Portal +//! add DASHBOARD_URL + "/callback" (…/dezio/callback) under OAuth2 → Redirects in the Developer Portal //! DASHBOARD_HOST / _PORT where to listen (default 0.0.0.0 and the port from DASHBOARD_URL) //! //! Security: sessions are random server-side tokens in an HttpOnly, SameSite=Lax cookie; every change needs the @@ -45,6 +47,8 @@ const ACTIVITY_CSP: &str = "default-src 'self'; script-src 'self' 'wasm-unsafe-e pub struct Cfg { pub url: String, + /// Path part of `url` without a trailing slash (`/dezio`), empty when the site lives at the root. + pub base: String, pub origin: String, pub secure: bool, pub host: String, @@ -52,6 +56,12 @@ pub struct Cfg { pub client_secret: String, } +/// The path part of the public address, without a trailing slash: `https://x.ts.net/dezio/` → `/dezio`, no path → ``. +pub fn base_path(url: &str) -> String { + let path = reqwest::Url::parse(url).map(|u| u.path().trim_end_matches('/').to_string()).unwrap_or_default(); + if path.is_empty() { String::new() } else { path } +} + impl Cfg { pub fn from_env() -> Self { let url = std::env::var("DASHBOARD_URL").ok().filter(|u| !u.is_empty()).unwrap_or_else(|| "http://192.168.1.71:8080".into()).trim_end_matches('/').to_string(); @@ -60,6 +70,7 @@ impl Cfg { let origin = parsed.as_ref().map(|u| format!("{}://{}", u.scheme(), u.host_str().unwrap_or("localhost").to_string() + &u.port().map(|p| format!(":{p}")).unwrap_or_default())).unwrap_or_else(|| url.clone()); let default_port = parsed.as_ref().and_then(|u| u.port_or_known_default()).unwrap_or(8080); Self { + base: base_path(&url), origin, secure, host: std::env::var("DASHBOARD_HOST").ok().filter(|h| !h.is_empty()).unwrap_or_else(|| "0.0.0.0".into()), @@ -137,7 +148,7 @@ impl Web { } fn set_cookie(&self, resp: &mut Response, name: &str, value: &str, max_age: u64) { - let c = format!("{name}={value}; Max-Age={max_age}; Path=/; HttpOnly; SameSite=Lax{}", if self.cfg.secure { "; Secure" } else { "" }); + let c = format!("{name}={value}; Max-Age={max_age}; Path={}; HttpOnly; SameSite=Lax{}", if self.cfg.base.is_empty() { "/" } else { &self.cfg.base }, if self.cfg.secure { "; Secure" } else { "" }); if let Ok(v) = HeaderValue::from_str(&c) { resp.headers_mut().append(header::SET_COOKIE, v); } @@ -197,7 +208,7 @@ impl Web { async fn login(AxState(w): AxState, axum::extract::Query(q): axum::extract::Query>) -> Response { if !w.sign_in_ready() { - return Redirect::to("/dashboard?error=setup").into_response(); + return Redirect::to(&format!("{}/dashboard?error=setup", w.cfg.base)).into_response(); } let state = random_token(24); let params = [("client_id", w.state.app_id().to_string()), ("redirect_uri", format!("{}/callback", w.cfg.url)), ("response_type", "code".into()), ("scope", "identify".into()), ("state", state.clone()), ("prompt", "none".into())]; @@ -211,7 +222,7 @@ async fn login(AxState(w): AxState, axum::extract::Query(q): axum::extra } async fn callback(AxState(w): AxState, headers: HeaderMap, axum::extract::Query(q): axum::extract::Query>) -> Response { - let fail = |why: &str| Redirect::to(&format!("/dashboard?error={why}")).into_response(); + let fail = |why: &str| Redirect::to(&format!("{}/dashboard?error={why}", w.cfg.base)).into_response(); let (state, code) = (q.get("state").cloned().unwrap_or_default(), q.get("code").cloned().unwrap_or_default()); let expected = cookie_value(&headers, STATE_COOKIE).unwrap_or_default(); if code.is_empty() || expected.is_empty() || state != expected { @@ -238,7 +249,7 @@ async fn callback(AxState(w): AxState, headers: HeaderMap, axum::extract })); tracing::info!("Dashboard sign-in: {} ({})", me["username"], me["id"]); let after = cookie_value(&headers, NEXT_COOKIE).filter(|a| AFTER_LOGIN.contains(&a.as_str())).unwrap_or_else(|| "/dashboard".into()); - let mut resp = Redirect::to(&after).into_response(); + let mut resp = Redirect::to(&format!("{}{after}", w.cfg.base)).into_response(); w.set_cookie(&mut resp, SESSION_COOKIE, &raw, SESSION_DAYS * 86400); w.set_cookie(&mut resp, STATE_COOKIE, "", 0); w.set_cookie(&mut resp, NEXT_COOKIE, "", 0); @@ -258,8 +269,10 @@ async fn logout(AxState(w): AxState, headers: HeaderMap) -> ApiResult { // ---- headers + pages -------------------------------------------------------------------------------------------- -async fn headers_mw(request: Request, next: Next) -> Response { - let path = request.uri().path().to_string(); +async fn headers_mw(AxState(base): AxState, request: Request, next: Next) -> Response { + let full = request.uri().path().to_string(); + // Rules below match the path without the base, so they hold under /dezio/ and without it. + let path = if base.is_empty() { full } else { full.strip_prefix(base.as_str()).unwrap_or(&full).to_string() }; let mut resp = next.run(request).await; let h = resp.headers_mut(); h.insert("x-content-type-options", HeaderValue::from_static("nosniff")); @@ -286,27 +299,43 @@ async fn headers_mw(request: Request, next: Next) -> Response { pub fn router(w: Shared) -> Router { let site = paths::web(&["site"]); let app = paths::web(&["dashboard"]); - let page = |dir: &std::path::Path, name: &str| ServeFile::new(dir.join(name)); - Router::new() + let base = w.cfg.base.clone(); + // HTML pages carry `__BASE__` where a root-absolute path would go; it becomes the base path here. + let page = |dir: &std::path::Path, name: &str| { + let file = dir.join(name); + let base = base.clone(); + get(move || { + let (file, base) = (file.clone(), base.clone()); + async move { + let html = tokio::fs::read_to_string(&file).await.unwrap_or_default().replace("__BASE__", &base); + ([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html).into_response() + } + }) + }; + let inner: Router = Router::new() .route("/login", get(login)) .route("/callback", get(callback)) .route("/logout", post(logout)) .merge(api::routes()) .merge(activity::routes()) - .route_service("/dashboard", page(&app, "index.html")) - .route_service("/dashboard/", page(&app, "index.html")) - .route_service("/", page(&site, "index.html")) - .route_service("/index.html", page(&site, "index.html")) - .route_service("/terms", page(&site, "terms.html")) - .route_service("/terms.html", page(&site, "terms.html")) - .route_service("/privacy", page(&site, "privacy.html")) - .route_service("/privacy.html", page(&site, "privacy.html")) + .route("/dashboard", page(&app, "index.html")) + .route("/dashboard/", page(&app, "index.html")) + .route("/", page(&site, "index.html")) + .route("/index.html", page(&site, "index.html")) + .route("/terms", page(&site, "terms.html")) + .route("/terms.html", page(&site, "terms.html")) + .route("/privacy", page(&site, "privacy.html")) + .route("/privacy.html", page(&site, "privacy.html")) .nest_service("/dashboard/static", ServeDir::new(app.join("static"))) .nest_service("/assets", ServeDir::new(site.join("assets"))) .nest_service("/images", ServeDir::new(site.join("images"))) // files too big for Discord, kept for a few hours (see hosted.rs) - .nest_service("/f", ServeDir::new(crate::hosted::dir())) - .layer(middleware::from_fn(headers_mw)) + .nest_service("/f", ServeDir::new(crate::hosted::dir())); + // Under a base path (/dezio) the routes live there. The un-prefixed paths stay too, so it works whether the + // reverse proxy (tailscale serve --set-path) strips the prefix or not. + let routes = if base.is_empty() { inner } else { Router::new().nest(&base, inner.clone()).merge(inner) }; + routes + .layer(middleware::from_fn_with_state(base, headers_mw)) .layer(axum::extract::DefaultBodyLimit::max(64 * 1024)) .with_state(w) } @@ -314,7 +343,8 @@ pub fn router(w: Shared) -> Router { /// For `--web-dev`: serve on 127.0.0.1:8099 with a signed-in test session (cookie `dezio_session=devtoken`). pub fn start_dev(state: Arc) { let url = "http://127.0.0.1:8099".to_string(); - let cfg = Cfg { origin: url.clone(), url, secure: false, host: "127.0.0.1".into(), port: 8099, client_secret: "dev".into() }; + let base = base_path(&url); + let cfg = Cfg { origin: url.clone(), base, url, secure: false, host: "127.0.0.1".into(), port: 8099, client_secret: "dev".into() }; let sessions = JsonStore::open(std::env::temp_dir().join("dezio-dev-sessions.json")); sessions.set(sha("devtoken"), json!({"user_id": 4242u64, "name": "Dev Tester", "username": "devtester", "avatar": null, "csrf": "devcsrf", "created": now(), "expires": now() + 86400})); let web = Arc::new(Web { state, cfg, sessions, activity: Arc::new(activity::Activity::new()), preview: tokio::sync::Semaphore::new(2) }); @@ -357,13 +387,23 @@ mod tests { use axum::http::{Method, Request as HttpRequest}; use tower::ServiceExt; + #[test] + fn base_path_from_dashboard_url() { + assert_eq!(base_path("https://archlinux.tail7c4f5e.ts.net/dezio"), "/dezio"); + assert_eq!(base_path("https://archlinux.tail7c4f5e.ts.net/dezio/"), "/dezio"); + assert_eq!(base_path("http://127.0.0.1:8099/a/b"), "/a/b"); + assert_eq!(base_path("http://192.168.1.71:8080"), ""); + assert_eq!(base_path("http://192.168.1.71:8080/"), ""); + assert_eq!(base_path("not a url"), ""); + } + fn web() -> Shared { let _ = rustls::crypto::ring::default_provider().install_default(); let http = Arc::new(twilight_http::Client::new("x".into())); let state = Arc::new(State::new(http, crate::cmd::Registry::new(vec![]), "x".into())); state.set_app_id(twilight_model::id::Id::new(1)); state.set_bot_id(twilight_model::id::Id::new(2)); - let cfg = Cfg { url: "http://dashboard.test".into(), origin: "http://dashboard.test".into(), secure: false, host: "127.0.0.1".into(), port: 0, client_secret: "secret".into() }; + let cfg = Cfg { url: "http://dashboard.test".into(), base: String::new(), origin: "http://dashboard.test".into(), secure: false, host: "127.0.0.1".into(), port: 0, client_secret: "secret".into() }; Arc::new(Web { state, cfg, sessions: JsonStore::open(std::env::temp_dir().join(format!("dezio-ws-{}.json", rand::random::()))), activity: Arc::new(activity::Activity::new()), preview: tokio::sync::Semaphore::new(2) }) } diff --git a/web/activity/static/app.js b/web/activity/static/app.js index f176c76..7637868 100644 --- a/web/activity/static/app.js +++ b/web/activity/static/app.js @@ -7,7 +7,8 @@ */ 'use strict'; -const BASE = location.pathname.startsWith('/activity') ? '/activity' : ''; +// Where this page is served from: /dezio/activity in a browser, / inside Discord (its URL mapping hides the prefix). +const BASE = location.pathname.replace(/\/(index\.html)?$/, ''); const $ = (s) => document.querySelector(s); const CPU_HZ = 4194304; const AUDIO_FRAMES = 4096; diff --git a/web/dashboard/index.html b/web/dashboard/index.html index fd08dfe..6a0a9db 100644 --- a/web/dashboard/index.html +++ b/web/dashboard/index.html @@ -1,14 +1,14 @@ - + Dezio dashboard - - - - + + + +