diff --git a/.env.example b/.env.example index da7f53f..40d53fc 100644 --- a/.env.example +++ b/.env.example @@ -47,6 +47,16 @@ TELEGRAM_SET_PROFILE=true # refuses a widget the bot sends the ordinary message instead, by itself. TELEGRAM_WIDGETS=true +# --- Chat flow ---------------------------------------------------------------- +# A queued download shows its position and wait only when the expected wait +# is above this many seconds or it is not first in line. Otherwise the +# status simply says it is downloading. +QUEUE_NOTICE_THRESHOLD_SECONDS=10 +# How many links of one message are handled, each with its own status. +MULTI_LINK_MAX=5 +# Add a "via @botname" line under the caption of every file the bot sends. +CAPTION_ATTRIBUTION=true + # Add the pseudo-locale en-XA (accented, bracketed English) for checking # that every text comes from the catalog. Only owners can pick it. I18N_PSEUDO=false diff --git a/config.example.toml b/config.example.toml index d1f07f7..5d9130a 100644 --- a/config.example.toml +++ b/config.example.toml @@ -18,6 +18,14 @@ i18n_pseudo = false # Who looks links up for the card: "auto", "local" or "worker". probe_mode = "auto" +# Chat flow. A queued download shows its position only above this wait or +# when it is not first in line. +queue_notice_threshold_seconds = 10 +# Links of one message that are handled. +multi_link_max = 5 +# A "via @botname" line under file captions. +caption_attribution = true + [telegram] api_url = "https://api.telegram.org" mode = "polling" # polling or webhook diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index bf85708..101aa7f 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -867,3 +867,116 @@ telego v1.13.0, which has `SendWidget`, `EditMessageWidgetData`, API: this environment has no bot token. - Load test: 90 of 90 and 240 of 240 requests delivered (embedded worker; three remote workers). Numbers in [MONITORING.md](MONITORING.md). + +## Update round: flows, Stars, affiliate program + +Decisions made while improving the flows and adding Telegram Stars and +the affiliate program. What was found and planned is in +[UPDATE_NOTES.md](UPDATE_NOTES.md). + +### Phase 1: quick flow fixes + +- **One message per job.** Once the file is in the chat, the status + message (the card, the placeholder or the status widget) is deleted. + If Telegram refuses the delete, the message is cut down to "Sent.". + `editMessageMedia` could have turned the status into the file instead, + but the file then could not quote the link message in groups, and an + upload through an edit cannot fall back to a document. Deleting is + simpler and works in every case. +- **Quotes.** Answers in private chats never quote the user's message; + groups still do. The rule sits in one place (`replyParams`) and uses + the chat ID: private chats have the user's positive ID, groups have + negative IDs. +- **Queue noise.** "Position N" is shown when the expected wait is above + `QUEUE_NOTICE_THRESHOLD_SECONDS` or somebody is queued ahead. Position + counts queued jobs ahead, as before. The wait estimate now gives 0 when + a worker slot is free, and ignores a job that was claimed between being + loaded and being measured. Before, such a job could count itself as + running and show a wait of half a job. +- **Edit throttle.** Every status message is edited at most once per + 2.5 s, phase changes included. A state that arrives too soon is kept + and shown when the gap is over. It is never dropped, so the last state + before the file arrives is always correct. +- **Caption.** The caption has the title, then the uploader and duration, + then a short link without tracking parameters, then the optional + `via @bot` line. A title counts as generic when it is empty, the video + ID, the uploader's name, a site placeholder ("Video", "Instagram") or + "Video by ...". It is then replaced by "uploader · upload date" in the + reader's date format. The removed parameters are: `utm_*`, `igsh`, + `igshid`, `jplx`, `fbclid`, `gclid`, `dclid`, `gbraid`, `wbraid`, + `msclkid`, `yclid`, `twclid`, `ttclid`, `si`, `mc_cid`, `mc_eid`, + `mibextid`, `ref_src`, `ref_url`, `_hsenc`, `_hsmi`, `feature`, + `share_id` and `rdt`. On X and Twitter `s` and `t` are removed too, and + on TikTok its share parameters. Everything else stays, `v` and `t` on + YouTube included. +- **Thumbnail with the video.** Telegram only takes an uploaded JPEG of + at most 320 px and under 200 kB, never a URL. The core fetches the + source's thumbnail image (5 MB, 8 s, no private addresses, also after + DNS) and shrinks it. YouTube WebP thumbnails are swapped for their JPEG + copy; other WebP images are skipped, since the standard library cannot + read WebP. A failure only means no thumbnail: Telegram makes its own + from an MP4. The worker protocol was not changed for this. +- **faststart.** yt-dlp is given `-movflags +faststart` for its Merger + and FixupM3u8 steps, the ffmpeg runs that write MP4s. A single file + downloaded as is, without ffmpeg, keeps the layout the site served. + Transcoded profiles already had faststart. +- **Result buttons.** The buttons are Audio (MP3), Other quality, + Thumbnail and Delete. Each one is only offered when it makes sense: + there is no MP3 button under an MP3, and no thumbnail button when the + source has none. Each follow-up is a new download under the usual + limits. Callback data carries the request ID only. In groups only the + requester may press them. +- **Language.** The language is resolved once per update, before routing, + and travels in the context. The order is: the user's stored choice, + then Telegram's `language_code`, then English. A group's own language + wins inside that group. The i18n bundle now logs a text that falls + back to English like a missing message, so every app test that runs in + Spanish or Dutch fails on a fallback. `TestEveryScreenInSpanishAndDutch` + walks every user screen in both languages. It fails on any word that + only the English catalog uses, which catches hardcoded strings too. + The fake Bot API now sends each user's language with their button + presses, like Telegram does. It used to send "en" for every press. +- **Sizes.** Sizes drop a decimal that is zero ("50 MB", "1.5 GB"), in + the bot and in the Mini App, and keep the locale's decimal separator. +- **First run and quality values.** `users.default_quality` now has + three special values. "" means the user never chose, "ask" means ask + every time, and "fit" means the best quality that fits the limit. + Before, "" meant ask, so an existing user who once picked "ask every + time" sees the card one more time and then gets "fit", like a new + user. The card says so, and /quality changes it. The Mini App keeps + writing "" for "ask"; the API maps it. +- **"Best that fits my limit"** compares yt-dlp's size estimates of Best, + 1080p, 720p and 480p with the user's size cap, which is capped by the + upload limit. A quality without an estimate only counts when no quality + has one; the worker's `--max-filesize` then still guards the real file. + When nothing fits, the smallest quality is started, which fails the + limit check and leads to the over-limit offer. +- **Errors.** A lookup that fails with a passing error (network, rate + limit, a lost worker) is tried once more after a second, before the + user sees anything. Timeouts are not retried, since they already took + the full probe time. Download failures keep the scheduler's existing + single retry. The error buttons are: + - Try again after a passing failure. + - Smaller quality and Upgrade after "too large". + - Upgrade after "too long" and after the daily limits. + - Open app after content errors (private, login, region, unsupported). + + A failed lookup is kept as a failed request, so that "Try again" knows + the link. +- **Several links.** Up to `MULTI_LINK_MAX` links per message are + handled, each with its own status. A link counts as already sent when + the same user got a file for it in the same chat within the last 10 + minutes. Links are compared without their tracking parameters. The + 10 minutes are a constant, not a setting. Commands (/dl, /fresh, + /audio) never answer "already sent". +- **Menu button.** The default menu button opens the Mini App with the + source language's label. `setChatMenuButton` takes no language, so + each private chat gets its own label the first time the user writes, + and again when they change language. What was set is remembered in the + `kv` table, so a restart does not repeat the calls. The "/" button of + the message field keeps the command list. +- **Personal /settings.** It shows the default format, the audio-only and + ask-every-time switches, the language, the pass and balance, invited + friends, Open app, and "Add me to a group" + (`https://t.me/?startgroup=settings`). The bot username comes from + `getMe`. diff --git a/docs/UPDATE_NOTES.md b/docs/UPDATE_NOTES.md new file mode 100644 index 0000000..2348dca --- /dev/null +++ b/docs/UPDATE_NOTES.md @@ -0,0 +1,81 @@ +# Update notes: flows, Stars, affiliate program + +What I found in the repository before changing it, and what this round of +work changes. Decisions made on the way are recorded in +[ASSUMPTIONS.md](ASSUMPTIONS.md) under "Update round". + +## What is there + +- **Shape.** `cmd/core` (Telegram, DB, queue, HTTP) and `cmd/worker` + (yt-dlp, ffmpeg). The core embeds a worker by default. See + [ARCHITECTURE.md](ARCHITECTURE.md). +- **Bot front end** (`internal/bot`). `bot.go` routes updates and holds the + send and edit helpers. `commands.go` dispatches commands, `card.go` runs + the link flow (placeholder, probe, card, start), `status.go` keeps the + status message current with a throttle, `deliver.go` sends files, + `money.go` covers buying, offers and fulfilment, `groups.go` covers group + admin commands and personal preferences, `extras.go` covers playlists, + subtitles and history, `live.go` the HTML widgets, `appops.go` the Mini + App operations. +- **Language.** `actorFor` already resolves the language once per update: + the stored choice, then Telegram's `language_code`, then English. A + group's own language wins in that group. Handlers take the result as + `act.lang`. Catalogs are `locales/{en,es,nl}.toml`. The catalog tests + already check for missing keys, placeholders and unused messages. +- **Errors.** yt-dlp output is classified in `internal/ytdlp/classify.go` + into codes with an `error.` message each. A retryable job failure + is retried once by the scheduler. Lookups are not retried. +- **Entitlement** (`internal/entitle`) is a pure resolver. `service.Start` + and `service.Preview` are the single gate for all paths: chat, Mini + App, cache hits and resends. +- **Billing** (`internal/billing`) is Lightning only (LNbits), with a + wallet and ledger per user or group, passes, credits, one-off payments, + gift codes and Cashu. +- **Referrals** store the inviter's Telegram ID from `/start ref_`. + Only the count is shown and nothing is rewarded yet, although the + `REFERRAL_REWARD` setting exists. +- **Mini App** (`web/miniapp`, React and Vite, built into `dist/` and + embedded). Pages: Home, Queue, History, Buy, Me (`Profile.tsx`), + Groups. The API is in `internal/api/miniapp.go`. +- **Tests** run the real core against a fake Bot API + (`internal/tg/fakeserver`) and a scripted yt-dlp, on SQLite by default + and on Postgres with `DLBOT_TEST_DB=postgres`. + +## Flow problems found + +- A finished download leaves two messages: the file, and the card edited + to "Done. Enjoy." under it. +- Every answer in a private chat quotes the user's message. +- A job that starts at once still shows "In the queue. Position 1". +- Phase changes skip the edit throttle, so a fast job can edit its status + several times a second. +- The caption is only the title. There is no source link, and no + thumbnail is uploaded with videos. Merged MP4 files are not written + with `faststart`. +- `/settings` refuses in a private chat. +- Sizes read "50.0 MB". +- Errors are text only, with no next step. +- At most 3 links per message. The same link sent twice is downloaded + twice. +- Referral links show the raw Telegram user ID. + +## What changes, by phase + +1. **Quick flow fixes.** One status message per job that is removed once + the file is sent. No reply quotes in private chats. Quieter queue + status and a strict 2.5 s edit throttle. A full caption with a cleaned + source link, an optional `via @bot` line, and a thumbnail for uploaded + videos. Buttons under the result. Personal `/settings`. Localized menu + button. Error buttons and one automatic retry of lookups. Up to N links + per message, with "Already sent" for repeats. First-run quality prompt. + A strict language test. +2. **Command screens.** Sectioned `/help`, a reworked `/quality` with + "Best that fits my limit", and a paginated `/history` with richer rows. +3. **Own referral system.** Short random codes, rewards paid only after a + first settled Lightning purchase, and a daily cap. +4. **Telegram Stars.** A second payment method next to Lightning: + invoices in XTR, pre-checkout, successful payment, refunds, and a + per-method price table. +5. **Telegram affiliate program.** Owner docs, Mini App Stars invoices, + tolerant `/start` payload handling, and an Earn section. +6. **Inline mode and polish** (optional). diff --git a/internal/api/miniapp.go b/internal/api/miniapp.go index b5101cb..6438cf1 100644 --- a/internal/api/miniapp.go +++ b/internal/api/miniapp.go @@ -237,7 +237,7 @@ func (m *MiniApp) me(w http.ResponseWriter, r *http.Request, s *session) { "lang_override": s.user.LangOverride, "dir": i18n.Dir(s.lang), "languages": langs, - "quality": s.user.Quality, + "quality": appQuality(s.user.Quality), "pass_until": st.PassUntil, "balance": st.Credits, "source": string(dec.Source), @@ -256,6 +256,26 @@ func (m *MiniApp) me(w http.ResponseWriter, r *http.Request, s *session) { }) } +// The app writes "" for "ask every time", as it does for groups. In the +// users table "" means the user never chose, which behaves like "fit" +// (best that fits the limit) after the first link, and "ask" is stored. +func appQuality(stored string) string { + switch stored { + case "": + return "fit" + case "ask": + return "" + } + return stored +} + +func storedQuality(app string) string { + if app == "" { + return "ask" + } + return app +} + func (m *MiniApp) updateMe(w http.ResponseWriter, r *http.Request, s *session) { var in struct { Quality *string `json:"quality"` @@ -267,8 +287,8 @@ func (m *MiniApp) updateMe(w http.ResponseWriter, r *http.Request, s *session) { } ctx := r.Context() if in.Quality != nil { - q := *in.Quality - if q != "" { + q := storedQuality(*in.Quality) + if q != "ask" && q != "fit" { p, err := media.Parse(q) if err != nil || (p.Kind() != media.KindVideo && p.Kind() != media.KindAudio) { m.fail(w, http.StatusBadRequest, "bad_request", "") diff --git a/internal/app/app_test.go b/internal/app/app_test.go index e6fc3a7..21f00b8 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -107,7 +107,10 @@ func (h *harness) boot() { Config: h.cfg, Log: slog.New(&guardHandler{Handler: base, t: h.t}), Runner: h.runner, Transcoder: h.trans, - Tune: func(b *bot.Bot) { b.SetTimings(60*time.Millisecond, 0) }, + Tune: func(b *bot.Bot) { + b.SetTimings(60*time.Millisecond, 0) + b.SetThumbnails(testThumbs{}) + }, }) if err != nil { cancel() @@ -124,6 +127,20 @@ func (h *harness) boot() { } } +// testThumbs stands in for fetching thumbnails from the web: the fake +// yt-dlp's thumbnail URL gives a fixed small JPEG, anything else none. +type testThumbs struct{} + +// testThumbJPEG is what testThumbs returns. +var testThumbJPEG = []byte("\xff\xd8\xff\xe0test-thumbnail\xff\xd9") + +func (testThumbs) Fetch(_ context.Context, url string) []byte { + if url == "https://img.example.com/t.jpg" { + return testThumbJPEG + } + return nil +} + // guardHandler fails the test when the core logs something that is always // a bug: a message ID that is missing from the catalog, or a panic. type guardHandler struct { @@ -193,6 +210,29 @@ func (h *harness) never(after int, method string, match func(fakeserver.Call) bo } } +// fileMethods are the calls that send a downloaded file. +const fileMethods = "sendVideo|sendAudio|sendDocument|sendPhoto" + +// isResult matches a delivered file: it carries the buttons for the next +// step, among them Delete. A card, which is also a photo, has format +// buttons instead. +func isResult(chat int64) func(fakeserver.Call) bool { + return func(c fakeserver.Call) bool { + _, ok := c.Button("fx:") + return ok && (chat == 0 || c.ChatID() == chat) + } +} + +// finished waits for a download to end the way it should: the file in the +// chat, then the status message deleted so the file is the only message +// left. chat 0 matches any chat. It returns the file call. +func (h *harness) finished(after int, chat int64) fakeserver.Call { + h.t.Helper() + file := h.wait(after, fileMethods, isResult(chat)) + h.wait(file.Seq, "deleteMessage", func(c fakeserver.Call) bool { return c.ChatID() == file.ChatID() }) + return file +} + func textHas(sub string) func(fakeserver.Call) bool { return func(c fakeserver.Call) bool { return strings.Contains(c.Text(), sub) } } @@ -203,9 +243,11 @@ func textIs(want string) func(fakeserver.Call) bool { const edits = "editMessageText|editMessageCaption" -// card sends a link and returns the card call. +// card sends a link and returns the card call. The user is set to "ask +// every time" first, the setting under which every link shows a card. func (h *harness) card(chat, user int64, text string, opts ...fakeserver.MsgOpt) fakeserver.Call { h.t.Helper() + h.askEveryTime(user) seq := h.srv.Seq() h.srv.PushMessage(chat, user, text, opts...) return h.wait(seq, "sendPhoto|editMessageText", func(c fakeserver.Call) bool { @@ -214,6 +256,26 @@ func (h *harness) card(chat, user int64, text string, opts ...fakeserver.MsgOpt) }) } +// askEveryTime makes sure a user sees the card for every link. A user who +// never chose a default gets the card once and "best that fits" after it. +func (h *harness) askEveryTime(user int64) { + h.t.Helper() + ctx := context.Background() + u, err := h.app.Store.GetUser(ctx, user) + if err == db.ErrNotFound { + if u, err = h.app.Store.UpsertUser(ctx, user, "", "User", "en"); err != nil { + h.t.Fatal(err) + } + } else if err != nil { + h.t.Fatal(err) + } + if u.Quality == "" { + if err := h.app.Store.SetUserQuality(ctx, user, "ask"); err != nil { + h.t.Fatal(err) + } + } +} + func (h *harness) press(chat, user int64, card fakeserver.Call, prefix string) (seq int) { h.t.Helper() btn, ok := card.Button(prefix) @@ -270,17 +332,23 @@ func TestPrivateLinkReturnsFile(t *testing.T) { seq := h.srv.Seq() msgID := h.srv.PushMessage(alice, alice, "look at this "+link) - h.wait(seq, "sendMessage", textHas("Looking up")) + looking := h.wait(seq, "sendMessage", textHas("Looking up")) card := h.wait(seq, "sendPhoto", nil) if !strings.Contains(card.Text(), "Test Video") || !strings.Contains(card.Text(), "1:00") || !strings.Contains(card.Text(), "example.com") { t.Fatalf("card text = %q", card.Text()) } + // The first link of a new user shows the card once and says what + // happens from now on. + if !strings.Contains(card.Text(), "best quality that fits your limit") { + t.Fatalf("the first card does not explain the new default: %q", card.Text()) + } if card.Params["photo"] != "https://img.example.com/t.jpg" { t.Fatalf("card photo = %q", card.Params["photo"]) } - if replyTarget(card) != msgID { - t.Fatalf("the card must reply to the link message") + // A private chat has one conversation: nothing is quoted. + if replyTarget(card) != 0 || replyTarget(looking) != 0 { + t.Fatalf("a private answer quotes the link message") } var labels []string for _, b := range card.Buttons() { @@ -290,7 +358,7 @@ func TestPrivateLinkReturnsFile(t *testing.T) { t.Errorf("bad callback data %q", b.Data) } } - want := []string{"Best · 10.0 MB", "480p · 5.0 MB", "MP3 · 1.0 MB", "Thumbnail", "Cancel"} + want := []string{"Best · 10 MB", "480p · 5 MB", "MP3 · 1 MB", "Thumbnail", "Cancel"} if strings.Join(labels, "|") != strings.Join(want, "|") { t.Fatalf("buttons = %v, want %v", labels, want) } @@ -309,21 +377,56 @@ func TestPrivateLinkReturnsFile(t *testing.T) { if video.Params["supports_streaming"] != "true" || video.Params["width"] != "1280" || video.Params["duration"] != "60" { t.Fatalf("video params = %+v", video.Params) } - if replyTarget(video) != msgID { - t.Fatalf("the file must reply to the link message") + if replyTarget(video) != 0 { + t.Fatalf("the file quotes the link message in a private chat") } - done := h.wait(seq, "editMessageCaption", textHas("Done")) - if done.MessageID != card.MessageID || len(done.Buttons()) != 0 { - t.Fatalf("the card must end as a status without buttons: %+v", done.Params) + // Forwarding works: the content is not protected. + if video.Params["protect_content"] == "true" { + t.Fatal("the video is protected") } + // The caption: title, uploader and length, a clean link, the bot. + wantCaption := "Test Video\nTester · 1:00\n" + + `example.com/watch?v=1` + "\nvia @" + fakeserver.BotUsername + if video.Text() != wantCaption { + t.Fatalf("caption = %q, want %q", video.Text(), wantCaption) + } + // The thumbnail is uploaded with the video. + if f, ok := video.Files["thumbnail"]; !ok || f.Size != int64(len(testThumbJPEG)) { + t.Fatalf("thumbnail = %+v, %v", f, ok) + } + var next []string + for _, b := range video.Buttons() { + next = append(next, b.Text) + } + if strings.Join(next, "|") != "Audio (MP3)|Other quality|Thumbnail|Delete" { + t.Fatalf("buttons under the file = %v", next) + } + // One message per job: the card that showed the status is gone, and + // nothing says "Done" under the file. + gone := h.wait(video.Seq, "deleteMessage", nil) + if gone.MessageID != card.MessageID { + t.Fatalf("deleted message %d, want the card %d", gone.MessageID, card.MessageID) + } + h.never(video.Seq, edits, textHas("Done")) + _ = msgID - h.waitJobs(db.JobDone, 1) - // The delivered file stays as the cache's stored copy. - if n := h.storedFiles(); n != 1 { - t.Fatalf("%d files in storage after delivery, want the one cached copy", n) + // The user's default is now "best that fits": the next link starts + // right away, with one status message that becomes the file. + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "https://example.com/watch?v=2") + status := h.wait(seq, "sendMessage", textHas("Looking up")) + h.never(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok }) + second := h.finished(seq, alice) + if gone := h.wait(second.Seq, "deleteMessage", nil); gone.MessageID != status.MessageID { + t.Fatalf("deleted %d, want the status %d", gone.MessageID, status.MessageID) } - if n := len(h.fake.Probes()); n != 1 { - t.Fatalf("probes = %d, want 1", n) + h.waitJobs(db.JobDone, 2) + // The delivered files stay as the cache's stored copies. + if n := h.storedFiles(); n != 2 { + t.Fatalf("%d files in storage after delivery, want the two cached copies", n) + } + if n := len(h.fake.Probes()); n != 2 { + t.Fatalf("probes = %d, want 2", n) } } @@ -346,7 +449,7 @@ func TestStatusGoesThroughDownloadingAndUploading(t *testing.T) { h.wait(seq, edits, textHas("Sending it to Telegram")) h.wait(seq, "sendChatAction", func(c fakeserver.Call) bool { return c.Params["action"] == "upload_video" }) h.wait(seq, "sendVideo", nil) - h.wait(seq, edits, textHas("Done")) + h.finished(seq, 0) } // --- acceptance: groups work with /dl -------------------------------------- @@ -552,10 +655,12 @@ func TestThumbnailFetchFailureFallsBackToTextCard(t *testing.T) { // The text card works exactly like the photo card. seq = h.press(alice, alice, card, "dl:") - h.wait(seq, "sendVideo", nil) - done := h.wait(seq, "editMessageText", textHas("Done")) - if done.MessageID != card.MessageID { - t.Fatal("the text card must become the status message") + h.wait(seq, edits, func(c fakeserver.Call) bool { + return c.MessageID == card.MessageID && !strings.Contains(c.Text(), "Pick a format") + }) + h.finished(seq, alice) + if gone := h.wait(seq, "deleteMessage", nil); gone.MessageID != card.MessageID { + t.Fatal("the text card must be the status message, and go once the file is there") } } @@ -568,7 +673,7 @@ func TestRejectedVideoIsSentAsDocument(t *testing.T) { if doc.Files["document"].Size != 1024 { t.Fatalf("document upload = %+v", doc.Files) } - h.wait(seq, edits, textHas("Done")) + h.finished(seq, 0) } func TestTransientSendFailureIsRetried(t *testing.T) { @@ -577,7 +682,7 @@ func TestTransientSendFailureIsRetried(t *testing.T) { h.srv.FailNext("sendVideo", 500, "Internal Server Error") seq := h.press(alice, alice, card, "dl:") h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return !c.Failed }) - h.wait(seq, edits, textHas("Done")) + h.finished(seq, 0) h.waitJobs(db.JobDone, 1) } @@ -611,7 +716,7 @@ func TestOverSizeAndOverDurationAreRefused(t *testing.T) { card := h.card(alice, alice, big) seq := h.press(alice, alice, card, "dl:") alert := h.wait(seq, "answerCallbackQuery", nil) - if !strings.Contains(alert.Params["text"], "larger than your limit of 50.0 MB") || alert.Params["show_alert"] != "true" { + if !strings.Contains(alert.Params["text"], "larger than your limit of 50 MB") || alert.Params["show_alert"] != "true" { t.Fatalf("alert = %+v", alert.Params) } // The card stays usable: the thumbnail-free card still lets the user @@ -686,7 +791,7 @@ func TestAudioCommandSkipsTheCard(t *testing.T) { if audio.Files["audio"].Name != "Test Video.mp3" || audio.Params["title"] != "Test Video" || audio.Params["performer"] != "Tester" { t.Fatalf("sendAudio = %+v files=%+v", audio.Params, audio.Files) } - h.wait(seq, "editMessageText", textHas("Done")) + h.finished(seq, alice) if len(h.srv.Calls("sendPhoto")) != 0 { t.Fatal("/audio must not show a card") } @@ -707,7 +812,7 @@ func TestInfoCommandListsFormatsWithoutDownloading(t *testing.T) { seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/info "+link) info := h.wait(seq, "sendMessage", textHas("Test Video")) - for _, want := range []string{"Best: 10.0 MB", "720p: 10.0 MB", "480p: 5.0 MB", "MP3: 1.0 MB", "Tester"} { + for _, want := range []string{"Best: 10 MB", "720p: 10 MB", "480p: 5 MB", "MP3: 1 MB", "Tester"} { if !strings.Contains(info.Text(), want) { t.Errorf("info text lacks %q: %q", want, info.Text()) } @@ -738,7 +843,7 @@ func TestStartHelpAndHints(t *testing.T) { seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/help") - h.wait(seq, "sendMessage", textHas("Up to 50.0 MB and 10 minutes per download")) + h.wait(seq, "sendMessage", textHas("Up to 50 MB and 10 minutes per download")) seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "hello bot") @@ -776,7 +881,7 @@ func TestRestartResumesQueuedJob(t *testing.T) { if video.ChatID() != alice { t.Fatalf("sendVideo after restart = %+v", video.Params) } - h.wait(seq, edits, textHas("Done")) + h.finished(seq, 0) h.waitJobs(db.JobDone, 1) } diff --git a/internal/app/cache_test.go b/internal/app/cache_test.go index 7336231..976adbf 100644 --- a/internal/app/cache_test.go +++ b/internal/app/cache_test.go @@ -82,7 +82,7 @@ func (h *harness) fetch(user int64, url string) fakeserver.Call { card := h.card(user, user, url) seq := h.press(user, user, card, "dl:") video := h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == user && !c.Failed }) - h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == user && strings.Contains(c.Text(), "Done") }) + h.finished(seq, user) return video } @@ -170,7 +170,7 @@ func TestCacheHitEnforcesSizeLimit(t *testing.T) { // the cache, and he still must not get it. card := h.card(bob, bob, link) seq := h.press(bob, bob, card, "dl:") - offer := h.wait(seq, "sendMessage", textHas("larger than your limit of 2.0 MB")) + offer := h.wait(seq, "sendMessage", textHas("larger than your limit of 2 MB")) if !strings.Contains(offer.Text(), "You can lift the limit") { t.Fatalf("offer = %q", offer.Text()) } @@ -224,7 +224,9 @@ func TestCacheHitCountsAgainstAndIsStoppedByTheDailyQuota(t *testing.T) { t.Fatalf("usage after a cache hit = %+v, want 1 download and its bytes", u) } // Bob's quota is used up. The cached file is refused like a fresh one. - card := h.card(bob, bob, link) + // (/dl, because a plain link he just got is answered with "already + // sent", whose button runs into the same limit.) + card := h.card(bob, bob, "/dl "+link) seq := h.press(bob, bob, card, "dl:") alert := h.wait(seq, "answerCallbackQuery", nil) if !strings.Contains(alert.Params["text"], "You used your 1 download for today") { @@ -307,8 +309,8 @@ func TestTwoRequestersShareOneDownload(t *testing.T) { // Everyone is notified on completion: both get the file. toAlice := h.wait(seqA, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice }) toGroup := h.wait(seqA, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == group }) - h.wait(seqA, edits, func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Done") }) - h.wait(seqA, edits, func(c fakeserver.Call) bool { return c.ChatID() == group && strings.Contains(c.Text(), "Done") }) + h.finished(seqA, alice) + h.finished(seqA, group) // The file went over the wire once; the second requester got the // file_id of the first upload. @@ -433,7 +435,7 @@ func TestInvalidFileIDFallsBackToTheStoredCopy(t *testing.T) { if !uploaded(healed, "video") || healed.Files["video"].Size != 4096 { t.Fatalf("the fallback must upload the stored copy: %+v %+v", healed.Params, healed.Files) } - h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "Done") }) + h.finished(seq, bob) if n := len(h.fake.Downloads()); n != 1 { t.Fatalf("yt-dlp ran %d times; the stored copy should have been enough", n) } @@ -472,7 +474,7 @@ func TestInvalidFileIDWithoutStoredCopyDownloadsAgain(t *testing.T) { if !uploaded(fresh, "video") { t.Fatal("the fresh download must be uploaded") } - h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "Done") }) + h.finished(seq, bob) if n := len(h.fake.Downloads()); n != 2 { t.Fatalf("yt-dlp ran %d times, want 2 (the original and the re-download)", n) } @@ -512,7 +514,7 @@ func TestLowerProfileIsDerivedFromTheStoredCopy(t *testing.T) { if video.Files["video"].Size != 500 || video.Params["height"] != "480" { t.Fatalf("derived video = %+v %+v", video.Params, video.Files) } - h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "Done") }) + h.finished(seq, bob) if trans.calls.Load() != 1 { t.Fatalf("transcoder ran %d times, want 1", trans.calls.Load()) } @@ -572,7 +574,7 @@ func TestFreshCommandSkipsTheCacheUnderNormalLimits(t *testing.T) { if !uploaded(video, "video") { t.Fatal("/fresh must download and upload again") } - h.wait(seq, edits, textHas("Done")) + h.finished(seq, 0) if n := len(h.fake.Downloads()); n != 2 { t.Fatalf("downloads = %d, want 2", n) } diff --git a/internal/app/flow_test.go b/internal/app/flow_test.go new file mode 100644 index 0000000..3bf0763 --- /dev/null +++ b/internal/app/flow_test.go @@ -0,0 +1,510 @@ +package app_test + +import ( + "context" + "fmt" + "io/fs" + "regexp" + "sort" + "strings" + "testing" + "time" + + "github.com/BurntSushi/toml" + + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/tg/fakeserver" + "github.com/noderunners/dlbot/internal/ytdlp" + "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" + "github.com/noderunners/dlbot/locales" +) + +// --- acceptance: no English in Spanish or Dutch ------------------------------ + +// catalogWords returns the words of every message of a catalog. +func catalogWords(t *testing.T, lang string) map[string]bool { + t.Helper() + data, err := fs.ReadFile(locales.FS, lang+".toml") + if err != nil { + t.Fatal(err) + } + var doc map[string]any + if err := toml.Unmarshal(data, &doc); err != nil { + t.Fatal(err) + } + out := map[string]bool{} + var walk func(v any) + walk = func(v any) { + switch x := v.(type) { + case string: + for _, w := range words(x) { + out[w] = true + } + case map[string]any: + for _, e := range x { + walk(e) + } + } + } + walk(doc) + return out +} + +var ( + wordRe = regexp.MustCompile(`[\p{L}]{4,}`) + placeholderRe = regexp.MustCompile(`\{\{[^}]*\}\}`) + linkRe = regexp.MustCompile(`]*>.*?|https?://\S+|@\w+|/\w+`) + tagRe = regexp.MustCompile(`<[^>]+>`) +) + +// words splits text into lowercase words, leaving out links, commands, +// usernames, placeholders and markup, which are the same in every language. +func words(s string) []string { + s = placeholderRe.ReplaceAllString(s, " ") + s = linkRe.ReplaceAllString(s, " ") + s = tagRe.ReplaceAllString(s, " ") + var out []string + for _, w := range wordRe.FindAllString(s, -1) { + out = append(out, strings.ToLower(w)) + } + return out +} + +// englishOnly are the words of the English catalog that neither the +// Spanish nor the Dutch one uses. One of them in a Spanish or Dutch +// message means English leaked in: a fallback, or a hardcoded string. +func englishOnly(t *testing.T) map[string]bool { + t.Helper() + en, es, nl := catalogWords(t, "en"), catalogWords(t, "es"), catalogWords(t, "nl") + out := map[string]bool{} + for w := range en { + if !es[w] && !nl[w] { + out[w] = true + } + } + // Words of the test fixtures, not of the bot, and "English": language + // pickers list each language under its own name. + for _, w := range []string{"test", "tester", "video", "user", "english"} { + delete(out, w) + } + return out +} + +// shownTo collects every text and button label the bot showed in a chat, +// with the call each came from. +func shownTo(h *harness, chat int64) map[string]string { + out := map[string]string{} + for _, c := range h.srv.Calls("") { + if c.Failed { + continue + } + mine := c.ChatID() == chat || (c.Method == "answerCallbackQuery" && c.ChatID() == 0) + if !mine || strings.HasPrefix(c.Method, "get") || strings.HasPrefix(c.Method, "setMy") { + continue + } + if t := c.Text(); t != "" { + out[t] = c.Method + } + if t := c.Params["text"]; t != "" { + out[t] = c.Method + } + for _, b := range c.Buttons() { + out[b.Text] = c.Method + " button" + } + } + return out +} + +// tour walks a new user through every screen of the bot: first start, +// help, settings with each of their pages, quality and language pickers, +// a first link and the buttons under its file, a repeated link, errors +// with their buttons, and the account and money commands. +func tour(t *testing.T, h *moneyHarness, user int64, lang string) { + t.Helper() + opt := fakeserver.Lang(lang) + send := func(text string) int { + seq := h.srv.Seq() + h.srv.PushMessage(user, user, text, opt) + return seq + } + inChat := func(c fakeserver.Call) bool { return c.ChatID() == user } + pressOn := func(c fakeserver.Call, prefix string) int { + t.Helper() + btn, ok := c.Button(prefix) + if !ok { + t.Fatalf("no %q button in %+v", prefix, c.Buttons()) + } + seq := h.srv.Seq() + h.srv.PushCallback(user, user, c.MessageID, btn.Data) + return seq + } + answered := func(seq int) { h.wait(seq, "answerCallbackQuery", nil) } + + // First start: a welcome with the language picker. + seq := send("/start") + welcome := h.wait(seq, "sendMessage", inChat) + if _, ok := welcome.Button("lw:"); !ok { + t.Fatalf("the first /start has no language picker: %+v", welcome.Buttons()) + } + + // A first link: the card once, then the file with its buttons. + seq = send(link) + card := h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok }) + seq = pressOn(card, "dl:") + video := h.finished(seq, user) + for _, prefix := range []string{"ft:", "fa:"} { + seq = pressOn(video, prefix) + file := h.finished(seq, user) + seq = pressOn(file, "fx:") + h.wait(seq, "deleteMessage", func(c fakeserver.Call) bool { return c.MessageID == file.MessageID }) + } + seq = pressOn(video, "fq:") + other := h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok }) + seq = pressOn(other, "cx:") + answered(seq) + + // The same link again: already sent, with a button to get it again. + seq = send(link) + dup := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { _, ok := c.Button("rs:"); return ok }) + seq = pressOn(dup, "rs:") + h.finished(seq, user) + + // Errors, each with its next step. + seq = send(busyLink) + failed := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { _, ok := c.Button("fl:"); return ok }) + seq = pressOn(failed, "fl:") + h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == failed.MessageID && c.Text() != failed.Text() }) + seq = send(privateLink) + h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { _, ok := c.Button(""); return ok && c.ChatID() == user }) + seq = send(hugeLink) + h.wait(seq, edits, func(c fakeserver.Call) bool { _, ok := c.Button("fq:"); return ok }) + + // Settings and every page of them. + seq = send("/settings") + settings := h.wait(seq, "sendMessage", inChat) + for _, key := range []string{"ps:q", "ps:home", "ps:l", "ps:home", "ps:r", "ps:home", "ps:a", "ps:a", "ps:k", "ps:k"} { + seq = h.srv.Seq() + h.srv.PushCallback(user, user, settings.MessageID, key) + h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == settings.MessageID }) + } + + // Every command a user has. + for _, cmd := range []string{ + "/help", "/quality", "/language", "/queue", "/cancel", "/account", "/limits", "/referral", "/buy", + "/credits", "/donate", "/redeem", "/redeem NOPE", "/info " + link, "/info", "/history", "/dl", "/privacy", + "/terms", "/support", "/app", "/nonsense", "hello", + } { + seq = send(cmd) + h.wait(seq, "sendMessage", inChat) + } + // An invoice. + seq = send("/buy") + buy := h.wait(seq, "sendMessage", inChat) + seq = pressOn(buy, "by:pass_day") + h.wait(seq, "sendPhoto", inChat) +} + +// Links of the tour with scripted outcomes. +const ( + busyLink = "https://example.com/busy" + privateLink = "https://example.com/private" + hugeLink = "https://example.com/huge" +) + +func tourFake() *ytdlptest.Fake { + return &ytdlptest.Fake{ + ProbeErrs: map[string]error{ + busyLink: &ytdlp.Error{Code: ytdlp.CodeRateLimited, Retryable: true, Raw: "HTTP Error 429"}, + privateLink: &ytdlp.Error{Code: ytdlp.CodePrivate, Raw: "private video"}, + }, + DownloadErrs: map[string][]error{ + hugeLink: {&ytdlp.Error{Code: ytdlp.CodeTooLarge, Raw: "larger than max-filesize"}}, + }, + } +} + +func TestEveryScreenInSpanishAndDutch(t *testing.T) { + foreign := englishOnly(t) + for _, lang := range []string{"es", "nl"} { + t.Run(lang, func(t *testing.T) { + // A missing message or a fallback to English is logged as a bug, + // which fails the test (see guardHandler). + h := startApp(t, tourFake(), nil) + const user = int64(501) + tour(t, h, user, lang) + + var leaks []string + for text, where := range shownTo(h.harness, user) { + for _, w := range words(text) { + if foreign[w] { + leaks = append(leaks, fmt.Sprintf("%s %q in %q", where, w, text)) + break + } + } + } + sort.Strings(leaks) + if len(leaks) > 0 { + t.Fatalf("English in %s:\n%s", lang, strings.Join(leaks, "\n")) + } + }) + } +} + +// --- language resolution ----------------------------------------------------- + +func TestLanguageIsResolvedFromChoiceThenTelegramThenEnglish(t *testing.T) { + h := start(t, nil, nil) + ask := func(user int64, opts ...fakeserver.MsgOpt) string { + seq := h.srv.Seq() + h.srv.PushMessage(user, user, "hello", opts...) + return h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == user }).Text() + } + // Telegram's language_code. + if got := ask(61, fakeserver.Lang("nl")); !strings.Contains(got, "Stuur me een link") { + t.Fatalf("nl: %q", got) + } + // No catalog for it: English. + if got := ask(62, fakeserver.Lang("ja")); !strings.Contains(got, "Send me a link") { + t.Fatalf("ja: %q", got) + } + // A stored choice wins over Telegram's language. + if err := h.app.Store.SetUserLang(context.Background(), 61, "es"); err != nil { + t.Fatal(err) + } + if got := ask(61, fakeserver.Lang("nl")); !strings.Contains(got, "Envíame el enlace") { + t.Fatalf("stored es over nl: %q", got) + } + // Buttons pressed later use the same resolution. + seq := h.srv.Seq() + h.srv.PushCallback(61, 61, 1, "nonsense:1") + if c := h.wait(seq, "answerCallbackQuery", nil); !strings.Contains(c.Params["text"], "venció") { + t.Fatalf("callback answer = %q", c.Params["text"]) + } +} + +func TestFirstStartShowsTheLanguagePickerOnce(t *testing.T) { + h := start(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/start", fakeserver.Lang("en")) + welcome := h.wait(seq, "sendMessage", textHas("welcome")) + if _, ok := welcome.Button("lw:nl"); !ok { + t.Fatalf("no language picker under the first welcome: %+v", welcome.Buttons()) + } + // Picking Dutch writes the welcome again in Dutch. + seq = h.press(alice, alice, welcome, "lw:nl") + h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { + return c.MessageID == welcome.MessageID && strings.Contains(c.Text(), "welkom") + }) + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/start", fakeserver.Lang("en")) + again := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice }) + if len(again.Buttons()) != 0 || !strings.Contains(again.Text(), "welkom") { + t.Fatalf("the second /start = %q %+v", again.Text(), again.Buttons()) + } +} + +// --- errors with next steps -------------------------------------------------- + +func TestLookupErrorsAreRetriedOnceAndOfferANextStep(t *testing.T) { + h := startApp(t, tourFake(), nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, busyLink) + failed := h.wait(seq, "editMessageText", textHas("limiting requests")) + if n := countProbes(h.fake, busyLink); n != 2 { + t.Fatalf("a passing failure was looked up %d times, want 2 (one automatic retry)", n) + } + retry, ok := failed.Button("fl:") + if !ok || retry.Text != "Try again" { + t.Fatalf("buttons = %+v", failed.Buttons()) + } + // Try again: the same message runs the lookup again. + seq = h.press(alice, alice, failed, "fl:") + h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { + return c.MessageID == failed.MessageID && strings.Contains(c.Text(), "Looking up") + }) + h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { + return c.MessageID == failed.MessageID && strings.Contains(c.Text(), "limiting requests") + }) + + // A lasting failure is not retried and points to the app. + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, privateLink) + priv := h.wait(seq, "editMessageText", textHas("private")) + if n := countProbes(h.fake, privateLink); n != 1 { + t.Fatalf("a lasting failure was looked up %d times", n) + } + if b, ok := priv.Button(""); !ok || b.WebApp == nil { + t.Fatalf("buttons = %+v", priv.Buttons()) + } + + // Someone else cannot press the buttons of a group member. + seq = h.srv.Seq() + h.srv.PushCallback(alice, bob, failed.MessageID, retry.Data) + if c := h.wait(seq, "answerCallbackQuery", nil); !strings.Contains(c.Params["text"], "belong to the person") { + t.Fatalf("answer = %q", c.Params["text"]) + } +} + +func countProbes(f *ytdlptest.Fake, url string) int { + n := 0 + for _, p := range f.Probes() { + if p == url { + n++ + } + } + return n +} + +func TestFailedDownloadOffersASmallerQualityAndAnUpgrade(t *testing.T) { + h := startApp(t, tourFake(), nil) + card := h.card(alice, alice, hugeLink) + seq := h.press(alice, alice, card, "dl:") + failed := h.wait(seq, edits, textHas("larger than your limit")) + var labels []string + for _, b := range failed.Buttons() { + labels = append(labels, b.Text) + } + if strings.Join(labels, "|") != "Smaller quality|Upgrade" { + t.Fatalf("buttons = %v", labels) + } + // Smaller quality shows the formats again. + seq = h.press(alice, alice, failed, "fq:") + h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok }) + // Upgrade opens the buy screen. + seq = h.press(alice, alice, failed, "up") + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { _, ok := c.Button("by:"); return ok }) +} + +// --- buttons under the result ------------------------------------------------ + +func TestResultButtonsBelongToTheRequester(t *testing.T) { + h := startGroup(t, nil, nil) + h.settings(func(s *db.GroupSettings) { s.Quality = "" }) + card := h.card(group, alice, "/dl "+link) + seq := h.press(group, alice, card, "dl:") + video := h.finished(seq, group) + // In a group the file quotes the message with the link. + if replyTarget(video) == 0 { + t.Fatal("in a group the file must quote the link message") + } + // Bob may look, not press. + del, _ := video.Button("fx:") + seq = h.srv.Seq() + h.srv.PushCallback(group, bob, video.MessageID, del.Data) + if c := h.wait(seq, "answerCallbackQuery", nil); !strings.Contains(c.Params["text"], "belong to the person") { + t.Fatalf("answer to bob = %q", c.Params["text"]) + } + h.never(seq, "deleteMessage", nil) + // Alice asks for the MP3: a new download, quoted under her file. + seq = h.press(group, alice, video, "fa:") + audio := h.finished(seq, group) + if audio.Method != "sendAudio" || replyTarget(audio) != video.MessageID { + t.Fatalf("follow-up = %s replying to %d", audio.Method, replyTarget(audio)) + } + // And deletes the video. + seq = h.press(group, alice, video, "fx:") + if c := h.wait(seq, "deleteMessage", nil); c.MessageID != video.MessageID { + t.Fatalf("deleted %d, want %d", c.MessageID, video.MessageID) + } +} + +// --- several links, repeated links ------------------------------------------- + +func TestSeveralLinksInOneMessage(t *testing.T) { + h := start(t, nil, func(c *config.Config) { + c.MultiLinkMax = 3 + c.Limits.Free.ActiveJobs = 5 + }) + h.askEveryTime(alice) + seq := h.srv.Seq() + var text []string + for i := 1; i <= 4; i++ { + text = append(text, fmt.Sprintf("https://example.com/v%d", i)) + } + h.srv.PushMessage(alice, alice, strings.Join(text, " ")) + for i := 0; i < 3; i++ { + h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok && c.Seq > seq }) + seq = h.srv.Seq() - 1 + } + time.Sleep(300 * time.Millisecond) + if n := len(h.fake.Probes()); n != 3 { + t.Fatalf("%d links looked up, the limit is 3", n) + } +} + +func TestAlreadySentLinkOffersToSendAgain(t *testing.T) { + h := start(t, nil, func(c *config.Config) { c.Limits.Free.DailyDownloads = 2 }) + h.fetch(alice, link+"&utm_source=a") + // The same link, shared with other tracking tags. + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, link+"&si=XYZ") + dup := h.wait(seq, "sendMessage", textHas("a moment ago")) + if n := len(h.fake.Probes()); n != 1 { + t.Fatalf("a repeated link was looked up again (%d lookups)", n) + } + // Sending again is a new download under the same limits. + seq = h.press(alice, alice, dup, "rs:") + h.finished(seq, alice) + if u := h.usage(alice); u.Downloads != 2 { + t.Fatalf("usage = %+v, want 2 downloads", u) + } + seq = h.press(alice, alice, dup, "rs:") + h.wait(seq, edits, textHas("You used your 2 downloads for today")) +} + +// --- queue noise --------------------------------------------------------------- + +func TestQueuePositionIsShownOnlyWhenItMatters(t *testing.T) { + block := make(chan struct{}) + h := start(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { + c.Worker.Concurrency = 1 + c.QueueNoticeThresholdSeconds = 0 + }) + // Alice gets the free slot at once: no queue talk. + card := h.card(alice, alice, link) + seq := h.press(alice, alice, card, "dl:") + h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Downloading") }) + h.never(seq, edits, textHas("In the queue")) + // Bob and Carol wait behind her: that is worth knowing. + card = h.card(bob, bob, "https://example.com/other") + seqBob := h.press(bob, bob, card, "dl:") + h.wait(seqBob, edits, func(c fakeserver.Call) bool { + return c.ChatID() == bob && strings.Contains(c.Text(), "In the queue. Position 1") + }) + card = h.card(carol, carol, "https://example.com/third") + seq = h.press(carol, carol, card, "dl:") + h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == carol && strings.Contains(c.Text(), "Position 2") }) + close(block) + h.finished(seqBob, bob) +} + +// --- menu button ---------------------------------------------------------------- + +func TestMenuButtonOpensTheAppInTheUsersLanguage(t *testing.T) { + h := startApp(t, nil, nil) + if c := h.srv.Calls("setChatMenuButton"); len(c) == 0 || c[0].Params["chat_id"] != "" || + !strings.Contains(c[0].Params["menu_button"], `"web_app"`) { + t.Fatalf("default menu button = %+v", c) + } + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "hello", fakeserver.Lang("es")) + btn := h.wait(seq, "setChatMenuButton", func(c fakeserver.Call) bool { return c.Params["chat_id"] == "42" }) + if !strings.Contains(btn.Params["menu_button"], "Abrir la app") { + t.Fatalf("menu button = %s", btn.Params["menu_button"]) + } + // Once is enough. + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "hello again", fakeserver.Lang("es")) + h.wait(seq, "sendMessage", nil) + h.never(seq, "setChatMenuButton", nil) + // A new language relabels it. + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/language") + pick := h.wait(seq, "sendMessage", nil) + seq = h.press(alice, alice, pick, "lg:nl") + btn = h.wait(seq, "setChatMenuButton", func(c fakeserver.Call) bool { return c.Params["chat_id"] == "42" }) + if !strings.Contains(btn.Params["menu_button"], "App openen") { + t.Fatalf("menu button after switching = %s", btn.Params["menu_button"]) + } +} diff --git a/internal/app/groups_test.go b/internal/app/groups_test.go index db75eb3..a7b0d32 100644 --- a/internal/app/groups_test.go +++ b/internal/app/groups_test.go @@ -322,10 +322,22 @@ func TestGroupSettingsAreAdminOnly(t *testing.T) { h.srv.PushMessage(group, alice, cmd) h.wait(seq, "sendMessage", textHas("Pass: none")) } - // Group commands make no sense in a private chat. + // In a private chat /settings is about the person, not a group. seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/settings") - h.wait(seq, "sendMessage", textHas("works in groups")) + own := h.wait(seq, "sendMessage", textHas("Your settings")) + if strings.Contains(own.Text(), "Allowed sites") { + t.Fatalf("private /settings shows group settings: %q", own.Text()) + } + add, ok := own.Button("") + for _, b := range own.Buttons() { + if strings.Contains(b.URL, "?startgroup=") { + add, ok = b, true + } + } + if !ok || add.URL != "https://t.me/"+fakeserver.BotUsername+"?startgroup=settings" { + t.Fatalf("no add-to-group button in %+v", own.Buttons()) + } } func TestAdminStatusIsVerifiedWithTelegramAndCached(t *testing.T) { @@ -446,7 +458,8 @@ func TestUserDefaultQualityAndLanguageAndStaticPages(t *testing.T) { seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/quality") menu := h.wait(seq, "sendMessage", textHas("Pick your default format")) - if labels(menu) != "✓ Ask every time | Best | 1080p | 720p | 480p | MP3" { + // Somebody who never chose gets "best that fits my limit". + if labels(menu) != "Ask every time | ✓ Best that fits my limit | Best | 1080p | 720p | 480p | Audio only (MP3)" { t.Fatalf("quality buttons = %q", labels(menu)) } seq = h.press(alice, alice, menu, "ql:720") diff --git a/internal/app/i18n_test.go b/internal/app/i18n_test.go index dabfa05..50c1317 100644 --- a/internal/app/i18n_test.go +++ b/internal/app/i18n_test.go @@ -153,7 +153,7 @@ func TestTelegramLanguageIsFollowed(t *testing.T) { h.wait(seq, "sendMessage", textHas("te damos la bienvenida")) card := h.card(bob, bob, link, fakeserver.Lang("nl")) - if labels := card.Buttons(); labels[0].Text != "Beste · 10,0 MB" || labels[len(labels)-1].Text != "Annuleren" { + if labels := card.Buttons(); labels[0].Text != "Beste · 10 MB" || labels[len(labels)-1].Text != "Annuleren" { t.Fatalf("Dutch card buttons = %+v", labels) } // A language without a catalog gets English. @@ -181,7 +181,8 @@ func TestSwitchingLanguageChangesMessagesButtonsMenusAndApp(t *testing.T) { for _, b := range pick.Buttons() { names = append(names, b.Text) } - if strings.Join(names, "|") != "English|Español|Nederlands|Follow my Telegram language" { + // The active choice is checked. + if strings.Join(names, "|") != "English|Español|Nederlands|✓ Follow my Telegram language" { t.Fatalf("language buttons = %v", names) } seq = h.press(alice, alice, pick, "lg:es") @@ -198,12 +199,19 @@ func TestSwitchingLanguageChangesMessagesButtonsMenusAndApp(t *testing.T) { // Messages and buttons. card := h.card(alice, alice, link) labels := card.Buttons() - if labels[0].Text != "Mejor · 10,0 MB" || labels[len(labels)-1].Text != "Cancelar" { + if labels[0].Text != "Mejor · 10 MB" || labels[len(labels)-1].Text != "Cancelar" { t.Fatalf("Spanish card buttons = %+v", labels) } seq = h.press(alice, alice, card, "dl:") - h.wait(seq, "sendVideo", nil) - h.wait(seq, edits, textHas("Listo. Que lo disfrutes.")) + video := h.finished(seq, alice) + if !strings.Contains(video.Text(), "vía @") { + t.Fatalf("Spanish caption = %q", video.Text()) + } + for _, b := range video.Buttons() { + if b.Text == "Delete" || b.Text == "Other quality" { + t.Fatalf("English button under a Spanish file: %+v", video.Buttons()) + } + } seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/account") diff --git a/internal/app/miniapp_test.go b/internal/app/miniapp_test.go index 75907d6..39a38e1 100644 --- a/internal/app/miniapp_test.go +++ b/internal/app/miniapp_test.go @@ -391,7 +391,7 @@ func TestMiniAppHistoryResend(t *testing.T) { if again.Params["video"] == "" || len(again.Files) != 0 { t.Fatalf("the resend should reuse Telegram's copy: params %v, %d uploads", again.Params, len(again.Files)) } - h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Done") }) + h.finished(seq, alice) // One real download happened, and both deliveries count as usage. if n := len(h.fake.Downloads()); n != 1 { t.Fatalf("%d downloads ran, want 1", n) @@ -670,13 +670,24 @@ func TestMiniAppPreferences(t *testing.T) { // A default format has to be a video or audio format. h.refused(h.call(alice, "PUT", "me", map[string]any{"quality": "thumb"}), http.StatusBadRequest, "bad_request") h.refused(h.call(alice, "PUT", "me", map[string]any{"lang": "tlh"}), http.StatusBadRequest, "bad_request") + // "" is "ask every time" in the app, as for groups; "fit" is the best + // quality that fits the limit, which is also what a new user gets. h.must(alice, "PUT", "me", map[string]any{"quality": ""}) - + if me := h.must(alice, "GET", "me", nil); me.str("quality") != "" { + t.Fatalf("me after ask = %s", me.Raw) + } h.must(alice, "PUT", "me", map[string]any{"lang": "en"}) u, err := h.app.Store.GetUser(ctx, alice) - if err != nil || u.LangOverride != "en" || u.Quality != "" { + if err != nil || u.LangOverride != "en" || u.Quality != "ask" { t.Fatalf("user = %+v, %v", u, err) } + h.must(alice, "PUT", "me", map[string]any{"quality": "fit"}) + if me := h.must(alice, "GET", "me", nil); me.str("quality") != "fit" { + t.Fatalf("me after fit = %s", me.Raw) + } + if me := h.must(bob, "GET", "me", nil); me.str("quality") != "fit" { + t.Fatalf("a new user's quality = %s", me.Raw) + } h.must(alice, "PUT", "me", map[string]any{"lang": "auto"}) if u, _ = h.app.Store.GetUser(ctx, alice); u.LangOverride != "" { t.Fatalf("language override = %q, want none", u.LangOverride) diff --git a/internal/app/money_test.go b/internal/app/money_test.go index 6838b8f..5e29999 100644 --- a/internal/app/money_test.go +++ b/internal/app/money_test.go @@ -281,7 +281,7 @@ func TestCreditsTopUpAndPayPerDownload(t *testing.T) { card := h.card(alice, alice, bigLink) seq = h.press(alice, alice, card, "dl:") h.wait(seq, "sendVideo", nil) - h.wait(seq, edits, textHas("Done")) + h.finished(seq, 0) if got := h.balance(alice); got != 950 { t.Fatalf("balance = %d, want 950 after one 50 sat download", got) } @@ -383,7 +383,7 @@ func TestOverLimitPayForThisFileOnly(t *testing.T) { card := h.card(alice, alice, bigLink) seq := h.press(alice, alice, card, "dl:") offer := h.wait(seq, "sendMessage", textHas("You can lift the limit")) - if !strings.Contains(offer.Text(), "larger than your limit of 50.0 MB") { + if !strings.Contains(offer.Text(), "larger than your limit of 50 MB") { t.Fatalf("offer text = %q", offer.Text()) } // 80 MB is one started 100 MB step: 100 base + 50. @@ -410,10 +410,11 @@ func TestOverLimitPayForThisFileOnly(t *testing.T) { if video.Files["video"].Size != 4096 { t.Fatalf("video = %+v", video.Files) } - // The original card became the status message. - done := h.wait(seq, edits, textHas("Done")) - if done.MessageID != card.MessageID { - t.Fatalf("status went to message %d, want the card %d", done.MessageID, card.MessageID) + // The original card became the status message, and made way for the + // file. + file := h.finished(seq, 0) + if gone := h.wait(file.Seq, "deleteMessage", nil); gone.MessageID != card.MessageID { + t.Fatalf("deleted message %d, want the card %d", gone.MessageID, card.MessageID) } sent := h.waitSent(alice, 1) if sent[0].Source != "one_off" || sent[0].ChargeSats != 150 { @@ -689,7 +690,7 @@ func TestDailyQuota(t *testing.T) { for i := 0; i < 2; i++ { card := h.card(alice, alice, fmt.Sprintf("https://example.com/ok%d", i)) seq := h.press(alice, alice, card, "dl:") - h.wait(seq, edits, textHas("Done")) + h.finished(seq, 0) } card = h.card(alice, alice, "https://example.com/third") seq = h.press(alice, alice, card, "dl:") @@ -704,7 +705,7 @@ func TestDailyQuota(t *testing.T) { // Another user has their own quota. card = h.card(bob, bob, "https://example.com/bob") seq = h.press(bob, bob, card, "dl:") - h.wait(seq, edits, textHas("Done")) + h.finished(seq, 0) } func TestDailyVolumeCapAppliesToPaidUsers(t *testing.T) { @@ -714,12 +715,12 @@ func TestDailyVolumeCapAppliesToPaidUsers(t *testing.T) { } card := h.card(alice, alice, link) seq := h.press(alice, alice, card, "dl:") - h.wait(seq, edits, textHas("Done")) // 3 MB delivered, cap is 2 MB + h.finished(seq, 0) // 3 MB delivered, cap is 2 MB card = h.card(alice, alice, "https://example.com/more") seq = h.press(alice, alice, card, "dl:") alert := h.wait(seq, "answerCallbackQuery", nil) - if !strings.Contains(alert.Params["text"], "daily volume of 2.0 MB") { + if !strings.Contains(alert.Params["text"], "daily volume of 2 MB") { t.Fatalf("alert = %q", alert.Params["text"]) } } diff --git a/internal/app/widgets_test.go b/internal/app/widgets_test.go index 657af4c..e6c7316 100644 --- a/internal/app/widgets_test.go +++ b/internal/app/widgets_test.go @@ -103,11 +103,9 @@ func TestJobWidgetEndsWithTheFile(t *testing.T) { card := h.card(alice, alice, link) seq := h.press(alice, alice, card, "dl:") sent := h.wait(seq, "sendWidget", nil) - h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice && !c.Failed }) - h.wait(seq, "editMessageWidgetData", isWidgetEdit(sent.MessageID, func(s widget.Job) bool { - return s.Kind == "end" && s.Message == "Done. Enjoy." - })) - // The file replies to the link, like without widgets. + file := h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice && !c.Failed }) + // Once the file is there, the widget goes like any status message. + h.wait(file.Seq, "deleteMessage", func(c fakeserver.Call) bool { return c.MessageID == sent.MessageID }) h.waitJobs(db.JobDone, 1) if n := len(h.srv.Calls("sendWidget")); n != 1 { t.Fatalf("%d widgets for one download", n) @@ -129,15 +127,18 @@ func TestJobCardFallsBackWhenSendWidgetFails(t *testing.T) { t.Fatal("the scripted failure did not happen") } // The ordinary card carries on as if widgets did not exist. - h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice }) - done := h.wait(seq, "editMessageCaption", textHas("Done")) - if done.MessageID != card.MessageID { - t.Fatalf("the status went to message %d, the card is %d", done.MessageID, card.MessageID) + h.wait(seq, "editMessageCaption", func(c fakeserver.Call) bool { return c.MessageID == card.MessageID }) + file := h.finished(seq, alice) + if gone := h.wait(file.Seq, "deleteMessage", nil); gone.MessageID != card.MessageID { + t.Fatalf("deleted message %d, the card is %d", gone.MessageID, card.MessageID) } if n := len(h.srv.Calls("sendWidget")); n != 1 { t.Fatalf("sendWidget was tried %d times for one download", n) } - h.never(seq, "deleteMessage", func(c fakeserver.Call) bool { return c.Params["message_id"] == itoaInt(card.MessageID) }) + // The card is the status until the file is there. + h.never(seq, "deleteMessage", func(c fakeserver.Call) bool { + return c.Params["message_id"] == itoaInt(card.MessageID) && c.Seq < file.Seq + }) if body := scrapeMetrics(t, h); !strings.Contains(body, `dlbot_widgets_total{outcome="fallback",widget="status"} 1`) { t.Fatal("the fallback was not counted") } @@ -156,10 +157,10 @@ func TestWidgetsPauseWhenTheServerHasNone(t *testing.T) { h.srv.FailNext("sendWidget", 404, "Not Found: method not found") card := h.card(alice, alice, link) seq := h.press(alice, alice, card, "dl:") - h.wait(seq, "editMessageCaption", textHas("Done")) + h.finished(seq, alice) card = h.card(alice, alice, "https://example.com/second") seq = h.press(alice, alice, card, "dl:") - h.wait(seq, "editMessageCaption", textHas("Done")) + h.finished(seq, alice) if n := len(h.srv.Calls("sendWidget")); n != 1 { t.Fatalf("sendWidget tried %d times after the server said it has no such method", n) } diff --git a/internal/app/workers_test.go b/internal/app/workers_test.go index 4ada076..74e4617 100644 --- a/internal/app/workers_test.go +++ b/internal/app/workers_test.go @@ -195,7 +195,7 @@ func TestRemoteWorkerDoesEverythingOverHTTP(t *testing.T) { if video.Files["video"].Size != 5000 { t.Fatalf("the file that went through the worker upload is wrong: %+v", video.Files) } - f.wait(seq, edits, textHas("Done")) + f.finished(seq, 0) job := f.jobOf(db.JobDone) if job.WorkerID != "w1" || job.Attempts != 1 { t.Fatalf("job worker=%q attempts=%d", job.WorkerID, job.Attempts) @@ -236,7 +236,7 @@ func TestKilledWorkerJobIsRequeuedAndFinishedByTheOther(t *testing.T) { if video.Files["video"].Size != 7777 { t.Fatalf("the delivered file did not come from the second worker: %+v", video.Files) } - f.wait(seq, edits, textHas("Done")) + f.finished(seq, 0) done := f.jobOf(db.JobDone) if done.ID != running.ID || done.WorkerID != "w2" || done.Attempts != 2 { t.Fatalf("job id=%s worker=%q attempts=%d, want the same job finished by w2 on attempt 2", @@ -325,7 +325,7 @@ func TestDrainAndWorkersCommands(t *testing.T) { for i := 0; i < 3; i++ { card := f.card(bob, bob, fmt.Sprintf("https://example.com/d%d", i)) seq := f.press(bob, bob, card, "dl:") - f.wait(seq, edits, textHas("Done")) + f.finished(seq, 0) } if n := len(w1.fake.Downloads()); n != 0 { t.Fatalf("a draining worker took %d jobs", n) diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 97f07eb..e1557fa 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -24,6 +24,7 @@ import ( "github.com/noderunners/dlbot/internal/service" "github.com/noderunners/dlbot/internal/storage" "github.com/noderunners/dlbot/internal/tg" + "github.com/noderunners/dlbot/internal/thumb" "github.com/noderunners/dlbot/internal/widget" ) @@ -50,6 +51,15 @@ type Deps struct { ReloadI18n func() error // Metrics records what happens. Nil records nothing. Metrics *metrics.Metrics + // Thumbnails makes the thumbnail uploaded with a video. Nil gets the + // default, which fetches the source's thumbnail image. + Thumbnails Thumbnailer +} + +// Thumbnailer turns a thumbnail URL into a JPEG Telegram accepts as the +// thumbnail of a video, or nil. +type Thumbnailer interface { + Fetch(ctx context.Context, url string) []byte } // Bot handles Telegram updates and job events. @@ -79,6 +89,7 @@ type Bot struct { baseCtx context.Context metrics *metrics.Metrics + thumbs Thumbnailer // widgets decides whether HTML widgets are tried; nil turns them off. widgets *widget.Breaker liveMu sync.Mutex @@ -92,6 +103,9 @@ type Bot struct { // cancelledAt is when each user last sent /cancel. A playlist item // that was already being looked up at that moment must not start. cancelledAt map[int64]time.Time + // menuButtons is the language each private chat's menu button was + // last labelled in. + menuButtons map[int64]string // broadcasts holds texts waiting for the owner's confirmation. broadcasts map[string]string reloadI18n func() error @@ -142,22 +156,27 @@ func New(ctx context.Context, d Deps) (*Bot, error) { baseCtx: ctx, statuses: map[string]*statusState{}, metrics: d.Metrics, + thumbs: d.Thumbnails, live: map[string]*liveJob{}, liveTried: map[string]int{}, sending: map[string]bool{}, pumping: map[int64]bool{}, cancelledAt: map[int64]time.Time{}, broadcasts: map[string]string{}, + menuButtons: map[int64]string{}, reloadI18n: d.ReloadI18n, broadcastGap: 50 * time.Millisecond, admins: d.Admins, reconcileEvery: 5 * time.Second, - statusMinGap: 3 * time.Second, + statusMinGap: 2500 * time.Millisecond, invoiceGrace: 5 * time.Second, } if b.admins == nil { b.admins = groups.NewAdmins(d.API, 0) } + if b.thumbs == nil { + b.thumbs = thumb.New() + } if d.Config.Telegram.Widgets { b.widgets = widget.NewBreaker() } @@ -189,8 +208,13 @@ func (b *Bot) SetTimings(reconcile, statusGap time.Duration) { b.statusMinGap = statusGap b.invoiceGrace = 4 * reconcile b.broadcastGap = time.Millisecond + b.svc.SetProbeRetryDelay(10 * time.Millisecond) } +// SetThumbnails replaces the thumbnail maker. Tests use it to stay off the +// network. +func (b *Bot) SetThumbnails(t Thumbnailer) { b.thumbs = t } + // Admins returns the group admin checker, shared with the Mini App API. func (b *Bot) Admins() *groups.Admins { return b.admins } @@ -287,9 +311,18 @@ func updateChatID(u telego.Update) int64 { return int64(u.UpdateID) } -// HandleUpdate routes one update. +// HandleUpdate routes one update. The user behind it and the language to +// answer in are resolved once, here, and travel with the context. func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) { b.metrics.Update(updateType(u)) + if from, chat := updateUser(u); from != nil { + act, err := b.resolveActor(ctx, from, chat) + if err != nil { + b.log.Error("load user", "user_id", from.ID, "err", err) + return + } + ctx = withActor(ctx, act) + } switch { case u.Message != nil: b.handleMessage(ctx, u.Message) @@ -302,6 +335,22 @@ func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) { } } +// updateUser returns the person behind an update that needs an answer in +// their language, and the chat it happened in. +func updateUser(u telego.Update) (*telego.User, *telego.Chat) { + switch { + case u.Message != nil && u.Message.From != nil && !u.Message.From.IsBot: + return u.Message.From, &u.Message.Chat + case u.CallbackQuery != nil: + if m := u.CallbackQuery.Message; m != nil { + chat := m.GetChat() + return &u.CallbackQuery.From, &chat + } + return &u.CallbackQuery.From, nil + } + return nil, nil +} + func updateType(u telego.Update) string { switch { case u.Message != nil: @@ -320,6 +369,42 @@ func updateType(u telego.Update) string { type actor struct { user *db.User lang string + // group holds the settings of the group the update came from, nil in + // a private chat. + group *db.GroupSettings +} + +type actorKey struct{} + +func withActor(ctx context.Context, act actor) context.Context { + return context.WithValue(ctx, actorKey{}, act) +} + +// actorFrom returns the actor HandleUpdate resolved for this update. +func actorFrom(ctx context.Context) (actor, bool) { + act, ok := ctx.Value(actorKey{}).(actor) + return act, ok +} + +// resolveActor loads the user and picks the language to answer in: the +// language the user chose, then Telegram's language_code, then English. +// In a group with a language of its own, that language wins. +func (b *Bot) resolveActor(ctx context.Context, from *telego.User, chat *telego.Chat) (actor, error) { + act, err := b.actorFor(ctx, from) + if err != nil { + return act, err + } + if chat != nil && groups.IsGroup(chat.Type) { + gset, err := b.store.GetGroupSettings(ctx, chat.ID) + if err != nil { + return act, err + } + act.group = gset + if gset.Lang != "" { + act.lang = gset.Lang + } + } + return act, nil } func (b *Bot) actorFor(ctx context.Context, from *telego.User) (actor, error) { @@ -327,11 +412,15 @@ func (b *Bot) actorFor(ctx context.Context, from *telego.User) (actor, error) { if err != nil { return actor{}, err } - lang := u.LangOverride - if lang == "" { - lang = b.tr.Resolve(u.Lang) + return actor{user: u, lang: b.userLang(u)}, nil +} + +// userLang is the language a user reads in a private chat. +func (b *Bot) userLang(u *db.User) string { + if u.LangOverride != "" { + return u.LangOverride } - return actor{user: u, lang: lang}, nil + return b.tr.Resolve(u.Lang) } func isPrivate(chatType string) bool { return chatType == telego.ChatTypePrivate } @@ -340,8 +429,11 @@ func isPrivate(chatType string) bool { return chatType == telego.ChatTypePrivate func chatID(id int64) telego.ChatID { return telego.ChatID{ID: id} } -func replyParams(messageID int64) *telego.ReplyParameters { - if messageID == 0 { +// replyParams quotes a message, in groups only. In a private chat there +// is one conversation and a quote only adds noise. Private chats have the +// user's own, positive ID; groups have negative IDs. +func replyParams(chat, messageID int64) *telego.ReplyParameters { + if messageID == 0 || chat > 0 { return nil } return &telego.ReplyParameters{MessageID: int(messageID), AllowSendingWithoutReply: true} @@ -356,7 +448,7 @@ func (b *Bot) send(ctx context.Context, chat, replyTo int64, text string, kb *te Text: text, ParseMode: telego.ModeHTML, LinkPreviewOptions: noPreview, - ReplyParameters: replyParams(replyTo), + ReplyParameters: replyParams(chat, replyTo), } if kb != nil { p.ReplyMarkup = kb diff --git a/internal/bot/card.go b/internal/bot/card.go index e779276..0327f8c 100644 --- a/internal/bot/card.go +++ b/internal/bot/card.go @@ -36,6 +36,12 @@ type linkRequest struct { fresh bool // subs shows the subtitle languages instead of the format buttons. subs bool + // checkRecent answers "already sent" for a link this user got a + // moment ago, instead of downloading it again. + checkRecent bool + // messageID, when set, is an existing message to use as the status, + // such as the error message a "Try again" button sits under. + messageID int64 } // startLink runs the link flow in the background so a slow metadata lookup @@ -65,16 +71,24 @@ func (b *Bot) linkFlow(ctx context.Context, lr linkRequest) { lang := lr.act.lang log := b.log.With("user_id", lr.act.user.ID, "chat_id", lr.chatID, "url", links.Redact(lr.url)) - placeholder, err := b.send(ctx, lr.chatID, lr.sourceID, b.tr.HTML(lang, "card.looking", nil), nil) - if err != nil { + if lr.checkRecent && !lr.fresh && b.alreadySent(ctx, lr) { return } - phID := int64(placeholder.MessageID) + phID := lr.messageID + if phID != 0 { + _ = b.edit(ctx, lr.chatID, phID, false, b.tr.HTML(lang, "card.looking", nil), nil) + } else { + placeholder, err := b.send(ctx, lr.chatID, lr.sourceID, b.tr.HTML(lang, "card.looking", nil), nil) + if err != nil { + return + } + phID = int64(placeholder.MessageID) + } probed, err := b.svc.ProbeAny(ctx, lr.url) if err != nil { if ctx.Err() == nil { - _ = b.edit(ctx, lr.chatID, phID, false, b.probeErrorText(lang, err), nil) + b.lookupFailed(ctx, lr, phID, err) } return } @@ -101,7 +115,14 @@ func (b *Bot) linkFlow(ctx context.Context, lr linkRequest) { Info: info.JSON(), Lang: lang, } - if lr.preset != "" { + preset := lr.preset + if lr.subs { + preset = "" + } + if preset == presetFit { + preset = b.fitProfile(ctx, lr, info) + } + if preset != "" { req.Status = db.RequestChosen } if err := b.store.InsertRequest(ctx, req); err != nil { @@ -111,13 +132,24 @@ func (b *Bot) linkFlow(ctx context.Context, lr linkRequest) { } log = log.With("request_id", req.ID) - if lr.preset != "" { + if preset != "" { job, _, err := b.svc.Start(ctx, service.StartParams{ - Request: req, Info: info, Profile: lr.preset, + Request: req, Info: info, Profile: preset, StatusMessageID: phID, ReplyToMessageID: lr.sourceID, }) if err != nil { - _ = b.edit(ctx, lr.chatID, phID, false, titleLine(info.Title)+"\n"+html.EscapeString(b.startErrorText(lang, err)), nil) + // Give the request back, so the offer and the buttons under the + // error can still use it. + if _, rerr := b.store.TransitionRequest(ctx, req.ID, db.RequestChosen, db.RequestReady); rerr != nil { + log.Error("release request", "err", rerr) + } + var le *service.LimitError + if errors.As(err, &le) && le.Upgradable { + b.deleteMessage(ctx, lr.chatID, phID) + b.offerUpgrade(ctx, lr.chatID, lr.sourceID, lang, req, preset, le, isPrivate(lr.chatType)) + return + } + b.showStartError(ctx, req, info, preset, phID, false, err) return } b.refreshStatus(ctx, job.ID) @@ -129,28 +161,93 @@ func (b *Bot) linkFlow(ctx context.Context, lr linkRequest) { return } + // A first link from someone who never picked a default: show the card + // this once, and make "best that fits my limit" their default. + note := "" + if isPrivate(lr.chatType) && lr.act.user.Quality == qualityUnset && lr.preset == "" { + if err := b.store.SetUserQuality(context.WithoutCancel(ctx), lr.act.user.ID, qualityFit); err != nil { + log.Error("set first default quality", "err", err) + } else { + note = b.tr.HTML(lang, "card.first_run", nil) + } + } + b.showCard(ctx, lang, req, info, phID, note) +} + +// showCard shows the format card of a request: a photo with the +// thumbnail when Telegram can fetch it, text otherwise. replaceID is a +// message to turn into the card (or delete, once the photo is out); 0 +// sends a new one. +func (b *Bot) showCard(ctx context.Context, lang string, req *db.Request, info *service.CardInfo, replaceID int64, note string) { text := b.cardText(lang, info, true) + if note != "" { + text += "\n\n" + note + } kb := b.cardKeyboard(lang, req.ID, info) if info.Thumbnail != "" { msg, err := b.api.SendPhoto(ctx, &telego.SendPhotoParams{ - ChatID: chatID(lr.chatID), + ChatID: chatID(req.ChatID), Photo: telego.InputFile{URL: info.Thumbnail}, Caption: clip(text, 1024), ParseMode: telego.ModeHTML, - ReplyParameters: replyParams(lr.sourceID), + ReplyParameters: replyParams(req.ChatID, req.SourceMessageID), ReplyMarkup: kb, }) if err == nil { if err := b.store.SetRequestCard(context.WithoutCancel(ctx), req.ID, int64(msg.MessageID), true); err != nil { - log.Error("save card", "err", err) + b.log.Error("save card", "request_id", req.ID, "err", err) } - b.deleteMessage(ctx, lr.chatID, phID) + b.deleteMessage(ctx, req.ChatID, replaceID) return } // Telegram could not fetch the thumbnail. The text card still works. - log.Debug("photo card failed, using text card", "err", err) + b.log.Debug("photo card failed, using text card", "err", err) } - _ = b.edit(ctx, lr.chatID, phID, false, text, kb) + if replaceID != 0 { + _ = b.edit(ctx, req.ChatID, replaceID, false, text, kb) + return + } + msg, err := b.send(ctx, req.ChatID, req.SourceMessageID, text, kb) + if err == nil { + if err := b.store.SetRequestCard(context.WithoutCancel(ctx), req.ID, int64(msg.MessageID), false); err != nil { + b.log.Error("save card", "request_id", req.ID, "err", err) + } + } +} + +// fitProfile picks "the best quality that fits my limit" for a looked up +// link. When nothing fits, the smallest quality is returned and the start +// is refused by the usual limit check, which leads to the over-limit offer. +func (b *Bot) fitProfile(ctx context.Context, lr linkRequest, info *service.CardInfo) media.Profile { + who := service.Who{UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType} + dec, err := b.svc.Entitlement(ctx, who, false) + if err != nil { + return media.Best + } + p, _ := service.BestFit(info, min64(dec.Limits.MaxSize, b.cfg.MaxUploadBytes())) + return p +} + +// lookupFailed explains a link that could not be looked up. The request is +// kept, failed, so that "Try again" knows the link. +func (b *Bot) lookupFailed(ctx context.Context, lr linkRequest, messageID int64, err error) { + lang := lr.act.lang + code := string(ytdlp.CodeOf(err)) + if errors.Is(err, service.ErrPlaylist) { + code = "playlist" + } + req := &db.Request{ + ID: ids.New(), UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType, + SourceMessageID: lr.sourceID, CardMessageID: messageID, URL: lr.url, + Status: db.RequestFailed, Lang: lang, + } + var kb *telego.InlineKeyboardMarkup + if ierr := b.store.InsertRequest(ctx, req); ierr == nil { + kb = b.errorKeyboard(lang, req, "", code) + } else { + b.log.Error("insert failed request", "err", ierr) + } + _ = b.edit(ctx, lr.chatID, messageID, false, b.probeErrorText(lang, err), kb) } // cardText renders the card: title, a line of facts and, for cards with diff --git a/internal/bot/commands.go b/internal/bot/commands.go index a138f6d..c06cd21 100644 --- a/internal/bot/commands.go +++ b/internal/bot/commands.go @@ -18,33 +18,16 @@ import ( "github.com/noderunners/dlbot/internal/service" ) -// maxLinksPerMessage caps how many links of one message get a card. -const maxLinksPerMessage = 3 - func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { - if m.From == nil || m.From.IsBot { - return - } - act, err := b.actorFor(ctx, m.From) - if err != nil { - b.log.Error("load user", "user_id", m.From.ID, "err", err) - return - } - if act.user.Banned { + act, ok := actorFrom(ctx) + if !ok || act.user.Banned { return } private := isPrivate(m.Chat.Type) inGroup := groups.IsGroup(m.Chat.Type) - var gset *db.GroupSettings - if inGroup { - if gset, err = b.store.GetGroupSettings(ctx, m.Chat.ID); err != nil { - b.log.Error("load group settings", "chat_id", m.Chat.ID, "err", err) - return - } - // A group can pin its own language for everything said in it. - if gset.Lang != "" { - act.lang = gset.Lang - } + gset := act.group + if inGroup && gset == nil { + return } cmd, forUs, isCmd := b.parseCommand(m) if isCmd { @@ -59,6 +42,9 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { return } } + if private { + b.syncMenuButton(ctx, act) + } if b.ownerCommand(ctx, m, act, cmd) { return } @@ -83,34 +69,55 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { if !private { return } + b.syncMenuButton(ctx, act) if len(urls) == 0 { _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "hint.send_link", nil), nil) return } - if len(urls) > maxLinksPerMessage { - urls = urls[:maxLinksPerMessage] + if max := b.cfg.MultiLinkMax; max > 0 && len(urls) > max { + urls = urls[:max] } for _, u := range urls { b.startLink(ctx, linkRequest{ chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: int64(m.MessageID), act: act, url: u, - preset: presetFor(act, nil), + preset: presetFor(act, nil), checkRecent: true, }) } } +// Personal quality settings besides a profile. Stored in users.default_quality. +const ( + // qualityUnset is a user who never chose. Their first link shows the + // card once, and their default becomes qualityFit. + qualityUnset = "" + // qualityAsk shows the card for every link. + qualityAsk = "ask" + // qualityFit picks the best quality whose estimated size fits the + // user's size limit. + qualityFit = "fit" +) + // presetFor returns the format to start without showing the card: the // group's default quality in a group, the user's own in a private chat. +// An empty result means the card is shown. func presetFor(act actor, gset *db.GroupSettings) media.Profile { q := act.user.Quality if gset != nil { q = gset.Quality } + if q == qualityFit { + return presetFit + } if p, err := media.Parse(q); err == nil { return p } return "" } +// presetFit stands for "best that fits my limit" until the link has been +// looked up and the real profile can be picked. +const presetFit media.Profile = "fit" + // runCommand dispatches the commands everyone can use. func (b *Bot) runCommand(ctx context.Context, m *telego.Message, act actor, cmd string, gset *db.GroupSettings) { // Commands that carry a link. In a group their message can be removed @@ -177,6 +184,10 @@ func (b *Bot) runCommand(ctx context.Context, m *telego.Message, act actor, cmd b.cmdStatic(ctx, m, act, "static."+cmd) } case "settings": + if isPrivate(m.Chat.Type) { + b.cmdPersonalSettings(ctx, m.Chat.ID, act) + return + } b.cmdSettings(ctx, m, act) case "grouplang": b.cmdGroupLang(ctx, m, act) @@ -299,7 +310,13 @@ func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) { } } } - _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.private", i18n.Args{"Name": act.user.FirstName}), nil) + // Somebody new picks a language under the welcome. It starts in the + // language of their Telegram app, which is usually right. + var kb *telego.InlineKeyboardMarkup + if act.user.IsNew { + kb = b.languageKeyboard(act, func(l string) string { return cbData(cbWelcomeLang, l) }, false) + } + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.private", i18n.Args{"Name": act.user.FirstName}), kb) } func (b *Bot) cmdHelp(ctx context.Context, m *telego.Message, act actor) { @@ -475,20 +492,14 @@ func (b *Bot) release(ctx context.Context, d *db.Delivery) string { } func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { - act, err := b.actorFor(ctx, &q.From) - if err != nil { - b.log.Error("load user", "user_id", q.From.ID, "err", err) + act, ok := actorFrom(ctx) + if !ok { return } if act.user.Banned { b.answer(ctx, q, "", false) return } - if q.Message != nil && groups.IsGroup(q.Message.GetChat().Type) { - if gset, err := b.store.GetGroupSettings(ctx, q.Message.GetChat().ID); err == nil && gset.Lang != "" { - act.lang = gset.Lang - } - } action, id, arg := parseCallback(q.Data) switch action { case cbGroupSetting: @@ -499,6 +510,8 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { b.cbSetQuality(ctx, q, act, id) case cbLanguage: b.cbSetLanguage(ctx, q, act, id) + case cbWelcomeLang: + b.cbWelcomeLanguage(ctx, q, act, id) case cbBroadcast: b.cbBroadcastSend(ctx, q, act, id) case cbDownload: @@ -509,6 +522,22 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { b.cbPlaylistStart(ctx, q, act, id, arg) case cbResend: b.cbResendFile(ctx, q, act, id) + case cbFollowAudio: + b.cbFollow(ctx, q, act, id, media.MP3) + case cbFollowThumb: + b.cbFollow(ctx, q, act, id, media.Thumb) + case cbFollowQuality: + b.cbOtherQuality(ctx, q, act, id) + case cbFollowDelete: + b.cbDeleteResult(ctx, q, act, id) + case cbRetry: + b.cbRetryDownload(ctx, q, act, id, arg) + case cbRetryLookup: + b.cbRetryLookup(ctx, q, act, id) + case cbUpgrade: + b.cbShowUpgrade(ctx, q, act) + case cbPersonal: + b.cbPersonalSetting(ctx, q, act, id, arg) case cbSkipQueue: b.cbSkip(ctx, q, act, id) case cbBuy: diff --git a/internal/bot/deliver.go b/internal/bot/deliver.go index 32873aa..232a107 100644 --- a/internal/bot/deliver.go +++ b/internal/bot/deliver.go @@ -1,6 +1,7 @@ package bot import ( + "bytes" "context" "errors" "io" @@ -11,6 +12,7 @@ import ( "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/media" "github.com/noderunners/dlbot/internal/sched" + "github.com/noderunners/dlbot/internal/service" "github.com/noderunners/dlbot/internal/storage" "github.com/noderunners/dlbot/internal/tg" ) @@ -98,7 +100,7 @@ func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery) (stop // same job; that user is refused here, like on a download of their own. if code := overCap(job, d); code != "" { _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, code) - b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, code)+b.release(ctx, d)) + b.finalStatusKB(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, code)+b.release(ctx, d), b.failureKeyboard(ctx, d, job, code)) return false } @@ -130,7 +132,7 @@ func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery) (stop case tg.IsFileTooBig(err): log.Warn("telegram refused file size", "size", job.FileSize, "err", err) _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "too_large") - b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "too_large")+b.release(ctx, d)) + b.finalStatusKB(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "too_large")+b.release(ctx, d), b.failureKeyboard(ctx, d, job, "too_large")) case d.Attempts+1 < maxSendAttempts: log.Warn("send failed, will retry", "attempt", d.Attempts+1, "err", err) if wait := tg.RetryAfter(err); wait > 0 && wait <= time.Minute { @@ -140,7 +142,7 @@ func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery) (stop default: log.Error("send failed, giving up", "err", err) _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "send_failed") - b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "send_failed")+b.release(ctx, d)) + b.finalStatusKB(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "send_failed")+b.release(ctx, d), b.failureKeyboard(ctx, d, job, "send_failed")) } return false } @@ -166,7 +168,8 @@ func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery) (stop via = "cache" } b.metrics.Delivered(via) - b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.done", nil)) + // The file is the answer. The status message has done its job. + b.retireStatus(ctx, d, sent.MessageID) return false } @@ -317,17 +320,27 @@ func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delive defer rc.Close() input = telego.InputFile{File: namedReader{Reader: rc, name: fileName(job.Title, job.FileExt)}} } - caption := clip(titleLine(job.Title), 1024) + out := b.outgoing(ctx, job, d) + caption := clip(out.caption, 1024) chat := chatID(d.ChatID) - reply := replyParams(d.ReplyToMessageID) + reply := replyParams(d.ChatID, d.ReplyToMessageID) + // Content is never protected: people forward what they downloaded. switch mode { case "video": - msg, err := b.api.SendVideo(ctx, &telego.SendVideoParams{ + p := &telego.SendVideoParams{ ChatID: chat, Video: input, Caption: caption, ParseMode: telego.ModeHTML, Duration: int(job.Duration), Width: job.Width, Height: job.Height, - SupportsStreaming: true, ReplyParameters: reply, - }) + SupportsStreaming: true, ReplyParameters: reply, ReplyMarkup: out.keyboard, + } + // A thumbnail only counts with an upload; Telegram ignores it for a + // file_id, and it cannot be reused. + if reuseFileID == "" && out.thumbnailURL != "" { + if jpg := b.thumbs.Fetch(ctx, out.thumbnailURL); jpg != nil { + p.Thumbnail = &telego.InputFile{File: namedReader{Reader: bytes.NewReader(jpg), name: "thumb.jpg"}} + } + } + msg, err := b.api.SendVideo(ctx, p) if err != nil { return sentFile{}, err } @@ -341,7 +354,8 @@ func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delive case "audio": msg, err := b.api.SendAudio(ctx, &telego.SendAudioParams{ ChatID: chat, Audio: input, Title: shorten(job.Title, 120), Performer: shorten(job.Uploader, 60), - Duration: int(job.Duration), ReplyParameters: reply, + Caption: caption, ParseMode: telego.ModeHTML, + Duration: int(job.Duration), ReplyParameters: reply, ReplyMarkup: out.keyboard, }) if err != nil { return sentFile{}, err @@ -352,7 +366,8 @@ func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delive return sentFile{MessageID: int64(msg.MessageID)}, nil case "photo": msg, err := b.api.SendPhoto(ctx, &telego.SendPhotoParams{ - ChatID: chat, Photo: input, Caption: caption, ParseMode: telego.ModeHTML, ReplyParameters: reply, + ChatID: chat, Photo: input, Caption: caption, ParseMode: telego.ModeHTML, + ReplyParameters: reply, ReplyMarkup: out.keyboard, }) if err != nil { return sentFile{}, err @@ -363,7 +378,8 @@ func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delive return sentFile{MessageID: int64(msg.MessageID)}, nil default: msg, err := b.api.SendDocument(ctx, &telego.SendDocumentParams{ - ChatID: chat, Document: input, Caption: caption, ParseMode: telego.ModeHTML, ReplyParameters: reply, + ChatID: chat, Document: input, Caption: caption, ParseMode: telego.ModeHTML, + ReplyParameters: reply, ReplyMarkup: out.keyboard, }) if err != nil { return sentFile{}, err @@ -375,6 +391,36 @@ func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delive } } +// outgoingFile is what goes with a file besides the file itself. +type outgoingFile struct { + caption string + keyboard *telego.InlineKeyboardMarkup + thumbnailURL string +} + +// outgoing builds the caption and the buttons of a delivery's file from +// the request it answers. +func (b *Bot) outgoing(ctx context.Context, job *db.Job, d *db.Delivery) outgoingFile { + info := &service.CardInfo{Title: job.Title, Uploader: job.Uploader, Duration: job.Duration} + url := job.URL + var req *db.Request + if r, err := b.store.GetRequest(ctx, d.RequestID); err == nil { + req = r + url = r.URL + if ci, err := service.ParseCardInfo(r.Info); err == nil { + info = ci + } + } + out := outgoingFile{ + caption: b.caption(d.Lang, info, url, jobProfile(job)), + keyboard: b.resultKeyboard(d.Lang, req, info, jobProfile(job)), + } + if jobProfile(job).Kind() == media.KindVideo { + out.thumbnailURL = info.Thumbnail + } + return out +} + // finishIfServed closes a delivering job once nobody waits for it, and // decides what happens to the stored file: it enters the cache when the // result is cacheable, and is deleted otherwise. @@ -448,7 +494,8 @@ func (b *Bot) failJob(ctx context.Context, jobID string) { continue } // The automatic retry is spent: give back what the download cost. - b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, job.ErrorCode)+b.release(ctx, d)) + b.finalStatusKB(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, job.ErrorCode)+b.release(ctx, d), + b.failureKeyboard(ctx, d, job, job.ErrorCode)) } b.removeStored(ctx, job) } diff --git a/internal/bot/extras.go b/internal/bot/extras.go index 639ce8e..80f1a9f 100644 --- a/internal/bot/extras.go +++ b/internal/bot/extras.go @@ -299,7 +299,7 @@ func (b *Bot) subsCard(ctx context.Context, lr linkRequest, messageID int64, req label = b.tr.T(lang, "btn.subs_auto", i18n.Args{"Lang": e.code}) } if isMine(e.code) { - label = "✓ " + label + label = b.tr.T(lang, "btn.checked", i18n.Args{"Label": label}) } row = append(row, button(label, cbData(cbDownload, req.ID, string(p)))) if len(row) == 3 { diff --git a/internal/bot/groups.go b/internal/bot/groups.go index 67099a4..614453e 100644 --- a/internal/bot/groups.go +++ b/internal/bot/groups.go @@ -21,6 +21,7 @@ const ( cbGroupBuy = "gb" // gb::[:] cbQuality = "ql" // ql: cbLanguage = "lg" // lg: + cbWelcomeLang = "lw" // lw:, under the first welcome ) // handleMyChatMember records the groups the bot is in. Telegram sends this @@ -525,35 +526,14 @@ func (b *Bot) cbGroupBuyProduct(ctx context.Context, q *telego.CallbackQuery, ac // --- personal preferences --------------------------------------------------- func (b *Bot) cmdQuality(ctx context.Context, m *telego.Message, act actor) { - lang := act.lang - opt := func(value string) telego.InlineKeyboardButton { - label := b.qualityName(lang, value) - if value == act.user.Quality { - label = "✓ " + label - } - data := value - if data == "" { - data = "ask" - } - return button(label, cbData(cbQuality, data)) - } - kb := keyboard( - []telego.InlineKeyboardButton{opt("")}, - []telego.InlineKeyboardButton{opt(string(media.Best)), opt(string(media.P1080)), opt(string(media.P720)), opt(string(media.P480))}, - []telego.InlineKeyboardButton{opt(string(media.MP3))}, - ) - _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(lang, "quality.pick", nil), kb) + kb := b.qualityKeyboard(act, func(v string) string { return cbData(cbQuality, v) }, false) + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "quality.pick", nil), kb) } func (b *Bot) cbSetQuality(ctx context.Context, q *telego.CallbackQuery, act actor, value string) { - if value == "ask" { - value = "" - } - if value != "" { - if p, err := media.Parse(value); err != nil || (p.Kind() != media.KindVideo && p.Kind() != media.KindAudio) { - b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) - return - } + if !validUserQuality(value) { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return } if err := b.store.SetUserQuality(ctx, act.user.ID, value); err != nil { b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) @@ -562,42 +542,21 @@ func (b *Bot) cbSetQuality(ctx context.Context, q *telego.CallbackQuery, act act b.answer(ctx, q, b.tr.T(act.lang, "notice.saved", nil), false) if q.Message != nil { _ = b.edit(ctx, q.Message.GetChat().ID, int64(q.Message.GetMessageID()), false, - b.tr.HTML(act.lang, "quality.set", i18n.Args{"Quality": b.qualityName(act.lang, value)}), nil) + b.tr.HTML(act.lang, "quality.set", i18n.Args{"Quality": b.userQualityName(act.lang, value)}), nil) } } func (b *Bot) cmdLanguage(ctx context.Context, m *telego.Message, act actor) { - var row []telego.InlineKeyboardButton - var rows [][]telego.InlineKeyboardButton - for _, l := range b.visibleLangs(act.user.ID) { - // Each language is listed under its own name. - row = append(row, button(b.tr.T(l, "language.name", nil), cbData(cbLanguage, l))) - if len(row) == 3 { - rows = append(rows, row) - row = nil - } - } - rows = append(rows, row, []telego.InlineKeyboardButton{button(b.tr.T(act.lang, "language.auto", nil), cbData(cbLanguage, "auto"))}) - _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "language.pick", nil), keyboard(rows...)) + kb := b.languageKeyboard(act, func(l string) string { return cbData(cbLanguage, l) }, false) + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "language.pick", nil), kb) } func (b *Bot) cbSetLanguage(ctx context.Context, q *telego.CallbackQuery, act actor, value string) { - lang := "" - if value != "auto" { - if lang = b.findLang(value, act.user.ID); lang == "" { - b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) - return - } - } - if err := b.store.SetUserLang(ctx, act.user.ID, lang); err != nil { - b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) + shown, ok := b.applyLanguage(ctx, act, value) + if !ok { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) return } - shown := lang - if shown == "" { - shown = b.tr.Resolve(act.user.Lang) - } - b.SyncUserMenu(ctx, act.user.ID, lang) b.answer(ctx, q, b.tr.T(shown, "notice.saved", nil), false) if q.Message != nil { _ = b.edit(ctx, q.Message.GetChat().ID, int64(q.Message.GetMessageID()), false, @@ -605,6 +564,21 @@ func (b *Bot) cbSetLanguage(ctx context.Context, q *telego.CallbackQuery, act ac } } +// cbWelcomeLanguage is a language picked under the first welcome: the +// welcome is written again in that language. +func (b *Bot) cbWelcomeLanguage(ctx context.Context, q *telego.CallbackQuery, act actor, value string) { + shown, ok := b.applyLanguage(ctx, act, value) + if !ok { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.answer(ctx, q, b.tr.T(shown, "notice.saved", nil), false) + if q.Message != nil { + _ = b.edit(ctx, q.Message.GetChat().ID, int64(q.Message.GetMessageID()), false, + b.tr.HTML(shown, "start.private", i18n.Args{"Name": act.user.FirstName}), nil) + } +} + // cmdStatic answers /privacy, /terms and /support from the catalog. func (b *Bot) cmdStatic(ctx context.Context, m *telego.Message, act actor, key string) { contact := b.cfg.Support diff --git a/internal/bot/live.go b/internal/bot/live.go index 644ba72..ed53486 100644 --- a/internal/bot/live.go +++ b/internal/bot/live.go @@ -97,8 +97,12 @@ func (b *Bot) jobState(ctx context.Context, d *db.Delivery, job *db.Job) widget. s := widget.Job{Kind: "running", Progress: -1, RTL: i18n.Dir(lang) == "rtl", Cancel: b.tr.T(lang, "btn.cancel", nil)} switch job.Status { case db.JobQueued: - s.Kind = "queued" pos, _ := b.sched.Position(ctx, job, b.slots()) + if b.quietQueue(pos) { + s.Message = b.tr.T(lang, "status.downloading", nil) + break + } + s.Kind = "queued" s.Message = b.tr.T(lang, "app.queue.waiting", i18n.Args{"Position": pos.Ahead + 1, "Wait": b.tr.Span(lang, pos.Wait)}) case db.JobRunning: switch { @@ -190,9 +194,7 @@ func (b *Bot) startLiveJob(ctx context.Context, d *db.Delivery, job *db.Job, dat Caption: clip(titleLine(job.Title), 1024), ParseMode: telego.ModeHTML, AllowQueries: true, ReplyMarkup: kb, } - if d.ReplyToMessageID != 0 { - params.ReplyParameters = &telego.ReplyParameters{MessageID: int(d.ReplyToMessageID), AllowSendingWithoutReply: true} - } + // Widgets are for private chats, where nothing is quoted. msg, err := b.api.SendWidget(ctx, params) if err != nil { b.widgetFailed("status", err) @@ -226,7 +228,7 @@ func (b *Bot) startLiveJob(ctx context.Context, d *db.Delivery, job *db.Job, dat // liveFinal shows the outcome of a delivery on its widget. It reports // false when the delivery has no widget, or the widget is gone. -func (b *Bot) liveFinal(ctx context.Context, d *db.Delivery, text string) bool { +func (b *Bot) liveFinal(ctx context.Context, d *db.Delivery, text string, kb *telego.InlineKeyboardMarkup) bool { lj := b.liveFor(ctx, d) b.liveMu.Lock() delete(b.live, d.ID) @@ -243,9 +245,10 @@ func (b *Bot) liveFinal(ctx context.Context, d *db.Delivery, text string) bool { if err := b.editWidget(ctx, d.ChatID, lj.messageID, data); err != nil && tg.IsMessageGone(err) { return false } - // The caption keeps the title; the buttons under it go. - if lj.buttons != "" { - _ = b.edit(ctx, d.ChatID, lj.messageID, true, title, nil) + // The caption keeps the title; the live buttons under it go, and the + // next steps, if any, take their place. + if lj.buttons != "" || kb != nil { + _ = b.edit(ctx, d.ChatID, lj.messageID, true, title, kb) } return true } diff --git a/internal/bot/menu.go b/internal/bot/menu.go index 4d4f113..257d206 100644 --- a/internal/bot/menu.go +++ b/internal/bot/menu.go @@ -18,20 +18,24 @@ var ( privateMenu = []string{ "dl", "audio", "thumb", "subs", "info", "queue", "cancel", "history", "account", "buy", "credits", "limits", "redeem", "referral", "donate", - "quality", "language", "app", "support", "privacy", "terms", "help", + "settings", "quality", "language", "app", "support", "privacy", "terms", "help", } groupMenu = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "groupwallet", "grouppass", "app", "help"} adminMenu = append(append([]string{}, groupMenu...), "settings", "grouplang", "autodetect", "allow", "block", "spending", "groupstats") ) -func (b *Bot) menu(lang string, names []string) []telego.BotCommand { +func (b *Bot) menu(lang string, names []string, private bool) []telego.BotCommand { cmds := make([]telego.BotCommand, 0, len(names)) for _, name := range names { if name == "app" && !b.cfg.MiniAppEnabled() { continue } - cmds = append(cmds, telego.BotCommand{Command: name, Description: b.tr.T(lang, "menu."+name, nil)}) + key := "menu." + name + if name == "settings" && private { + key = "menu.settings_private" // /settings in a private chat is personal + } + cmds = append(cmds, telego.BotCommand{Command: name, Description: b.tr.T(lang, key, nil)}) } return cmds } @@ -58,13 +62,15 @@ func (b *Bot) menuLangs() []string { // ignored: the bot works without a menu. func (b *Bot) RegisterCommands(ctx context.Context) { scopes := []struct { - scope telego.BotCommandScope - names []string + scope telego.BotCommandScope + names []string + private bool }{ - {&telego.BotCommandScopeAllPrivateChats{Type: telego.ScopeTypeAllPrivateChats}, privateMenu}, - {&telego.BotCommandScopeAllGroupChats{Type: telego.ScopeTypeAllGroupChats}, groupMenu}, - {&telego.BotCommandScopeAllChatAdministrators{Type: telego.ScopeTypeAllChatAdministrators}, adminMenu}, + {&telego.BotCommandScopeAllPrivateChats{Type: telego.ScopeTypeAllPrivateChats}, privateMenu, true}, + {&telego.BotCommandScopeAllGroupChats{Type: telego.ScopeTypeAllGroupChats}, groupMenu, false}, + {&telego.BotCommandScopeAllChatAdministrators{Type: telego.ScopeTypeAllChatAdministrators}, adminMenu, false}, } + b.setDefaultMenuButton(ctx) for i, lang := range b.menuLangs() { code := lang if i == 0 { @@ -72,7 +78,7 @@ func (b *Bot) RegisterCommands(ctx context.Context) { } for _, s := range scopes { err := b.api.SetMyCommands(ctx, &telego.SetMyCommandsParams{ - Commands: b.menu(lang, s.names), Scope: s.scope, LanguageCode: code, + Commands: b.menu(lang, s.names, s.private), Scope: s.scope, LanguageCode: code, }) if err != nil { b.log.Warn("setMyCommands failed", "lang", lang, "scope", s.scope.ScopeType(), "err", err) @@ -131,7 +137,7 @@ func (b *Bot) SyncUserMenu(ctx context.Context, userID int64, lang string) { if lang == "" { err = b.api.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{Scope: scope}) } else { - err = b.api.SetMyCommands(ctx, &telego.SetMyCommandsParams{Commands: b.menu(lang, privateMenu), Scope: scope}) + err = b.api.SetMyCommands(ctx, &telego.SetMyCommandsParams{Commands: b.menu(lang, privateMenu, true), Scope: scope}) } if err != nil { b.log.Warn("set the menu of a chat", "chat_id", userID, "err", err) @@ -157,7 +163,7 @@ func (b *Bot) SyncGroupMenu(ctx context.Context, chatID int64, lang string) { if lang == "" { err = b.api.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{Scope: s.scope}) } else { - err = b.api.SetMyCommands(ctx, &telego.SetMyCommandsParams{Commands: b.menu(lang, s.names), Scope: s.scope}) + err = b.api.SetMyCommands(ctx, &telego.SetMyCommandsParams{Commands: b.menu(lang, s.names, false), Scope: s.scope}) } if err != nil { b.log.Warn("set the menu of a group", "chat_id", chatID, "err", err) @@ -186,3 +192,64 @@ func (b *Bot) findLang(code string, userID int64) string { } return "" } + +// menuButton is the button left of the message field that opens the Mini +// App. The command list stays one tap away in the "/" button of the field. +func (b *Bot) menuButton(lang string) *telego.MenuButtonWebApp { + return &telego.MenuButtonWebApp{ + Type: telego.ButtonTypeWebApp, + Text: b.tr.T(lang, "btn.open_app", nil), + WebApp: telego.WebAppInfo{URL: b.cfg.PublicURL + "/app/"}, + } +} + +// setDefaultMenuButton makes the Mini App the menu button of every chat, +// labelled in the source language. setChatMenuButton takes no language, +// so each private chat gets its own label later, by syncMenuButton. +func (b *Bot) setDefaultMenuButton(ctx context.Context) { + if !b.cfg.MiniAppEnabled() { + return + } + if err := b.api.SetChatMenuButton(ctx, &telego.SetChatMenuButtonParams{MenuButton: b.menuButton(b.tr.Langs()[0])}); err != nil { + b.log.Warn("setChatMenuButton failed", "err", err) + } +} + +// syncMenuButton labels the menu button of a private chat in the user's +// language. It runs once per user and language: what was set is kept in +// memory and in the database, so it survives a restart. +func (b *Bot) syncMenuButton(ctx context.Context, act actor) { + if !b.cfg.MiniAppEnabled() { + return + } + lang := b.userLang(act.user) + b.statusMu.Lock() + known := b.menuButtons[act.user.ID] == lang + b.statusMu.Unlock() + if known { + return + } + key := "menubtn:" + itoa(act.user.ID) + if old, _ := b.store.GetKV(ctx, key); old == lang { + b.rememberMenuButton(act.user.ID, lang) + return + } + if !b.rate.allow("menubtn:"+itoa(act.user.ID), 3, time.Minute) { + return + } + err := b.api.SetChatMenuButton(ctx, &telego.SetChatMenuButtonParams{ChatID: act.user.ID, MenuButton: b.menuButton(lang)}) + if err != nil { + b.log.Warn("setChatMenuButton failed", "chat_id", act.user.ID, "err", err) + return + } + if err := b.store.SetKV(ctx, key, lang); err != nil { + b.log.Warn("remember menu button", "chat_id", act.user.ID, "err", err) + } + b.rememberMenuButton(act.user.ID, lang) +} + +func (b *Bot) rememberMenuButton(userID int64, lang string) { + b.statusMu.Lock() + b.menuButtons[userID] = lang + b.statusMu.Unlock() +} diff --git a/internal/bot/money.go b/internal/bot/money.go index c52b1a4..73cbbfe 100644 --- a/internal/bot/money.go +++ b/internal/bot/money.go @@ -215,18 +215,26 @@ func (b *Bot) cmdReferral(ctx context.Context, m *telego.Message, act actor) { if !b.privateOnly(ctx, m, act) { return } - n, err := b.store.CountReferrals(ctx, act.user.ID) + text, err := b.referralText(ctx, act) if err != nil { b.internalError(ctx, m.Chat.ID, act, err) return } + _, _ = b.send(ctx, m.Chat.ID, 0, text, nil) +} + +// referralText explains the referral program with the user's own link. +func (b *Bot) referralText(ctx context.Context, act actor) (string, error) { + n, err := b.store.CountReferrals(ctx, act.user.ID) + if err != nil { + return "", err + } link := "https://t.me/" + b.username + "?start=ref_" + strconv.FormatInt(act.user.ID, 10) - text := b.tr.HTML(act.lang, "referral.text", i18n.Args{ + return b.tr.HTML(act.lang, "referral.text", i18n.Args{ "Link": link, "Reward": b.tr.Sats(act.lang, b.cfg.Prices.ReferralReward), "Count": n, - }) - _, _ = b.send(ctx, m.Chat.ID, 0, text, nil) + }), nil } func (b *Bot) cmdRedeem(ctx context.Context, m *telego.Message, act actor, arg string) { diff --git a/internal/bot/personal.go b/internal/bot/personal.go new file mode 100644 index 0000000..d390cfd --- /dev/null +++ b/internal/bot/personal.go @@ -0,0 +1,286 @@ +package bot + +import ( + "context" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/media" +) + +// This file is /settings in a private chat: the person's own settings in +// one message that edits itself as buttons are pressed. Group settings +// stay in groups.go. + +// cbPersonal is a button of the personal settings: ps:[:]. +const cbPersonal = "ps" + +// Keys of cbPersonal. +const ( + psHome = "home" // back to the overview + psQuality = "q" // the quality picker + psSetQ = "qs" // ps:qs: + psAudio = "a" // toggle audio only + psAsk = "k" // toggle asking every time + psLanguage = "l" // the language picker + psSetLang = "ls" // ps:ls: + psReferral = "r" // the referral program +) + +// userQualities are the choices of a person's default format, in order. +var userQualities = []string{ + qualityAsk, qualityFit, string(media.Best), string(media.P1080), string(media.P720), string(media.P480), string(media.MP3), +} + +// userQualityName names a person's quality setting. Somebody who never +// chose gets "best that fits my limit" after their first link, so that is +// what an empty value shows. +func (b *Bot) userQualityName(lang, q string) string { + switch q { + case qualityUnset, qualityFit: + return b.tr.T(lang, "quality.fit", nil) + case qualityAsk: + return b.tr.T(lang, "quality.ask", nil) + case string(media.MP3): + return b.tr.T(lang, "quality.audio_only", nil) + } + p, err := media.Parse(q) + if err != nil { + return q + } + return b.profileLabel(lang, p) +} + +// validUserQuality reports whether a value may be stored as a default. +func validUserQuality(q string) bool { + for _, v := range userQualities { + if v == q { + return true + } + } + return false +} + +// personalView renders the overview of a person's settings. +func (b *Bot) personalView(ctx context.Context, act actor) (string, *telego.InlineKeyboardMarkup) { + lang := act.lang + u := act.user + st, _ := b.bill.State(ctx, db.OwnerUser, u.ID) + pass := b.tr.T(lang, "word.none", nil) + if st.PassUntil > 0 { + pass = b.tr.DateTime(lang, time.UnixMilli(st.PassUntil)) + } + invited, _ := b.store.CountReferrals(ctx, u.ID) + langName := b.tr.T(lang, "language.name", nil) + if u.LangOverride == "" { + langName = b.tr.T(lang, "settings.lang_follow", i18n.Args{"Lang": langName}) + } + text := b.tr.HTML(lang, "settings.personal", i18n.Args{ + "Quality": b.userQualityName(lang, u.Quality), + "Lang": langName, + "Pass": pass, + "Balance": b.tr.Sats(lang, st.Credits), + "Invited": invited, + }) + row := func(key, label, value string) []telego.InlineKeyboardButton { + return []telego.InlineKeyboardButton{button( + b.tr.T(lang, "settings.button", i18n.Args{"Label": label, "Value": value}), cbData(cbPersonal, key))} + } + rows := [][]telego.InlineKeyboardButton{ + row(psQuality, b.tr.T(lang, "settings.quality", nil), b.userQualityName(lang, u.Quality)), + row(psAudio, b.tr.T(lang, "settings.audio_only", nil), b.onOff(lang, u.Quality == string(media.MP3))), + row(psAsk, b.tr.T(lang, "settings.ask", nil), b.onOff(lang, u.Quality == qualityAsk)), + row(psLanguage, b.tr.T(lang, "settings.language", nil), langName), + {button(b.tr.T(lang, "btn.referral", nil), cbData(cbPersonal, psReferral))}, + } + if btn, ok := b.appButton(lang, true, ""); ok { + rows = append(rows, []telego.InlineKeyboardButton{btn}) + } + rows = append(rows, []telego.InlineKeyboardButton{b.addToGroupButton(lang)}) + return text, keyboard(rows...) +} + +// addToGroupButton opens Telegram's group picker to add the bot. +func (b *Bot) addToGroupButton(lang string) telego.InlineKeyboardButton { + return urlButton(b.tr.T(lang, "btn.add_to_group", nil), "https://t.me/"+b.username+"?startgroup=settings") +} + +// backRow leads back to the overview. +func (b *Bot) backRow(lang string) []telego.InlineKeyboardButton { + return []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.back", nil), cbData(cbPersonal, psHome))} +} + +func (b *Bot) cmdPersonalSettings(ctx context.Context, chat int64, act actor) { + text, kb := b.personalView(ctx, act) + _, _ = b.send(ctx, chat, 0, text, kb) +} + +// cbPersonalSetting handles every button of the personal settings. Each +// press edits the same message. +func (b *Bot) cbPersonalSetting(ctx context.Context, q *telego.CallbackQuery, act actor, key, value string) { + if q.Message == nil || !isPrivate(q.Message.GetChat().Type) { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + chat, msgID := q.Message.GetChat().ID, int64(q.Message.GetMessageID()) + show := func(text string, kb *telego.InlineKeyboardMarkup) { + _ = b.edit(ctx, chat, msgID, false, text, kb) + } + setQuality := func(v string) bool { + if err := b.store.SetUserQuality(ctx, act.user.ID, v); err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) + return false + } + act.user.Quality = v + return true + } + switch key { + case psHome: + case psQuality: + b.answer(ctx, q, "", false) + show(b.tr.HTML(act.lang, "quality.pick", nil), b.qualityKeyboard(act, func(v string) string { + return cbData(cbPersonal, psSetQ, v) + }, true)) + return + case psSetQ: + if !validUserQuality(value) { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + if !setQuality(value) { + return + } + case psAudio: + v := string(media.MP3) + if act.user.Quality == v { + v = qualityFit + } + if !setQuality(v) { + return + } + case psAsk: + v := qualityAsk + if act.user.Quality == v { + v = qualityFit + } + if !setQuality(v) { + return + } + case psLanguage: + b.answer(ctx, q, "", false) + show(b.tr.HTML(act.lang, "language.pick", nil), b.languageKeyboard(act, func(l string) string { + return cbData(cbPersonal, psSetLang, l) + }, true)) + return + case psSetLang: + lang, ok := b.applyLanguage(ctx, act, value) + if !ok { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + act.lang = lang + act.user.LangOverride = "" + if value != "auto" { + act.user.LangOverride = lang + } + case psReferral: + b.answer(ctx, q, "", false) + text, err := b.referralText(ctx, act) + if err != nil { + b.log.Error("referral text", "err", err) + return + } + show(text, keyboard(b.backRow(act.lang))) + return + default: + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + if key != psHome { + b.answer(ctx, q, b.tr.T(act.lang, "notice.saved", nil), false) + } else { + b.answer(ctx, q, "", false) + } + show(b.personalView(ctx, act)) +} + +// qualityKeyboard lists the default formats with the active one checked. +// data builds the callback data of a choice. +func (b *Bot) qualityKeyboard(act actor, data func(v string) string, back bool) *telego.InlineKeyboardMarkup { + lang := act.lang + cur := act.user.Quality + if cur == qualityUnset { + cur = qualityFit + } + opt := func(v string) telego.InlineKeyboardButton { + label := b.userQualityName(lang, v) + if v == cur { + label = b.tr.T(lang, "btn.checked", i18n.Args{"Label": label}) + } + return button(label, data(v)) + } + rows := [][]telego.InlineKeyboardButton{ + {opt(qualityAsk)}, + {opt(qualityFit)}, + {opt(string(media.Best)), opt(string(media.P1080)), opt(string(media.P720)), opt(string(media.P480))}, + {opt(string(media.MP3))}, + } + if back { + rows = append(rows, b.backRow(lang)) + } + return keyboard(rows...) +} + +// languageKeyboard lists the languages, each under its own name, and the +// choice to follow Telegram. +func (b *Bot) languageKeyboard(act actor, data func(l string) string, back bool) *telego.InlineKeyboardMarkup { + var row []telego.InlineKeyboardButton + var rows [][]telego.InlineKeyboardButton + for _, l := range b.visibleLangs(act.user.ID) { + label := b.tr.T(l, "language.name", nil) + if l == act.user.LangOverride { + label = b.tr.T(act.lang, "btn.checked", i18n.Args{"Label": label}) + } + row = append(row, button(label, data(l))) + if len(row) == 3 { + rows = append(rows, row) + row = nil + } + } + auto := b.tr.T(act.lang, "language.auto", nil) + if act.user.LangOverride == "" { + auto = b.tr.T(act.lang, "btn.checked", i18n.Args{"Label": auto}) + } + rows = append(rows, row, []telego.InlineKeyboardButton{button(auto, data("auto"))}) + if back { + rows = append(rows, b.backRow(act.lang)) + } + return keyboard(rows...) +} + +// applyLanguage stores a language choice ("auto" follows Telegram) and +// returns the language the user now reads. +func (b *Bot) applyLanguage(ctx context.Context, act actor, value string) (string, bool) { + lang := "" + if value != "auto" { + if lang = b.findLang(value, act.user.ID); lang == "" { + return "", false + } + } + if err := b.store.SetUserLang(ctx, act.user.ID, lang); err != nil { + b.log.Error("set language", "user_id", act.user.ID, "err", err) + return "", false + } + shown := lang + if shown == "" { + shown = b.tr.Resolve(act.user.Lang) + } + b.SyncUserMenu(ctx, act.user.ID, lang) + u := *act.user + u.LangOverride = lang + b.syncMenuButton(ctx, actor{user: &u, lang: shown}) + return shown, true +} diff --git a/internal/bot/result.go b/internal/bot/result.go new file mode 100644 index 0000000..dc8458a --- /dev/null +++ b/internal/bot/result.go @@ -0,0 +1,472 @@ +package bot + +import ( + "context" + "errors" + "html" + "strings" + "time" + "unicode/utf8" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/ids" + "github.com/noderunners/dlbot/internal/links" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/service" + "github.com/noderunners/dlbot/internal/tg" + "github.com/noderunners/dlbot/internal/ytdlp" +) + +// This file is about what a finished download looks like: the caption and +// the buttons under the file, the status message making way for it, and +// the buttons under an error that offer the next step. + +// Callback data of the buttons under a result or an error. Each carries the +// ID of the request the result answers. +const ( + cbFollowAudio = "fa" // fa: + cbFollowQuality = "fq" // fq: + cbFollowThumb = "ft" // ft: + cbFollowDelete = "fx" // fx: + cbRetry = "fr" // fr:: + cbRetryLookup = "fl" // fl: + cbUpgrade = "up" // up +) + +// genericTitles are titles sites give to posts that have none of their own. +var genericTitles = map[string]bool{ + "video": true, "untitled": true, "instagram": true, "tiktok": true, "facebook": true, + "reel": true, "post": true, "twitter": true, "x": true, "threads": true, "media": true, + "instagram video": true, "tiktok video": true, "facebook video": true, +} + +// genericTitlePrefixes start titles that only say who posted. +var genericTitlePrefixes = []string{"video by ", "post by ", "reel by ", "photo by ", "instagram post by ", "tiktok video #"} + +// isGenericTitle reports whether a title says nothing about the content: +// empty, the bare video ID, the uploader's name or a site placeholder. +func isGenericTitle(info *service.CardInfo) bool { + t := strings.ToLower(strings.TrimSpace(info.Title)) + if t == "" || t == strings.ToLower(info.VideoID) || genericTitles[t] { + return true + } + if u := strings.ToLower(strings.TrimSpace(info.Uploader)); u != "" && (t == u || t == "@"+u) { + return true + } + for _, p := range genericTitlePrefixes { + if strings.HasPrefix(t, p) { + return true + } + } + return false +} + +// uploadDay parses yt-dlp's YYYYMMDD upload date. +func uploadDay(s string) (time.Time, bool) { + if len(s) != 8 { + return time.Time{}, false + } + t, err := time.Parse("20060102", s) + return t, err == nil +} + +// displayTitle is a plain text title for people. A generic title becomes +// the uploader and the upload date, such as "nasa · 3 May 2025". +func (b *Bot) displayTitle(lang string, info *service.CardInfo) (title string, generic bool) { + if !isGenericTitle(info) { + return strings.TrimSpace(info.Title), false + } + var parts []string + if u := strings.TrimSpace(info.Uploader); u != "" { + parts = append(parts, u) + } + if day, ok := uploadDay(info.UploadDate); ok { + parts = append(parts, b.tr.Date(lang, day)) + } + if len(parts) == 0 { + if info.Site != "" { + return info.Site, true + } + return strings.TrimSpace(info.Title), true + } + return strings.Join(parts, " · "), true +} + +// caption is the HTML caption of a delivered file: the title, who posted +// it and how long it is, a short link to the source without tracking +// parameters, and optionally the bot's name. +func (b *Bot) caption(lang string, info *service.CardInfo, url string, profile media.Profile) string { + title, generic := b.displayTitle(lang, info) + var lines []string + if title != "" { + lines = append(lines, titleLine(title)) + } + var facts []string + if u := strings.TrimSpace(info.Uploader); u != "" && !generic { + facts = append(facts, html.EscapeString(shorten(u, 40))) + } + if info.Duration > 0 && profile.Kind() != media.KindThumb && profile.Kind() != media.KindSubs { + facts = append(facts, i18n.Clock(info.Duration)) + } + if len(facts) > 0 { + lines = append(lines, strings.Join(facts, " · ")) + } + if url != "" { + clean := links.Clean(url) + lines = append(lines, ``+html.EscapeString(links.Short(clean, 40))+``) + } + if b.cfg.CaptionAttribution && b.username != "" { + lines = append(lines, b.tr.HTML(lang, "caption.via", i18n.Args{"Bot": b.username})) + } + return strings.Join(lines, "\n") +} + +// resultKeyboard is the row of next steps under a delivered file. Only +// what makes sense for the file is offered: no MP3 of an MP3. +func (b *Bot) resultKeyboard(lang string, req *db.Request, info *service.CardInfo, profile media.Profile) *telego.InlineKeyboardMarkup { + if req == nil { + return nil + } + id := req.ID + del := button(b.tr.T(lang, "btn.delete", nil), cbData(cbFollowDelete, id)) + other := button(b.tr.T(lang, "btn.other_quality", nil), cbData(cbFollowQuality, id)) + switch profile.Kind() { + case media.KindVideo: + var first, second []telego.InlineKeyboardButton + if info.HasAudio { + first = append(first, button(b.tr.T(lang, "btn.result_audio", nil), cbData(cbFollowAudio, id))) + } + first = append(first, other) + if info.Thumbnail != "" { + second = append(second, button(b.profileLabel(lang, media.Thumb), cbData(cbFollowThumb, id))) + } + second = append(second, del) + return keyboard(first, second) + case media.KindAudio: + return keyboard([]telego.InlineKeyboardButton{other, del}) + } + return keyboard([]telego.InlineKeyboardButton{del}) +} + +// retireStatus removes the status message of a delivery once its file is +// in the chat, so one message per download remains. When Telegram does not +// let it go, it is cut down to a short line instead. +func (b *Bot) retireStatus(ctx context.Context, d *db.Delivery, resultID int64) { + b.forgetStatus(d.ID) + b.liveMu.Lock() + delete(b.live, d.ID) + delete(b.liveTried, d.ID) + b.liveMu.Unlock() + // A status widget may have replaced the message since d was loaded. + if cur, err := b.store.GetDelivery(context.WithoutCancel(ctx), d.ID); err == nil { + d.StatusMessageID, d.StatusIsPhoto = cur.StatusMessageID, cur.StatusIsPhoto + } + if d.StatusMessageID == 0 || d.StatusMessageID == resultID { + return + } + err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ChatID: chatID(d.ChatID), MessageID: int(d.StatusMessageID)}) + if err == nil || tg.IsMessageGone(err) { + return + } + b.log.Debug("status message not deleted, shortening it", "delivery_id", d.ID, "err", err) + _ = b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, b.tr.HTML(d.Lang, "status.sent", nil), nil) +} + +// --- buttons under a result --------------------------------------------------- + +// ownRequest loads the request behind a result or error button and checks +// that the person pressing it is the one who asked. In a group everyone +// sees the buttons; only the requester may use them. +func (b *Bot) ownRequest(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string) (*db.Request, bool) { + req, err := b.store.GetRequest(ctx, requestID) + if err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return nil, false + } + if req.UserID != act.user.ID { + b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false) + return nil, false + } + return req, true +} + +// pressedIn returns the chat a button was pressed in and the message it +// sits under. +func pressedIn(q *telego.CallbackQuery, req *db.Request) (chat int64, chatType string, messageID int64) { + if q.Message == nil { + return req.ChatID, req.ChatType, 0 + } + c := q.Message.GetChat() + return c.ID, c.Type, int64(q.Message.GetMessageID()) +} + +// cbFollow starts another format of a past result: the MP3 or the +// thumbnail. It is a new download with the usual limits. +func (b *Bot) cbFollow(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string, profile media.Profile) { + req, ok := b.ownRequest(ctx, q, act, requestID) + if !ok { + return + } + info, err := service.ParseCardInfo(req.Info) + if err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.answer(ctx, q, "", false) + chat, chatType, msgID := pressedIn(q, req) + b.startAgain(ctx, act, chat, chatType, msgID, req, info, profile) +} + +// cbRetryDownload is "Try again" under a failed download. +func (b *Bot) cbRetryDownload(ctx context.Context, q *telego.CallbackQuery, act actor, requestID, profileArg string) { + req, ok := b.ownRequest(ctx, q, act, requestID) + if !ok { + return + } + profile, perr := media.Parse(profileArg) + info, ierr := service.ParseCardInfo(req.Info) + if perr != nil || ierr != nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.answer(ctx, q, "", false) + chat, chatType, msgID := pressedIn(q, req) + // The error message turns back into the status of the new attempt. + b.deleteMessage(ctx, chat, msgID) + b.startAgain(ctx, act, chat, chatType, req.SourceMessageID, req, info, profile) +} + +// cbRetryLookup is "Try again" under a link that could not be looked up. +func (b *Bot) cbRetryLookup(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string) { + req, ok := b.ownRequest(ctx, q, act, requestID) + if !ok { + return + } + chat, chatType, msgID := pressedIn(q, req) + if !b.rate.allow("u:"+itoa(act.user.ID), b.cfg.Rate.UserPerMinute, time.Minute) { + b.answer(ctx, q, b.tr.T(act.lang, "notice.rate_limited", nil), true) + return + } + b.answer(ctx, q, "", false) + lr := linkRequest{ + chatID: chat, chatType: chatType, sourceID: req.SourceMessageID, act: act, url: req.URL, + preset: presetFor(act, act.group), messageID: msgID, + } + b.goBG("link", func() { b.linkFlow(ctx, lr) }) +} + +// cbOtherQuality shows the format card again for a past result, or for a +// download that was too big. +func (b *Bot) cbOtherQuality(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string) { + orig, ok := b.ownRequest(ctx, q, act, requestID) + if !ok { + return + } + info, err := service.ParseCardInfo(orig.Info) + if err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.answer(ctx, q, "", false) + chat, chatType, msgID := pressedIn(q, orig) + info.Fresh = false + req := &db.Request{ + ID: ids.New(), UserID: act.user.ID, ChatID: chat, ChatType: chatType, URL: orig.URL, + SourceMessageID: msgID, Status: db.RequestReady, Info: info.JSON(), Lang: act.lang, + } + if err := b.store.InsertRequest(ctx, req); err != nil { + b.internalError(ctx, chat, act, err) + return + } + b.showCard(ctx, act.lang, req, info, 0, "") +} + +// cbDeleteResult removes the message the button is under. +func (b *Bot) cbDeleteResult(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string) { + req, ok := b.ownRequest(ctx, q, act, requestID) + if !ok { + return + } + chat, _, msgID := pressedIn(q, req) + if msgID == 0 { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ChatID: chatID(chat), MessageID: int(msgID)}); err != nil && !tg.IsMessageGone(err) { + // Older than 48 hours: Telegram keeps it. + b.answer(ctx, q, b.tr.T(act.lang, "notice.cannot_delete", nil), true) + return + } + b.answer(ctx, q, "", false) +} + +// cbShowUpgrade is "Upgrade" under an error: the buy screen. +func (b *Bot) cbShowUpgrade(ctx context.Context, q *telego.CallbackQuery, act actor) { + if q.Message != nil && !isPrivate(q.Message.GetChat().Type) { + // Invoices are personal: open the private chat. + if err := b.api.AnswerCallbackQuery(ctx, &telego.AnswerCallbackQueryParams{ + CallbackQueryID: q.ID, URL: "https://t.me/" + b.username + "?start=buy", + }); err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.private_only", nil), true) + } + return + } + b.answer(ctx, q, "", false) + b.showBuy(ctx, act.user.ID, act) +} + +// startAgain starts a known link in a chat with a new status message, +// under the usual limits. Resends and follow-ups go through here. +func (b *Bot) startAgain(ctx context.Context, act actor, chat int64, chatType string, replyTo int64, orig *db.Request, info *service.CardInfo, profile media.Profile) { + lang := act.lang + info.Fresh = false + req := &db.Request{ + ID: ids.New(), UserID: act.user.ID, ChatID: chat, ChatType: chatType, URL: orig.URL, + SourceMessageID: replyTo, Status: db.RequestReady, Info: info.JSON(), Lang: lang, + } + msg, err := b.send(ctx, chat, replyTo, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "status.preparing", nil), nil) + if err != nil { + return + } + req.CardMessageID = int64(msg.MessageID) + if err := b.store.InsertRequest(ctx, req); err != nil { + b.internalError(ctx, chat, act, err) + return + } + err = b.startFromRequest(ctx, req, info, profile, nil) + var le *service.LimitError + switch { + case err == nil: + case errors.As(err, &le) && le.Upgradable: + b.deleteMessage(ctx, chat, req.CardMessageID) + b.offerUpgrade(ctx, chat, replyTo, lang, req, profile, le, isPrivate(chatType)) + default: + b.showStartError(ctx, req, info, profile, req.CardMessageID, false, err) + } +} + +// showStartError turns a message into the reason a download could not +// start, with the buttons that may help. +func (b *Bot) showStartError(ctx context.Context, req *db.Request, info *service.CardInfo, profile media.Profile, messageID int64, isPhoto bool, err error) { + lang := req.Lang + code := "internal" + var le *service.LimitError + if errors.As(err, &le) { + code = le.Code + } + text := titleLine(info.Title) + "\n" + html.EscapeString(b.startErrorText(lang, err)) + _ = b.edit(ctx, req.ChatID, messageID, isPhoto, text, b.errorKeyboard(lang, req, profile, code)) +} + +// --- buttons under an error ----------------------------------------------------- + +// transientCodes are failures that may well work a moment later. +var transientCodes = map[string]bool{ + string(ytdlp.CodeRateLimited): true, string(ytdlp.CodeSiteBlocked): true, string(ytdlp.CodeNetwork): true, + string(ytdlp.CodeTimeout): true, string(ytdlp.CodeWorkerLost): true, string(ytdlp.CodeInternal): true, + string(ytdlp.CodeUnknown): true, string(ytdlp.CodeProcessing): true, "send_failed": true, +} + +// contentCodes are failures that come from the content itself. +var contentCodes = map[string]bool{ + string(ytdlp.CodePrivate): true, string(ytdlp.CodeLoginRequired): true, string(ytdlp.CodeGeoBlocked): true, + string(ytdlp.CodeUnsupported): true, string(ytdlp.CodeNotFound): true, string(ytdlp.CodeDRM): true, + string(ytdlp.CodeLive): true, service.LimitLive: true, service.LimitBlocked: true, +} + +// errorKeyboard offers the next step after a failure: try again after a +// passing problem, a smaller quality or an upgrade after a limit, the app +// otherwise. req is the request that failed; for a failed lookup its info +// is empty and "Try again" repeats the lookup. +func (b *Bot) errorKeyboard(lang string, req *db.Request, profile media.Profile, code string) *telego.InlineKeyboardMarkup { + if req == nil { + return nil + } + private := isPrivate(req.ChatType) + var row []telego.InlineKeyboardButton + switch { + case transientCodes[code]: + data := cbData(cbRetryLookup, req.ID) + if profile != "" { + data = cbData(cbRetry, req.ID, string(profile)) + } + row = append(row, button(b.tr.T(lang, "btn.try_again", nil), data)) + case code == string(ytdlp.CodeTooLarge) || code == service.LimitTooLarge: + if profile.Kind() == media.KindVideo && profile != media.P480 { + row = append(row, button(b.tr.T(lang, "btn.smaller_quality", nil), cbData(cbFollowQuality, req.ID))) + } + row = append(row, b.upgradeButton(lang, private)...) + case code == string(ytdlp.CodeTooLong) || code == service.LimitTooLong || + code == service.LimitDailyDownloads || code == service.LimitDailyVolume: + row = append(row, b.upgradeButton(lang, private)...) + case contentCodes[code]: + if btn, ok := b.appButton(lang, private, ""); ok { + row = append(row, btn) + } + } + if len(row) == 0 { + return nil + } + return keyboard(row) +} + +// upgradeButton is "Upgrade", when there is something to buy. +func (b *Bot) upgradeButton(lang string, private bool) []telego.InlineKeyboardButton { + if !b.bill.Enabled() { + return nil + } + if !private { + return []telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.upgrade", nil), "https://t.me/"+b.username+"?start=buy")} + } + return []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.upgrade", nil), cbUpgrade)} +} + +// appButton opens the Mini App, at an optional page. In a private chat it +// opens in place; in a group it has to be a link, because web app buttons +// do not work there. +func (b *Bot) appButton(lang string, private bool, page string) (telego.InlineKeyboardButton, bool) { + if !b.cfg.MiniAppEnabled() { + return telego.InlineKeyboardButton{}, false + } + label := b.tr.T(lang, "btn.open_app", nil) + if !private { + return urlButton(label, "https://t.me/"+b.username+"?startapp"), true + } + url := b.cfg.PublicURL + "/app/" + if page != "" { + url += "?page=" + page + } + return telego.InlineKeyboardButton{Text: label, WebApp: &telego.WebAppInfo{URL: url}}, true +} + +// alreadySent answers a link this user got in this chat a moment ago with +// a pointer and a button to send it again. Sending again is a new +// download under the usual limits. +func (b *Bot) alreadySent(ctx context.Context, lr linkRequest) bool { + since := time.Now().Add(-recentWindow).UnixMilli() + recent, err := b.store.RecentSent(ctx, lr.act.user.ID, lr.chatID, since, 20) + if err != nil { + b.log.Error("recent deliveries", "err", err) + return false + } + want := links.Clean(lr.url) + for _, r := range recent { + if links.Clean(r.URL) != want { + continue + } + title := r.Title + if utf8.RuneCountInString(title) == 0 { + title = links.Short(want, 40) + } + kb := keyboard([]telego.InlineKeyboardButton{button(b.tr.T(lr.act.lang, "btn.send_again", nil), cbData(cbResend, r.DeliveryID))}) + _, _ = b.send(ctx, lr.chatID, lr.sourceID, titleLine(title)+"\n"+b.tr.HTML(lr.act.lang, "dup.already_sent", nil), kb) + return true + } + return false +} + +// recentWindow is how long a sent link counts as "already sent". +const recentWindow = 10 * time.Minute diff --git a/internal/bot/result_test.go b/internal/bot/result_test.go new file mode 100644 index 0000000..1f46c5d --- /dev/null +++ b/internal/bot/result_test.go @@ -0,0 +1,221 @@ +package bot + +import ( + "context" + "io" + "log/slog" + "strings" + "sync" + "testing" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/sched" + "github.com/noderunners/dlbot/internal/service" + "github.com/noderunners/dlbot/internal/tg" + "github.com/noderunners/dlbot/locales" +) + +// testBot is a Bot with just enough set up for the pure parts: texts, +// captions, keyboards and the status throttle. +func testBot(t *testing.T, api tg.API) *Bot { + t.Helper() + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + tr, err := i18n.Load(locales.FS, log) + if err != nil { + t.Fatal(err) + } + return &Bot{ + api: api, cfg: config.Default(), tr: tr, log: log, username: "nr_bot", + statuses: map[string]*statusState{}, live: map[string]*liveJob{}, liveTried: map[string]int{}, + statusMinGap: 2500 * time.Millisecond, + } +} + +func info(title, uploader string) *service.CardInfo { + return &service.CardInfo{ + VideoID: "abc123", Title: title, Uploader: uploader, Duration: 75, Site: "instagram.com", + UploadDate: "20250503", HasAudio: true, Thumbnail: "https://img.example.com/t.jpg", + } +} + +func TestCaption(t *testing.T) { + b := testBot(t, nil) + url := "https://www.instagram.com/reel/C1x/?igsh=MWQ1&utm_source=ig_web" + got := b.caption("en", info("Sunset over the bay", "nasa"), url, media.Best) + want := "Sunset over the bay\nnasa · 1:15\n" + + `instagram.com/reel/C1x` + "\nvia @nr_bot" + if got != want { + t.Fatalf("caption =\n%s\nwant\n%s", got, want) + } + + // A generic title becomes the uploader and the date; the uploader is + // then not repeated on the next line. + got = b.caption("en", info("Video by nasa", "nasa"), url, media.Best) + if !strings.HasPrefix(got, "nasa · 3 May 2025\n1:15\n") { + t.Fatalf("generic title caption = %q", got) + } + got = b.caption("nl", info("", "nasa"), url, media.Best) + if !strings.HasPrefix(got, "nasa · 3 mei 2025") { + t.Fatalf("Dutch generic title caption = %q", got) + } + + // Titles from the web cannot inject markup. + got = b.caption("en", info("