Compare commits
9 Commits
d5369a0188
..
v1.2.1
| Author | SHA1 | Date | |
|---|---|---|---|
| 384bd143d0 | |||
| 9d1ca213d6 | |||
| 1f78bb274b | |||
| 81b716569f | |||
| aa330b726e | |||
| c5d22fceca | |||
| deaa7a29c5 | |||
| 24017bcb7f | |||
| 2c4f4b10dc |
@@ -158,7 +158,12 @@ arrive from a platform rather than completing a mandatory registration).
|
|||||||
rendered in the recipient's **interface language** (`preferred_language`, en/ru), not in
|
rendered in the recipient's **interface language** (`preferred_language`, en/ru), not in
|
||||||
any bot-scoped language, and the friend-invite **share link** (and its caption) point at
|
any bot-scoped language, and the friend-invite **share link** (and its caption) point at
|
||||||
that one bot. First Telegram contact seeds the new account's `preferred_language` from the
|
that one bot. First Telegram contact seeds the new account's `preferred_language` from the
|
||||||
launch `language_code` (§4); the interface language is otherwise edited in Settings.
|
launch `language_code` (§4), but the **interface language follows the device** — the system
|
||||||
|
guess, or an explicit Settings choice saved locally — and the bot never dictates the UI.
|
||||||
|
`preferred_language` is then **reconciled to the active interface locale on every session
|
||||||
|
adopt** (not only on a Settings change; a no-op for guests and when already equal), so the
|
||||||
|
server-rendered language surfaces — this push and the ad banner — always match the UI rather
|
||||||
|
than stranding a user who never opened Settings on the creation-time seed.
|
||||||
- **Variant preferences (New Game gating).** Which variants a player may be matched into is a
|
- **Variant preferences (New Game gating).** Which variants a player may be matched into is a
|
||||||
per-user **profile** setting — `variant_preferences`, a set of `engine.Variant` labels
|
per-user **profile** setting — `variant_preferences`, a set of `engine.Variant` labels
|
||||||
(`scrabble_en`, `scrabble_ru`, `erudit_ru`) edited on the Settings/Profile screen. New
|
(`scrabble_en`, `scrabble_ru`, `erudit_ru`) edited on the Settings/Profile screen. New
|
||||||
@@ -640,7 +645,7 @@ in either direction (the enqueue excludes the caller's `BlockedWith` set);
|
|||||||
**floats games with any unread entry to the top** of the your-turn and opponent-turn
|
**floats games with any unread entry to the top** of the your-turn and opponent-turn
|
||||||
sections (the finished section keeps its activity order). On each clear the publish-to-read
|
sections (the finished section keeps its activity order). On each clear the publish-to-read
|
||||||
latency is recorded; the read time itself is not retained.
|
latency is recorded; the read time itself is not retained.
|
||||||
- **Profile**: `preferred_language` (en/ru, edited in Settings), display name, email
|
- **Profile**: `preferred_language` (en/ru; tracks the interface language — §4), display name, email
|
||||||
(confirm-code binding, see §4), **timezone**, the daily **away window**, the
|
(confirm-code binding, see §4), **timezone**, the daily **away window**, the
|
||||||
**variant preferences** (`variant_preferences`, the matchable-variant set that gates New
|
**variant preferences** (`variant_preferences`, the matchable-variant set that gates New
|
||||||
Game — §3, defaulting to Erudit only, at least one enforced) and the
|
Game — §3, defaulting to Erudit only, at least one enforced) and the
|
||||||
|
|||||||
@@ -38,10 +38,17 @@ Telegram identity to an account from a browser. Both map a rejection to gRPC
|
|||||||
operator-chosen for broadcasts) with a Mini App launch button and sends it. It replies
|
operator-chosen for broadcasts) with a Mini App launch button and sends it. It replies
|
||||||
with an `Ack` per command (`delivered` mirrors the former connector semantics —
|
with an `Ack` per command (`delivered` mirrors the former connector semantics —
|
||||||
false when the kind is not rendered out-of-app or the user never started the bot).
|
false when the kind is not rendered out-of-app or the user never started the bot).
|
||||||
- **Bot chat.** `/start <payload>` (and the chat menu button) reply with a Mini App
|
- **Bot chat.** `/start <payload>` (and the chat menu button) reply with a localized
|
||||||
launch button; a deep-link payload routes the launch to a game / invitation / friend
|
welcome and a Mini App launch button; a deep-link payload routes the launch to a game /
|
||||||
code. This is **self-contained** — the bot never calls back into the game, so `/start`
|
invitation / friend code. The welcome is **Russian or English** by the sender's reported
|
||||||
onboarding works even when the game is down.
|
Telegram language (`Message.from.language_code`, which the Bot API carries on the message
|
||||||
|
itself — no separate user-update event — English fallback) and links the game channel and
|
||||||
|
discussion chat by their public `@username`, **resolved once at startup** from
|
||||||
|
`TELEGRAM_GAME_CHANNEL_ID` / `TELEGRAM_CHAT_ID` via `getChat` (a chat that is unset,
|
||||||
|
private, or unreadable degrades that link to a generic noun — "the channel" / "our
|
||||||
|
chat" — rather than a dangling "@"). This is otherwise **self-contained**
|
||||||
|
— the bot never calls back into the game, so `/start` onboarding works even when the game
|
||||||
|
is down.
|
||||||
- **Moderated-chat gating.** When `TELEGRAM_CHAT_ID` names a channel's linked discussion
|
- **Moderated-chat gating.** When `TELEGRAM_CHAT_ID` names a channel's linked discussion
|
||||||
group, the bot gates who may write there. The group **allows sending by default** (a
|
group, the bot gates who may write there. The group **allows sending by default** (a
|
||||||
human setting) and the bot only **restricts** — Telegram intersects the chat default with
|
human setting) and the bot only **restricts** — Telegram intersects the chat default with
|
||||||
|
|||||||
@@ -72,6 +72,7 @@ func run(ctx context.Context, cfg config.BotConfig, logger *zap.Logger) error {
|
|||||||
MiniAppURL: cfg.MiniAppURL,
|
MiniAppURL: cfg.MiniAppURL,
|
||||||
SendRatePerSecond: cfg.SendRatePerSecond,
|
SendRatePerSecond: cfg.SendRatePerSecond,
|
||||||
ChatID: cfg.ChatID,
|
ChatID: cfg.ChatID,
|
||||||
|
GameChannelID: cfg.GameChannelID,
|
||||||
}, logger)
|
}, logger)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -33,8 +33,12 @@ type Config struct {
|
|||||||
SendRatePerSecond int
|
SendRatePerSecond int
|
||||||
// ChatID is the moderated discussion chat the bot gates write access in; 0
|
// ChatID is the moderated discussion chat the bot gates write access in; 0
|
||||||
// disables chat gating (and the chat_member long-poll subscription). Gating needs
|
// disables chat gating (and the chat_member long-poll subscription). Gating needs
|
||||||
// the bot to be an administrator there with the restrict-members right.
|
// the bot to be an administrator there with the restrict-members right. Its public
|
||||||
|
// @username is also resolved at startup for the /start welcome's discussion link.
|
||||||
ChatID int64
|
ChatID int64
|
||||||
|
// GameChannelID is the game channel whose public @username the /start welcome links
|
||||||
|
// to (resolved from this id via getChat at startup); 0 omits that follow link.
|
||||||
|
GameChannelID int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// EligibilityResolver answers whether the Telegram user identified by externalID
|
// EligibilityResolver answers whether the Telegram user identified by externalID
|
||||||
@@ -54,6 +58,13 @@ type Bot struct {
|
|||||||
limiter *rate.Limiter
|
limiter *rate.Limiter
|
||||||
// chatID is the moderated discussion chat (0 disables gating).
|
// chatID is the moderated discussion chat (0 disables gating).
|
||||||
chatID int64
|
chatID int64
|
||||||
|
// channelID is the game channel (0 omits its welcome follow link).
|
||||||
|
channelID int64
|
||||||
|
// channelUsername and chatUsername are the public @usernames (without the leading
|
||||||
|
// @) of the game channel and the discussion chat, resolved once at startup
|
||||||
|
// (resolveWelcomeHandles) for the /start welcome's follow links; "" when unresolved.
|
||||||
|
channelUsername string
|
||||||
|
chatUsername string
|
||||||
// botID is the bot's own Telegram user id (resolved at startup); it skips the
|
// botID is the bot's own Telegram user id (resolved at startup); it skips the
|
||||||
// chat_member updates the bot's own restrict actions generate — the grant loop guard.
|
// chat_member updates the bot's own restrict actions generate — the grant loop guard.
|
||||||
botID int64
|
botID int64
|
||||||
@@ -69,7 +80,7 @@ func New(cfg Config, log *zap.Logger) (*Bot, error) {
|
|||||||
if log == nil {
|
if log == nil {
|
||||||
log = zap.NewNop()
|
log = zap.NewNop()
|
||||||
}
|
}
|
||||||
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log, chatID: cfg.ChatID}
|
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log, chatID: cfg.ChatID, channelID: cfg.GameChannelID}
|
||||||
if cfg.SendRatePerSecond > 0 {
|
if cfg.SendRatePerSecond > 0 {
|
||||||
t.limiter = rate.NewLimiter(rate.Limit(cfg.SendRatePerSecond), cfg.SendRatePerSecond)
|
t.limiter = rate.NewLimiter(rate.Limit(cfg.SendRatePerSecond), cfg.SendRatePerSecond)
|
||||||
}
|
}
|
||||||
@@ -123,9 +134,43 @@ func (t *Bot) Run(ctx context.Context) {
|
|||||||
if t.chatID != 0 {
|
if t.chatID != 0 {
|
||||||
t.logChatAdminStatus(ctx)
|
t.logChatAdminStatus(ctx)
|
||||||
}
|
}
|
||||||
|
t.resolveWelcomeHandles(ctx)
|
||||||
t.api.Start(ctx)
|
t.api.Start(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resolveWelcomeHandles resolves, once at startup, the public @usernames of the game
|
||||||
|
// channel and the discussion chat from their configured ids (getChat), caching them for
|
||||||
|
// the /start welcome's follow links. It runs before the update loop, so the handles are
|
||||||
|
// set before any /start is handled; a chat that is unset, private (no public username)
|
||||||
|
// or unreadable simply leaves its handle empty and the welcome omits that follow link.
|
||||||
|
func (t *Bot) resolveWelcomeHandles(ctx context.Context) {
|
||||||
|
t.channelUsername = t.resolveUsername(ctx, t.channelID, "game channel")
|
||||||
|
t.chatUsername = t.resolveUsername(ctx, t.chatID, "discussion chat")
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveUsername returns the public @username (without the leading @) of the chat with
|
||||||
|
// the given id, or "" when id is 0, the chat has no public username, or getChat fails —
|
||||||
|
// logging the reason, since a missing handle silently drops a welcome follow link.
|
||||||
|
func (t *Bot) resolveUsername(ctx context.Context, id int64, label string) string {
|
||||||
|
if id == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
chat, err := t.api.GetChat(ctx, &tgbot.GetChatParams{ChatID: id})
|
||||||
|
if err != nil {
|
||||||
|
t.log.Warn("welcome: getChat failed; follow link omitted",
|
||||||
|
zap.String("chat", label), zap.Int64("id", id), zap.Error(err))
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if chat.Username == "" {
|
||||||
|
t.log.Warn("welcome: chat has no public @username; follow link omitted",
|
||||||
|
zap.String("chat", label), zap.Int64("id", id))
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
t.log.Info("welcome: resolved follow link",
|
||||||
|
zap.String("chat", label), zap.String("username", chat.Username))
|
||||||
|
return chat.Username
|
||||||
|
}
|
||||||
|
|
||||||
// logChatAdminStatus checks, at startup, whether the bot can actually gate the
|
// logChatAdminStatus checks, at startup, whether the bot can actually gate the
|
||||||
// moderated chat — it must be an administrator there with the restrict-members
|
// moderated chat — it must be an administrator there with the restrict-members
|
||||||
// ("Ban users") right, or Telegram delivers no chat_member updates and restricts
|
// ("Ban users") right, or Telegram delivers no chat_member updates and restricts
|
||||||
@@ -198,11 +243,19 @@ func (t *Bot) handleStart(ctx context.Context, api *tgbot.Bot, update *models.Up
|
|||||||
if update.Message.Chat.Type != models.ChatTypePrivate {
|
if update.Message.Chat.Type != models.ChatTypePrivate {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// The sender's Telegram language rides on the message itself (Message.from.language_code
|
||||||
|
// in the Bot API — there is no separate user-update event); fall back to English when it
|
||||||
|
// is absent.
|
||||||
|
lang := ""
|
||||||
|
if update.Message.From != nil {
|
||||||
|
lang = update.Message.From.LanguageCode
|
||||||
|
}
|
||||||
|
text, button := startText(lang, t.channelUsername, t.chatUsername)
|
||||||
startParam := startPayload(update.Message.Text)
|
startParam := startPayload(update.Message.Text)
|
||||||
if _, err := api.SendMessage(ctx, &tgbot.SendMessageParams{
|
if _, err := api.SendMessage(ctx, &tgbot.SendMessageParams{
|
||||||
ChatID: update.Message.Chat.ID,
|
ChatID: update.Message.Chat.ID,
|
||||||
Text: "Tap to open Scrabble.",
|
Text: text,
|
||||||
ReplyMarkup: t.launchMarkup("Open Scrabble", startParam),
|
ReplyMarkup: t.launchMarkup(button, startParam),
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
t.log.Warn("reply to start failed", zap.Error(err))
|
t.log.Warn("reply to start failed", zap.Error(err))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,10 @@ func (f *fakeBotAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
f.text = r.FormValue("text")
|
f.text = r.FormValue("text")
|
||||||
f.replyMarkup = r.FormValue("reply_markup")
|
f.replyMarkup = r.FormValue("reply_markup")
|
||||||
io.WriteString(w, `{"ok":true,"result":{"message_id":1}}`)
|
io.WriteString(w, `{"ok":true,"result":{"message_id":1}}`)
|
||||||
|
case strings.HasSuffix(r.URL.Path, "/getChat"):
|
||||||
|
// Echo the requested id into the username so a resolver test can tell the
|
||||||
|
// channel lookup from the chat lookup.
|
||||||
|
io.WriteString(w, `{"ok":true,"result":{"id":-100,"type":"channel","username":"u`+r.FormValue("chat_id")+`"}}`)
|
||||||
default:
|
default:
|
||||||
io.WriteString(w, `{"ok":true,"result":true}`)
|
io.WriteString(w, `{"ok":true,"result":true}`)
|
||||||
}
|
}
|
||||||
@@ -105,7 +109,7 @@ func TestTestEnvironmentRoutesGetMe(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestHandleStartRepliesPrivateOnly(t *testing.T) {
|
func TestHandleStartRepliesPrivateOnly(t *testing.T) {
|
||||||
t.Run("private replies", func(t *testing.T) {
|
t.Run("private replies in english by default", func(t *testing.T) {
|
||||||
api := &fakeBotAPI{}
|
api := &fakeBotAPI{}
|
||||||
b := newTestBot(t, api)
|
b := newTestBot(t, api)
|
||||||
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
|
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
|
||||||
@@ -114,6 +118,35 @@ func TestHandleStartRepliesPrivateOnly(t *testing.T) {
|
|||||||
if api.chatID != "42" || !strings.Contains(api.replyMarkup, "web_app") {
|
if api.chatID != "42" || !strings.Contains(api.replyMarkup, "web_app") {
|
||||||
t.Errorf("private /start: chat=%q markup=%q, want a web_app reply", api.chatID, api.replyMarkup)
|
t.Errorf("private /start: chat=%q markup=%q, want a web_app reply", api.chatID, api.replyMarkup)
|
||||||
}
|
}
|
||||||
|
// No reported language -> English welcome + English button.
|
||||||
|
if !strings.Contains(api.text, "Hi!") {
|
||||||
|
t.Errorf("text = %q, want the English welcome", api.text)
|
||||||
|
}
|
||||||
|
if !strings.Contains(api.replyMarkup, "Open") {
|
||||||
|
t.Errorf("reply_markup = %q, want the English button", api.replyMarkup)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("uses the sender's reported language", func(t *testing.T) {
|
||||||
|
api := &fakeBotAPI{}
|
||||||
|
b := newTestBot(t, api)
|
||||||
|
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
|
||||||
|
Chat: models.Chat{ID: 42, Type: models.ChatTypePrivate}, Text: "/start",
|
||||||
|
From: &models.User{ID: 7, LanguageCode: "ru"},
|
||||||
|
}})
|
||||||
|
if !strings.Contains(api.text, "Привет!") {
|
||||||
|
t.Errorf("text = %q, want the Russian welcome for a ru sender", api.text)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("embeds resolved follow handles", func(t *testing.T) {
|
||||||
|
api := &fakeBotAPI{}
|
||||||
|
b := newTestBot(t, api)
|
||||||
|
b.channelUsername, b.chatUsername = "erudit", "erudite_chat"
|
||||||
|
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
|
||||||
|
Chat: models.Chat{ID: 42, Type: models.ChatTypePrivate}, Text: "/start",
|
||||||
|
}})
|
||||||
|
if !strings.Contains(api.text, "@erudit") || !strings.Contains(api.text, "@erudite_chat") {
|
||||||
|
t.Errorf("text = %q, want the follow handles", api.text)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
t.Run("group ignored", func(t *testing.T) {
|
t.Run("group ignored", func(t *testing.T) {
|
||||||
api := &fakeBotAPI{}
|
api := &fakeBotAPI{}
|
||||||
@@ -127,6 +160,26 @@ func TestHandleStartRepliesPrivateOnly(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestResolveWelcomeHandles(t *testing.T) {
|
||||||
|
api := &fakeBotAPI{}
|
||||||
|
b := newTestBot(t, api)
|
||||||
|
b.channelID, b.chatID = 111, 222
|
||||||
|
b.resolveWelcomeHandles(context.Background())
|
||||||
|
// The fake echoes the requested id into the username, so each lookup is independent.
|
||||||
|
if b.channelUsername != "u111" {
|
||||||
|
t.Errorf("channelUsername = %q, want u111", b.channelUsername)
|
||||||
|
}
|
||||||
|
if b.chatUsername != "u222" {
|
||||||
|
t.Errorf("chatUsername = %q, want u222", b.chatUsername)
|
||||||
|
}
|
||||||
|
// An unset id resolves to no handle (and makes no getChat call).
|
||||||
|
b.channelID = 0
|
||||||
|
b.resolveWelcomeHandles(context.Background())
|
||||||
|
if b.channelUsername != "" {
|
||||||
|
t.Errorf("channelUsername = %q, want empty for id 0", b.channelUsername)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestStartPayload(t *testing.T) {
|
func TestStartPayload(t *testing.T) {
|
||||||
cases := map[string]string{
|
cases := map[string]string{
|
||||||
"/start g123": "g123",
|
"/start g123": "g123",
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package bot
|
||||||
|
|
||||||
|
import "strings"
|
||||||
|
|
||||||
|
// startText returns the localized /start welcome body and the launch-button label.
|
||||||
|
// Russian is used when lang (the IETF language tag the Telegram client reports on the
|
||||||
|
// message's sender) starts with "ru", English otherwise and when it is absent — so a
|
||||||
|
// user with no reported language still gets a sensible message. channel and chat are
|
||||||
|
// the resolved public @usernames (without the leading @) of the game channel and the
|
||||||
|
// discussion chat; when either is empty its follow link degrades to a generic noun
|
||||||
|
// (e.g. "the channel" / "our chat") rather than rendering a dangling "@", since the
|
||||||
|
// bot's own info screen still lists the real links.
|
||||||
|
func startText(lang, channel, chat string) (text, button string) {
|
||||||
|
if strings.HasPrefix(strings.ToLower(lang), "ru") {
|
||||||
|
return ruWelcome(channel, chat), "Открыть «Эрудит»"
|
||||||
|
}
|
||||||
|
return enWelcome(channel, chat), "Open “Erudite”"
|
||||||
|
}
|
||||||
|
|
||||||
|
// ruWelcome builds the Russian welcome. A known handle is named as "@<username>"; an
|
||||||
|
// unresolved one degrades to a plain noun.
|
||||||
|
func ruWelcome(channel, chat string) string {
|
||||||
|
ch := "канал"
|
||||||
|
if channel != "" {
|
||||||
|
ch = "@" + channel
|
||||||
|
}
|
||||||
|
ct := "чате"
|
||||||
|
if chat != "" {
|
||||||
|
ct = "@" + chat
|
||||||
|
}
|
||||||
|
return strings.Join([]string{
|
||||||
|
"Привет! 👋",
|
||||||
|
"Здесь можно сражаться в «Эрудит» со случайными игроками или в компании друзей.",
|
||||||
|
"Подписывайтесь на " + ch + ", чтобы быть в курсе последних игровых событий и вовремя " +
|
||||||
|
"получать важные уведомления. Игроки могут обсуждать игру и просто общаться в нашем " +
|
||||||
|
ct + "! 💬",
|
||||||
|
"Ни слова больше.\nПервая партия сама себя не сыграет 😊",
|
||||||
|
}, "\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// enWelcome builds the English welcome (the fallback for any non-Russian or missing
|
||||||
|
// language). A known handle is named as "@<username>"; an unresolved one degrades to a
|
||||||
|
// plain noun.
|
||||||
|
func enWelcome(channel, chat string) string {
|
||||||
|
ch := "the channel"
|
||||||
|
if channel != "" {
|
||||||
|
ch = "@" + channel
|
||||||
|
}
|
||||||
|
ct := "group chat"
|
||||||
|
if chat != "" {
|
||||||
|
ct = "@" + chat
|
||||||
|
}
|
||||||
|
return strings.Join([]string{
|
||||||
|
"Hi! 👋",
|
||||||
|
"Play Scrabble against random players — or with a group of friends.",
|
||||||
|
"Follow " + ch + " to stay up to date with the latest game events and receive important " +
|
||||||
|
"notifications in time. Players can discuss the game and simply chat in our " + ct + "! 💬",
|
||||||
|
"Okay, no more talking.\nFirst game won't play itself 😊",
|
||||||
|
}, "\n\n")
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package bot
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestStartTextLocalizesByLanguage(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
lang string
|
||||||
|
wantButton string
|
||||||
|
wantSubstr string // a phrase unique to the chosen language body
|
||||||
|
}{
|
||||||
|
{"russian", "ru", "Открыть «Эрудит»", "Привет!"},
|
||||||
|
{"russian region tag", "ru-RU", "Открыть «Эрудит»", "Первая партия"},
|
||||||
|
{"english", "en", "Open “Erudite”", "Hi!"},
|
||||||
|
{"other language falls back to english", "de", "Open “Erudite”", "Hi!"},
|
||||||
|
{"absent language falls back to english", "", "Open “Erudite”", "no more talking"},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
text, button := startText(tc.lang, "erudit", "erudite_chat")
|
||||||
|
if button != tc.wantButton {
|
||||||
|
t.Errorf("button = %q, want %q", button, tc.wantButton)
|
||||||
|
}
|
||||||
|
if !strings.Contains(text, tc.wantSubstr) {
|
||||||
|
t.Errorf("text %q does not contain %q", text, tc.wantSubstr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStartTextEmbedsFollowHandles(t *testing.T) {
|
||||||
|
for _, lang := range []string{"ru", "en"} {
|
||||||
|
text, _ := startText(lang, "erudit", "erudite_chat")
|
||||||
|
if !strings.Contains(text, "@erudit") || !strings.Contains(text, "@erudite_chat") {
|
||||||
|
t.Errorf("lang %q: follow paragraph missing the handles: %q", lang, text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStartTextFallsBackToGenericWhenHandleMissing(t *testing.T) {
|
||||||
|
// An unresolved handle degrades to a generic noun rather than a dangling "@" — and
|
||||||
|
// only that slot degrades; a resolved sibling still shows its "@username".
|
||||||
|
t.Run("both missing leaves no @", func(t *testing.T) {
|
||||||
|
for _, lang := range []string{"ru", "en"} {
|
||||||
|
text, _ := startText(lang, "", "")
|
||||||
|
if strings.Contains(text, "@") {
|
||||||
|
t.Errorf("lang %q: text shows a dangling @: %q", lang, text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The generic nouns are present in each language.
|
||||||
|
ru, _ := startText("ru", "", "")
|
||||||
|
if !strings.Contains(ru, "на канал") || !strings.Contains(ru, "в нашем чате") {
|
||||||
|
t.Errorf("russian generic fallback missing: %q", ru)
|
||||||
|
}
|
||||||
|
en, _ := startText("en", "", "")
|
||||||
|
if !strings.Contains(en, "Follow the channel") || !strings.Contains(en, "in our group chat") {
|
||||||
|
t.Errorf("english generic fallback missing: %q", en)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("only the missing slot degrades", func(t *testing.T) {
|
||||||
|
// Channel resolved, chat missing: the channel keeps its @handle, the chat is generic.
|
||||||
|
en, _ := startText("en", "erudit", "")
|
||||||
|
if !strings.Contains(en, "@erudit") || strings.Contains(en, "@erudite") {
|
||||||
|
t.Errorf("channel handle not shown / chat handle leaked: %q", en)
|
||||||
|
}
|
||||||
|
if !strings.Contains(en, "in our group chat") {
|
||||||
|
t.Errorf("chat slot did not degrade to a generic noun: %q", en)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
+17
-18
@@ -68,7 +68,6 @@ export const app = $state<{
|
|||||||
locale: Locale;
|
locale: Locale;
|
||||||
reduceMotion: boolean;
|
reduceMotion: boolean;
|
||||||
boardLabels: BoardLabelMode;
|
boardLabels: BoardLabelMode;
|
||||||
localeLocked: boolean;
|
|
||||||
/** Pending incoming friend requests, for the lobby ⚙️ badge and the Settings Friends tab. */
|
/** Pending incoming friend requests, for the lobby ⚙️ badge and the Settings Friends tab. */
|
||||||
notifications: number;
|
notifications: number;
|
||||||
/** Per-game flag: the player has at least one unread chat entry (message or nudge) in that
|
/** Per-game flag: the player has at least one unread chat entry (message or nudge) in that
|
||||||
@@ -109,7 +108,6 @@ export const app = $state<{
|
|||||||
locale: 'en',
|
locale: 'en',
|
||||||
reduceMotion: false,
|
reduceMotion: false,
|
||||||
boardLabels: 'beginner',
|
boardLabels: 'beginner',
|
||||||
localeLocked: false,
|
|
||||||
notifications: 0,
|
notifications: 0,
|
||||||
chatUnread: {},
|
chatUnread: {},
|
||||||
messageUnread: {},
|
messageUnread: {},
|
||||||
@@ -451,18 +449,20 @@ async function adoptSession(s: Session): Promise<void> {
|
|||||||
await saveSession(s);
|
await saveSession(s);
|
||||||
try {
|
try {
|
||||||
app.profile = await gateway.profileGet();
|
app.profile = await gateway.profileGet();
|
||||||
// The live interface language follows the device — the explicit local choice (locked, saved
|
// The live interface language follows the device — the explicit local choice (saved in
|
||||||
// in prefs) or the system guess made at bootstrap — and is no longer overridden from the
|
// prefs) or the system guess made at bootstrap — and is no longer overridden from the
|
||||||
// account here. preferred_language stays the user's saved choice (written from Settings,
|
// account here: the Telegram bot a user signs in through must not dictate the UI, so a
|
||||||
// and used for out-of-app push routing), but the Telegram bot a user signs in through must
|
// ru-bot launch on an English system stays English.
|
||||||
// not dictate the UI: a ru-bot launch on an English system stays English.
|
|
||||||
//
|
//
|
||||||
// But the banner and out-of-app push routing ARE resolved from preferred_language, so an
|
// The banner and out-of-app push are resolved server-side from preferred_language, so it
|
||||||
// explicit device choice the account has not recorded yet (picked while a guest, or
|
// must track whatever language the UI actually shows — the explicit choice AND the system
|
||||||
// differing from the Telegram system-language seed) would otherwise leave them in the wrong
|
// guess. Reconcile it to the active locale on every adopt, not only after an explicit
|
||||||
// language until the next Settings change. Reconcile the account to the saved local choice
|
// Settings choice: a user who never opened Settings would otherwise be stuck on the
|
||||||
// here; persistLanguageToServer no-ops for guests and when already equal.
|
// creation-time seed — e.g. an English banner under a Russian UI. This keeps every
|
||||||
if (app.localeLocked) void persistLanguageToServer(app.locale);
|
// server-rendered, language-dependent surface (banner, out-of-app push) aligned with the
|
||||||
|
// interface, not just one. persistLanguageToServer self-gates (a no-op for guests and when
|
||||||
|
// already equal), so there is no write in the steady state.
|
||||||
|
void persistLanguageToServer(app.locale);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
handleError(err);
|
handleError(err);
|
||||||
}
|
}
|
||||||
@@ -483,9 +483,10 @@ export async function applyLinkResult(r: LinkResult): Promise<void> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
app.profile = await gateway.profileGet();
|
app.profile = await gateway.profileGet();
|
||||||
// A guest who chose a language and then linked in place now has a durable account: push the
|
// A guest who linked in place now has a durable account: push the active interface language
|
||||||
// saved choice so the banner + push routing follow it (see adoptSession).
|
// so the banner + push routing follow it (see adoptSession — reconciled regardless of an
|
||||||
if (app.localeLocked) void persistLanguageToServer(app.locale);
|
// explicit Settings choice).
|
||||||
|
void persistLanguageToServer(app.locale);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -538,7 +539,6 @@ export async function bootstrap(): Promise<void> {
|
|||||||
applyReduceMotion(app.reduceMotion);
|
applyReduceMotion(app.reduceMotion);
|
||||||
if (prefs.locale) {
|
if (prefs.locale) {
|
||||||
app.locale = prefs.locale;
|
app.locale = prefs.locale;
|
||||||
app.localeLocked = true;
|
|
||||||
setLocale(prefs.locale);
|
setLocale(prefs.locale);
|
||||||
} else {
|
} else {
|
||||||
const guess = localeFrom(typeof navigator !== 'undefined' ? navigator.language : 'en');
|
const guess = localeFrom(typeof navigator !== 'undefined' ? navigator.language : 'en');
|
||||||
@@ -754,7 +754,6 @@ export function setTheme(theme: ThemePref): void {
|
|||||||
|
|
||||||
export function setLocalePref(locale: Locale): void {
|
export function setLocalePref(locale: Locale): void {
|
||||||
app.locale = locale;
|
app.locale = locale;
|
||||||
app.localeLocked = true;
|
|
||||||
setLocale(locale);
|
setLocale(locale);
|
||||||
persistPrefs();
|
persistPrefs();
|
||||||
void persistLanguageToServer(locale);
|
void persistLanguageToServer(locale);
|
||||||
|
|||||||
Reference in New Issue
Block a user