diff --git a/.env.example b/.env.example index 9995b05..70a212c 100644 --- a/.env.example +++ b/.env.example @@ -232,6 +232,13 @@ STARS_PRICES=pass_day=50,pass_week=200,pass_month=600,credits_1000=70,credits_50 # do that itself. See docs/AFFILIATE.md. AFFILIATE_ENABLED=false +# --- Inline mode ---------------------------------------------------------------------- +# Answer "@bot " in any chat: the cached file when the user's limits +# allow it, a link into the bot otherwise. Also switch on inline mode +# (/setinline) and inline feedback (/setinlinefeedback, 100%) in @BotFather; +# see docs/OPERATIONS.md. +INLINE_MODE_ENABLED=false + # --- Rate limits ------------------------------------------------------------ # Links per minute. 0 means no limit. RATE_USER_PER_MINUTE=10 diff --git a/README.md b/README.md index 9bc9e47..86eabbd 100644 --- a/README.md +++ b/README.md @@ -9,21 +9,41 @@ and in groups. Written in Go on top of yt-dlp. ## What works today -- Send a link in a private chat and get a card with title, thumbnail, - duration and format buttons: Best, 720p, 480p, MP3, Thumbnail, Cancel. +- Send a link in a private chat and get the file. The first link shows a + card with title, thumbnail, duration and format buttons. After that the + bot starts right away with the best quality that fits the user's limit, + or with the default set in /quality ("Ask every time" brings the card + back). Up to five links per message; a link sent a moment ago gets + "already sent" with a button to send it again. - In groups: `/dl `, or reply `/dl` to a message with a link. Buttons - only work for the person who asked. -- One status message, edited live: queued with position and wait, - downloading with a progress bar, processing, sending, done. + only work for the person who asked. Private chats are never quoted; + groups are. +- One status message per download, edited at most every 2.5 seconds: + downloading with a progress bar (the queue position only when the wait + is worth mentioning), processing, sending. Once the file is in the chat + the status message is deleted, so the file is the only message left. +- The file comes with a clean caption (title, uploader, length, a short + source link without tracking parameters, optionally "via @bot"), a + thumbnail, and buttons for the MP3, another quality, the thumbnail, and + Delete. Errors come with a next step: try again, a smaller quality, + upgrade, or the app. Passing failures are retried once by themselves. - A database backed queue with leases, one automatic retry and cancel. - Free tier limits: size, duration, daily quota, one active job. - Payments in sats over Lightning (LNbits): day, week and month passes, credits, "pay for this file only" and "skip the queue". Paid downloads get higher limits and a priority lane, with one slot always kept for free users. +- Telegram Stars as a second way to pay for passes and credits, with + prices of their own, in the chat and in the Mini App (`STARS_ENABLED`). +- A referral program in sats: random invite codes, a reward once an + invited user's first Lightning purchase settles, and a daily cap. Next + to it, Telegram's own affiliate program for Stars spent in the Mini App + ([docs/AFFILIATE.md](docs/AFFILIATE.md)). +- Inline mode (`INLINE_MODE_ENABLED`): `@bot ` in any chat sends a + cached file when the user's limits allow it, or opens the bot for it. - Money is safe: append-only ledger, idempotent settlement, reconciliation at startup, automatic refunds for failed downloads. -- Gift codes, referral rewards and tips. +- Gift codes and tips. - A smart cache: repeat downloads are instant, two people asking for the same video share one download, lower qualities are made from a stored copy. A cache hit is checked against exactly the same limits as a fresh @@ -95,15 +115,16 @@ curl localhost:8080/healthz | Command | What it does | | --- | --- | -| `/start` | Welcome message | -| `/help` | Usage and your limits | +| `/start` | Welcome message, with a language picker the first time | +| `/help` | A short introduction and your limits, with sections for commands, account and groups | +| `/settings` | Your settings in one place (private chat): format, audio only, ask every time, language, pass, balance, invites, "Add me to a group" | | `/dl ` | Download a video. In groups also works as a reply to a link. | | `/audio ` | Download the audio as MP3 | | `/thumb ` | Send the thumbnail | | `/subs ` | Pick a subtitle language and get the file | | `/info ` | Show formats and sizes without downloading | | `/fresh ` | Download again instead of using a saved copy | -| `/history` | Your past downloads, one tap to get them again | +| `/history` | Your past downloads, five per page: send again, the thumbnail, remove one or clear all | | `/queue` | Your downloads in progress | | `/cancel` | Cancel your downloads | | `/account` | Your pass, balance and usage today (private chat) | @@ -111,10 +132,9 @@ curl localhost:8080/healthz | `/buy` | Buy a pass or credits (private chat) | | `/credits` | Balance and top up (private chat) | | `/redeem ` | Use a gift code (private chat) | -| `/referral` | Your invite link and how many joined (private chat) | +| `/referral` | Your invite link, what it earned, share, copy and QR buttons (private chat) | | `/donate` | Send a tip (private chat) | - -| `/quality` | Your default format, to skip the card | +| `/quality` | Your default format: ask every time, best that fits your limit, a quality, or audio only | | `/language` | Change the bot's language | | `/privacy`, `/terms`, `/support` | Short texts (private chat) | @@ -139,10 +159,10 @@ Owner commands (private chat, only for the IDs in `OWNER_IDS`): | `/workers` | Workers, their state, load, tags and yt-dlp version | | `/drain ` | Let a worker finish its jobs and take no new ones | | `/ytdlp update` | Update yt-dlp on every worker now | -| `/stats`, `/queue all` | Numbers, and every active job | +| `/stats`, `/queue all` | Numbers (revenue by payment method included), and every active job | | `/user `, `/group ` | Look up a user or a group | | `/ban `, `/unban ` | Ban a user | -| `/grant`, `/credit`, `/refund` | Passes, credits and gift codes | +| `/grant`, `/credit`, `/refund` | Passes, credits and gift codes. `/refund ` returns a Stars payment. | | `/blocklist` | Block sites or single videos | | `/broadcast ` | Message every user, after a confirmation | | `/maint on\|off` | Maintenance mode | @@ -219,6 +239,9 @@ change it. A test fails when `dist` is older than its sources. - [docs/WORKERS.md](docs/WORKERS.md): adding download workers, tags, drain. - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): how the pieces fit. - [docs/TRANSLATING.md](docs/TRANSLATING.md): editing a catalog, adding a language. +- [docs/AFFILIATE.md](docs/AFFILIATE.md): opening Telegram's affiliate program for the bot. +- [docs/SCREENS.md](docs/SCREENS.md): every screen of the bot in English, Spanish and Dutch, generated by a test. +- [docs/UPDATE_NOTES.md](docs/UPDATE_NOTES.md): what the latest round of changes found and changed. - [docs/ASSUMPTIONS.md](docs/ASSUMPTIONS.md): decisions and verified facts. ## Layout diff --git a/config.example.toml b/config.example.toml index a336f9c..784c546 100644 --- a/config.example.toml +++ b/config.example.toml @@ -40,6 +40,9 @@ stars_enabled = false # Telegram first, see docs/AFFILIATE.md). affiliate_enabled = false +# Inline mode ("@bot "); also needs /setinline in @BotFather. +inline_mode_enabled = false + [telegram] api_url = "https://api.telegram.org" mode = "polling" # polling or webhook diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1becf8d..7043b79 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -43,6 +43,7 @@ phase; sections for later phases say so. | `internal/billing/lnbits` | LNbits HTTP client. | | `internal/cache` | file_id and stored-copy cache, TTLs, eviction, takedown. | | `internal/ffmpeg` | Transcoding lower profiles from a stored copy. | +| `internal/thumb` | The small JPEG thumbnail uploaded with a video, made from the source's thumbnail image, with no access to private addresses. | | `internal/groups` | Group admin verification with a cache, host list matching. | | `internal/links` | URL extraction, validation, redaction. | | `internal/storage` | `Storage` interface and the local disk backend. | diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index 8e32496..aad3fdf 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -1170,3 +1170,32 @@ the affiliate program. What was found and planned is in - **Checked in a browser.** The Mini App browser test (headless Chromium against a core in test mode) checks the Earn section in English, Spanish and Dutch, and the new referral link format. + +### Phase 6: inline mode and polish + +- **Inline mode is off by default** (`INLINE_MODE_ENABLED`). It also + needs `/setinline` in @BotFather. +- **The cached file.** An inline query with a link looks it up, using + the remembered metadata when there is some, for at most 5 seconds. The + file is picked with the user's default format; "ask every time" counts + as Best. It is offered by `file_id` only when: + - the cache has the file, + - the same admission check as every other path passes on the cached + file's real size and length, and + - nothing has to be paid. A download paid with credits needs the bot + chat, so it gets the deep link. +- **Everything else** gets one article result. Choosing it posts the + cleaned link with a button that opens the bot, and the button above the + results opens the bot too. Both carry `/start il_`, where the + token names the link in the `kv` table, because a link does not fit in + the 64 character start parameter. The bot then runs the usual flow. +- **Counting.** An inline send counts as a download of the day when + Telegram reports it chosen (`chosen_inline_result`), which needs inline + feedback at 100% in @BotFather. Each offered result counts once. + Without inline feedback, inline sends are only offered within the + limits but do not use up the quota; OPERATIONS.md says so. +- Answers are personal (`is_personal`) and cached by Telegram for 10 + seconds, since they depend on the user's limits. +- **Docs.** README and OPERATIONS describe the new flows, Stars, inline + mode and every new setting. `docs/SCREENS.md` is regenerated from the + language test. diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index 92a5839..0c98782 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -176,6 +176,59 @@ opened again. If step 3 is skipped, the button in private chats still works. Only the `?startapp` links from groups and the profile button need it. +With the app on, the bot also sets the **menu button** next to the message +field to open the app. The default label is in the source language; each +private chat gets the label in its user's language the first time they +write, and again when they switch language. The command list stays one +tap away under "/". + +## Telegram Stars + +Stars are a second way to pay for passes and credit packs, next to +Lightning. They need nothing in @BotFather. + +```sh +STARS_ENABLED=true +STARS_PRICES=pass_day=50,pass_week=200,pass_month=600,credits_1000=70,credits_5000=330,credits_20000=1300 +``` + +Prices in Stars are set on their own and are never converted from sats. +A product without a price is not sold for Stars. Lightning stays the first +option on every screen; "Pay with Stars" switches to the Stars prices. +Stars purchases are confirmed by Telegram's `successful_payment` update, +never by polling, and each Telegram charge settles once. + +To refund a Stars payment, send `/refund ` (or the Telegram +charge ID from the log). Telegram returns the Stars, and the credits or the +pass are taken back. `/stats` shows revenue per payment method. + +Stars and Telegram's affiliate program: see [AFFILIATE.md](AFFILIATE.md). + +## Inline mode + +`@bot ` in any chat. When the file is in the cache and the user's +limits allow it without paying, it is sent as is; otherwise the result +opens the bot, which downloads it the usual way. + +1. In @BotFather: `/setinline`, pick the bot, enter a placeholder such as + "Paste a link". +2. In @BotFather: `/setinlinefeedback`, pick the bot, **100%**. Telegram + then reports which result was sent, and an inline send counts as a + download of the day. Without it, inline sends are still only offered + within the limits, but they do not count against the daily quota. +3. Set `INLINE_MODE_ENABLED=true` and restart. + +## Referrals and flow settings + +| Setting | Default | What it does | +| --- | --- | --- | +| `QUEUE_NOTICE_THRESHOLD_SECONDS` | 10 | Show the queue position only above this wait, or with somebody ahead | +| `MULTI_LINK_MAX` | 5 | Links of one message that are handled | +| `CAPTION_ATTRIBUTION` | true | A "via @bot" line under file captions | +| `REFERRAL_REWARD_SATS` | 200 | Sats an inviter earns when an invited user's first Lightning purchase settles (old name `REFERRAL_REWARD` still works) | +| `REFERRAL_DAILY_CAP` | 2000 | Most an inviter earns per day; more waits for the next day. 0 means no cap. | +| `AFFILIATE_ENABLED` | false | Explain Telegram's affiliate program in the Mini App | + ## Languages, menus and the bot's profile At every start the core publishes its command menus in every language it @@ -230,7 +283,7 @@ Only in a private chat, only for the user IDs in `OWNER_IDS`. | `/cache` | Cache size, hit rate, volume saved | | `/purge ` | Take a video down: delete its files and block it for good | | `/blocklist add site ` | Refuse a whole site. Also `add key `, `remove`, and no argument to list. | -| `/stats` | Users, jobs, queue, cache, payments, and whether the ledger and balances agree | +| `/stats` | Users, jobs, queue, cache, payments, revenue per payment method, and whether the ledger and balances agree | | `/queue all` | Every queued and running job with its worker and tags | | `/user `, `/group ` | Look one up | | `/ban `, `/unban ` | A banned user gets no answers | @@ -238,6 +291,7 @@ Only in a private chat, only for the user IDs in `OWNER_IDS`. | `/grant code credits [uses]` | Create a gift code. Also `code day\|week\|month`. | | `/credit ` | Add credits | | `/refund `, `/refund pass ` | Give sats back, or extend a pass | +| `/refund ` | Return a Stars payment and take back what it granted | | `/broadcast ` | Preview, then send to everyone on confirmation | | `/maint on\|off` | Refuse new downloads for everyone but owners | | `/reload i18n` | Reload translations from `LOCALES_DIR` | diff --git a/docs/SCREENS.md b/docs/SCREENS.md index b251b6a..8113e45 100644 --- a/docs/SCREENS.md +++ b/docs/SCREENS.md @@ -145,6 +145,14 @@ Downloading… editMessageText +``` +Test Video +Sending it to Telegram… +[Cancel] +``` + +editMessageText + ``` Test Video Sending it to Telegram… @@ -354,7 +362,7 @@ editMessageText Share your link. When somebody you invited pays for a first purchase in sats (Lightning), you get 200 sats in credits. -https://t.me/nr_dl_test_bot?start=rf_YY6OJU6T +https://t.me/nr_dl_test_bot?start=rf_QY6RIIO4 Invited: 0 · Bought something: 0 Earned: 0 sats · Waiting: 0 sats @@ -567,7 +575,7 @@ sendMessage Share your link. When somebody you invited pays for a first purchase in sats (Lightning), you get 200 sats in credits. -https://t.me/nr_dl_test_bot?start=rf_YY6OJU6T +https://t.me/nr_dl_test_bot?start=rf_QY6RIIO4 Invited: 0 · Bought something: 0 Earned: 0 sats · Waiting: 0 sats @@ -865,7 +873,7 @@ sendPhoto ``` Day pass · 700 sats -lnbc7000n1fakee38a3d34236055a47c726ecb0a1c30d15a717a59fccef6acb0cff8dcb7dc200f +lnbc7000n1fake1f8874acf5beade88ce311a2ad90ee98ca4d002223ea4dc5b52cf9633bb128f1 Scan the code or tap the invoice to copy it. Valid for 10 minutes. [Open in wallet] @@ -1257,7 +1265,7 @@ editMessageText Comparte tu enlace. Cuando alguien que invitaste pague una primera compra en sats (Lightning), recibes 200 sats en créditos. -https://t.me/nr_dl_test_bot?start=rf_Q3U2NIQH +https://t.me/nr_dl_test_bot?start=rf_5NFHSMPX Invitados: 0 · Compraron algo: 0 Ganado: 0 sats · En espera: 0 sats @@ -1470,7 +1478,7 @@ sendMessage Comparte tu enlace. Cuando alguien que invitaste pague una primera compra en sats (Lightning), recibes 200 sats en créditos. -https://t.me/nr_dl_test_bot?start=rf_Q3U2NIQH +https://t.me/nr_dl_test_bot?start=rf_5NFHSMPX Invitados: 0 · Compraron algo: 0 Ganado: 0 sats · En espera: 0 sats @@ -1768,7 +1776,7 @@ sendPhoto ``` Pase de un día · 700 sats -lnbc7000n1fake7bf3f553278730f9f02e2e8e66bb1524a1efc083ab3bfe31c83c00e15d64e033 +lnbc7000n1fake98f92f6fc418f27ce78a3b0d003099e8ed16dd676184d3f10c43d66624527b10 Escanea el código o toca la factura para copiarla. Vale por 10 minutos. [Abrir en la billetera] @@ -1881,7 +1889,7 @@ editMessageText ``` Test Video -Naar Telegram sturen… +Downloaden… [Annuleren] ``` @@ -1889,7 +1897,7 @@ editMessageText ``` Test Video -Downloaden… +Naar Telegram sturen… [Annuleren] ``` @@ -2160,7 +2168,7 @@ editMessageText Deel je link. Als iemand die je uitnodigde een eerste aankoop in sats (Lightning) betaalt, krijg jij 200 sats aan tegoed. -https://t.me/nr_dl_test_bot?start=rf_TXUCNI2E +https://t.me/nr_dl_test_bot?start=rf_I4ADMUUF Uitgenodigd: 0 · Iets gekocht: 0 Verdiend: 0 sats · Wacht nog: 0 sats @@ -2373,7 +2381,7 @@ sendMessage Deel je link. Als iemand die je uitnodigde een eerste aankoop in sats (Lightning) betaalt, krijg jij 200 sats aan tegoed. -https://t.me/nr_dl_test_bot?start=rf_TXUCNI2E +https://t.me/nr_dl_test_bot?start=rf_I4ADMUUF Uitgenodigd: 0 · Iets gekocht: 0 Verdiend: 0 sats · Wacht nog: 0 sats @@ -2671,7 +2679,7 @@ sendPhoto ``` Dagpas · 700 sats -lnbc7000n1fake5443af8ff471a30e71eaa1ee0db07d5d314f447f88f895369ea8892d717b5879 +lnbc7000n1fakebd6d73f6fb17f69e4afb76c52ffb1d278cc127bc403371b1bafbcd7b580e457b Scan de code of tik op de factuur om hem te kopiëren. Geldig voor 10 minuten. [Openen in wallet] diff --git a/internal/app/app.go b/internal/app/app.go index dd6134a..268d106 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -371,7 +371,7 @@ func New(ctx context.Context, opts Options) (*App, error) { } // allowedUpdates is the list of update types the bot asks Telegram for. -var allowedUpdates = []string{"message", "callback_query", "my_chat_member", "widget_query", "pre_checkout_query"} +var allowedUpdates = []string{"message", "callback_query", "my_chat_member", "widget_query", "pre_checkout_query", "inline_query", "chosen_inline_result"} // Run starts every loop and blocks until ctx ends. Shutdown is ordered: // updates stop first, then the worker hands back its jobs, then the diff --git a/internal/app/inline_test.go b/internal/app/inline_test.go new file mode 100644 index 0000000..32ce5b1 --- /dev/null +++ b/internal/app/inline_test.go @@ -0,0 +1,123 @@ +package app_test + +import ( + "encoding/json" + "strings" + "testing" + "time" + + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/tg/fakeserver" +) + +type inlineAnswer struct { + Results []struct { + Type string `json:"type"` + ID string `json:"id"` + VideoFileID string `json:"video_file_id"` + Caption string `json:"caption"` + ReplyMarkup struct { + Rows [][]struct { + URL string `json:"url"` + } `json:"inline_keyboard"` + } `json:"reply_markup"` + } + Button struct { + Text string `json:"text"` + StartParameter string `json:"start_parameter"` + } + Personal bool +} + +func (h *harness) inline(user int64, query string) inlineAnswer { + h.t.Helper() + seq := h.srv.Seq() + id := h.srv.PushInlineQuery(user, query) + c := h.wait(seq, "answerInlineQuery", func(c fakeserver.Call) bool { return c.Params["inline_query_id"] == id }) + var a inlineAnswer + if err := json.Unmarshal([]byte(c.Params["results"]), &a.Results); err != nil { + h.t.Fatalf("results: %v (%s)", err, c.Params["results"]) + } + _ = json.Unmarshal([]byte(c.Params["button"]), &a.Button) + a.Personal = c.Params["is_personal"] == "true" + return a +} + +func TestInlineModeSendsCachedFilesWithinLimits(t *testing.T) { + h := start(t, nil, func(c *config.Config) { + c.InlineModeEnabled = true + c.Limits.Free.DailyDownloads = 1 + }) + h.fetch(alice, link) // the file is now in the cache + entry := h.entry(link, "best") + + // Bob gets the cached file itself, by file_id, with the usual caption. + a := h.inline(bob, link) + if len(a.Results) != 1 || a.Results[0].Type != "video" || a.Results[0].VideoFileID != entry.TgFileID || !a.Personal { + t.Fatalf("answer = %+v, want the cached video %q", a, entry.TgFileID) + } + if !strings.Contains(a.Results[0].Caption, "Test Video") { + t.Fatalf("caption = %q", a.Results[0].Caption) + } + if n := len(h.fake.Downloads()); n != 1 { + t.Fatalf("an inline answer downloaded (%d downloads)", n) + } + // Sending it counts as his download of the day. + h.srv.PushChosenInlineResult(bob, a.Results[0].ID, link) + waitFor(t, func() bool { return h.usage(bob).Downloads == 1 }) + // The same result reported twice counts once. + h.srv.PushChosenInlineResult(bob, a.Results[0].ID, link) + + // His one download is used up: no file, a way into the bot instead. + a = h.inline(bob, link) + if len(a.Results) != 1 || a.Results[0].Type != "article" { + t.Fatalf("over the limit: %+v", a) + } + if u := h.usage(bob); u.Downloads != 1 { + t.Fatalf("usage = %+v", u) + } +} + +func TestInlineModeOpensTheBotForWhatIsNotCached(t *testing.T) { + h := start(t, nil, func(c *config.Config) { c.InlineModeEnabled = true }) + a := h.inline(carol, "look https://example.com/new?utm_source=x") + if len(a.Results) != 1 || a.Results[0].Type != "article" || !strings.HasPrefix(a.Button.StartParameter, "il_") { + t.Fatalf("answer = %+v", a) + } + open := a.Results[0].ReplyMarkup.Rows[0][0].URL + if open != "https://t.me/"+fakeserver.BotUsername+"?start="+a.Button.StartParameter || len(a.Button.StartParameter) > 64 { + t.Fatalf("deep link %q, start parameter %q", open, a.Button.StartParameter) + } + // Opening the bot with it runs the usual flow for the link. + seq := h.srv.Seq() + h.srv.PushMessage(carol, carol, "/start "+a.Button.StartParameter) + h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok && c.ChatID() == carol }) + + // Not a link: a button that explains inline mode in the bot. + if a := h.inline(carol, "cats"); len(a.Results) != 0 || a.Button.StartParameter != "inline" { + t.Fatalf("no link: %+v", a) + } + seq = h.srv.Seq() + h.srv.PushMessage(carol, carol, "/start inline") + h.wait(seq, "sendMessage", textHas("@"+fakeserver.BotUsername)) +} + +func TestInlineModeIsOffByDefault(t *testing.T) { + h := start(t, nil, nil) + h.fetch(alice, link) + if a := h.inline(bob, link); len(a.Results) != 0 { + t.Fatalf("inline mode answered while off: %+v", a) + } +} + +// waitFor polls a condition for a few seconds. +func waitFor(t *testing.T, cond func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatal("condition not met in time") + } + time.Sleep(20 * time.Millisecond) + } +} diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 738ef01..c7d380f 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -103,6 +103,8 @@ 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 + // inlineChoices are cached files offered inline, by result token. + inlineChoices map[string]inlineChoice // menuButtons is the language each private chat's menu button was // last labelled in. menuButtons map[int64]string @@ -164,6 +166,7 @@ func New(ctx context.Context, d Deps) (*Bot, error) { cancelledAt: map[int64]time.Time{}, broadcasts: map[string]string{}, menuButtons: map[int64]string{}, + inlineChoices: map[string]inlineChoice{}, reloadI18n: d.ReloadI18n, broadcastGap: 50 * time.Millisecond, admins: d.Admins, @@ -304,6 +307,10 @@ func updateChatID(u telego.Update) int64 { return u.MyChatMember.Chat.ID case u.PreCheckoutQuery != nil: return u.PreCheckoutQuery.From.ID + case u.InlineQuery != nil: + return u.InlineQuery.From.ID + case u.ChosenInlineResult != nil: + return u.ChosenInlineResult.From.ID case u.WidgetQuery != nil: if u.WidgetQuery.Chat != nil { return u.WidgetQuery.Chat.ID @@ -336,6 +343,10 @@ func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) { b.handleWidgetQuery(ctx, u.WidgetQuery) case u.PreCheckoutQuery != nil: b.handlePreCheckout(ctx, u.PreCheckoutQuery) + case u.InlineQuery != nil: + b.handleInlineQuery(ctx, u.InlineQuery) + case u.ChosenInlineResult != nil: + b.handleChosenInlineResult(ctx, u.ChosenInlineResult) } } @@ -353,6 +364,8 @@ func updateUser(u telego.Update) (*telego.User, *telego.Chat) { return &u.CallbackQuery.From, nil case u.PreCheckoutQuery != nil: return &u.PreCheckoutQuery.From, nil + case u.InlineQuery != nil: + return &u.InlineQuery.From, nil } return nil, nil } @@ -369,6 +382,10 @@ func updateType(u telego.Update) string { return "widget_query" case u.PreCheckoutQuery != nil: return "pre_checkout_query" + case u.InlineQuery != nil: + return "inline_query" + case u.ChosenInlineResult != nil: + return "chosen_inline_result" } return "other" } diff --git a/internal/bot/commands.go b/internal/bot/commands.go index 21e6540..9ea8843 100644 --- a/internal/bot/commands.go +++ b/internal/bot/commands.go @@ -313,6 +313,12 @@ func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) { case payload == "buy": b.showBuy(ctx, m.Chat.ID, act) return + case strings.HasPrefix(payload, inlineStartPrefix): + b.startInlineLink(ctx, m, act, strings.TrimPrefix(payload, inlineStartPrefix)) + return + case payload == "inline": + b.inlineHint(ctx, m.Chat.ID, act.lang) + return default: b.applyReferral(ctx, act, payload) } diff --git a/internal/bot/inline.go b/internal/bot/inline.go new file mode 100644 index 0000000..4320182 --- /dev/null +++ b/internal/bot/inline.go @@ -0,0 +1,236 @@ +package bot + +import ( + "context" + "crypto/rand" + "encoding/base32" + "strings" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/cache" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/links" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/service" +) + +// Inline mode: typing "@bot " in any chat. A file that is in the +// cache, and that the user's limits allow without paying, comes back as +// the file itself (by file_id). Anything else comes back as one result +// that opens the bot with a /start payload for the link, where the usual +// flow takes over. Inline mode must also be switched on in @BotFather. +// +// A file sent inline counts against the daily limits when Telegram says +// it was chosen (chosen_inline_result, which needs inline feedback on in +// @BotFather). Without that, a result is only offered when it is within +// the limits. + +// inlineStartPrefix starts the /start payload of an inline deep link: +// il_, where the token names the link in the kv table. +const inlineStartPrefix = "il_" + +// inlineProbeTimeout bounds a lookup while Telegram waits for the answer. +const inlineProbeTimeout = 5 * time.Second + +// inlineChoice is a cached file offered inline, kept until it is chosen. +type inlineChoice struct { + userID int64 + size int64 + at time.Time +} + +func inlineToken() string { + var b [8]byte + _, _ = rand.Read(b[:]) + return strings.ToLower(strings.TrimRight(base32.StdEncoding.EncodeToString(b[:]), "=")) +} + +// handleInlineQuery answers "@bot ". +func (b *Bot) handleInlineQuery(ctx context.Context, q *telego.InlineQuery) { + act, ok := actorFrom(ctx) + if !b.cfg.InlineModeEnabled || !ok || act.user.Banned { + b.answerInline(ctx, q, nil, nil) + return + } + lang := act.lang + urls := links.Extract(q.Query, nil) + if len(urls) == 0 { + // Not a link (yet): a button that explains itself in the bot. + b.answerInline(ctx, q, nil, &telego.InlineQueryResultsButton{ + Text: b.tr.T(lang, "inline.paste_link", nil), StartParameter: "inline", + }) + return + } + url := urls[0] + if !b.rate.allow("u:"+itoa(act.user.ID), b.cfg.Rate.UserPerMinute, time.Minute) { + b.answerInline(ctx, q, nil, nil) + return + } + if r := b.inlineCached(ctx, act, url); r != nil { + b.answerInline(ctx, q, []telego.InlineQueryResult{r}, nil) + return + } + results, button := b.inlineDeepLink(ctx, lang, url) + b.answerInline(ctx, q, results, button) +} + +// inlineCached returns the cached file for a link as an inline result, or +// nil when there is none, or the user's limits do not allow it without +// paying. +func (b *Bot) inlineCached(ctx context.Context, act actor, url string) telego.InlineQueryResult { + pctx, cancel := context.WithTimeout(ctx, inlineProbeTimeout) + defer cancel() + probed, err := b.svc.ProbeAny(pctx, url) + if err != nil || probed.Info == nil { + return nil + } + info := probed.Info + who := service.Who{UserID: act.user.ID, ChatID: act.user.ID, ChatType: telego.ChatTypePrivate} + dec, err := b.svc.Entitlement(ctx, who, false) + if err != nil || dec.Charge > 0 { + return nil // paying needs the bot chat + } + profile := b.inlineProfile(act, info, dec.Limits.MaxSize) + ext, vid := cache.Canonical(info.Extractor, info.VideoID, url) + e, err := b.cache.Lookup(ctx, ext, vid, profile) + if err != nil || e == nil || e.TgFileID == "" || e.Private { + return nil + } + // The same rules as every other path, on what the cache holds. + known := *info + known.Sizes = map[string]int64{string(profile): e.Size} + if e.Duration > 0 { + known.Duration = e.Duration + } + if err := b.svc.Preview(ctx, who, url, &known, profile); err != nil { + return nil + } + token := inlineToken() + b.statusMu.Lock() + for k, c := range b.inlineChoices { + if time.Since(c.at) > time.Hour { + delete(b.inlineChoices, k) + } + } + b.inlineChoices[token] = inlineChoice{userID: act.user.ID, size: e.Size, at: time.Now()} + b.statusMu.Unlock() + + id := "c_" + token + caption := clip(b.caption(act.lang, info, url, profile), 1024) + title, _ := b.displayTitle(act.lang, info) + title = shorten(title, 60) + desc := b.profileLabel(act.lang, profile) + if e.Size > 0 { + desc += " · " + b.tr.Size(act.lang, e.Size) + } + switch profile.Kind() { + case media.KindAudio: + return &telego.InlineQueryResultCachedAudio{Type: telego.ResultTypeAudio, ID: id, AudioFileID: e.TgFileID, + Caption: caption, ParseMode: telego.ModeHTML} + case media.KindVideo: + if streamable(e.FileExt) || e.FileExt == "" { + return &telego.InlineQueryResultCachedVideo{Type: telego.ResultTypeVideo, ID: id, VideoFileID: e.TgFileID, + Title: title, Description: desc, Caption: caption, ParseMode: telego.ModeHTML} + } + } + return &telego.InlineQueryResultCachedDocument{Type: telego.ResultTypeDocument, ID: id, DocumentFileID: e.TgFileID, + Title: title, Description: desc, Caption: caption, ParseMode: telego.ModeHTML} +} + +// inlineProfile is the format an inline request means: the user's default, +// with "ask every time" read as Best. +func (b *Bot) inlineProfile(act actor, info *service.CardInfo, maxSize int64) media.Profile { + switch q := act.user.Quality; q { + case qualityUnset, qualityFit: + p, _ := service.BestFit(info, min64(maxSize, b.cfg.MaxUploadBytes())) + return p + case qualityAsk: + return media.Best + default: + if p, err := media.Parse(q); err == nil { + return p + } + } + return media.Best +} + +// inlineDeepLink is the one result for a link that is not ready to send +// inline: choosing it posts the link with a button that opens the bot, +// and the button above the results opens the bot directly. Both carry a +// /start payload that names the link. +func (b *Bot) inlineDeepLink(ctx context.Context, lang, url string) ([]telego.InlineQueryResult, *telego.InlineQueryResultsButton) { + token := inlineToken() + if err := b.store.SetKV(ctx, "inline:"+token, url); err != nil { + b.log.Error("remember inline link", "err", err) + return nil, nil + } + start := inlineStartPrefix + token + open := "https://t.me/" + b.username + "?start=" + start + clean := links.Clean(url) + result := &telego.InlineQueryResultArticle{ + Type: telego.ResultTypeArticle, ID: "d_" + token, + Title: b.tr.T(lang, "inline.download_title", nil), + Description: links.Short(clean, 60), + InputMessageContent: &telego.InputTextMessageContent{ + MessageText: clean, LinkPreviewOptions: noPreview, + }, + ReplyMarkup: keyboard([]telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "inline.open_bot", nil), open)}), + } + return []telego.InlineQueryResult{result}, &telego.InlineQueryResultsButton{ + Text: b.tr.T(lang, "inline.open_bot", nil), StartParameter: start, + } +} + +func (b *Bot) answerInline(ctx context.Context, q *telego.InlineQuery, results []telego.InlineQueryResult, button *telego.InlineQueryResultsButton) { + if results == nil { + results = []telego.InlineQueryResult{} + } + err := b.api.AnswerInlineQuery(ctx, &telego.AnswerInlineQueryParams{ + InlineQueryID: q.ID, Results: results, Button: button, + // Answers depend on the user's limits, so they are not shared. + IsPersonal: true, CacheTime: 10, + }) + if err != nil { + b.log.Debug("answerInlineQuery failed", "err", err) + } +} + +// handleChosenInlineResult counts a cached file that was sent inline as a +// download of the user who sent it, once. +func (b *Bot) handleChosenInlineResult(ctx context.Context, r *telego.ChosenInlineResult) { + token, ok := strings.CutPrefix(r.ResultID, "c_") + if !ok { + return + } + b.statusMu.Lock() + c, found := b.inlineChoices[token] + delete(b.inlineChoices, token) + b.statusMu.Unlock() + if !found || c.userID != r.From.ID { + return + } + if err := b.store.AddUsage(ctx, c.userID, service.Day(time.Now()), 1, c.size); err != nil { + b.log.Error("count inline download", "user_id", c.userID, "err", err) + } + b.metrics.Delivered("inline") +} + +// startInlineLink handles /start il_: the link from an inline +// query, downloaded in the private chat like a pasted link. +func (b *Bot) startInlineLink(ctx context.Context, m *telego.Message, act actor, token string) { + url, err := b.store.GetKV(ctx, "inline:"+token) + if err != nil || url == "" { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "notice.expired", nil), nil) + return + } + b.startLink(ctx, linkRequest{ + chatID: m.Chat.ID, chatType: m.Chat.Type, act: act, url: url, preset: presetFor(act, nil), + }) +} + +// inlineHint is the welcome for "/start inline": how inline mode works. +func (b *Bot) inlineHint(ctx context.Context, chat int64, lang string) { + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "inline.hint", i18n.Args{"Bot": b.username}), nil) +} diff --git a/internal/config/config.go b/internal/config/config.go index dc926ca..1ebf29f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -128,6 +128,11 @@ type Config struct { // Telegram). Turn it on once the program is set up for the bot, see // docs/AFFILIATE.md. AffiliateEnabled bool `toml:"affiliate_enabled" env:"AFFILIATE_ENABLED"` + // InlineModeEnabled answers "@bot " in any chat: the cached file + // when the user's limits allow it, a link into the bot otherwise. Inline + // mode must also be switched on in @BotFather (/setinline), and inline + // feedback (/setinlinefeedback) for inline sends to count as downloads. + InlineModeEnabled bool `toml:"inline_mode_enabled" env:"INLINE_MODE_ENABLED"` } // StarsPrice returns the price in Stars of a product, or false when it diff --git a/internal/tg/api.go b/internal/tg/api.go index 19cfd09..4000bd3 100644 --- a/internal/tg/api.go +++ b/internal/tg/api.go @@ -41,6 +41,7 @@ type API interface { CreateInvoiceLink(ctx context.Context, params *telego.CreateInvoiceLinkParams) (*string, error) AnswerPreCheckoutQuery(ctx context.Context, params *telego.AnswerPreCheckoutQueryParams) error RefundStarPayment(ctx context.Context, params *telego.RefundStarPaymentParams) error + AnswerInlineQuery(ctx context.Context, params *telego.AnswerInlineQueryParams) error } var _ API = (*telego.Bot)(nil) diff --git a/internal/tg/fakeserver/server.go b/internal/tg/fakeserver/server.go index f2a51b6..cd8673a 100644 --- a/internal/tg/fakeserver/server.go +++ b/internal/tg/fakeserver/server.go @@ -399,6 +399,33 @@ func (s *Server) pushPaymentLocked(userID int64, field string, body map[string]a }}) } +// PushInlineQuery queues "@bot " typed by a user, and returns the +// query ID. +func (s *Server) PushInlineQuery(userID int64, query string) string { + s.mu.Lock() + defer s.mu.Unlock() + id := fmt.Sprintf("iq%d", s.updateID+1) + s.pushLocked(map[string]any{"inline_query": map[string]any{ + "id": id, + "from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": s.userLang(userID)}, + "query": query, + "offset": "", + }}) + return id +} + +// PushChosenInlineResult queues the report that a user sent an inline +// result (inline feedback). +func (s *Server) PushChosenInlineResult(userID int64, resultID, query string) { + s.mu.Lock() + defer s.mu.Unlock() + s.pushLocked(map[string]any{"chosen_inline_result": map[string]any{ + "result_id": resultID, + "from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": s.userLang(userID)}, + "query": query, + }}) +} + // PushRaw queues an arbitrary update body, for example my_chat_member. func (s *Server) PushRaw(update map[string]any) { s.mu.Lock() diff --git a/locales/en.toml b/locales/en.toml index 80b7da2..c78b3a8 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -970,3 +970,11 @@ other = "Lightning: {{.Amount}} from {{.Count}} purchases" [owner.revenue_stars] one = "Stars: {{.Amount}} from {{.Count}} purchase, {{.Refunded}} refunded" other = "Stars: {{.Amount}} from {{.Count}} purchases, {{.Refunded}} refunded" + +[inline] +hint = """ +Send files in any chat +Type @{{.Bot}} and a link in any chat. When I already have the file and your limits allow it, it goes right into that chat. Otherwise I open here and download it for you.""" +open_bot = "Download in the bot" +download_title = "Download it in the bot" +paste_link = "Paste a link to send the file" diff --git a/locales/es.toml b/locales/es.toml index 8308bae..7f2b1fe 100644 --- a/locales/es.toml +++ b/locales/es.toml @@ -943,3 +943,11 @@ other = "Lightning: {{.Amount}} de {{.Count}} compras" [owner.revenue_stars] one = "Estrellas: {{.Amount}} de {{.Count}} compra, {{.Refunded}} devueltas" other = "Estrellas: {{.Amount}} de {{.Count}} compras, {{.Refunded}} devueltas" + +[inline] +hint = """ +Envía archivos en cualquier chat +Escribe @{{.Bot}} y un enlace en cualquier chat. Si ya tengo el archivo y tus límites lo permiten, va directo a ese chat. Si no, me abro aquí y te lo descargo.""" +open_bot = "Descargar en el bot" +download_title = "Descargarlo en el bot" +paste_link = "Pega un enlace para enviar el archivo" diff --git a/locales/nl.toml b/locales/nl.toml index 48eec18..bbef95e 100644 --- a/locales/nl.toml +++ b/locales/nl.toml @@ -942,3 +942,11 @@ other = "Lightning: {{.Amount}} uit {{.Count}} aankopen" [owner.revenue_stars] one = "Stars: {{.Amount}} uit {{.Count}} aankoop, {{.Refunded}} terugbetaald" other = "Stars: {{.Amount}} uit {{.Count}} aankopen, {{.Refunded}} terugbetaald" + +[inline] +hint = """ +Bestanden sturen in elke chat +Typ @{{.Bot}} en een link in een willekeurige chat. Heb ik het bestand al en laten je limieten het toe, dan gaat het meteen die chat in. Anders open ik hier en download ik het voor je.""" +open_bot = "Downloaden in de bot" +download_title = "Download het in de bot" +paste_link = "Plak een link om het bestand te sturen"