diff --git a/.env.example b/.env.example index 5b7c0e9..b0f5176 100644 --- a/.env.example +++ b/.env.example @@ -27,6 +27,12 @@ OWNER_IDS= # without it (invoices are then settled by polling only). PUBLIC_URL= +# Where /support sends users: a @username or a link. +SUPPORT_CONTACT= +# Load translations from this directory instead of the built-in ones, and +# let "/reload i18n" pick up edits. +LOCALES_DIR= + # --- HTTP ------------------------------------------------------------------- # Listen address of the health endpoint and the webhook. HTTP_LISTEN=:8080 diff --git a/README.md b/README.md index 9e4cd8b..6d5b511 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ A Telegram bot that downloads video and audio from links, in private chats and in groups. Written in Go on top of yt-dlp. -> Status: Phase 4 of 8 (core bot, payments, cache, scale-out). Group -> settings, the Mini App and more languages follow. See +> Status: Phase 5 of 8 (core bot, payments, cache, scale-out, groups). +> The Mini App and more languages follow. See > [docs/ASSUMPTIONS.md](docs/ASSUMPTIONS.md) for the decisions made so far. ## What works today @@ -33,6 +33,9 @@ and in groups. Written in Go on top of yt-dlp. ports, per-worker revocable tokens, tags to route sites to the right network, drain, automatic requeue when a worker dies. - SQLite or Postgres, local disk or S3, chosen by configuration. +- Groups: a group wallet and group pass, spending rules, admin-only + settings with inline toggles, allowed and blocked sites, optional link + detection, per-member usage. - Friendly, translated error messages. Raw tool output stays in the logs. ## Quick start with docker compose @@ -95,6 +98,22 @@ curl localhost:8080/healthz | `/referral` | Your invite link and how many joined (private chat) | | `/donate` | Send a tip (private chat) | +| `/quality` | Your default format, to skip the card | +| `/language` | Change the bot's language | +| `/privacy`, `/terms`, `/support` | Short texts (private chat) | + +In groups: + +| Command | Who | What it does | +| --- | --- | --- | +| `/groupwallet`, `/grouppass` | anyone | Group balance and pass, with a link to top up | +| `/settings` | admins | Quick switches | +| `/grouplang ` | admins | Language of the bot in the group | +| `/autodetect on\|off` | admins | Fetch pasted links without a command | +| `/allow `, `/block ` | admins | Site lists | +| `/spending ` | admins | Who may spend group credits | +| `/groupstats` | admins | Usage by member, last 7 days | + Owner commands (private chat, only for the IDs in `OWNER_IDS`): | Command | What it does | @@ -104,6 +123,14 @@ 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 | +| `/user `, `/group ` | Look up a user or a group | +| `/ban `, `/unban ` | Ban a user | +| `/grant`, `/credit`, `/refund` | Passes, credits and gift codes | +| `/blocklist` | Block sites or single videos | +| `/broadcast ` | Message every user, after a confirmation | +| `/maint on\|off` | Maintenance mode | +| `/reload i18n` | Reload translations from `LOCALES_DIR` | ### Turning on payments diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f8b9a1d..62633ff 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/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. | | `internal/db` | Schema migrations and queries for SQLite and Postgres. | @@ -329,6 +330,27 @@ when over budget (least recently and least often used first, keeping their `file_id`), and removes stored files that no live job and no cache entry references. +## Groups + +A group has a row in `groups`, optional `group_settings`, and a wallet of +its own (`wallets.owner_type = 'group'`). `group_usage_daily` counts what +each member used per day; it backs the spending caps and the +usage-by-member view. + +For a request from a group, `service.entitle` loads the group's settings +and wallet, asks `groups.Admins` whether the requester is an admin, works +out whether this requester may spend group credits right now (rule, +per-person cap, group daily cap), and hands all of it to the resolver as +plain data. The resolver stays pure. + +`service.gate` then applies what is not about money: maintenance mode, +whether the bot is on in the group, who may use it, and the site lists. +It runs before a link is even looked up, and again when a download starts. + +Admin-only actions are checked in one place each: `requireAdmin` for +commands and `cbSetting` for buttons, both through `groups.Admins`, which +asks Telegram and caches the answer. + ## Internationalization Handlers never contain user-facing text. They call `i18n.Bundle` with a diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index dccc10a..55b61a8 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -452,3 +452,67 @@ Read from the LNbits source at `v0.12.12` (the target) and `v1.7.1` (current). - Each worker updates its own yt-dlp on a schedule (`yt-dlp -U`). `/ytdlp update` is delivered to workers with their next claim, so it reaches every connected worker within seconds. + +## Phase 5 + +### Groups + +- **Groups are recorded** from `my_chat_member` updates, and also the first + time a command is used in one, in case that update was missed. +- **Admin rights come from Telegram only** (`getChatMember`), cached for + five minutes per group and user. A change of admins can therefore take up + to five minutes to reach the bot. The cache for a group is dropped when + the bot's own status in it changes. +- **Anonymous admins are not supported for commands.** A message sent "as + the group" carries no user to verify. Buttons work, because a button + press always carries the real user. +- **The settings panel is visible to every member**, so each button press + is checked again. A member who presses gets a notice and nothing changes. +- **A switched-off bot is silent in that group**, except for `/settings` + from an admin, which is how it is switched on again. +- **"Pass holders"** means: the requester has a pass of their own, or the + group has one, or they are an admin. +- **Spending rule "capped"** counts group credits a member spent today + (UTC). The first time it is chosen in the quick settings the cap defaults + to four downloads' worth. +- **Site lists** match a host and its subdomains. With an empty allow list + every site is allowed. At most 50 entries per list. +- **Group size and duration caps** can only lower what the group's pass or + credits allow, and only apply when the group pays. They are set from the + Mini App (Phase 6), not from a command. +- **Group language** overrides each member's language for everything the + bot says in that group. +- **Default quality** (group or personal) skips the card and starts that + format at once. +- **"Delete command messages"** needs the bot to be an admin with the right + to delete. Without it the delete fails quietly. +- **Auto-detect** takes the first link of a message. It needs the bot to + see ordinary messages (admin, or group privacy off), which the bot says + when the setting is turned on. + +### Paying for a group + +- **Anyone can pay into a group wallet.** What is bought belongs to the + group. Invoices only ever appear in the payer's private chat; the group + shows deep links (`?start=gw_`) with the group pre-selected. +- A purchase for a group does not auto-start the download that was refused. + The requester presses the format button again. +- Refunds for downloads paid with group credits go back to the group. + +### Owner tools + +- Owner commands exist only in a private chat with a configured owner. For + everyone else, and for owners in groups, they are unknown commands. +- `/grant ` and `/credit`, `/refund` take a user ID, + or a negative chat ID for a group. `/refund pass ` extends + a running pass. +- `/grant code ...` creates gift codes. +- `/broadcast` shows a preview and sends only after the owner presses the + confirm button. It goes to every user who is not banned, about 20 + messages per second. +- `/maint on` refuses new downloads for everyone but owners. Running jobs + finish. +- `/reload i18n` needs `LOCALES_DIR`; catalogs built into the binary cannot + change at runtime. +- `/privacy`, `/terms` and `/support` are short texts in the catalog. + Replace them with your own before running a public bot. diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index fd105b7..e764a98 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -158,6 +158,18 @@ Only in a private chat, only for the user IDs in `OWNER_IDS`. | `/ytdlp update` | Update yt-dlp on every worker now | | `/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 | +| `/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 | +| `/grant day\|week\|month` | Give a pass to a user, or to a group (negative ID) | +| `/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 | +| `/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` | ## Backups diff --git a/internal/app/app.go b/internal/app/app.go index 3d595f2..9d9149f 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -5,6 +5,7 @@ package app import ( "context" "fmt" + "io/fs" "log/slog" "os" "strings" @@ -188,10 +189,20 @@ func New(ctx context.Context, opts Options) (*App, error) { return fail(fmt.Errorf("app: unknown storage backend %q", cfg.Storage.Backend)) } - tr, err := i18n.Load(locales.FS, log) + // Catalogs are built in. LOCALES_DIR loads them from disk instead, so + // a translator can edit and "/reload i18n" without a new build. + var catalogs fs.FS = locales.FS + var reload func() error + if cfg.LocalesDir != "" { + catalogs = os.DirFS(cfg.LocalesDir) + } + tr, err := i18n.Load(catalogs, log) if err != nil { return fail(err) } + if cfg.LocalesDir != "" { + reload = func() error { return tr.Reload(os.DirFS(cfg.LocalesDir)) } + } a.runner = opts.Runner if a.runner == nil { @@ -254,6 +265,7 @@ func New(ctx context.Context, opts Options) (*App, error) { I18n: tr, Log: log, WorkerSlots: func() int { return cfg.Worker.Concurrency }, + ReloadI18n: reload, }) if err != nil { return fail(err) @@ -289,7 +301,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"} +var allowedUpdates = []string{"message", "callback_query", "my_chat_member"} // 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/groups_test.go b/internal/app/groups_test.go new file mode 100644 index 0000000..db75eb3 --- /dev/null +++ b/internal/app/groups_test.go @@ -0,0 +1,703 @@ +package app_test + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/service" + "github.com/noderunners/dlbot/internal/tg/fakeserver" + "github.com/noderunners/dlbot/internal/ytdlp" + "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" +) + +// In these tests bob is an admin of the group and alice and carol are +// ordinary members. +func startGroup(t *testing.T, fake *ytdlptest.Fake, mut func(*config.Config)) *moneyHarness { + t.Helper() + h := startMoney(t, fake, mut) + h.srv.SetMember(group, bob, "administrator") + return h +} + +func (h *moneyHarness) groupWallet() *db.Wallet { + h.t.Helper() + w, err := h.app.Billing.Wallet(context.Background(), db.OwnerGroup, group) + if err != nil { + h.t.Fatal(err) + } + return w +} + +func (h *moneyHarness) grantGroup(sats int64) { + h.t.Helper() + if _, err := h.app.Billing.Credit(context.Background(), h.groupWallet().ID, sats, "test", "", fmt.Sprintf("tg:%d", time.Now().UnixNano()), 0); err != nil { + h.t.Fatal(err) + } +} + +func (h *moneyHarness) settings(mut func(*db.GroupSettings)) *db.GroupSettings { + h.t.Helper() + st, err := h.app.Store.GetGroupSettings(context.Background(), group) + if err != nil { + h.t.Fatal(err) + } + if mut != nil { + mut(st) + if err := h.app.Store.SaveGroupSettings(context.Background(), st); err != nil { + h.t.Fatal(err) + } + } + return st +} + +// source resolves what would pay for a download by user in chat. +func (h *moneyHarness) source(user, chat int64) string { + h.t.Helper() + chatType := "private" + if chat < 0 { + chatType = "supergroup" + } + d, err := h.app.Service.Entitlement(context.Background(), service.Who{UserID: user, ChatID: chat, ChatType: chatType}, false) + if err != nil { + h.t.Fatal(err) + } + return string(d.Source) +} + +// groupFetch has a user get a link in the group and waits for the file. +func (h *moneyHarness) groupFetch(user int64, url string) fakeserver.Call { + h.t.Helper() + card := h.card(group, user, "/dl "+url) + seq := h.press(group, user, card, "dl:") + return h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == group && !c.Failed }) +} + +func (h *moneyHarness) lastDelivery(user int64) *db.Delivery { + h.t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + d := h.deliveriesOf(user, db.DeliverySent) + if len(d) > 0 { + return d[len(d)-1] + } + if time.Now().After(deadline) { + h.t.Fatalf("user %d has no delivered file", user) + } + time.Sleep(20 * time.Millisecond) + } +} + +// --- acceptance: entitlement across user and group wallets ------------------ + +func TestEntitlementAcrossUserAndGroupWallets(t *testing.T) { + h := startGroup(t, nil, nil) + ctx := context.Background() + + // Nobody has anything: free everywhere. + if got := h.source(alice, group); got != "free" { + t.Fatalf("empty wallets: %s", got) + } + + // Group credits with the default rule: only admins may spend them. + h.grantGroup(500) + if got := h.source(alice, group); got != "free" { + t.Fatalf("a member must not spend group credits under the admins rule: %s", got) + } + if got := h.source(bob, group); got != "group_credits" { + t.Fatalf("an admin may spend group credits: %s", got) + } + // The group wallet is no use outside the group. + if got := h.source(bob, bob); got != "free" { + t.Fatalf("group credits leaked into a private chat: %s", got) + } + + // Alice's own credits pay for her when the group will not. + h.grant(alice, 100) + if got := h.source(alice, group); got != "own_credits" { + t.Fatalf("own credits behind refused group credits: %s", got) + } + // Once the group lets anyone spend, the group pays before she does. + h.settings(func(s *db.GroupSettings) { s.SpendRule = db.SpendAnyone }) + if got := h.source(alice, group); got != "group_credits" { + t.Fatalf("group credits come before own credits: %s", got) + } + + // A group pass covers every member and beats group credits. + if _, err := h.app.Billing.GrantPass(ctx, h.groupWallet().ID, "day", "test"); err != nil { + t.Fatal(err) + } + if got := h.source(carol, group); got != "group_pass" { + t.Fatalf("group pass for a member with nothing: %s", got) + } + if got := h.source(carol, carol); got != "free" { + t.Fatalf("the group pass does not follow a member home: %s", got) + } + // Her own pass beats everything the group has. + if _, err := h.app.Billing.GrantPass(ctx, h.wallet(carol).ID, "day", "test"); err != nil { + t.Fatal(err) + } + if got := h.source(carol, group); got != "own_pass" { + t.Fatalf("own pass before the group pass: %s", got) + } +} + +func TestGroupPassLiftsLimitsForMembersInTheGroupOnly(t *testing.T) { + h := startGroup(t, nil, nil) + if _, err := h.app.Billing.GrantPass(context.Background(), h.groupWallet().ID, "week", "test"); err != nil { + t.Fatal(err) + } + // The 80 MB file is over alice's free limit and fine under the pass. + h.groupFetch(alice, bigLink) + d := h.lastDelivery(alice) + if d.Source != "group_pass" || d.ChargeSats != 0 || d.WalletID != "" { + t.Fatalf("delivery = %+v", d) + } + job, _ := h.app.Store.GetJob(context.Background(), d.JobID) + if job.Lane != db.LanePaid { + t.Fatalf("lane = %s", job.Lane) + } + // In her private chat she is on the free tier again. + card := h.card(alice, alice, bigLink2) + seq := h.press(alice, alice, card, "dl:") + h.wait(seq, "sendMessage", textHas("larger than your limit")) +} + +func TestGroupCreditsAreChargedToTheGroupAndRefundedToIt(t *testing.T) { + failing := "https://example.com/fails" + h := startGroup(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{ + failing: {&ytdlp.Error{Code: ytdlp.CodePrivate, Raw: "x"}}, + }}, nil) + h.grantGroup(500) + h.grant(bob, 300) // his own money must not be touched + + h.groupFetch(bob, link) + d := h.lastDelivery(bob) + if d.Source != "group_credits" || d.ChargeSats != 50 || d.WalletID != h.groupWallet().ID { + t.Fatalf("delivery = %+v", d) + } + if g, own := h.groupWallet().Balance, h.balance(bob); g != 450 || own != 300 { + t.Fatalf("group balance %d, bob's own %d; want 450 and 300", g, own) + } + // The ledger says who spent it. + es, _ := h.app.Store.ListLedger(context.Background(), h.groupWallet().ID, 5) + if es[0].Kind != db.LedgerDebit || es[0].ActorID != bob { + t.Fatalf("ledger = %+v", es[0]) + } + + // A failed download gives the sats back to the group, not to bob. + card := h.card(group, bob, "/dl "+failing) + seq := h.press(group, bob, card, "dl:") + h.wait(seq, edits, textHas("50 sats went back")) + if g, own := h.groupWallet().Balance, h.balance(bob); g != 450 || own != 300 { + t.Fatalf("after the refund: group %d, bob %d", g, own) + } + h.booksBalance() +} + +func TestGroupSpendingCaps(t *testing.T) { + h := startGroup(t, nil, func(c *config.Config) { c.Limits.Free.DailyDownloads = 50 }) + h.grantGroup(1000) + + // Capped: anyone may spend, up to 100 sats (two downloads) a day each. + h.settings(func(s *db.GroupSettings) { s.SpendRule, s.SpendCap = db.SpendCapped, 100 }) + for i := 0; i < 2; i++ { + h.groupFetch(alice, fmt.Sprintf("https://example.com/a%d", i)) + } + if got := h.groupWallet().Balance; got != 900 { + t.Fatalf("group balance = %d, want 900", got) + } + // Her third download is hers to pay: here, the free tier. + if got := h.source(alice, group); got != "free" { + t.Fatalf("over her cap alice resolves to %s", got) + } + // Carol has her own allowance. + if got := h.source(carol, group); got != "group_credits" { + t.Fatalf("carol resolves to %s", got) + } + + // The group's daily cap stops everyone, admins included. + h.settings(func(s *db.GroupSettings) { s.SpendRule, s.DailyCap = db.SpendAnyone, 150 }) + h.groupFetch(carol, "https://example.com/c0") // total today: 150 + for _, u := range []int64{alice, bob, carol} { + if got := h.source(u, group); got == "group_credits" { + t.Fatalf("user %d may still spend past the group's daily cap", u) + } + } + if got := h.groupWallet().Balance; got != 850 { + t.Fatalf("group balance = %d, want 850", got) + } +} + +// --- acceptance: admin-only settings ---------------------------------------- + +func TestGroupSettingsAreAdminOnly(t *testing.T) { + h := startGroup(t, nil, nil) + + // A member asks for the settings and is turned away. + seq := h.srv.Seq() + h.srv.PushMessage(group, alice, "/settings") + h.wait(seq, "sendMessage", textHas("Only admins of this group")) + + // An admin gets the panel. + seq = h.srv.Seq() + h.srv.PushMessage(group, bob, "/settings") + panel := h.wait(seq, "sendMessage", textHas("Group settings")) + want := "Bot: on | Detect pasted links: off | Delete command messages: off | Who can use it: everyone | " + + "Group credits: admins only | Default quality: Ask every time | Open full settings" + if labels(panel) != want { + t.Fatalf("settings buttons = %q", labels(panel)) + } + // "Open full settings" is a link, never a web app button. + last := panel.Buttons()[len(panel.Buttons())-1] + if !strings.HasPrefix(last.URL, "https://t.me/") || strings.Contains(panel.Params["reply_markup"], "web_app") { + t.Fatalf("full settings button = %+v", last) + } + + // The panel is visible to everyone, so every press is checked again. + seq = h.press(group, alice, panel, "gs:ad") + alert := h.wait(seq, "answerCallbackQuery", nil) + if !strings.Contains(alert.Params["text"], "Only admins") || alert.Params["show_alert"] != "true" { + t.Fatalf("alert for a member = %+v", alert.Params) + } + if h.settings(nil).AutoDetect { + t.Fatal("a member changed a group setting") + } + + seq = h.press(group, bob, panel, "gs:ad") + edited := h.wait(seq, "editMessageText", textHas("Group settings")) + if !strings.Contains(labels(edited), "Detect pasted links: on") || !h.settings(nil).AutoDetect { + t.Fatalf("after the admin's press: %q", labels(edited)) + } + // The cycling settings walk through their values. + h.press(group, bob, panel, "gs:wu") + h.press(group, bob, panel, "gs:sp") + seq = h.press(group, bob, panel, "gs:dq") + h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { + l := labels(c) + return strings.Contains(l, "Who can use it: pass holders") && strings.Contains(l, "Group credits: anyone") && + strings.Contains(l, "Default quality: Best") + }) + + // Every admin command refuses members. + for _, cmd := range []string{"/grouplang en", "/autodetect off", "/allow example.com", "/block example.com", "/spending anyone", "/groupstats"} { + before := *h.settings(nil) + seq := h.srv.Seq() + h.srv.PushMessage(group, alice, cmd) + h.wait(seq, "sendMessage", textHas("Only admins of this group")) + after := *h.settings(nil) + after.UpdatedAt = before.UpdatedAt + if before != after { + t.Fatalf("%s by a member changed the settings", cmd) + } + } + // And works for admins. + for cmd, want := range map[string]string{ + "/autodetect off": "only act on commands", + "/allow https://Example.com/x": "Allowed sites: example.com", + "/block bad.example": "Blocked sites: bad.example", + "/spending capped 200": "anyone, capped", + "/spending daily 5000": "Group per day: 5,000 sats", + "/grouplang en": "now speaks English", + "/grouplang xx": "Available: en", + } { + seq := h.srv.Seq() + h.srv.PushMessage(group, bob, cmd) + h.wait(seq, "sendMessage", textHas(want)) + } + st := h.settings(nil) + if st.AutoDetect || st.Allowed != "example.com" || st.Blocked != "bad.example" || st.SpendRule != db.SpendCapped || + st.SpendCap != 200 || st.DailyCap != 5000 || st.Lang != "en" { + t.Fatalf("settings after the admin commands = %+v", st) + } + + // The wallet and the pass are for everyone to see. + for _, cmd := range []string{"/groupwallet", "/grouppass"} { + seq := h.srv.Seq() + h.srv.PushMessage(group, alice, cmd) + h.wait(seq, "sendMessage", textHas("Pass: none")) + } + // Group commands make no sense in a private chat. + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/settings") + h.wait(seq, "sendMessage", textHas("works in groups")) +} + +func TestAdminStatusIsVerifiedWithTelegramAndCached(t *testing.T) { + h := startGroup(t, nil, nil) + for i := 0; i < 4; i++ { + seq := h.srv.Seq() + h.srv.PushMessage(group, bob, "/settings") + h.wait(seq, "sendMessage", textHas("Group settings")) + } + asked := 0 + for _, c := range h.srv.Calls("getChatMember") { + if c.Params["user_id"] == fmt.Sprint(bob) && c.Params["chat_id"] == fmt.Sprint(group) { + asked++ + } + } + if asked != 1 { + t.Fatalf("getChatMember was called %d times for four checks, want 1 (cached)", asked) + } + // Somebody who claims nothing is still asked about, and found wanting. + seq := h.srv.Seq() + h.srv.PushMessage(group, carol, "/settings") + h.wait(seq, "getChatMember", func(c fakeserver.Call) bool { return c.Params["user_id"] == fmt.Sprint(carol) }) + h.wait(seq, "sendMessage", textHas("Only admins")) +} + +// --- group switches --------------------------------------------------------- + +func TestGroupSwitches(t *testing.T) { + h := startGroup(t, nil, nil) + + // Who can use it: admins. + h.settings(func(s *db.GroupSettings) { s.WhoCanUse = db.UseAdmins }) + seq := h.srv.Seq() + h.srv.PushMessage(group, alice, "/dl "+link) + h.wait(seq, "sendMessage", textHas("only admins can use the bot")) + if n := len(h.fake.Probes()); n != 0 { + t.Fatalf("a refused member's link was looked up %d times", n) + } + h.groupFetch(bob, link) + + // Who can use it: pass holders. + h.settings(func(s *db.GroupSettings) { s.WhoCanUse = db.UsePassHolders }) + seq = h.srv.Seq() + h.srv.PushMessage(group, alice, "/dl https://example.com/p1") + h.wait(seq, "sendMessage", textHas("you need a pass")) + if _, err := h.app.Billing.GrantPass(context.Background(), h.wallet(alice).ID, "day", "test"); err != nil { + t.Fatal(err) + } + h.groupFetch(alice, "https://example.com/p1") + + // Allowed and blocked sites. + h.settings(func(s *db.GroupSettings) { s.WhoCanUse, s.Allowed = db.UseEveryone, "good.example" }) + card := h.card(group, alice, "/dl https://example.com/s1") + seq = h.press(group, alice, card, "dl:") + alert := h.wait(seq, "answerCallbackQuery", nil) + if !strings.Contains(alert.Params["text"], "do not allow downloads from that site") { + t.Fatalf("alert = %q", alert.Params["text"]) + } + h.groupFetch(alice, "https://media.good.example/s2") + h.settings(func(s *db.GroupSettings) { s.Allowed, s.Blocked = "", "example.com" }) + card = h.card(group, alice, "/dl https://www.example.com/s3") + seq = h.press(group, alice, card, "dl:") + h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool { + return strings.Contains(c.Params["text"], "do not allow downloads from that site") + }) + + // Bot off: commands are met with silence, except /settings by an admin. + h.settings(func(s *db.GroupSettings) { s.Blocked, s.Enabled = "", false }) + seq = h.srv.Seq() + h.srv.PushMessage(group, alice, "/dl https://example.com/off") + h.srv.PushMessage(group, bob, "/help") + h.never(seq, "sendMessage", nil) + seq = h.srv.Seq() + h.srv.PushMessage(group, bob, "/settings") + h.wait(seq, "sendMessage", textHas("Group settings")) +} + +func TestAutoDetectDeleteCommandsAndDefaultQuality(t *testing.T) { + h := startGroup(t, nil, nil) + + // Off by default: a pasted link is ignored. + seq := h.srv.Seq() + h.srv.PushMessage(group, alice, "look "+link) + h.never(seq, "sendMessage", nil) + + h.settings(func(s *db.GroupSettings) { s.AutoDetect = true }) + seq = h.srv.Seq() + msgID := h.srv.PushMessage(group, alice, "look "+link) + card := h.wait(seq, "sendPhoto", nil) + if replyTarget(card) != msgID { + t.Fatal("the card must reply to the message with the link") + } + // Chatter without links stays unanswered. + seq = h.srv.Seq() + h.srv.PushMessage(group, alice, "nice weather") + h.never(seq, "sendMessage", nil) + + // Tidy mode removes the command message. + h.settings(func(s *db.GroupSettings) { s.DeleteCmds = true }) + seq = h.srv.Seq() + cmdID := h.srv.PushMessage(group, alice, "/dl https://example.com/tidy") + h.wait(seq, "deleteMessage", func(c fakeserver.Call) bool { return c.Params["message_id"] == fmt.Sprint(cmdID) }) + h.wait(seq, "sendPhoto", nil) // its card still appears + + // A default quality skips the card. + h.settings(func(s *db.GroupSettings) { s.DeleteCmds, s.Quality = false, "mp3" }) + cards := len(h.srv.Calls("sendPhoto")) + seq = h.srv.Seq() + h.srv.PushMessage(group, alice, "/dl https://example.com/q1") + h.wait(seq, "sendAudio", nil) + if n := len(h.srv.Calls("sendPhoto")); n != cards { + t.Fatal("a card was shown although the group has a default quality") + } +} + +func TestUserDefaultQualityAndLanguageAndStaticPages(t *testing.T) { + h := startMoney(t, nil, nil) + 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" { + t.Fatalf("quality buttons = %q", labels(menu)) + } + seq = h.press(alice, alice, menu, "ql:720") + h.wait(seq, "editMessageText", textHas("Default format: 720p")) + + // Now a pasted link starts at once, without a card. + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, link) + h.wait(seq, "sendVideo", nil) + if dl := h.fake.Downloads(); len(dl) != 1 || string(dl[0].Profile) != "720" { + t.Fatalf("downloads = %+v", dl) + } + if n := len(h.srv.Calls("sendPhoto")); n != 0 { + t.Fatalf("%d cards shown with a default format set", n) + } + // A crafted value is refused. + seq = h.srv.Seq() + h.srv.PushCallback(alice, alice, menu.MessageID, "ql:thumb") + h.wait(seq, "answerCallbackQuery", nil) + if u, _ := h.app.Store.GetUser(context.Background(), alice); u.Quality != "720" { + t.Fatalf("quality = %q", u.Quality) + } + + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/language") + langs := h.wait(seq, "sendMessage", textHas("Pick a language")) + if !strings.Contains(labels(langs), "English") || !strings.Contains(labels(langs), "Follow my Telegram language") { + t.Fatalf("language buttons = %q", labels(langs)) + } + seq = h.press(alice, alice, langs, "lg:en") + h.wait(seq, "editMessageText", textHas("Language: English")) + if u, _ := h.app.Store.GetUser(context.Background(), alice); u.LangOverride != "en" { + t.Fatalf("language override = %q", u.LangOverride) + } + + for cmd, want := range map[string]string{"/privacy": "Privacy", "/terms": "Terms", "/support": "Need help"} { + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, cmd) + h.wait(seq, "sendMessage", textHas(want)) + } +} + +// --- group wallet purchases -------------------------------------------------- + +func TestGroupWalletIsToppedUpThroughADeepLink(t *testing.T) { + h := startGroup(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(group, alice, "/groupwallet") + info := h.wait(seq, "sendMessage", textHas("Group wallet")) + btns := info.Buttons() + link := fmt.Sprintf("https://t.me/%s?start=gw_%d", fakeserver.BotUsername, group) + if len(btns) != 1 || btns[0].URL != link || btns[0].Text != "Add group credits" { + t.Fatalf("group wallet buttons = %+v, want a deep link to %s", btns, link) + } + if n, _ := h.ln.Calls(); n != 0 { + t.Fatal("no invoice may be created in the group") + } + + // Alice follows the link into her private chat. The group is the + // pre-selected target. + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, fmt.Sprintf("/start gw_%d", group)) + menu := h.wait(seq, "sendMessage", textHas("belongs to the group")) + if !strings.Contains(menu.Text(), "Test Group") { + t.Fatalf("group buy menu = %q", menu.Text()) + } + seq = h.press(alice, alice, menu, "gb:credits") + inv, msg := h.invoice(seq, 1) + if msg.ChatID() != alice || !strings.Contains(msg.Text(), "For the group Test Group") { + t.Fatalf("invoice message = %q in chat %d", msg.Text(), msg.ChatID()) + } + h.pay(inv) + h.wait(seq, "editMessageCaption", textHas("The group balance is now 1,000 sats.")) + // The payment hash mapped to the right wallet: the group's. + if g, own := h.groupWallet().Balance, h.balance(alice); g != 1000 || own != 0 { + t.Fatalf("group balance %d, alice's own %d; want 1000 and 0", g, own) + } + + // A group pass is bought the same way. + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, fmt.Sprintf("/start gw_%d", group)) + menu = h.wait(seq, "sendMessage", textHas("belongs to the group")) + seq = h.press(alice, alice, menu, "gb:pass_day") + inv, _ = h.invoice(seq, 2) + h.pay(inv) + h.wait(seq, "editMessageCaption", textHas("The group pass is active until")) + if got := h.source(carol, group); got != "group_pass" { + t.Fatalf("after the purchase a member resolves to %s", got) + } + // A link to a group the bot does not know leads nowhere. + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/start gw_-100999") + h.wait(seq, "sendMessage", textHas("do not know that group")) + h.booksBalance() +} + +func TestGroupsAreRecordedFromMyChatMember(t *testing.T) { + h := startGroup(t, nil, nil) + const newGroup = int64(-1005550001) + member := func(status string) map[string]any { + return map[string]any{"status": status, "user": map[string]any{"id": fakeserver.BotID, "is_bot": true, "first_name": "Bot"}} + } + push := func(old, now string) { + h.srv.PushRaw(map[string]any{"my_chat_member": map[string]any{ + "chat": map[string]any{"id": newGroup, "type": "supergroup", "title": "Fresh Group"}, + "from": map[string]any{"id": bob, "is_bot": false, "first_name": "Bob"}, + "date": time.Now().Unix(), + "old_chat_member": member(old), + "new_chat_member": member(now), + }}) + } + waitStatus := func(want string) *db.Group { + deadline := time.Now().Add(5 * time.Second) + for { + g, err := h.app.Store.GetGroup(context.Background(), newGroup) + if err == nil && g.BotStatus == want { + return g + } + if time.Now().After(deadline) { + t.Fatalf("group status never became %q (%+v, %v)", want, g, err) + } + time.Sleep(20 * time.Millisecond) + } + } + push("left", "member") + g := waitStatus("member") + if g.Title != "Fresh Group" || g.AddedBy != bob || !g.Present() { + t.Fatalf("group = %+v", g) + } + push("member", "administrator") + waitStatus("administrator") + push("administrator", "left") + if g := waitStatus("left"); g.Present() { + t.Fatal("a group the bot left must not count as present") + } + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, fmt.Sprintf("/start gw_%d", newGroup)) + h.wait(seq, "sendMessage", textHas("no longer in it")) +} + +// --- owner commands --------------------------------------------------------- + +func TestOwnerCommands(t *testing.T) { + const owner = int64(900) + h := startMoney(t, nil, func(c *config.Config) { c.Owners = []int64{owner} }) + ctx := context.Background() + say := func(user int64, text, want string) fakeserver.Call { + t.Helper() + seq := h.srv.Seq() + h.srv.PushMessage(user, user, text) + return h.wait(seq, "sendMessage", textHas(want)) + } + h.fetch(alice, link) // gives the stats something to count + + // For everyone else these commands do not exist. + for _, cmd := range []string{"/stats", "/ban 42", "/grant 42 week", "/credit 42 100", "/maint on", "/broadcast hi", "/blocklist"} { + say(alice, cmd, "do not know that command") + } + + stats := say(owner, "/stats", "Stats") + for _, want := range []string{"Users: 2", "1 done, 0 failed", "ledger and balances agree", "Maintenance: off", "Lightning: reachable"} { + if !strings.Contains(stats.Text(), want) { + t.Errorf("/stats lacks %q:\n%s", want, stats.Text()) + } + } + say(owner, "/user 42", "User 42") + say(owner, "/user 999999", "Not found") + + // Grants and credits, for users and for groups. + say(owner, "/grant 42 week", "The pass of 42 runs until") + if got := h.source(alice, alice); got != "own_pass" { + t.Fatalf("after /grant alice resolves to %s", got) + } + say(owner, "/credit 42 500", "500 sats added to 42. Balance: 500 sats.") + say(owner, "/refund 42 250", "Balance: 750 sats.") + say(owner, "/refund 42 pass 24h", "The pass of 42 runs until") + say(owner, "/refund 43 pass 24h", "Not found") // bob never used the bot + say(owner, "/credit 42 -5", "Example") + es, _ := h.app.Store.ListLedger(ctx, h.wallet(alice).ID, 5) + if len(es) != 2 || es[0].Kind != db.LedgerRefund || es[1].Kind != db.LedgerCredit || es[0].ActorID != owner { + t.Fatalf("ledger after owner credit and refund = %+v", es) + } + + // A gift code made by the owner works for a user. + code := say(owner, "/grant code credits 300 2", "Gift code") + i := strings.Index(code.Text(), "NR-") + say(alice, "/redeem "+code.Text()[i:i+17], "300 sats were added") + + // Blocklist: a blocked site is refused before any download. + say(owner, "/blocklist add site Example.com abuse report", "Blocked: example.com") + say(owner, "/blocklist", "site: example.com abuse report") + card := h.card(alice, alice, "https://cdn.example.com/other") + seq := h.press(alice, alice, card, "dl:") + h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool { + return strings.Contains(c.Params["text"], "not available through this bot") + }) + say(owner, "/blocklist remove site example.com", "Unblocked") + + // Ban: a banned user gets no answer at all. + say(owner, "/ban 42", "User 42 is banned") + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/help") + h.never(seq, "sendMessage", nil) + say(owner, "/ban 900", "An owner cannot be banned") + say(owner, "/unban 42", "no longer banned") + say(alice, "/help", "How to use me") + + // Maintenance: users are told, owners carry on. + say(owner, "/maint on", "Maintenance mode is on") + say(alice, "https://example.com/during-maint", "down for maintenance") + h.card(owner, owner, "https://example.com/owner-during-maint") + say(owner, "/maint off", "Maintenance mode is off") + + say(owner, "/queue all", "No jobs are queued or running") + say(owner, "/reload i18n", "built into the binary") + + // Broadcast needs a confirmation and reaches everyone. + preview := say(owner, "/broadcast Maintenance tonight at 22:00 UTC", "Preview") + if labels(preview) != "Send to 2 users" { + t.Fatalf("broadcast button = %q", labels(preview)) + } + h.never(h.srv.Seq(), "sendMessage", textIs("Maintenance tonight at 22:00 UTC")) + // Somebody else pressing the button sends nothing. + seq = h.press(owner, alice, preview, "bc:") + h.never(seq, "sendMessage", textIs("Maintenance tonight at 22:00 UTC")) + seq = h.press(owner, owner, preview, "bc:") + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { + return c.ChatID() == alice && c.Text() == "Maintenance tonight at 22:00 UTC" + }) + h.wait(seq, "sendMessage", textHas("Broadcast finished. Sent: 2. Failed: 0.")) + h.booksBalance() +} + +func TestOwnerCanGrantAGroupPass(t *testing.T) { + const owner = int64(900) + h := startGroup(t, nil, func(c *config.Config) { c.Owners = []int64{owner} }) + h.groupFetch(alice, link) // makes the group known + seq := h.srv.Seq() + h.srv.PushMessage(owner, owner, fmt.Sprintf("/grant %d month", group)) + h.wait(seq, "sendMessage", textHas("runs until")) + if got := h.source(carol, group); got != "group_pass" { + t.Fatalf("after the grant a member resolves to %s", got) + } + seq = h.srv.Seq() + h.srv.PushMessage(owner, owner, fmt.Sprintf("/group %d", group)) + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { + return strings.Contains(c.Text(), "Title: Test Group") && strings.Contains(c.Text(), "Who can use it: everyone") + }) + // Owner commands are private-chat only, even for an owner. + seq = h.srv.Seq() + h.srv.PushMessage(group, owner, "/stats") + h.never(seq, "sendMessage", textHas("Stats")) + _ = billing.ProductCredits +} diff --git a/internal/app/money_test.go b/internal/app/money_test.go index 5673fae..709d029 100644 --- a/internal/app/money_test.go +++ b/internal/app/money_test.go @@ -479,10 +479,20 @@ func TestGroupOverLimitUsesDeepLinks(t *testing.T) { if offer.ChatID() != group { t.Fatalf("the offer must answer in the group") } + // Both targets are offered, and both are plain links: web app buttons + // and invoices do not belong in a group. btns := offer.Buttons() - if len(btns) != 1 || btns[0].Text != "Buy for me" || btns[0].Data != "" { + if len(btns) != 2 || btns[0].Text != "Buy for me" || btns[1].Text != "Add group credits" { t.Fatalf("group offer buttons = %+v", btns) } + for _, b := range btns { + if b.Data != "" || !strings.HasPrefix(b.URL, "https://t.me/"+fakeserver.BotUsername+"?start=") { + t.Fatalf("group offer button is not a deep link: %+v", b) + } + } + if !strings.HasSuffix(btns[1].URL, fmt.Sprintf("?start=gw_%d", group)) { + t.Fatalf("group credits link = %q", btns[1].URL) + } prefix := "https://t.me/" + fakeserver.BotUsername + "?start=buy_" if !strings.HasPrefix(btns[0].URL, prefix) { t.Fatalf("deep link = %q", btns[0].URL) diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 686fca8..006e9e8 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -17,6 +17,7 @@ import ( "github.com/noderunners/dlbot/internal/cache" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/groups" "github.com/noderunners/dlbot/internal/i18n" "github.com/noderunners/dlbot/internal/sched" "github.com/noderunners/dlbot/internal/service" @@ -41,6 +42,10 @@ type Deps struct { // WorkerSlots is the number of download slots serving the queue. It // only feeds the wait estimate. WorkerSlots func() int + // Admins verifies group admins. A nil value gets a default checker. + Admins *groups.Admins + // ReloadI18n reloads the catalogs from disk. Nil when they are built in. + ReloadI18n func() error } // Bot handles Telegram updates and job events. @@ -53,6 +58,7 @@ type Bot struct { bill *billing.Billing cashu billing.Cashu cache *cache.Cache + admins *groups.Admins storage storage.Storage tr *i18n.Bundle log *slog.Logger @@ -75,6 +81,11 @@ 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 + // broadcasts holds texts waiting for the owner's confirmation. + broadcasts map[string]string + reloadI18n func() error + // broadcastGap is the pause between two broadcast messages. + broadcastGap time.Duration // Tunables, shortened in tests. reconcileEvery time.Duration @@ -122,10 +133,18 @@ func New(ctx context.Context, d Deps) (*Bot, error) { sending: map[string]bool{}, pumping: map[int64]bool{}, cancelledAt: map[int64]time.Time{}, + broadcasts: map[string]string{}, + reloadI18n: d.ReloadI18n, + broadcastGap: 50 * time.Millisecond, + admins: d.Admins, reconcileEvery: 5 * time.Second, statusMinGap: 3 * time.Second, invoiceGrace: 5 * time.Second, } + if b.admins == nil { + b.admins = groups.NewAdmins(d.API, 0) + } + d.Service.SetAdmins(b.admins) d.Sched.Subscribe(func(ev sched.Event) { select { case b.events <- ev: @@ -152,8 +171,12 @@ func (b *Bot) SetTimings(reconcile, statusGap time.Duration) { b.reconcileEvery = reconcile b.statusMinGap = statusGap b.invoiceGrace = 4 * reconcile + b.broadcastGap = time.Millisecond } +// Admins returns the group admin checker, shared with the Mini App API. +func (b *Bot) Admins() *groups.Admins { return b.admins } + // Run processes updates and job events until ctx ends, then waits for // in-flight work to finish. func (b *Bot) Run(ctx context.Context, updates <-chan telego.Update) { @@ -236,6 +259,8 @@ func updateChatID(u telego.Update) int64 { return u.CallbackQuery.Message.GetChat().ID } return u.CallbackQuery.From.ID + case u.MyChatMember != nil: + return u.MyChatMember.Chat.ID } return int64(u.UpdateID) } @@ -247,6 +272,8 @@ func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) { b.handleMessage(ctx, u.Message) case u.CallbackQuery != nil: b.handleCallback(ctx, u.CallbackQuery) + case u.MyChatMember != nil: + b.handleMyChatMember(ctx, u.MyChatMember) } } diff --git a/internal/bot/card.go b/internal/bot/card.go index e8db005..e779276 100644 --- a/internal/bot/card.go +++ b/internal/bot/card.go @@ -51,6 +51,13 @@ func (b *Bot) startLink(ctx context.Context, lr linkRequest) { } return } + // Whether the requester may use the bot here at all is settled before + // anything is looked up: maintenance, and a group's own rules. + who := service.Who{UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType} + if err := b.svc.Gate(ctx, who); err != nil { + b.refuse(ctx, lr.chatID, lr.sourceID, lr.act.lang, err) + return + } b.goBG("link", func() { b.linkFlow(ctx, lr) }) } diff --git a/internal/bot/commands.go b/internal/bot/commands.go index 8d89796..a138f6d 100644 --- a/internal/bot/commands.go +++ b/internal/bot/commands.go @@ -10,6 +10,7 @@ import ( "github.com/mymmrac/telego" "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/groups" "github.com/noderunners/dlbot/internal/i18n" "github.com/noderunners/dlbot/internal/links" "github.com/noderunners/dlbot/internal/media" @@ -33,79 +34,55 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { 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 + } + } cmd, forUs, isCmd := b.parseCommand(m) if isCmd { if !forUs { return // addressed to another bot in the group } - switch cmd { - case "start": - b.cmdStart(ctx, m, act) - case "help": - b.cmdHelp(ctx, m, act) - case "dl": - b.cmdDownload(ctx, m, act, "") - case "audio": - b.cmdDownload(ctx, m, act, media.MP3) - case "thumb": - b.cmdDownload(ctx, m, act, media.Thumb) - case "fresh": - b.cmdLink(ctx, m, act, linkRequest{fresh: true}) - case "subs": - b.cmdLink(ctx, m, act, linkRequest{subs: true}) - case "history": - b.cmdHistory(ctx, m, act) - case "purge": - if b.isOwner(m) { - b.cmdPurge(ctx, m, act) - } - case "cache": - if b.isOwner(m) { - b.cmdCache(ctx, m, act) - } - case "workers": - if b.isOwner(m) { - b.cmdWorkers(ctx, m, act) - } - case "drain": - if b.isOwner(m) { - b.cmdDrain(ctx, m, act) - } - case "ytdlp": - if b.isOwner(m) { - b.cmdYtDlp(ctx, m, act) - } - case "info": - b.cmdInfo(ctx, m, act) - case "queue": - b.cmdQueue(ctx, m, act) - case "cancel": - b.cmdCancel(ctx, m, act) - case "buy": - b.cmdBuy(ctx, m, act) - case "account": - b.cmdAccount(ctx, m, act) - case "limits": - b.cmdLimits(ctx, m, act) - case "credits": - b.cmdCredits(ctx, m, act) - case "donate": - b.cmdDonate(ctx, m, act) - case "redeem": - b.cmdRedeem(ctx, m, act, commandArgs(m)) - case "referral": - b.cmdReferral(ctx, m, act) - default: - if private { - _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "cmd.unknown", nil), nil) + if inGroup { + b.noteGroup(ctx, m.Chat, act.user.ID) + // A group that switched the bot off only hears from it when an + // admin opens the settings to switch it back on. + if !gset.Enabled && cmd != "settings" { + return } } + if b.ownerCommand(ctx, m, act, cmd) { + return + } + b.runCommand(ctx, m, act, cmd, gset) + return + } + urls := messageLinks(m) + if inGroup { + // Without a command the bot only acts when the admins turned on + // link detection. It then needs to see ordinary messages, which + // means group privacy mode off or the bot being an admin. + if !gset.Enabled || !gset.AutoDetect || len(urls) == 0 { + return + } + b.noteGroup(ctx, m.Chat, act.user.ID) + b.startLink(ctx, linkRequest{ + chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: int64(m.MessageID), act: act, url: urls[0], + preset: presetFor(act, gset), + }) return } if !private { - return // groups are driven by commands; auto-detect is an admin opt-in + return } - urls := messageLinks(m) if len(urls) == 0 { _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "hint.send_link", nil), nil) return @@ -116,10 +93,131 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { 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), }) } } +// 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. +func presetFor(act actor, gset *db.GroupSettings) media.Profile { + q := act.user.Quality + if gset != nil { + q = gset.Quality + } + if p, err := media.Parse(q); err == nil { + return p + } + return "" +} + +// 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 + // afterwards when the admins asked for a tidy chat. + tidy := func() { + if gset != nil && gset.DeleteCmds { + b.deleteMessage(ctx, m.Chat.ID, int64(m.MessageID)) + } + } + switch cmd { + case "start": + b.cmdStart(ctx, m, act) + case "help": + b.cmdHelp(ctx, m, act) + case "dl": + b.cmdDownload(ctx, m, act, presetFor(act, gset)) + tidy() + case "audio": + b.cmdDownload(ctx, m, act, media.MP3) + tidy() + case "thumb": + b.cmdDownload(ctx, m, act, media.Thumb) + tidy() + case "fresh": + b.cmdLink(ctx, m, act, linkRequest{fresh: true}) + tidy() + case "subs": + b.cmdLink(ctx, m, act, linkRequest{subs: true}) + tidy() + case "info": + b.cmdInfo(ctx, m, act) + case "history": + b.cmdHistory(ctx, m, act) + case "queue": + if b.isOwner(m) && strings.TrimSpace(commandArgs(m)) == "all" { + b.cmdQueueAll(ctx, m, act) + return + } + b.cmdQueue(ctx, m, act) + case "cancel": + b.cmdCancel(ctx, m, act) + case "quality": + b.cmdQuality(ctx, m, act) + case "language": + b.cmdLanguage(ctx, m, act) + case "app": + b.cmdApp(ctx, m, act) + case "buy": + b.cmdBuy(ctx, m, act) + case "account": + b.cmdAccount(ctx, m, act) + case "limits": + b.cmdLimits(ctx, m, act) + case "credits": + b.cmdCredits(ctx, m, act) + case "donate": + b.cmdDonate(ctx, m, act) + case "redeem": + b.cmdRedeem(ctx, m, act, commandArgs(m)) + case "referral": + b.cmdReferral(ctx, m, act) + case "privacy", "terms", "support": + if b.privateOnly(ctx, m, act) { + b.cmdStatic(ctx, m, act, "static."+cmd) + } + case "settings": + b.cmdSettings(ctx, m, act) + case "grouplang": + b.cmdGroupLang(ctx, m, act) + case "autodetect": + b.cmdAutoDetect(ctx, m, act) + case "allow": + b.cmdSiteList(ctx, m, act, true) + case "block": + b.cmdSiteList(ctx, m, act, false) + case "spending": + b.cmdSpending(ctx, m, act) + case "groupwallet": + b.cmdGroupWallet(ctx, m, act, false) + case "grouppass": + b.cmdGroupWallet(ctx, m, act, true) + case "groupstats": + b.cmdGroupStats(ctx, m, act) + default: + if isPrivate(m.Chat.Type) { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "cmd.unknown", nil), nil) + } + } +} + +// cmdApp points to the Mini App. In a private chat the button opens it in +// place; in a group it has to be a plain link, because web app buttons do +// not work there. +func (b *Bot) cmdApp(ctx context.Context, m *telego.Message, act actor) { + if !b.cfg.MiniAppEnabled() { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "app.unavailable", nil), nil) + return + } + label := b.tr.T(act.lang, "btn.open_app", nil) + btn := urlButton(label, "https://t.me/"+b.username+"?startapp") + if isPrivate(m.Chat.Type) { + btn = telego.InlineKeyboardButton{Text: label, WebApp: &telego.WebAppInfo{URL: b.cfg.PublicURL + "/app/"}} + } + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "app.open", nil), + keyboard([]telego.InlineKeyboardButton{btn})) +} + // commandArgs returns the text after the command of a message. func commandArgs(m *telego.Message) string { for _, e := range m.Entities { @@ -184,6 +282,12 @@ func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) { case strings.HasPrefix(payload, "skip_"): b.startSkipLink(ctx, m, act, strings.TrimPrefix(payload, "skip_")) return + case strings.HasPrefix(payload, "gw_"): + b.startGroupLink(ctx, m, act, strings.TrimPrefix(payload, "gw_"), false) + return + case strings.HasPrefix(payload, "gs_"): + b.startGroupLink(ctx, m, act, strings.TrimPrefix(payload, "gs_"), true) + return case payload == "buy": b.showBuy(ctx, m.Chat.ID, act) return @@ -380,8 +484,23 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { 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: + b.cbSetting(ctx, q, act, id) + case cbGroupBuy: + b.cbGroupBuyProduct(ctx, q, act, id, arg) + case cbQuality: + b.cbSetQuality(ctx, q, act, id) + case cbLanguage: + b.cbSetLanguage(ctx, q, act, id) + case cbBroadcast: + b.cbBroadcastSend(ctx, q, act, id) case cbDownload: b.cbDownload(ctx, q, act, id, arg) case cbCancelCard: diff --git a/internal/bot/groups.go b/internal/bot/groups.go new file mode 100644 index 0000000..fea3114 --- /dev/null +++ b/internal/bot/groups.go @@ -0,0 +1,619 @@ +package bot + +import ( + "context" + "strconv" + "strings" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/groups" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/service" +) + +const ( + cbGroupSetting = "gs" // gs: + cbGroupBuy = "gb" // gb::[:] + cbQuality = "ql" // ql: + cbLanguage = "lg" // lg: +) + +// handleMyChatMember records the groups the bot is in. Telegram sends this +// update whenever the bot is added, removed, promoted or demoted. +func (b *Bot) handleMyChatMember(ctx context.Context, u *telego.ChatMemberUpdated) { + if !groups.IsGroup(u.Chat.Type) || u.NewChatMember == nil { + return + } + g := &db.Group{ + ChatID: u.Chat.ID, Title: u.Chat.Title, Type: u.Chat.Type, + BotStatus: u.NewChatMember.MemberStatus(), AddedBy: u.From.ID, + } + if err := b.store.UpsertGroup(ctx, g); err != nil { + b.log.Error("record group", "chat_id", u.Chat.ID, "err", err) + return + } + b.admins.Forget(u.Chat.ID) + b.log.Info("group status changed", "chat_id", g.ChatID, "status", g.BotStatus, "by", u.From.ID) +} + +// noteGroup makes sure a group the bot is used in is on record, also when +// the my_chat_member update was missed, and notes who uses it. +func (b *Bot) noteGroup(ctx context.Context, chat telego.Chat, userID int64) { + if _, err := b.store.GetGroup(ctx, chat.ID); err != nil { + _ = b.store.UpsertGroup(ctx, &db.Group{ChatID: chat.ID, Title: chat.Title, Type: chat.Type, BotStatus: "member"}) + } + if err := b.store.SeeGroupUser(ctx, chat.ID, userID); err != nil { + b.log.Debug("note group user", "err", err) + } +} + +// requireAdmin checks that a command was sent in a group by one of its +// admins, and tells the sender when it was not. +func (b *Bot) requireAdmin(ctx context.Context, m *telego.Message, act actor) bool { + if !groups.IsGroup(m.Chat.Type) { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "notice.group_only", nil), nil) + return false + } + if !b.admins.IsAdmin(ctx, m.Chat.ID, act.user.ID) { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "notice.admins_only", nil), nil) + return false + } + return true +} + +func (b *Bot) requireGroup(ctx context.Context, m *telego.Message, act actor) bool { + if groups.IsGroup(m.Chat.Type) { + return true + } + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "notice.group_only", nil), nil) + return false +} + +func (b *Bot) onOff(lang string, on bool) string { + if on { + return b.tr.T(lang, "word.on", nil) + } + return b.tr.T(lang, "word.off", nil) +} + +func (b *Bot) qualityName(lang, q string) string { + if q == "" { + return b.tr.T(lang, "quality.ask", nil) + } + p, err := media.Parse(q) + if err != nil { + return q + } + return b.profileLabel(lang, p) +} + +// groupSettingsLink opens the full settings of a group: the Mini App page +// when the Mini App is set up, the private chat otherwise. Web app buttons +// do not work in groups, so this is always a plain link. +func (b *Bot) groupSettingsLink(chatID int64) string { + id := strconv.FormatInt(chatID, 10) + if b.cfg.MiniAppEnabled() { + return "https://t.me/" + b.username + "?startapp=group_" + id + } + return "https://t.me/" + b.username + "?start=gs_" + id +} + +func (b *Bot) groupWalletLink(chatID int64) string { + return "https://t.me/" + b.username + "?start=gw_" + strconv.FormatInt(chatID, 10) +} + +// settingsView renders the quick settings of a group. +func (b *Bot) settingsView(ctx context.Context, lang string, st *db.GroupSettings) (string, *telego.InlineKeyboardMarkup) { + wallet, _ := b.bill.State(ctx, db.OwnerGroup, st.ChatID) + pass := b.tr.T(lang, "word.none", nil) + if wallet.PassUntil > 0 { + pass = b.tr.DateTime(lang, time.UnixMilli(wallet.PassUntil)) + } + groupLang := st.Lang + if groupLang == "" { + groupLang = b.tr.T(lang, "settings.lang_auto", nil) + } + sites := func(list string) string { + if list == "" { + return b.tr.T(lang, "word.none", nil) + } + return strings.Join(db.Sites(list), ", ") + } + text := b.tr.HTML(lang, "settings.text", i18n.Args{ + "Balance": b.tr.Sats(lang, wallet.Credits), + "Pass": pass, + "Lang": groupLang, + "Allowed": sites(st.Allowed), + "Blocked": sites(st.Blocked), + "SpendCap": b.tr.Sats(lang, st.SpendCap), + "DailyCap": b.capSats(lang, st.DailyCap), + }) + 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(cbGroupSetting, key))} + } + kb := keyboard( + row("en", b.tr.T(lang, "settings.enabled", nil), b.onOff(lang, st.Enabled)), + row("ad", b.tr.T(lang, "settings.auto_detect", nil), b.onOff(lang, st.AutoDetect)), + row("dc", b.tr.T(lang, "settings.delete_commands", nil), b.onOff(lang, st.DeleteCmds)), + row("wu", b.tr.T(lang, "settings.who", nil), b.tr.T(lang, "settings.who_"+st.WhoCanUse, nil)), + row("sp", b.tr.T(lang, "settings.spend", nil), b.tr.T(lang, "settings.spend_"+st.SpendRule, nil)), + row("dq", b.tr.T(lang, "settings.quality", nil), b.qualityName(lang, st.Quality)), + []telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.full_settings", nil), b.groupSettingsLink(st.ChatID))}, + ) + return text, kb +} + +func (b *Bot) capSats(lang string, n int64) string { + if n <= 0 { + return b.tr.T(lang, "account.unlimited", nil) + } + return b.tr.Sats(lang, n) +} + +func (b *Bot) cmdSettings(ctx context.Context, m *telego.Message, act actor) { + if !b.requireAdmin(ctx, m, act) { + return + } + st, err := b.store.GetGroupSettings(ctx, m.Chat.ID) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + text, kb := b.settingsView(ctx, act.lang, st) + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), text, kb) +} + +// next returns the value after cur in a cycle. +func next(cur string, cycle ...string) string { + for i, v := range cycle { + if v == cur { + return cycle[(i+1)%len(cycle)] + } + } + return cycle[0] +} + +// cbSetting handles a quick toggle under /settings. The admin check runs +// on every press: the buttons are visible to everyone in the group. +func (b *Bot) cbSetting(ctx context.Context, q *telego.CallbackQuery, act actor, key string) { + if q.Message == nil || !groups.IsGroup(q.Message.GetChat().Type) { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + chat := q.Message.GetChat().ID + if !b.admins.IsAdmin(ctx, chat, act.user.ID) { + b.answer(ctx, q, b.tr.T(act.lang, "notice.admins_only", nil), true) + return + } + st, err := b.store.GetGroupSettings(ctx, chat) + if err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) + return + } + switch key { + case "en": + st.Enabled = !st.Enabled + case "ad": + st.AutoDetect = !st.AutoDetect + case "dc": + st.DeleteCmds = !st.DeleteCmds + case "wu": + st.WhoCanUse = next(st.WhoCanUse, db.UseEveryone, db.UsePassHolders, db.UseAdmins) + case "sp": + st.SpendRule = next(st.SpendRule, db.SpendAdmins, db.SpendAnyone, db.SpendCapped) + if st.SpendRule == db.SpendCapped && st.SpendCap == 0 { + st.SpendCap = 4 * b.cfg.Prices.CreditPerDownload + } + case "dq": + st.Quality = next(st.Quality, "", string(media.Best), string(media.P720), string(media.P480), string(media.MP3)) + default: + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + if err := b.store.SaveGroupSettings(ctx, st); err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) + return + } + b.log.Info("group setting changed", "chat_id", chat, "key", key, "by", act.user.ID) + // The group may have its own language; the view follows it. + lang := act.lang + if st.Lang != "" { + lang = st.Lang + } + text, kb := b.settingsView(ctx, lang, st) + b.answer(ctx, q, b.tr.T(lang, "notice.saved", nil), false) + _ = b.edit(ctx, chat, int64(q.Message.GetMessageID()), false, text, kb) +} + +// changeSettings loads, changes and saves a group's settings for an admin +// command, and confirms with the given message. +func (b *Bot) changeSettings(ctx context.Context, m *telego.Message, act actor, change func(*db.GroupSettings) (key string, args i18n.Args)) { + st, err := b.store.GetGroupSettings(ctx, m.Chat.ID) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + key, args := change(st) + if key == "" { + return + } + if strings.HasPrefix(key, "!") { // a refusal: nothing to save + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, key[1:], args), nil) + return + } + if err := b.store.SaveGroupSettings(ctx, st); err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + lang := act.lang + if st.Lang != "" { + lang = st.Lang + } + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(lang, key, args), nil) +} + +func (b *Bot) cmdGroupLang(ctx context.Context, m *telego.Message, act actor) { + if !b.requireAdmin(ctx, m, act) { + return + } + arg := strings.ToLower(strings.TrimSpace(commandArgs(m))) + b.changeSettings(ctx, m, act, func(st *db.GroupSettings) (string, i18n.Args) { + if arg == "" { + return "!grouplang.usage", i18n.Args{"Langs": strings.Join(b.tr.Langs(), ", ")} + } + if arg == "auto" { + st.Lang = "" + return "grouplang.auto", nil + } + for _, l := range b.tr.Langs() { + if l == arg { + st.Lang = l + return "grouplang.set", i18n.Args{"Lang": b.tr.T(l, "language.name", nil)} + } + } + return "!grouplang.usage", i18n.Args{"Langs": strings.Join(b.tr.Langs(), ", ")} + }) +} + +func (b *Bot) cmdAutoDetect(ctx context.Context, m *telego.Message, act actor) { + if !b.requireAdmin(ctx, m, act) { + return + } + arg := strings.ToLower(strings.TrimSpace(commandArgs(m))) + b.changeSettings(ctx, m, act, func(st *db.GroupSettings) (string, i18n.Args) { + switch arg { + case "on": + st.AutoDetect = true + return "autodetect.on", nil + case "off": + st.AutoDetect = false + return "autodetect.off", nil + } + return "!autodetect.usage", nil + }) +} + +// cmdSiteList handles /allow and /block: no argument shows the list, a +// host adds it, "remove " removes it, "clear" empties the list. +func (b *Bot) cmdSiteList(ctx context.Context, m *telego.Message, act actor, allow bool) { + if !b.requireAdmin(ctx, m, act) { + return + } + name := "block" + if allow { + name = "allow" + } + fields := strings.Fields(commandArgs(m)) + b.changeSettings(ctx, m, act, func(st *db.GroupSettings) (string, i18n.Args) { + list := &st.Blocked + if allow { + list = &st.Allowed + } + show := func() i18n.Args { + v := strings.Join(db.Sites(*list), ", ") + if v == "" { + v = b.tr.T(act.lang, "word.none", nil) + } + return i18n.Args{"Sites": v} + } + switch { + case len(fields) == 0: + return "!" + name + ".list", show() + case fields[0] == "clear": + *list = "" + return name + ".list", show() + } + remove := fields[0] == "remove" + if remove { + fields = fields[1:] + } + if len(fields) == 0 { + return "!" + name + ".list", show() + } + host := groups.CleanHost(fields[0]) + if host == "" { + return "!sites.bad_host", nil + } + var kept []string + for _, h := range db.Sites(*list) { + if h != host { + kept = append(kept, h) + } + } + if !remove && len(kept) < 50 { + kept = append(kept, host) + } + *list = strings.Join(kept, ",") + return name + ".list", show() + }) +} + +// cmdSpending handles /spending anyone | admins | capped and +// /spending daily . +func (b *Bot) cmdSpending(ctx context.Context, m *telego.Message, act actor) { + if !b.requireAdmin(ctx, m, act) { + return + } + fields := strings.Fields(strings.ToLower(commandArgs(m))) + b.changeSettings(ctx, m, act, func(st *db.GroupSettings) (string, i18n.Args) { + amount := func(i int) (int64, bool) { + if len(fields) <= i { + return 0, false + } + n, err := strconv.ParseInt(fields[i], 10, 64) + return n, err == nil && n >= 0 && n <= billing.MaxAmount + } + if len(fields) == 0 { + return "!spending.usage", nil + } + switch fields[0] { + case db.SpendAnyone, db.SpendAdmins: + st.SpendRule = fields[0] + case db.SpendCapped: + n, ok := amount(1) + if !ok || n == 0 { + return "!spending.usage", nil + } + st.SpendRule, st.SpendCap = db.SpendCapped, n + case "daily": + n, ok := amount(1) + if !ok { + return "!spending.usage", nil + } + st.DailyCap = n + default: + return "!spending.usage", nil + } + return "spending.set", i18n.Args{ + "Rule": b.tr.T(act.lang, "settings.spend_"+st.SpendRule, nil), + "SpendCap": b.tr.Sats(act.lang, st.SpendCap), + "DailyCap": b.capSats(act.lang, st.DailyCap), + } + }) +} + +// cmdGroupWallet shows the group's balance and pass to anyone, with links +// to top it up. Paying happens in the private chat. +func (b *Bot) cmdGroupWallet(ctx context.Context, m *telego.Message, act actor, passOnly bool) { + if !b.requireGroup(ctx, m, act) { + return + } + lang := act.lang + wallet, err := b.bill.State(ctx, db.OwnerGroup, m.Chat.ID) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + st, err := b.store.GetGroupSettings(ctx, m.Chat.ID) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + pass := b.tr.T(lang, "groupwallet.pass_none", nil) + if wallet.PassUntil > 0 { + pass = b.tr.T(lang, "groupwallet.pass_until", i18n.Args{"Until": b.tr.DateTime(lang, time.UnixMilli(wallet.PassUntil))}) + } + key := "groupwallet.text" + if passOnly { + key = "grouppass.text" + } + text := b.tr.HTML(lang, key, i18n.Args{ + "Balance": b.tr.Sats(lang, wallet.Credits), + "Pass": pass, + "Rule": b.tr.T(lang, "settings.spend_"+st.SpendRule, nil), + }) + var kb *telego.InlineKeyboardMarkup + if b.bill.Enabled() { + label := "btn.add_group_credits" + if passOnly { + label = "btn.buy_group_pass" + } + kb = keyboard([]telego.InlineKeyboardButton{urlButton(b.tr.T(lang, label, nil), b.groupWalletLink(m.Chat.ID))}) + } + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), text, kb) +} + +func (b *Bot) cmdGroupStats(ctx context.Context, m *telego.Message, act actor) { + if !b.requireAdmin(ctx, m, act) { + return + } + lang := act.lang + since := service.Day(time.Now().AddDate(0, 0, -6)) + usage, err := b.store.GroupUsage(ctx, m.Chat.ID, since, 15) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + if len(usage) == 0 { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(lang, "groupstats.empty", nil), nil) + return + } + var sb strings.Builder + sb.WriteString(b.tr.HTML(lang, "groupstats.header", nil)) + for _, u := range usage { + name := u.Name + if name == "" { + name = strconv.FormatInt(u.UserID, 10) + } + sb.WriteString("\n") + sb.WriteString(b.tr.HTML(lang, "groupstats.line", i18n.Args{ + "Name": shorten(name, 30), "Count": u.Downloads, + "Size": b.tr.Size(lang, u.Bytes), "Sats": b.tr.Sats(lang, u.Sats), + })) + } + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), nil) +} + +// --- paying for a group, in the private chat -------------------------------- + +// startGroupLink handles /start gw_ and gs_, the deep +// links from a group. The target wallet is the group's, pre-selected. +func (b *Bot) startGroupLink(ctx context.Context, m *telego.Message, act actor, arg string, settings bool) { + lang := act.lang + chatID, err := strconv.ParseInt(arg, 10, 64) + g, gerr := b.store.GetGroup(ctx, chatID) + if err != nil || gerr != nil || !g.Present() { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "groupbuy.unknown", nil), nil) + return + } + if settings { + // Without the Mini App the full settings are the admin commands. + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "settings.commands", i18n.Args{"Group": g.Title}), nil) + return + } + if !b.bill.Enabled() { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "buy.unavailable", nil), nil) + return + } + wallet, _ := b.bill.State(ctx, db.OwnerGroup, chatID) + gid := strconv.FormatInt(chatID, 10) + rows := b.passButtons(lang, func(product string) string { return cbData(cbGroupBuy, product, gid) }) + var packs []telego.InlineKeyboardButton + for _, a := range b.cfg.Prices.CreditPacks { + packs = append(packs, button(b.tr.Sats(lang, a), cbData(cbGroupBuy, billing.ProductCredits, gid, strconv.FormatInt(a, 10)))) + } + rows = append(rows, packs) + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "groupbuy.intro", i18n.Args{ + "Group": g.Title, "Balance": b.tr.Sats(lang, wallet.Credits), + }), keyboard(rows...)) +} + +// cbGroupBuyProduct creates an invoice whose target is a group wallet. +// Anyone may pay for a group; what they buy belongs to the group. +func (b *Bot) cbGroupBuyProduct(ctx context.Context, q *telego.CallbackQuery, act actor, product, rest string) { + gidArg, amountArg, _ := strings.Cut(rest, ":") + chatID, err := strconv.ParseInt(gidArg, 10, 64) + g, gerr := b.store.GetGroup(ctx, chatID) + if err != nil || gerr != nil || !g.Present() { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.answer(ctx, q, "", false) + amount, _ := strconv.ParseInt(amountArg, 10, 64) + b.startPurchase(ctx, act.user.ID, act, product, amount, purchaseContext{groupID: chatID}) +} + +// --- 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) +} + +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 err := b.store.SetUserQuality(ctx, act.user.ID, value); err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) + return + } + 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) + } +} + +func (b *Bot) cmdLanguage(ctx context.Context, m *telego.Message, act actor) { + var row []telego.InlineKeyboardButton + var rows [][]telego.InlineKeyboardButton + for _, l := range b.tr.Langs() { + if b.tr.Hidden(l) { + continue + } + // 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...)) +} + +func (b *Bot) cbSetLanguage(ctx context.Context, q *telego.CallbackQuery, act actor, value string) { + lang := "" + if value != "auto" { + for _, l := range b.tr.Langs() { + if l == value { + lang = l + } + } + if 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) + return + } + shown := lang + if shown == "" { + shown = b.tr.Resolve(act.user.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, + b.tr.HTML(shown, "language.set", i18n.Args{"Lang": b.tr.T(shown, "language.name", nil)}), 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 + if contact == "" { + contact = "@" + b.username + } + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, key, i18n.Args{"Contact": contact}), nil) +} diff --git a/internal/bot/money.go b/internal/bot/money.go index bc505ed..8e65acd 100644 --- a/internal/bot/money.go +++ b/internal/bot/money.go @@ -305,6 +305,8 @@ type purchaseContext struct { requestID string profile string deliveryID string + // groupID makes a group's wallet the target instead of the payer's. + groupID int64 } // startPurchase creates the invoice and shows it in the private chat. @@ -316,7 +318,12 @@ func (b *Bot) startPurchase(ctx context.Context, chat int64, act actor, product _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.bad_amount", nil), nil) return } - w, err := b.bill.Wallet(ctx, db.OwnerUser, act.user.ID) + // Every purchase has a target: the payer's own wallet or a group's. + ownerType, ownerID := db.OwnerUser, act.user.ID + if pc.groupID != 0 { + ownerType, ownerID = db.OwnerGroup, pc.groupID + } + w, err := b.bill.Wallet(ctx, ownerType, ownerID) if err != nil { b.internalError(ctx, chat, act, err) return @@ -347,12 +354,30 @@ func (b *Bot) startPurchase(ctx context.Context, chat int64, act actor, product func (b *Bot) invoiceText(p *db.Purchase) string { lang := p.Lang minutes := b.cfg.LNbits.InvoiceExpiry.D() - return b.tr.HTML(lang, "invoice.caption", i18n.Args{ + text := b.tr.HTML(lang, "invoice.caption", i18n.Args{ "Title": b.productTitle(lang, p.Product), "Amount": b.tr.Sats(lang, p.AmountSats), "Invoice": p.Bolt11, "Valid": b.tr.Span(lang, minutes), }) + if title := b.groupTitle(p); title != "" { + text = b.tr.HTML(lang, "invoice.for_group", i18n.Args{"Group": title}) + "\n" + text + } + return text +} + +// groupTitle returns the title of the group a purchase is for, or "" when +// its target is the payer's own wallet. +func (b *Bot) groupTitle(p *db.Purchase) string { + w, err := b.store.GetWallet(b.baseCtx, p.WalletID) + if err != nil || w.OwnerType != db.OwnerGroup { + return "" + } + g, err := b.store.GetGroup(b.baseCtx, w.OwnerID) + if err != nil || g.Title == "" { + return strconv.FormatInt(w.OwnerID, 10) + } + return g.Title } func (b *Bot) invoiceKeyboard(p *db.Purchase) *telego.InlineKeyboardMarkup { @@ -544,12 +569,18 @@ func (b *Bot) paidText(ctx context.Context, p *db.Purchase) string { if err != nil { return text } + // The same facts, worded for whose wallet it is. + balanceKey, passKey := "invoice.balance", "invoice.pass_until" + if w.OwnerType == db.OwnerGroup { + balanceKey, passKey = "invoice.group_balance", "invoice.group_pass_until" + text = b.tr.HTML(lang, "invoice.for_group", i18n.Args{"Group": b.groupTitle(p)}) + "\n" + text + } switch p.Product { case billing.ProductCredits: - text += "\n" + b.tr.HTML(lang, "invoice.balance", i18n.Args{"Balance": b.tr.Sats(lang, w.Balance)}) + text += "\n" + b.tr.HTML(lang, balanceKey, i18n.Args{"Balance": b.tr.Sats(lang, w.Balance)}) case billing.ProductPassDay, billing.ProductPassWeek, billing.ProductPassMonth: if until, err := b.store.PassUntil(ctx, w.ID, db.NowMilli()); err == nil && until > 0 { - text += "\n" + b.tr.HTML(lang, "invoice.pass_until", i18n.Args{"Until": b.tr.DateTime(lang, time.UnixMilli(until))}) + text += "\n" + b.tr.HTML(lang, passKey, i18n.Args{"Until": b.tr.DateTime(lang, time.UnixMilli(until))}) } case billing.ProductDonation: text += "\n" + b.tr.HTML(lang, "invoice.thanks", nil) @@ -712,8 +743,13 @@ func (b *Bot) offerUpgrade(ctx context.Context, chat, replyTo int64, lang string }) } } else { + // Two targets, both pre-selected by the link: the requester's own + // wallet, or the group's. link := "https://t.me/" + b.username + "?start=buy_" + req.ID + "_" + encodeProfile(string(profile)) - rows = append(rows, []telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.buy_for_me", nil), link)}) + rows = append(rows, + []telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.buy_for_me", nil), link)}, + []telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.add_group_credits", nil), b.groupWalletLink(chat))}, + ) } _, _ = b.send(ctx, chat, replyTo, text, keyboard(rows...)) } diff --git a/internal/bot/owner.go b/internal/bot/owner.go new file mode 100644 index 0000000..eb4b253 --- /dev/null +++ b/internal/bot/owner.go @@ -0,0 +1,538 @@ +package bot + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "strconv" + "strings" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/groups" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/service" + "github.com/noderunners/dlbot/internal/tg" +) + +const cbBroadcast = "bc" // bc: + +// ownerCommand runs an owner command and reports whether cmd was one. +// Owner commands only work in a private chat for the configured owners; +// for everyone else they do not exist. +func (b *Bot) ownerCommand(ctx context.Context, m *telego.Message, act actor, cmd string) bool { + if !b.isOwner(m) { + return false + } + switch cmd { + case "purge": + b.cmdPurge(ctx, m, act) + case "cache": + b.cmdCache(ctx, m, act) + case "workers": + b.cmdWorkers(ctx, m, act) + case "drain": + b.cmdDrain(ctx, m, act) + case "ytdlp": + b.cmdYtDlp(ctx, m, act) + case "stats": + b.cmdStats(ctx, m, act) + case "user": + b.cmdUser(ctx, m, act) + case "group": + b.cmdGroup(ctx, m, act) + case "ban", "unban": + b.cmdBan(ctx, m, act, cmd == "ban") + case "grant": + b.cmdGrant(ctx, m, act) + case "credit": + b.cmdCredit(ctx, m, act, false) + case "refund": + b.cmdCredit(ctx, m, act, true) + case "blocklist": + b.cmdBlocklist(ctx, m, act) + case "broadcast": + b.cmdBroadcast(ctx, m, act) + case "maint": + b.cmdMaint(ctx, m, act) + case "reload": + b.cmdReload(ctx, m, act) + default: + return false + } + return true +} + +func (b *Bot) ownerReply(ctx context.Context, m *telego.Message, act actor, key string, args i18n.Args) { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, key, args), nil) +} + +func (b *Bot) cmdStats(ctx context.Context, m *telego.Message, act actor) { + lang := act.lang + now := time.Now() + users, _ := b.store.CountUsers(ctx) + jobs, _ := b.store.JobCounts(ctx, now.Add(-24*time.Hour).UnixMilli()) + paid, free, oldest, _ := b.store.QueueDepth(ctx, now.UnixMilli()) + running, _ := b.store.CountRunning(ctx) + sats, _ := b.store.SatsReceived(ctx) + bst := b.bill.Stats() + cst := b.cache.Stats() + rate := "0%" + if t := cst.Hits + cst.Misses; t > 0 { + rate = b.tr.Percent(lang, float64(cst.Hits)/float64(t)) + } + books := b.tr.T(lang, "owner.books_ok", nil) + if bad, err := b.store.VerifyWallets(ctx); err != nil || len(bad) > 0 { + books = b.tr.T(lang, "owner.books_bad", i18n.Args{"Count": len(bad)}) + } + ln := b.tr.T(lang, "word.off", nil) + if b.bill.Enabled() { + ln = b.tr.T(lang, "owner.ln_ok", nil) + if !b.bill.Reachable() { + ln = b.tr.T(lang, "owner.ln_down", nil) + } + } + maint, _ := b.store.GetKV(ctx, "maintenance") + b.ownerReply(ctx, m, act, "owner.stats", i18n.Args{ + "Users": b.tr.Number(lang, users), + "Done": b.tr.Number(lang, jobs[db.JobDone]), + "Failed": b.tr.Number(lang, jobs[db.JobFailed]), + "Paid": paid, "Free": free, "Running": running, "Slots": b.sched.Capacity(), + "Oldest": b.tr.Span(lang, time.Duration(oldest)*time.Millisecond), + "Rate": rate, + "Saved": b.tr.Size(lang, cst.BytesSaved), + "Sats": b.tr.Sats(lang, sats), + "Created": bst.InvoicesCreated, "Settled": bst.InvoicesSettled, + "Lightning": ln, "Books": books, "Maint": b.onOff(lang, maint == "1"), + }) +} + +// cmdQueueAll is /queue all for owners: every queued and running job. +func (b *Bot) cmdQueueAll(ctx context.Context, m *telego.Message, act actor) { + jobs, err := b.store.ActiveJobs(ctx, 30) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + if len(jobs) == 0 { + b.ownerReply(ctx, m, act, "owner.queue_empty", nil) + return + } + var sb strings.Builder + sb.WriteString(b.tr.HTML(act.lang, "owner.queue_header", i18n.Args{"Count": len(jobs)})) + for _, j := range jobs { + worker := j.WorkerID + if worker == "" { + worker = "-" + } + tags := j.RequiredTags + if tags == "" { + tags = "-" + } + sb.WriteString("\n") + sb.WriteString(b.tr.HTML(act.lang, "owner.queue_line", i18n.Args{ + "ID": j.ID[len(j.ID)-6:], "Status": j.Status, "Lane": j.Lane, "Profile": j.Profile, + "Worker": worker, "Tags": tags, "Title": shorten(j.Title, 40), + })) + } + _, _ = b.send(ctx, m.Chat.ID, 0, sb.String(), nil) +} + +func idArg(m *telego.Message) (id int64, rest []string, ok bool) { + fields := strings.Fields(commandArgs(m)) + if len(fields) == 0 { + return 0, nil, false + } + id, err := strconv.ParseInt(fields[0], 10, 64) + return id, fields[1:], err == nil && id != 0 +} + +func (b *Bot) cmdUser(ctx context.Context, m *telego.Message, act actor) { + lang := act.lang + id, _, ok := idArg(m) + if !ok { + b.ownerReply(ctx, m, act, "owner.user_usage", nil) + return + } + u, err := b.store.GetUser(ctx, id) + if err != nil { + b.ownerReply(ctx, m, act, "owner.not_found", nil) + return + } + st, _ := b.bill.State(ctx, db.OwnerUser, id) + usage, _ := b.svc.Usage(ctx, id) + refs, _ := b.store.CountReferrals(ctx, id) + pass := b.tr.T(lang, "word.none", nil) + if st.PassUntil > 0 { + pass = b.tr.DateTime(lang, time.UnixMilli(st.PassUntil)) + } + b.ownerReply(ctx, m, act, "owner.user", i18n.Args{ + "ID": id, "Name": u.FirstName, "Username": u.Username, "Lang": u.Lang + "/" + u.LangOverride, + "Banned": b.onOff(lang, u.Banned), "Pass": pass, "Balance": b.tr.Sats(lang, st.Credits), + "Downloads": usage.Downloads, "Volume": b.tr.Size(lang, usage.Bytes), "Referrals": refs, + "Since": b.tr.DateTime(lang, time.UnixMilli(u.CreatedAt)), + }) +} + +func (b *Bot) cmdGroup(ctx context.Context, m *telego.Message, act actor) { + lang := act.lang + id, _, ok := idArg(m) + if !ok { + b.ownerReply(ctx, m, act, "owner.group_usage", nil) + return + } + g, err := b.store.GetGroup(ctx, id) + if err != nil { + b.ownerReply(ctx, m, act, "owner.not_found", nil) + return + } + st, _ := b.store.GetGroupSettings(ctx, id) + w, _ := b.bill.State(ctx, db.OwnerGroup, id) + pass := b.tr.T(lang, "word.none", nil) + if w.PassUntil > 0 { + pass = b.tr.DateTime(lang, time.UnixMilli(w.PassUntil)) + } + b.ownerReply(ctx, m, act, "owner.group", i18n.Args{ + "ID": id, "Title": g.Title, "Status": g.BotStatus, "Enabled": b.onOff(lang, st.Enabled), + "Who": st.WhoCanUse, "Spend": st.SpendRule, "Pass": pass, "Balance": b.tr.Sats(lang, w.Credits), + }) +} + +func (b *Bot) cmdBan(ctx context.Context, m *telego.Message, act actor, ban bool) { + id, _, ok := idArg(m) + if !ok { + b.ownerReply(ctx, m, act, "owner.ban_usage", nil) + return + } + if ban && b.cfg.IsOwner(id) { + b.ownerReply(ctx, m, act, "owner.ban_owner", nil) + return + } + found, err := b.store.SetUserBanned(ctx, id, ban) + switch { + case err != nil: + b.internalError(ctx, m.Chat.ID, act, err) + case !found: + b.ownerReply(ctx, m, act, "owner.not_found", nil) + case ban: + b.log.Info("user banned", "user_id", id, "by", act.user.ID) + b.ownerReply(ctx, m, act, "owner.banned", i18n.Args{"ID": id}) + default: + b.ownerReply(ctx, m, act, "owner.unbanned", i18n.Args{"ID": id}) + } +} + +// walletFor returns the wallet of a user (positive ID) or group (negative). +func (b *Bot) walletFor(ctx context.Context, id int64) (*db.Wallet, error) { + if id < 0 { + if _, err := b.store.GetGroup(ctx, id); err != nil { + return nil, err + } + return b.bill.Wallet(ctx, db.OwnerGroup, id) + } + if _, err := b.store.GetUser(ctx, id); err != nil { + return nil, err + } + return b.bill.Wallet(ctx, db.OwnerUser, id) +} + +func uniqueRef() string { + var raw [8]byte + _, _ = rand.Read(raw[:]) + return hex.EncodeToString(raw[:]) +} + +// cmdGrant handles +// +// /grant day|week|month a pass for a user or a group +// /grant code credits [uses] a gift code for credits +// /grant code day|week|month [uses] a gift code for a pass +func (b *Bot) cmdGrant(ctx context.Context, m *telego.Message, act actor) { + lang := act.lang + fields := strings.Fields(strings.ToLower(commandArgs(m))) + if len(fields) >= 2 && fields[0] == "code" { + kind, rest := fields[1], fields[2:] + var amount int64 + if kind == billing.GiftCredits { + if len(rest) == 0 { + b.ownerReply(ctx, m, act, "owner.grant_usage", nil) + return + } + amount, _ = strconv.ParseInt(rest[0], 10, 64) + rest = rest[1:] + } + uses := 1 + if len(rest) > 0 { + uses, _ = strconv.Atoi(rest[0]) + } + g, err := b.bill.NewGiftCode(ctx, kind, amount, uses, 0, act.user.ID) + if err != nil { + b.ownerReply(ctx, m, act, "owner.grant_usage", nil) + return + } + b.ownerReply(ctx, m, act, "owner.gift_code", i18n.Args{"Code": g.Code, "Uses": g.MaxUses}) + return + } + id, rest, ok := idArg(m) + if !ok || len(rest) != 1 || billing.PassLength(strings.ToLower(rest[0])) == 0 { + b.ownerReply(ctx, m, act, "owner.grant_usage", nil) + return + } + w, err := b.walletFor(ctx, id) + if err != nil { + b.ownerReply(ctx, m, act, "owner.not_found", nil) + return + } + pass, err := b.bill.GrantPass(ctx, w.ID, strings.ToLower(rest[0]), "owner:"+strconv.FormatInt(act.user.ID, 10)) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + b.log.Info("pass granted", "target", id, "kind", rest[0], "by", act.user.ID) + b.ownerReply(ctx, m, act, "owner.granted", i18n.Args{"ID": id, "Until": b.tr.DateTime(lang, time.UnixMilli(pass.ExpiresAt))}) +} + +// cmdCredit handles /credit and /refund , and +// /refund pass which extends a running pass. +func (b *Bot) cmdCredit(ctx context.Context, m *telego.Message, act actor, refund bool) { + lang := act.lang + usage := "owner.credit_usage" + if refund { + usage = "owner.refund_usage" + } + id, rest, ok := idArg(m) + if !ok || len(rest) == 0 { + b.ownerReply(ctx, m, act, usage, nil) + return + } + w, err := b.walletFor(ctx, id) + if err != nil { + b.ownerReply(ctx, m, act, "owner.not_found", nil) + return + } + if refund && rest[0] == "pass" { + if len(rest) != 2 { + b.ownerReply(ctx, m, act, usage, nil) + return + } + d, err := time.ParseDuration(rest[1]) + if err != nil || d <= 0 || d > 90*24*time.Hour { + b.ownerReply(ctx, m, act, usage, nil) + return + } + extended, err := b.store.ExtendPass(ctx, w.ID, d.Milliseconds(), db.NowMilli()) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + if !extended { + b.ownerReply(ctx, m, act, "owner.no_pass", nil) + return + } + until, _ := b.store.PassUntil(ctx, w.ID, db.NowMilli()) + b.ownerReply(ctx, m, act, "owner.granted", i18n.Args{"ID": id, "Until": b.tr.DateTime(lang, time.UnixMilli(until))}) + return + } + sats, err := strconv.ParseInt(rest[0], 10, 64) + if err != nil || sats <= 0 || sats > billing.MaxAmount { + b.ownerReply(ctx, m, act, usage, nil) + return + } + ref := uniqueRef() + if refund { + _, err = b.bill.Refund(ctx, w.ID, sats, "owner_refund", ref, "owner-refund:"+ref, act.user.ID) + } else { + _, err = b.bill.Credit(ctx, w.ID, sats, "owner_grant", ref, "owner-grant:"+ref, act.user.ID) + } + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + nw, _ := b.store.GetWallet(ctx, w.ID) + b.log.Info("wallet credited by owner", "target", id, "sats", sats, "refund", refund, "by", act.user.ID) + b.ownerReply(ctx, m, act, "owner.credited", i18n.Args{ + "ID": id, "Amount": b.tr.Sats(lang, sats), "Balance": b.tr.Sats(lang, nw.Balance), + }) +} + +// cmdBlocklist handles /blocklist, /blocklist add site|key [reason] +// and /blocklist remove site|key . +func (b *Bot) cmdBlocklist(ctx context.Context, m *telego.Message, act actor) { + fields := strings.Fields(commandArgs(m)) + if len(fields) == 0 || fields[0] == "list" { + list, err := b.store.ListBlocks(ctx, 50) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + if len(list) == 0 { + b.ownerReply(ctx, m, act, "owner.blocklist_empty", nil) + return + } + var sb strings.Builder + sb.WriteString(b.tr.HTML(act.lang, "owner.blocklist_header", nil)) + for _, e := range list { + sb.WriteString("\n") + sb.WriteString(b.tr.HTML(act.lang, "owner.blocklist_line", i18n.Args{"Kind": e.Kind, "Value": e.Value, "Reason": e.Reason})) + } + _, _ = b.send(ctx, m.Chat.ID, 0, sb.String(), nil) + return + } + if len(fields) < 3 || (fields[1] != db.BlockSite && fields[1] != db.BlockKey) { + b.ownerReply(ctx, m, act, "owner.blocklist_usage", nil) + return + } + kind, value := fields[1], fields[2] + if kind == db.BlockSite { + if value = groups.CleanHost(value); value == "" { + b.ownerReply(ctx, m, act, "owner.blocklist_usage", nil) + return + } + } + switch fields[0] { + case "add": + if err := b.store.AddBlock(ctx, kind, value, strings.Join(fields[3:], " "), act.user.ID); err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + b.ownerReply(ctx, m, act, "owner.blocked", i18n.Args{"Value": value}) + case "remove": + found, err := b.store.RemoveBlock(ctx, kind, value) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + if !found { + b.ownerReply(ctx, m, act, "owner.not_found", nil) + return + } + b.ownerReply(ctx, m, act, "owner.unblocked", i18n.Args{"Value": value}) + default: + b.ownerReply(ctx, m, act, "owner.blocklist_usage", nil) + } +} + +func (b *Bot) cmdMaint(ctx context.Context, m *telego.Message, act actor) { + arg := strings.ToLower(strings.TrimSpace(commandArgs(m))) + if arg != "on" && arg != "off" { + b.ownerReply(ctx, m, act, "owner.maint_usage", nil) + return + } + v := "0" + if arg == "on" { + v = "1" + } + if err := b.store.SetKV(ctx, "maintenance", v); err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + b.log.Info("maintenance mode", "on", arg == "on", "by", act.user.ID) + b.ownerReply(ctx, m, act, "owner.maint_"+arg, nil) +} + +func (b *Bot) cmdReload(ctx context.Context, m *telego.Message, act actor) { + if strings.TrimSpace(commandArgs(m)) != "i18n" { + b.ownerReply(ctx, m, act, "owner.reload_usage", nil) + return + } + if b.reloadI18n == nil { + b.ownerReply(ctx, m, act, "owner.reload_builtin", nil) + return + } + if err := b.reloadI18n(); err != nil { + b.log.Error("reload catalogs", "err", err) + b.ownerReply(ctx, m, act, "owner.reload_failed", i18n.Args{"Error": err.Error()}) + return + } + b.RegisterCommands(ctx) + b.ownerReply(ctx, m, act, "owner.reloaded", i18n.Args{"Langs": strings.Join(b.tr.Langs(), ", ")}) +} + +// cmdBroadcast shows a preview with a confirm button. Nothing is sent +// until the owner presses it. +func (b *Bot) cmdBroadcast(ctx context.Context, m *telego.Message, act actor) { + text := strings.TrimSpace(commandArgs(m)) + if text == "" { + b.ownerReply(ctx, m, act, "owner.broadcast_usage", nil) + return + } + users, _ := b.store.CountUsers(ctx) + token := uniqueRef() + b.statusMu.Lock() + b.broadcasts[token] = text + b.statusMu.Unlock() + kb := keyboard([]telego.InlineKeyboardButton{ + button(b.tr.T(act.lang, "owner.broadcast_send", i18n.Args{"Count": users}), cbData(cbBroadcast, token)), + }) + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "owner.broadcast_preview", i18n.Args{"Text": text}), kb) +} + +func (b *Bot) cbBroadcastSend(ctx context.Context, q *telego.CallbackQuery, act actor, token string) { + if !b.cfg.IsOwner(act.user.ID) { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.statusMu.Lock() + text, ok := b.broadcasts[token] + delete(b.broadcasts, token) + b.statusMu.Unlock() + if !ok { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.answer(ctx, q, "", false) + b.goBG("broadcast", func() { + sent, failed := b.broadcast(ctx, text) + b.log.Info("broadcast finished", "sent", sent, "failed", failed, "by", act.user.ID) + _, _ = b.send(ctx, act.user.ID, 0, b.tr.HTML(act.lang, "owner.broadcast_done", i18n.Args{"Sent": sent, "Failed": failed}), nil) + }) +} + +// broadcast sends a plain text message to every user, at a pace well +// under Telegram's limit of about 30 messages per second. +func (b *Bot) broadcast(ctx context.Context, text string) (sent, failed int) { + var after int64 + for ctx.Err() == nil { + ids, err := b.store.UserIDs(ctx, after, 200) + if err != nil || len(ids) == 0 { + return + } + for _, id := range ids { + after = id + _, err := b.api.SendMessage(ctx, &telego.SendMessageParams{ChatID: chatID(id), Text: text, LinkPreviewOptions: noPreview}) + switch { + case err == nil: + sent++ + case tg.RetryAfter(err) > 0: + sleepCtx(ctx, tg.RetryAfter(err)) + failed++ + default: + failed++ + } + sleepCtx(ctx, b.broadcastGap) + if ctx.Err() != nil { + return + } + } + } + return +} + +// refuse answers a link with the reason it cannot be handled here. Some +// refusals are silent: a group that switched the bot off does not want to +// hear from it. +func (b *Bot) refuse(ctx context.Context, chat, replyTo int64, lang string, err error) { + var le *service.LimitError + if !errors.As(err, &le) { + b.log.Error("gate", "err", err) + return + } + if le.Code == service.LimitGroupDisabled { + return + } + _, _ = b.send(ctx, chat, replyTo, b.tr.HTML(lang, "limit."+le.Code, nil), nil) +} diff --git a/internal/config/config.go b/internal/config/config.go index 15f57c6..1f22fc2 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -71,6 +71,17 @@ type Config struct { // when the embedded worker is on and worker otherwise. ProbeMode string `toml:"probe_mode" env:"PROBE_MODE"` + // Support is where /support points users: a @username or a link. + Support string `toml:"support" env:"SUPPORT_CONTACT"` + + // MiniApp turns the Mini App links on. It needs PublicURL. + MiniApp bool `toml:"miniapp" env:"MINIAPP_ENABLED"` + + // LocalesDir, when set, loads the translation catalogs from this + // directory instead of the ones built into the binary, and makes + // "/reload i18n" pick up edits without a restart. + LocalesDir string `toml:"locales_dir" env:"LOCALES_DIR"` + // PublicURL is the HTTPS base URL this server is reachable at from the // internet, without a trailing slash. It is used for payment webhooks, // "open in wallet" links and the Mini App. @@ -508,6 +519,10 @@ func (c Config) RequiredTags(site string) string { return strings.Join(tags, ",") } +// MiniAppEnabled reports whether Mini App links can be shown. The Mini App +// is served from PublicURL, so both are needed. +func (c Config) MiniAppEnabled() bool { return c.MiniApp && c.PublicURL != "" } + // ProbeLocally reports whether the core itself runs metadata lookups. func (c Config) ProbeLocally() bool { switch c.ProbeMode { diff --git a/internal/db/groups.go b/internal/db/groups.go new file mode 100644 index 0000000..2fda2aa --- /dev/null +++ b/internal/db/groups.go @@ -0,0 +1,308 @@ +package db + +import ( + "context" + "database/sql" + "errors" + "strings" +) + +// Group is a chat the bot was added to. +type Group struct { + ChatID int64 + Title string + Type string + BotStatus string // member, administrator, left, kicked + AddedBy int64 + CreatedAt int64 + UpdatedAt int64 +} + +// Present reports whether the bot is still in the group. +func (g *Group) Present() bool { + return g.BotStatus == "member" || g.BotStatus == "administrator" || g.BotStatus == "creator" || g.BotStatus == "restricted" +} + +// Who may use the bot in a group. +const ( + UseEveryone = "everyone" + UsePassHolders = "pass_holders" + UseAdmins = "admins" +) + +// Who may spend the group's credits. +const ( + SpendAnyone = "anyone" + SpendAdmins = "admins" + SpendCapped = "capped" // anyone, up to a number of sats per person per day +) + +// GroupSettings are the per-group options admins control. +type GroupSettings struct { + ChatID int64 + Enabled bool + AutoDetect bool + Allowed string // comma separated hosts; empty allows every site + Blocked string // comma separated hosts + WhoCanUse string + MaxSizeMB int64 // 0 means "whatever the tier allows" + MaxDuration int64 // seconds, 0 likewise + SpendRule string + SpendCap int64 // sats per person per day, for SpendCapped + DailyCap int64 // sats per day for the whole group, 0 for no cap + DeleteCmds bool + Quality string // default profile, "" shows the card + Lang string // "" follows each requester + UpdatedAt int64 +} + +// DefaultGroupSettings are the settings of a group nobody configured. +func DefaultGroupSettings(chatID int64) *GroupSettings { + return &GroupSettings{ChatID: chatID, Enabled: true, WhoCanUse: UseEveryone, SpendRule: SpendAdmins} +} + +// Sites splits a comma separated host list. +func Sites(list string) []string { + var out []string + for _, s := range strings.Split(list, ",") { + if s = strings.ToLower(strings.TrimSpace(s)); s != "" { + out = append(out, s) + } + } + return out +} + +// UpsertGroup records a group and the bot's status in it. +func (s *Store) UpsertGroup(ctx context.Context, g *Group) error { + now := NowMilli() + _, err := s.exec(ctx, `INSERT INTO groups (chat_id, title, type, bot_status, added_by, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (chat_id) DO UPDATE SET + title = CASE WHEN excluded.title <> '' THEN excluded.title ELSE groups.title END, + type = excluded.type, bot_status = excluded.bot_status, updated_at = excluded.updated_at`, + g.ChatID, g.Title, g.Type, g.BotStatus, g.AddedBy, now, now) + return err +} + +// GetGroup loads a group. +func (s *Store) GetGroup(ctx context.Context, chatID int64) (*Group, error) { + var g Group + err := s.row(ctx, `SELECT chat_id, title, type, bot_status, added_by, created_at, updated_at + FROM groups WHERE chat_id = ?`, chatID).Scan(&g.ChatID, &g.Title, &g.Type, &g.BotStatus, &g.AddedBy, + &g.CreatedAt, &g.UpdatedAt) + if err != nil { + return nil, notFound(err) + } + return &g, nil +} + +// GetGroupSettings loads a group's settings, or the defaults. +func (s *Store) GetGroupSettings(ctx context.Context, chatID int64) (*GroupSettings, error) { + g := DefaultGroupSettings(chatID) + err := s.row(ctx, `SELECT enabled, auto_detect, allowed_sites, blocked_sites, who_can_use, max_size_mb, + max_duration_s, spend_rule, spend_cap_sats, daily_cap_sats, delete_commands, default_quality, lang, updated_at + FROM group_settings WHERE chat_id = ?`, chatID).Scan(&g.Enabled, &g.AutoDetect, &g.Allowed, &g.Blocked, + &g.WhoCanUse, &g.MaxSizeMB, &g.MaxDuration, &g.SpendRule, &g.SpendCap, &g.DailyCap, &g.DeleteCmds, + &g.Quality, &g.Lang, &g.UpdatedAt) + if errors.Is(err, sql.ErrNoRows) { + return g, nil + } + return g, err +} + +// SaveGroupSettings stores a group's settings. +func (s *Store) SaveGroupSettings(ctx context.Context, g *GroupSettings) error { + g.UpdatedAt = NowMilli() + _, err := s.exec(ctx, `INSERT INTO group_settings (chat_id, enabled, auto_detect, allowed_sites, blocked_sites, + who_can_use, max_size_mb, max_duration_s, spend_rule, spend_cap_sats, daily_cap_sats, delete_commands, + default_quality, lang, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (chat_id) DO UPDATE SET + enabled = excluded.enabled, auto_detect = excluded.auto_detect, + allowed_sites = excluded.allowed_sites, blocked_sites = excluded.blocked_sites, + who_can_use = excluded.who_can_use, max_size_mb = excluded.max_size_mb, + max_duration_s = excluded.max_duration_s, spend_rule = excluded.spend_rule, + spend_cap_sats = excluded.spend_cap_sats, daily_cap_sats = excluded.daily_cap_sats, + delete_commands = excluded.delete_commands, default_quality = excluded.default_quality, + lang = excluded.lang, updated_at = excluded.updated_at`, + g.ChatID, g.Enabled, g.AutoDetect, g.Allowed, g.Blocked, g.WhoCanUse, g.MaxSizeMB, g.MaxDuration, + g.SpendRule, g.SpendCap, g.DailyCap, g.DeleteCmds, g.Quality, g.Lang, g.UpdatedAt) + return err +} + +// AddGroupUsage adds to a member's counters in a group for a day. Negative +// values give back. +func (s *Store) AddGroupUsage(ctx context.Context, chatID, userID int64, day, downloads int, sats, bytes int64) error { + _, err := s.exec(ctx, `INSERT INTO group_usage_daily (chat_id, user_id, day, downloads, sats, bytes) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (chat_id, user_id, day) DO UPDATE SET + downloads = group_usage_daily.downloads + excluded.downloads, + sats = group_usage_daily.sats + excluded.sats, + bytes = group_usage_daily.bytes + excluded.bytes`, chatID, userID, day, downloads, sats, bytes) + return err +} + +// GroupSpent returns the group credits spent on a day: by one member and +// by everyone. +func (s *Store) GroupSpent(ctx context.Context, chatID, userID int64, day int) (member, total int64, err error) { + var m, t sql.NullInt64 + err = s.row(ctx, `SELECT + SUM(CASE WHEN user_id = ? THEN sats ELSE 0 END), SUM(sats) + FROM group_usage_daily WHERE chat_id = ? AND day = ?`, userID, chatID, day).Scan(&m, &t) + return m.Int64, t.Int64, err +} + +// MemberUsage is one member's use of a group over a period. +type MemberUsage struct { + UserID int64 + Name string + Downloads int64 + Sats int64 + Bytes int64 +} + +// GroupUsage sums usage per member since a day, biggest first. +func (s *Store) GroupUsage(ctx context.Context, chatID int64, sinceDay, limit int) ([]MemberUsage, error) { + rows, err := s.rows(ctx, `SELECT g.user_id, COALESCE(u.first_name, ''), SUM(g.downloads), SUM(g.sats), SUM(g.bytes) + FROM group_usage_daily g LEFT JOIN users u ON u.id = g.user_id + WHERE g.chat_id = ? AND g.day >= ? + GROUP BY g.user_id, u.first_name + ORDER BY SUM(g.downloads) DESC, g.user_id LIMIT ?`, chatID, sinceDay, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []MemberUsage + for rows.Next() { + var m MemberUsage + if err := rows.Scan(&m.UserID, &m.Name, &m.Downloads, &m.Sats, &m.Bytes); err != nil { + return nil, err + } + out = append(out, m) + } + return out, rows.Err() +} + +// SeeGroupUser records that a user was active in a group. +func (s *Store) SeeGroupUser(ctx context.Context, chatID, userID int64) error { + _, err := s.exec(ctx, `INSERT INTO group_users (chat_id, user_id, last_seen_at) VALUES (?, ?, ?) + ON CONFLICT (chat_id, user_id) DO UPDATE SET last_seen_at = excluded.last_seen_at`, + chatID, userID, NowMilli()) + return err +} + +// GroupsOfUser lists the groups a user was seen in where the bot still is. +func (s *Store) GroupsOfUser(ctx context.Context, userID int64, limit int) ([]*Group, error) { + rows, err := s.rows(ctx, `SELECT g.chat_id, g.title, g.type, g.bot_status, g.added_by, g.created_at, g.updated_at + FROM groups g JOIN group_users gu ON gu.chat_id = g.chat_id + WHERE gu.user_id = ? AND g.bot_status IN ('member', 'administrator', 'restricted') + ORDER BY gu.last_seen_at DESC LIMIT ?`, userID, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*Group + for rows.Next() { + var g Group + if err := rows.Scan(&g.ChatID, &g.Title, &g.Type, &g.BotStatus, &g.AddedBy, &g.CreatedAt, &g.UpdatedAt); err != nil { + return nil, err + } + out = append(out, &g) + } + return out, rows.Err() +} + +// --- key-value ------------------------------------------------------------- + +// GetKV reads a value, or "" when the key is not set. +func (s *Store) GetKV(ctx context.Context, key string) (string, error) { + var v string + err := s.row(ctx, `SELECT v FROM kv WHERE k = ?`, key).Scan(&v) + if errors.Is(err, sql.ErrNoRows) { + return "", nil + } + return v, err +} + +// SetKV stores a value. +func (s *Store) SetKV(ctx context.Context, key, value string) error { + _, err := s.exec(ctx, `INSERT INTO kv (k, v) VALUES (?, ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v`, key, value) + return err +} + +// --- users, extended ------------------------------------------------------- + +// SetUserQuality stores a user's default format. +func (s *Store) SetUserQuality(ctx context.Context, userID int64, quality string) error { + _, err := s.exec(ctx, `UPDATE users SET default_quality = ? WHERE id = ?`, quality, userID) + return err +} + +// SetUserLang stores the language a user chose, "" to follow Telegram. +func (s *Store) SetUserLang(ctx context.Context, userID int64, lang string) error { + _, err := s.exec(ctx, `UPDATE users SET lang_override = ? WHERE id = ?`, lang, userID) + return err +} + +// SetUserBanned bans or unbans a user and reports whether the user exists. +func (s *Store) SetUserBanned(ctx context.Context, userID int64, banned bool) (bool, error) { + n, err := s.exec(ctx, `UPDATE users SET banned = ? WHERE id = ?`, banned, userID) + return n == 1, err +} + +// CountUsers counts known users. +func (s *Store) CountUsers(ctx context.Context) (int64, error) { + var n int64 + err := s.row(ctx, `SELECT COUNT(*) FROM users`).Scan(&n) + return n, err +} + +// UserIDs lists users for a broadcast, in ID order after a cursor. +func (s *Store) UserIDs(ctx context.Context, after int64, limit int) ([]int64, error) { + rows, err := s.rows(ctx, `SELECT id FROM users WHERE id > ? AND banned = ? ORDER BY id LIMIT ?`, after, false, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []int64 + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, err + } + out = append(out, id) + } + return out, rows.Err() +} + +// JobCounts counts jobs by status that were created since a time. +func (s *Store) JobCounts(ctx context.Context, since int64) (map[string]int64, error) { + rows, err := s.rows(ctx, `SELECT status, COUNT(*) FROM jobs WHERE created_at >= ? GROUP BY status`, since) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]int64{} + for rows.Next() { + var st string + var n int64 + if err := rows.Scan(&st, &n); err != nil { + return nil, err + } + out[st] = n + } + return out, rows.Err() +} + +// ActiveJobs lists queued and running jobs in claim order. +func (s *Store) ActiveJobs(ctx context.Context, limit int) ([]*Job, error) { + return scanJobs(s.rows(ctx, `SELECT `+jobCols+` FROM jobs WHERE status IN ('queued', 'running') + ORDER BY CASE status WHEN 'running' THEN 0 ELSE 1 END, `+queueOrder+` LIMIT ?`, limit)) +} + +// SatsReceived sums paid purchases. +func (s *Store) SatsReceived(ctx context.Context) (int64, error) { + var n sql.NullInt64 + err := s.row(ctx, `SELECT SUM(amount_sats) FROM purchases WHERE status = 'paid'`).Scan(&n) + return n.Int64, err +} diff --git a/internal/db/migrations/00005_groups.sql b/internal/db/migrations/00005_groups.sql new file mode 100644 index 0000000..a0c0196 --- /dev/null +++ b/internal/db/migrations/00005_groups.sql @@ -0,0 +1,70 @@ +-- +goose Up +-- Groups the bot was added to, recorded from my_chat_member updates. +CREATE TABLE groups ( + chat_id BIGINT PRIMARY KEY, + title TEXT NOT NULL DEFAULT '', + type TEXT NOT NULL DEFAULT 'supergroup', + bot_status TEXT NOT NULL DEFAULT 'member', + added_by BIGINT NOT NULL DEFAULT 0, + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL +); + +-- Per-group settings, changed by group admins only. A group without a row +-- runs on the defaults. +CREATE TABLE group_settings ( + chat_id BIGINT PRIMARY KEY, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + auto_detect BOOLEAN NOT NULL DEFAULT FALSE, + allowed_sites TEXT NOT NULL DEFAULT '', + blocked_sites TEXT NOT NULL DEFAULT '', + who_can_use TEXT NOT NULL DEFAULT 'everyone', + max_size_mb BIGINT NOT NULL DEFAULT 0, + max_duration_s BIGINT NOT NULL DEFAULT 0, + spend_rule TEXT NOT NULL DEFAULT 'admins', + spend_cap_sats BIGINT NOT NULL DEFAULT 0, + daily_cap_sats BIGINT NOT NULL DEFAULT 0, + delete_commands BOOLEAN NOT NULL DEFAULT FALSE, + default_quality TEXT NOT NULL DEFAULT '', + lang TEXT NOT NULL DEFAULT '', + updated_at BIGINT NOT NULL DEFAULT 0 +); + +-- What each member used in a group per UTC day: for spending caps and for +-- the usage-by-member view. +CREATE TABLE group_usage_daily ( + chat_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + day INTEGER NOT NULL, + downloads INTEGER NOT NULL DEFAULT 0, + sats BIGINT NOT NULL DEFAULT 0, + bytes BIGINT NOT NULL DEFAULT 0, + PRIMARY KEY (chat_id, user_id, day) +); + +-- Which users were seen in which group, so "my groups" can be listed +-- without asking Telegram about every group. +CREATE TABLE group_users ( + chat_id BIGINT NOT NULL, + user_id BIGINT NOT NULL, + last_seen_at BIGINT NOT NULL, + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX group_users_user_idx ON group_users (user_id); + +-- Small key-value store for owner switches such as maintenance mode. +CREATE TABLE kv ( + k TEXT PRIMARY KEY, + v TEXT NOT NULL +); + +-- A user's default format: "" asks every time. +ALTER TABLE users ADD COLUMN default_quality TEXT NOT NULL DEFAULT ''; + +-- +goose Down +ALTER TABLE users DROP COLUMN default_quality; +DROP TABLE kv; +DROP TABLE group_users; +DROP TABLE group_usage_daily; +DROP TABLE group_settings; +DROP TABLE groups; diff --git a/internal/db/models.go b/internal/db/models.go index 413d379..4e9c9e2 100644 --- a/internal/db/models.go +++ b/internal/db/models.go @@ -64,6 +64,8 @@ type User struct { CreatedAt int64 LastSeenAt int64 ReferredBy int64 // user who invited this one, 0 for none + // Quality is the user's default format, "" to be asked every time. + Quality string // IsNew is set by UpsertUser when the row was just created. IsNew bool } diff --git a/internal/db/users.go b/internal/db/users.go index 5a1b8a1..cc4136b 100644 --- a/internal/db/users.go +++ b/internal/db/users.go @@ -2,11 +2,11 @@ package db import "context" -const userCols = `id, username, first_name, lang, lang_override, banned, created_at, last_seen_at, referred_by` +const userCols = `id, username, first_name, lang, lang_override, banned, created_at, last_seen_at, referred_by, default_quality` func scanUser(sc interface{ Scan(...any) error }) (*User, error) { var u User - err := sc.Scan(&u.ID, &u.Username, &u.FirstName, &u.Lang, &u.LangOverride, &u.Banned, &u.CreatedAt, &u.LastSeenAt, &u.ReferredBy) + err := sc.Scan(&u.ID, &u.Username, &u.FirstName, &u.Lang, &u.LangOverride, &u.Banned, &u.CreatedAt, &u.LastSeenAt, &u.ReferredBy, &u.Quality) if err != nil { return nil, notFound(err) } diff --git a/internal/groups/admins.go b/internal/groups/admins.go new file mode 100644 index 0000000..6af5dfa --- /dev/null +++ b/internal/groups/admins.go @@ -0,0 +1,110 @@ +// Package groups holds what the bot and the Mini App share about group +// chats: who is an admin, and how site lists are matched. +package groups + +import ( + "context" + "strings" + "sync" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/tg" +) + +// Admins answers "is this user an admin of this chat" by asking Telegram +// (getChatMember) and remembering the answer for a few minutes. Admin +// rights are never taken from anything a client sends. +type Admins struct { + api tg.API + ttl time.Duration + now func() time.Time + + mu sync.Mutex + cache map[[2]int64]entry +} + +type entry struct { + admin bool + at time.Time +} + +// NewAdmins creates a checker. A ttl of 0 uses five minutes. +func NewAdmins(api tg.API, ttl time.Duration) *Admins { + if ttl <= 0 { + ttl = 5 * time.Minute + } + return &Admins{api: api, ttl: ttl, now: time.Now, cache: map[[2]int64]entry{}} +} + +// IsAdmin reports whether the user is the creator or an administrator of +// the chat. When Telegram cannot be asked the answer is no. +func (a *Admins) IsAdmin(ctx context.Context, chatID, userID int64) bool { + key := [2]int64{chatID, userID} + a.mu.Lock() + if e, ok := a.cache[key]; ok && a.now().Sub(e.at) < a.ttl { + a.mu.Unlock() + return e.admin + } + a.mu.Unlock() + + m, err := a.api.GetChatMember(ctx, &telego.GetChatMemberParams{ChatID: telego.ChatID{ID: chatID}, UserID: userID}) + if err != nil { + return false // not cached: a later call may succeed + } + status := m.MemberStatus() + admin := status == telego.MemberStatusCreator || status == telego.MemberStatusAdministrator + + a.mu.Lock() + if len(a.cache) > 20000 { + a.cache = map[[2]int64]entry{} + } + a.cache[key] = entry{admin: admin, at: a.now()} + a.mu.Unlock() + return admin +} + +// Forget drops what is remembered about a chat, for example after the +// bot's own status in it changed. +func (a *Admins) Forget(chatID int64) { + a.mu.Lock() + defer a.mu.Unlock() + for k := range a.cache { + if k[0] == chatID { + delete(a.cache, k) + } + } +} + +// HostInList reports whether a site is covered by a list of hosts. An +// entry covers the host itself and its subdomains. +func HostInList(site string, list []string) bool { + site = strings.ToLower(site) + for _, h := range list { + if site == h || strings.HasSuffix(site, "."+h) { + return true + } + } + return false +} + +// CleanHost turns what an admin typed (a host, or a whole link) into a +// bare host name, or "" when it is not one. +func CleanHost(s string) string { + s = strings.ToLower(strings.TrimSpace(s)) + s = strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://") + if i := strings.IndexAny(s, "/?#"); i >= 0 { + s = s[:i] + } + s = strings.TrimPrefix(strings.TrimPrefix(s, "www."), "m.") + if s == "" || !strings.Contains(s, ".") || strings.ContainsAny(s, " ,:@") { + return "" + } + return s +} + +// IsGroup reports whether a Telegram chat type is a group. +func IsGroup(chatType string) bool { + return chatType == telego.ChatTypeGroup || chatType == telego.ChatTypeSupergroup +} diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go index be46a1e..34d9078 100644 --- a/internal/i18n/i18n.go +++ b/internal/i18n/i18n.go @@ -89,8 +89,36 @@ func Load(fsys fs.FS, log *slog.Logger) (*Bundle, error) { return b, nil } +// Pseudo is the pseudo-locale: English with every letter accented and +// each string wrapped in brackets. Text that shows up plain while it is +// selected did not come from the catalog. +const Pseudo = "en-XA" + +// Hidden reports whether a language is for testing and should not be +// offered to users. +func (b *Bundle) Hidden(lang string) bool { return strings.EqualFold(lang, Pseudo) } + +// Reload replaces the catalogs with the ones in fsys. When they do not +// load, the old ones stay in use and the error says why. +func (b *Bundle) Reload(fsys fs.FS) error { + fresh, err := Load(fsys, b.log) + if err != nil { + return err + } + b.mu.Lock() + defer b.mu.Unlock() + b.bundle, b.tags, b.names, b.matcher = fresh.bundle, fresh.tags, fresh.names, fresh.matcher + b.localizers = map[string]*goi18n.Localizer{} + b.printers = map[string]*message.Printer{} + return nil +} + // Langs returns the loaded language tags, English first. -func (b *Bundle) Langs() []string { return append([]string(nil), b.names...) } +func (b *Bundle) Langs() []string { + b.mu.Lock() + defer b.mu.Unlock() + return append([]string(nil), b.names...) +} // Resolve maps any language code, such as the language_code Telegram sends, // to the closest loaded language. Regional variants fall back to their base @@ -103,6 +131,8 @@ func (b *Bundle) Resolve(code string) string { if err != nil { return Default } + b.mu.Lock() + defer b.mu.Unlock() _, idx, conf := b.matcher.Match(tag) if conf == language.No { return Default @@ -189,7 +219,10 @@ func (b *Bundle) Has(lang, id string) bool { if err != nil { return false } - _, gotTag, err := goi18n.NewLocalizer(b.bundle, lang).LocalizeWithTag(&goi18n.LocalizeConfig{ + b.mu.Lock() + bundle := b.bundle + b.mu.Unlock() + _, gotTag, err := goi18n.NewLocalizer(bundle, lang).LocalizeWithTag(&goi18n.LocalizeConfig{ MessageID: id, PluralCount: 2, TemplateData: map[string]any{}, }) return err == nil && gotTag == tag diff --git a/internal/service/service.go b/internal/service/service.go index c4e64e0..6aec269 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -155,8 +155,118 @@ const ( // LimitBlocked is a takedown by the owner: the video or its site is on // the blocklist. LimitBlocked = "blocked" + // Refusals from a group's own settings. + LimitGroupDisabled = "group_disabled" + LimitGroupAdminsOnly = "group_admins_only" + LimitGroupPassOnly = "group_pass_only" + LimitGroupSite = "group_site" + // LimitMaintenance is the owner's maintenance switch. + LimitMaintenance = "maintenance" ) +// AdminChecker says whether a user is an admin of a group chat. +type AdminChecker interface { + IsAdmin(ctx context.Context, chatID, userID int64) bool +} + +// SetAdmins gives the service the means to check group admins. Until it +// is set nobody counts as an admin. +func (s *Service) SetAdmins(a AdminChecker) { s.admins = a } + +// groupContext is what a request from a group is judged by. +type groupContext struct { + settings *db.GroupSettings + wallet entitle.Wallet + admin bool + // memberSpent and totalSpent are group credits spent today. + memberSpent, totalSpent int64 +} + +func isGroup(chatType string) bool { return chatType == "group" || chatType == "supergroup" } + +func (s *Service) groupContext(ctx context.Context, who Who) (*groupContext, error) { + if !isGroup(who.ChatType) { + return nil, nil + } + gc := &groupContext{} + var err error + if gc.settings, err = s.store.GetGroupSettings(ctx, who.ChatID); err != nil { + return nil, err + } + if gc.wallet, err = s.billing.State(ctx, db.OwnerGroup, who.ChatID); err != nil { + return nil, err + } + if s.admins != nil { + gc.admin = s.admins.IsAdmin(ctx, who.ChatID, who.UserID) + } + if gc.memberSpent, gc.totalSpent, err = s.store.GroupSpent(ctx, who.ChatID, who.UserID, Day(s.now())); err != nil { + return nil, err + } + return gc, nil +} + +// creditsAllowed applies the group's spending rule and caps to one more +// download by this member. +func (gc *groupContext) creditsAllowed(cost int64) bool { + st := gc.settings + if st.DailyCap > 0 && gc.totalSpent+cost > st.DailyCap { + return false + } + switch st.SpendRule { + case db.SpendAnyone: + return true + case db.SpendCapped: + return gc.memberSpent+cost <= st.SpendCap + default: // admins only + return gc.admin + } +} + +// gate applies the group's own settings: whether the bot is on, who may +// use it, and which sites are allowed. +func (s *Service) gate(ctx context.Context, who Who, info *CardInfo, dec entitle.Decision, gc *groupContext) error { + if on, _ := s.store.GetKV(ctx, "maintenance"); on == "1" && !s.cfg.IsOwner(who.UserID) { + return &LimitError{Code: LimitMaintenance, Decision: dec} + } + if gc == nil { + return nil + } + st := gc.settings + refuse := func(code string) error { return &LimitError{Code: code, Decision: dec} } + if !st.Enabled { + return refuse(LimitGroupDisabled) + } + switch st.WhoCanUse { + case db.UseAdmins: + if !gc.admin { + return refuse(LimitGroupAdminsOnly) + } + case db.UsePassHolders: + if !gc.admin && dec.Source != entitle.OwnPass && dec.Source != entitle.GroupPass { + return refuse(LimitGroupPassOnly) + } + } + if info != nil && info.Site != "" { + if allowed := db.Sites(st.Allowed); len(allowed) > 0 && !hostInList(info.Site, allowed) { + return refuse(LimitGroupSite) + } + if hostInList(info.Site, db.Sites(st.Blocked)) { + return refuse(LimitGroupSite) + } + } + return nil +} + +func hostInList(site string, list []string) bool { + site = strings.ToLower(site) + for _, h := range list { + if site == h || strings.HasSuffix(site, "."+h) { + return true + } + } + return false +} + // ErrPlaylist is returned by Probe for links that resolve to a list. var ErrPlaylist = errors.New("service: link is a playlist") @@ -168,6 +278,7 @@ type Service struct { billing *billing.Billing cache *cache.Cache prober Prober + admins AdminChecker log *slog.Logger probes chan struct{} now func() time.Time @@ -281,6 +392,13 @@ type Who struct { // which limits apply. oneOffPaid is true when an invoice for exactly this // file was paid. func (s *Service) Entitlement(ctx context.Context, who Who, oneOffPaid bool) (entitle.Decision, error) { + dec, _, err := s.entitle(ctx, who, oneOffPaid) + return dec, err +} + +// entitle resolves the entitlement and returns the group context it was +// resolved with, which is nil in a private chat. +func (s *Service) entitle(ctx context.Context, who Who, oneOffPaid bool) (entitle.Decision, *groupContext, error) { in := entitle.Input{ Now: s.now().UnixMilli(), OneOffPaid: oneOffPaid, @@ -291,10 +409,22 @@ func (s *Service) Entitlement(ctx context.Context, who Who, oneOffPaid bool) (en } user, err := s.billing.State(ctx, db.OwnerUser, who.UserID) if err != nil { - return entitle.Decision{}, err + return entitle.Decision{}, nil, err } in.User = user - return entitle.Resolve(in), nil + gc, err := s.groupContext(ctx, who) + if err != nil { + return entitle.Decision{}, nil, err + } + if gc != nil { + in.Group = &entitle.Group{ + Wallet: gc.wallet, + CreditsAllowed: gc.creditsAllowed(in.CreditCost), + MaxSize: gc.settings.MaxSizeMB << 20, + MaxDuration: gc.settings.MaxDuration, + } + } + return entitle.Resolve(in), gc, nil } // Usage returns what the user consumed today. @@ -347,7 +477,8 @@ func (s *Service) admit(ctx context.Context, who Who, info *CardInfo, profile me func (s *Service) limitError(code string, info *CardInfo, profile media.Profile, dec entitle.Decision) *LimitError { le := &LimitError{Code: code, Decision: dec, Size: info.Sizes[string(profile)]} - if code == LimitLive || code == LimitQueueFull || code == LimitBlocked || dec.Source.Paid() || !s.billing.Enabled() { + if code == LimitLive || code == LimitQueueFull || code == LimitBlocked || strings.HasPrefix(code, "group_") || + code == LimitMaintenance || dec.Source.Paid() || !s.billing.Enabled() { return le } // Would the paid tier accept it? Only then is it worth offering. @@ -416,10 +547,13 @@ func (s *Service) resolve(ctx context.Context, url string, info *CardInfo, profi // queueing or charging anything. It returns *LimitError when a rule would // refuse it. func (s *Service) Preview(ctx context.Context, who Who, url string, info *CardInfo, profile media.Profile) error { - dec, err := s.Entitlement(ctx, who, false) + dec, gc, err := s.entitle(ctx, who, false) if err != nil { return err } + if err := s.gate(ctx, who, info, dec, gc); err != nil { + return err + } r, err := s.resolve(ctx, url, info, profile, dec) if err != nil { return err @@ -427,6 +561,16 @@ func (s *Service) Preview(ctx context.Context, who Who, url string, info *CardIn return s.admit(ctx, who, r.view, profile, dec) } +// Gate reports whether the requester may use the bot in this chat at all, +// before a link is even looked up. It returns *LimitError when not. +func (s *Service) Gate(ctx context.Context, who Who) error { + dec, gc, err := s.entitle(ctx, who, false) + if err != nil { + return err + } + return s.gate(ctx, who, nil, dec, gc) +} + // StartParams describes a download a requester asked for. type StartParams struct { Request *db.Request @@ -462,10 +606,13 @@ func (s *Service) Start(ctx context.Context, p StartParams) (*db.Job, *db.Delive } func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Job, *db.Delivery, error) { - dec, err := s.Entitlement(ctx, who, p.OneOff != nil) + dec, gc, err := s.entitle(ctx, who, p.OneOff != nil) if err != nil { return nil, nil, err } + if err := s.gate(ctx, who, p.Info, dec, gc); err != nil { + return nil, nil, err + } r, err := s.resolve(ctx, p.Request.URL, p.Info, p.Profile, dec) if err != nil { return nil, nil, err @@ -565,6 +712,17 @@ func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Jo return err } } + if gc != nil { + // Per-member use of the group: the base for spending caps and + // for the usage-by-member view. + var sats int64 + if dec.Source == entitle.GroupCredits { + sats = dec.Charge + } + if err := tx.AddGroupUsage(ctx, who.ChatID, who.UserID, day, 1, sats, 0); err != nil { + return err + } + } return tx.AddUsage(ctx, who.UserID, day, 1, 0) }) switch { @@ -618,6 +776,15 @@ func (s *Service) Release(ctx context.Context, deliveryID string) (refunded int6 } } if d.QuotaDay > 0 { + if isGroup(d.ChatType) { + var sats int64 + if d.Source == string(entitle.GroupCredits) { + sats = d.ChargeSats + } + if err := tx.AddGroupUsage(ctx, d.ChatID, d.UserID, d.QuotaDay, -1, -sats, 0); err != nil { + return err + } + } return tx.AddUsage(ctx, d.UserID, d.QuotaDay, -1, 0) } return nil @@ -649,6 +816,11 @@ func (s *Service) RecordDelivered(ctx context.Context, d *db.Delivery, bytes int if day == 0 { day = Day(s.now()) } + if isGroup(d.ChatType) { + if err := s.store.AddGroupUsage(ctx, d.ChatID, d.UserID, day, 0, 0, bytes); err != nil { + return err + } + } return s.store.AddUsage(ctx, d.UserID, day, 0, bytes) } diff --git a/locales/en.toml b/locales/en.toml index fc3c987..4fdbe17 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -37,6 +37,8 @@ In a group, use /dl with a link, or reply /dl to a message that has a link. /history - your past downloads, with one tap to get them again /queue - your running downloads /cancel - cancel your downloads +/quality - your default format +/language - change my language Account /account - your pass, balance and usage @@ -47,6 +49,10 @@ In a group, use /dl with a link, or reply /dl to a message that has a link. /referral - invite friends and earn sats /donate - send a tip +In groups +/groupwallet and /grouppass - the group's balance and pass +/settings - group settings, for admins + Your limits Up to {{.MaxSize}} and {{.MaxDuration}} per download.""" @@ -97,6 +103,10 @@ pick = "Pick a format:" cancelled = "Cancelled." [btn] +full_settings = "Open full settings" +add_group_credits = "Add group credits" +buy_group_pass = "Buy a group pass" +open_app = "Open app" best = "Best" res = "{{.Height}}p" mp3 = "MP3" @@ -128,6 +138,9 @@ failed = "That did not work. {{.Reason}}" refunded = "{{.Amount}} went back to your balance." [notice] +group_only = "This command works in groups." +admins_only = "Only admins of this group can do that." +saved = "Saved." cancelled = "Cancelled." not_yours = "These buttons belong to the person who asked." too_late = "Too late to cancel that." @@ -143,6 +156,11 @@ skip_too_late = "This download is not waiting in the queue anymore." skip_private = "Open a private chat with me to pay for this." [limit] +group_disabled = "The bot is switched off in this group." +group_admins_only = "In this group only admins can use the bot." +group_pass_only = "In this group you need a pass to use the bot. /buy in a private chat with me." +group_site = "The admins of this group do not allow downloads from that site." +maintenance = "I am down for maintenance. Please try again in a little while." too_large = "This file is larger than your limit of {{.MaxSize}}. Try a lower quality." too_long = "This is longer than your limit of {{.MaxDuration}}." live = "Live streams cannot be downloaded." @@ -292,6 +310,9 @@ cashu_off = "Cashu tokens are not accepted on this bot." cashu_mint = "I do not accept tokens from that mint." [invoice] +for_group = "For the group {{.Group}}" +group_balance = "The group balance is now {{.Balance}}." +group_pass_until = "The group pass is active until {{.Until}}." memo = "The Noderunners Download Bot: {{.Title}}" caption = """ {{.Title}} · {{.Amount}} @@ -354,6 +375,81 @@ line = "{{.N}}. {{.Title}} · {{.Label}}" # --- Owner commands --------------------------------------------------------- [owner] +books_ok = "ledger and balances agree" +ln_ok = "reachable" +ln_down = "NOT reachable" +queue_empty = "No jobs are queued or running." +queue_line = "{{.ID}} {{.Status}} · {{.Lane}} · {{.Profile}} · worker {{.Worker}} · tags {{.Tags}}\n{{.Title}}" +user_usage = "Example: /user 123456789" +group_usage = "Example: /group -1001234567890" +not_found = "Not found." +user = """ +User {{.ID}} +Name: {{.Name}} (@{{.Username}}) +Language: {{.Lang}} +Banned: {{.Banned}} +Pass until: {{.Pass}} +Balance: {{.Balance}} +Today: {{.Downloads}} downloads, {{.Volume}} +Referrals: {{.Referrals}} +First seen: {{.Since}}""" +group = """ +Group {{.ID}} +Title: {{.Title}} +Bot status: {{.Status}} +Bot enabled: {{.Enabled}} +Who can use it: {{.Who}} +Credit spending: {{.Spend}} +Pass until: {{.Pass}} +Balance: {{.Balance}}""" +ban_usage = "Example: /ban 123456789 and /unban 123456789" +ban_owner = "An owner cannot be banned." +banned = "User {{.ID}} is banned." +unbanned = "User {{.ID}} is no longer banned." +grant_usage = """ +Give a pass to a user or a group (groups have negative IDs): +/grant 123456789 week +Create a gift code: +/grant code credits 1000 5 +/grant code month""" +gift_code = "Gift code: {{.Code}}\nUses: {{.Uses}}" +granted = "Done. The pass of {{.ID}} runs until {{.Until}}." +credit_usage = "Example: /credit 123456789 500" +refund_usage = "Examples:\n/refund 123456789 500\n/refund 123456789 pass 24h" +no_pass = "That wallet has no active pass to extend." +credited = "Done. {{.Amount}} added to {{.ID}}. Balance: {{.Balance}}." +blocklist_empty = "The blocklist is empty." +blocklist_header = "Blocklist" +blocklist_line = "{{.Kind}}: {{.Value}} {{.Reason}}" +blocklist_usage = """ +/blocklist +/blocklist add site example.com spam +/blocklist add key youtube:VIDEOID +/blocklist remove site example.com""" +blocked = "Blocked: {{.Value}}" +unblocked = "Unblocked: {{.Value}}" +maint_usage = "Use /maint on or /maint off." +maint_on = "Maintenance mode is on. New downloads are refused for everyone but owners." +maint_off = "Maintenance mode is off." +reload_usage = "Use /reload i18n." +reload_builtin = "The translations are built into the binary. Set LOCALES_DIR to load them from a directory." +reload_failed = "Reloading failed, the old translations stay in use.\n{{.Error}}" +reloaded = "Translations reloaded: {{.Langs}}" +broadcast_usage = "Example: /broadcast The bot will be down tonight from 22:00 UTC." +broadcast_preview = "Preview\n\n{{.Text}}" +broadcast_done = "Broadcast finished. Sent: {{.Sent}}. Failed: {{.Failed}}." +stats = """ +Stats +Users: {{.Users}} +Last 24 hours: {{.Done}} done, {{.Failed}} failed +Queue: {{.Paid}} paid, {{.Free}} free, oldest waiting {{.Oldest}} +Workers: {{.Running}} of {{.Slots}} slots busy +Cache hit rate: {{.Rate}}, saved {{.Saved}} +Received: {{.Sats}} +Invoices since start: {{.Created}} created, {{.Settled}} settled +Lightning: {{.Lightning}} +Books: {{.Books}} +Maintenance: {{.Maint}}""" never = "never" state_active = "active" state_offline = "offline" @@ -389,3 +485,145 @@ other = "Asked {{.Count}} workers to update yt-dlp. They do so when they next ch [owner.purged] one = "Taken down: {{.Key}}\n{{.Count}} cached file was removed. The key is blocked." other = "Taken down: {{.Key}}\n{{.Count}} cached files were removed. The key is blocked." + +[owner.books_bad] +one = "{{.Count}} wallet DISAGREES with its ledger" +other = "{{.Count}} wallets DISAGREE with their ledgers" + +[owner.queue_header] +one = "{{.Count}} active job" +other = "{{.Count}} active jobs" + +[owner.broadcast_send] +one = "Send to {{.Count}} user" +other = "Send to {{.Count}} users" + +# --- Groups ------------------------------------------------------------------ + +[word] +on = "on" +off = "off" +none = "none" + +[settings] +text = """ +Group settings +Balance: {{.Balance}} · Pass until: {{.Pass}} +Language: {{.Lang}} +Allowed sites: {{.Allowed}} +Blocked sites: {{.Blocked}} +Per person per day: {{.SpendCap}} · Group per day: {{.DailyCap}} + +Tap to change. More with /grouplang, /allow, /block and /spending.""" +button = "{{.Label}}: {{.Value}}" +enabled = "Bot" +auto_detect = "Detect pasted links" +delete_commands = "Delete command messages" +who = "Who can use it" +who_everyone = "everyone" +who_pass_holders = "pass holders" +who_admins = "admins" +spend = "Group credits" +spend_anyone = "anyone" +spend_admins = "admins only" +spend_capped = "anyone, capped" +quality = "Default quality" +lang_auto = "each member's own" +commands = """ +Settings of {{.Group}} + +Send these in the group, as an admin: +/settings - quick switches +/grouplang code - language of the bot in the group +/autodetect on - fetch links without a command +/allow site - only allow some sites +/block site - block a site +/spending rule - who may spend group credits""" + +[quality] +ask = "Ask every time" +pick = "Pick your default format. I will then start right away instead of asking." +set = "Default format: {{.Quality}}" + +[language] +name = "English" +auto = "Follow my Telegram language" +pick = "Pick a language:" +set = "Language: {{.Lang}}" + +[grouplang] +usage = "Add a language code, or auto to follow each member.\nAvailable: {{.Langs}}" +auto = "The bot now answers each member in their own language." +set = "The bot now speaks {{.Lang}} in this group." + +[autodetect] +usage = "Use /autodetect on or /autodetect off." +on = "I will now fetch links pasted in this group without a command. For that I need to see messages: make me an admin, or turn off group privacy for me in @BotFather." +off = "I will only act on commands in this group." + +[allow] +list = "Allowed sites: {{.Sites}}\nAdd with /allow example.com, remove with /allow remove example.com, reset with /allow clear. With an empty list every site is allowed." + +[block] +list = "Blocked sites: {{.Sites}}\nAdd with /block example.com, remove with /block remove example.com, reset with /block clear." + +[sites] +bad_host = "That does not look like a site. Example: example.com" + +[spending] +usage = """ +Who may spend group credits: +/spending admins +/spending anyone +/spending capped 200 (sats per person per day) +/spending daily 5000 (sats per day for the whole group, 0 for no cap)""" +set = "Group credits: {{.Rule}}.\nPer person per day: {{.SpendCap}}. Group per day: {{.DailyCap}}." + +[groupwallet] +text = "Group wallet\nBalance: {{.Balance}}\n{{.Pass}}\nWho can spend credits: {{.Rule}}" +pass_none = "Pass: none" +pass_until = "Pass: active until {{.Until}}" + +[grouppass] +text = "Group pass\n{{.Pass}}\nWith a group pass everyone here downloads with the higher limits and in the priority queue." + +[groupstats] +empty = "Nobody used the bot here in the last 7 days." +header = "Last 7 days" + +[groupstats.line] +one = "{{.Name}}: {{.Count}} download, {{.Size}}, {{.Sats}}" +other = "{{.Name}}: {{.Count}} downloads, {{.Size}}, {{.Sats}}" + +[groupbuy] +unknown = "I do not know that group, or I am no longer in it." +intro = "{{.Group}}\nGroup balance: {{.Balance}}\n\nWhat you buy here belongs to the group: a pass covers every member, credits are spent by the group's rules." + +[app] +unavailable = "The app is not set up on this bot." +open = "Open the app to manage downloads, passes and groups." + +# --- Static pages ------------------------------------------------------------ + +[static] +privacy = """ +Privacy + +I store what I need to work: your Telegram ID and name, your language, the links you send me and the files made from them, your balance and purchases, and counts of your usage. + +Downloaded files are kept for a limited time so repeats are fast, then deleted. Files from links that need a login are never kept or shared. + +I do not sell data and I do not ask who you are. Payments are in sats over Lightning. + +To have your data removed, contact {{.Contact}}.""" +terms = """ +Terms + +Use the bot only for content you have the right to download. You are responsible for what you fetch and share. + +Passes and credits are not refundable once used. A download that fails is refunded automatically. + +The service comes as it is, without a guarantee that a given site works. Abuse leads to a ban. + +Questions: {{.Contact}}""" +support = "Need help? Write to {{.Contact}}.\n\n/help lists what I can do."