- /help: a short introduction with the user's default format, how to be asked every time and the limits on one line, plus buttons Commands, Account, Groups, Open app and Upgrade that switch the same message to a section. Group commands are hidden in private chats; "Add me to a group" takes their place. - /quality: Ask every time, Best that fits my limit, Best, 1080p, 720p, 480p and Audio only, with the active one checked. Free users see which qualities may go over their limit. - /history: pages of five compact buttons (site, title, format, when), a view per download with Send again, Thumbnail, Remove from history, and Clear history with a confirmation. Thumbnails are grouped under their video. Migration 00007 stores extractor, title, uploader and profile on deliveries and adds a hidden flag. - docs/SCREENS.md shows every screen in en, es and nl, generated by the language test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
717 lines
27 KiB
Go
717 lines
27 KiB
Go
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"))
|
|
}
|
|
// In a private chat /settings is about the person, not a group.
|
|
seq = h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, "/settings")
|
|
own := h.wait(seq, "sendMessage", textHas("Your settings"))
|
|
if strings.Contains(own.Text(), "Allowed sites") {
|
|
t.Fatalf("private /settings shows group settings: %q", own.Text())
|
|
}
|
|
add, ok := own.Button("")
|
|
for _, b := range own.Buttons() {
|
|
if strings.Contains(b.URL, "?startgroup=") {
|
|
add, ok = b, true
|
|
}
|
|
}
|
|
if !ok || add.URL != "https://t.me/"+fakeserver.BotUsername+"?startgroup=settings" {
|
|
t.Fatalf("no add-to-group button in %+v", own.Buttons())
|
|
}
|
|
}
|
|
|
|
func TestAdminStatusIsVerifiedWithTelegramAndCached(t *testing.T) {
|
|
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("Your default format"))
|
|
// Somebody who never chose gets "best that fits my limit".
|
|
if labels(menu) != "Ask every time | ✓ Best that fits my limit | Best ⚠ | 1080p ⚠ | 720p ⚠ | 480p ⚠ | Audio only (MP3)" {
|
|
t.Fatalf("quality buttons = %q", labels(menu))
|
|
}
|
|
seq = h.press(alice, alice, menu, "ql:720")
|
|
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 <b>Test Group</b>") {
|
|
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: <code>example.com</code>")
|
|
say(owner, "/blocklist", "site: <code>example.com</code> 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
|
|
}
|