package app_test import ( "encoding/json" "net/http" "strings" "testing" "unicode/utf8" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/i18n" "github.com/noderunners/dlbot/internal/tg/fakeserver" "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" ) type menuEntry struct { Command string `json:"command"` Description string `json:"description"` } type scope struct { Type string `json:"type"` ChatID int64 `json:"chat_id"` } func menuOf(t *testing.T, c fakeserver.Call) []menuEntry { t.Helper() var cmds []menuEntry if err := json.Unmarshal([]byte(c.Params["commands"]), &cmds); err != nil { t.Fatalf("commands of %+v: %v", c.Params, err) } return cmds } func scopeOf(c fakeserver.Call) scope { var s scope _ = json.Unmarshal([]byte(c.Params["scope"]), &s) return s } // menuFor finds the setMyCommands call for a scope and language code. func menuFor(t *testing.T, calls []fakeserver.Call, scopeType, lang string, chat int64) []menuEntry { t.Helper() var found []menuEntry for _, c := range calls { if s := scopeOf(c); s.Type == scopeType && s.ChatID == chat && c.Params["language_code"] == lang { found = menuOf(t, c) } } if found == nil { t.Fatalf("no setMyCommands for scope %s, chat %d, language %q", scopeType, chat, lang) } return found } func describe(menu []menuEntry, cmd string) string { for _, e := range menu { if e.Command == cmd { return e.Description } } return "" } // --- acceptance: menus and profile in every language ------------------------ func TestMenusAndProfileArePublishedPerLanguage(t *testing.T) { h := start(t, nil, nil) calls := h.srv.Calls("setMyCommands") want := map[string]string{"": "Download a video from a link", "es": "Descargar un video desde un enlace", "nl": "Een video downloaden via een link"} for lang, dl := range want { private := menuFor(t, calls, "all_private_chats", lang, 0) groups := menuFor(t, calls, "all_group_chats", lang, 0) admins := menuFor(t, calls, "all_chat_administrators", lang, 0) if describe(private, "dl") != dl || describe(groups, "dl") != dl { t.Errorf("%q: /dl is described as %q", lang, describe(private, "dl")) } // Admin commands are only offered to admins, money commands only in private. if describe(groups, "settings") != "" || describe(admins, "settings") == "" || describe(groups, "buy") != "" || describe(private, "buy") == "" { t.Errorf("%q: commands are in the wrong scopes", lang) } // The app is not set up here, so it is not offered. if describe(private, "app") != "" { t.Errorf("%q: /app is listed without a Mini App", lang) } for _, menu := range [][]menuEntry{private, groups, admins} { if len(menu) > 100 { t.Errorf("%q: %d commands, Telegram allows 100", lang, len(menu)) } for _, e := range menu { if n := utf8.RuneCountInString(e.Description); n < 1 || n > 256 || strings.HasPrefix(e.Description, "menu.") { t.Errorf("%q: bad entry %+v", lang, e) } } } } // The pseudo-locale is never published: Telegram wants two letters. for _, c := range calls { if l := c.Params["language_code"]; l != "" && len(l) != 2 { t.Errorf("menu published for language code %q", l) } } profile := map[string]map[string]string{} for _, method := range []string{"setMyName", "setMyDescription", "setMyShortDescription"} { for _, c := range h.srv.Calls(method) { lang := c.Params["language_code"] if profile[lang] == nil { profile[lang] = map[string]string{} } for _, k := range []string{"name", "description", "short_description"} { if v := c.Params[k]; v != "" { profile[lang][k] = v } } } } if len(profile) != 3 || !strings.Contains(profile["es"]["description"], "Envíame") || !strings.Contains(profile["nl"]["short_description"], "Stuur een link") || profile[""]["name"] != "Noderunners Download Bot" { t.Fatalf("profile texts = %+v", profile) } // Those calls are rate limited by Telegram, so a restart with the same // texts does not repeat them. h.stop() before := len(h.srv.Calls("setMyName")) h.boot() if n := len(h.srv.Calls("setMyName")); n != before { t.Fatalf("setMyName was called %d more times after a restart", n-before) } } func TestProfileIsLeftAloneWhenTurnedOff(t *testing.T) { h := start(t, nil, func(c *config.Config) { c.Telegram.SetProfile = false }) for _, m := range []string{"setMyName", "setMyDescription", "setMyShortDescription"} { if n := len(h.srv.Calls(m)); n != 0 { t.Errorf("%s was called %d times with TELEGRAM_SET_PROFILE=false", m, n) } } if len(h.srv.Calls("setMyCommands")) == 0 { t.Fatal("the menus must still be published") } } // --- acceptance: switching language changes everything ---------------------- func TestTelegramLanguageIsFollowed(t *testing.T) { h := start(t, &ytdlptest.Fake{FileSize: 2000}, nil) seq := h.srv.Seq() // Paraguayan Spanish falls back to Spanish. h.srv.PushMessage(alice, alice, "/start", fakeserver.Lang("es-PY")) h.wait(seq, "sendMessage", textHas("te damos la bienvenida")) card := h.card(bob, bob, link, fakeserver.Lang("nl")) if labels := card.Buttons(); labels[0].Text != "Beste · 10,0 MB" || labels[len(labels)-1].Text != "Annuleren" { t.Fatalf("Dutch card buttons = %+v", labels) } // A language without a catalog gets English. seq = h.srv.Seq() h.srv.PushMessage(44, 44, "/start", fakeserver.Lang("ja")) h.wait(seq, "sendMessage", textHas("welcome")) } func TestSwitchingLanguageChangesMessagesButtonsMenusAndApp(t *testing.T) { h := startApp(t, &ytdlptest.Fake{FileSize: 2000}, nil) appKey := func() string { msgs, _ := h.must(alice, "GET", "i18n", nil).Body["messages"].(map[string]any) s, _ := msgs["app.tab.home"].(string) return s } if got := appKey(); got != "Home" { t.Fatalf("app text before = %q", got) } // /language, then pick Spanish. seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/language") pick := h.wait(seq, "sendMessage", textHas("Pick a language")) var names []string for _, b := range pick.Buttons() { names = append(names, b.Text) } if strings.Join(names, "|") != "English|Español|Nederlands|Follow my Telegram language" { t.Fatalf("language buttons = %v", names) } seq = h.press(alice, alice, pick, "lg:es") h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool { return c.Params["text"] == "Guardado." }) h.wait(seq, "editMessageText", textHas("Idioma: Español")) // The menu of this chat follows, whatever language the app is in. menuCall := h.wait(seq, "setMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat", ChatID: alice} }) menu := menuOf(t, menuCall) if describe(menu, "dl") != "Descargar un video desde un enlace" || describe(menu, "app") != "Abrir la app" || menuCall.Params["language_code"] != "" { t.Fatalf("chat menu = %+v (%s)", menu, menuCall.Params["language_code"]) } // Messages and buttons. card := h.card(alice, alice, link) labels := card.Buttons() if labels[0].Text != "Mejor · 10,0 MB" || labels[len(labels)-1].Text != "Cancelar" { t.Fatalf("Spanish card buttons = %+v", labels) } seq = h.press(alice, alice, card, "dl:") h.wait(seq, "sendVideo", nil) h.wait(seq, edits, textHas("Listo. Que lo disfrutes.")) seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/account") acct := h.wait(seq, "sendMessage", textHas("Tu cuenta")) if !strings.Contains(acct.Text(), "Descargas: 1 de 5") { t.Fatalf("account in Spanish = %q", acct.Text()) } // The Mini App. if got := appKey(); got != "Inicio" { t.Fatalf("app text after = %q", got) } me := h.must(alice, "GET", "me", nil) if me.str("lang") != "es" || me.str("lang_override") != "es" { t.Fatalf("me = %s", me.Raw) } // Switching in the app works the same way, and back to automatic // removes the chat's own menu. seq = h.srv.Seq() h.must(alice, "PUT", "me", map[string]any{"lang": "nl"}) menuCall = h.wait(seq, "setMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat", ChatID: alice} }) if describe(menuOf(t, menuCall), "dl") != "Een video downloaden via een link" { t.Fatalf("chat menu after the app switch = %+v", menuOf(t, menuCall)) } if got := appKey(); got != "Start" { t.Fatalf("app text in Dutch = %q", got) } seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/language") pick = h.wait(seq, "sendMessage", textHas("Kies een taal")) seq = h.press(alice, alice, pick, "lg:auto") h.wait(seq, "deleteMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat", ChatID: alice} }) seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/help") h.wait(seq, "sendMessage", textHas("How to use me")) if got := appKey(); got != "Home" { t.Fatalf("app text after auto = %q", got) } } func TestGroupLanguageChangesTheGroup(t *testing.T) { h := startApp(t, nil, nil) h.meetGroup(alice, bob) seq := h.srv.Seq() h.srv.PushMessage(group, bob, "/grouplang nl") h.wait(seq, "sendMessage", textHas("De bot spreekt nu Nederlands")) members := h.wait(seq, "setMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat", ChatID: group} }) admins := h.wait(seq, "setMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat_administrators", ChatID: group} }) if describe(menuOf(t, members), "dl") != "Een video downloaden via een link" || describe(menuOf(t, members), "settings") != "" || describe(menuOf(t, admins), "settings") != "Groepsinstellingen" { t.Fatalf("group menus = %+v / %+v", menuOf(t, members), menuOf(t, admins)) } // Everybody gets Dutch in the group, whatever their own language. seq = h.srv.Seq() h.srv.PushMessage(group, alice, "/dl", fakeserver.Lang("es")) h.wait(seq, "sendMessage", textHas("Zet een link achter het commando")) // The Mini App's group settings switch it back. seq = h.srv.Seq() st := h.must(bob, "GET", "groups/-1001234567890", nil).Body["settings"].(map[string]any) st["lang"] = "" h.must(bob, "PUT", "groups/-1001234567890/settings", st) h.wait(seq, "deleteMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat", ChatID: group} }) h.wait(seq, "deleteMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat_administrators", ChatID: group} }) } // --- the pseudo-locale ------------------------------------------------------ func TestPseudoLocaleIsForOwners(t *testing.T) { const owner = int64(7) h := startApp(t, nil, func(c *config.Config) { c.Pseudo = true c.Owners = []int64{owner} }) seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/language") pick := h.wait(seq, "sendMessage", textHas("Pick a language")) if _, ok := pick.Button("lg:" + i18n.Pseudo); ok { t.Fatal("a user is offered the pseudo-locale") } h.srv.PushCallback(alice, alice, pick.MessageID, "lg:"+i18n.Pseudo) h.wait(seq, "answerCallbackQuery", textHas("")) if r := h.call(alice, "PUT", "me", map[string]any{"lang": i18n.Pseudo}); r.Status != http.StatusBadRequest { t.Fatalf("a user set the pseudo-locale in the app: %d", r.Status) } seq = h.srv.Seq() h.srv.PushMessage(owner, owner, "/language") pick = h.wait(seq, "sendMessage", textHas("Pick a language")) seq = h.press(owner, owner, pick, "lg:"+i18n.Pseudo) h.wait(seq, "editMessageText", textHas("Ļáñĝûáĝé")) seq = h.srv.Seq() h.srv.PushMessage(owner, owner, "/help") help := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == owner }) if !strings.Contains(help.Text(), "/dl") || strings.Contains(help.Text(), "How to use me") || !strings.Contains(help.Text(), "[") { t.Fatalf("help in the pseudo-locale = %q", help.Text()) } // Never published as a menu language. for _, c := range h.srv.Calls("setMyCommands") { if c.Params["language_code"] == i18n.Pseudo { t.Fatal("the pseudo-locale was published to Telegram") } } }