From 78e7fe526ee0edd8c6574c4eb4a5407447f11bbf Mon Sep 17 00:00:00 2001 From: amtiYo Date: Mon, 16 Nov 2026 16:35:23 +0100 Subject: [PATCH] feat(bot): welcome a new group and warm it up after its reveal A group that added maply heard nothing until the next post, so it took the bot for dead. Now the moment maply joins, the group gets one welcome: its home panel with what maply is, the post time and the reveal in the group's zone, and what comes next. Before the post that is the morning's first place; during the day it is today's real round, which the scheduler already sends within seconds; after the reveal it is a warm-up, since the group would otherwise wait until tomorrow. The warm-up plays the archive's newest day, closed in every zone, from a startapp payload signed for the group and the day (version 3). Each player's game is their own day from the free game's archive, so it counts in no day's table, world, profile, streak or rating, and nobody who answered that day can take it. warmup_game ties those games to the group, and a new warmup job sends the group's table an hour later. One warm-up a group, ever. A supergroup where maply is not an admin is asked once, in the welcome, for the right to pin, with a link that requests just that right; the morning post then does not ask again. /start in a group shows the warm-up's button while it runs. Closes #57 Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 13 +- CHANGELOG.md | 9 + cmd/maply-dev/fakebot.go | 2 +- cmd/maply/main.go | 3 +- docs/design.md | 11 +- docs/mvp-plan.md | 2 +- internal/api/api.go | 2 + internal/api/free.go | 5 +- internal/api/free_more.go | 56 +++++ internal/api/warmup_integration_test.go | 262 ++++++++++++++++++++++++ internal/auth/payload.go | 10 +- internal/bot/bot.go | 9 + internal/bot/bot_test.go | 30 ++- internal/bot/menu.go | 9 +- internal/bot/menu_test.go | 10 +- internal/bot/panels.go | 17 +- internal/bot/welcome.go | 187 +++++++++++++++++ internal/bot/welcome_test.go | 169 +++++++++++++++ internal/db/warmup.go | 118 +++++++++++ internal/i18n/translations.json | 216 +++++++++++++++++++ internal/schedule/schedule.go | 5 + internal/schedule/warmup.go | 75 +++++++ internal/schedule/warmup_test.go | 27 +++ migrations/031_warmup.sql | 29 +++ web/app/free.js | 21 +- 25 files changed, 1271 insertions(+), 26 deletions(-) create mode 100644 internal/api/warmup_integration_test.go create mode 100644 internal/bot/welcome.go create mode 100644 internal/bot/welcome_test.go create mode 100644 internal/db/warmup.go create mode 100644 internal/schedule/warmup.go create mode 100644 internal/schedule/warmup_test.go create mode 100644 migrations/031_warmup.sql diff --git a/AGENTS.md b/AGENTS.md index 4b38434..49c9368 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,6 +63,10 @@ player, and production-minded. count. Do not add a fourth: the rules in a group's first post and the admins' note when maply may not pin go into the post itself, and so does the month's season champion, in the look back of the month's last day. + The welcome when maply is added answers the admin, as `/start` does, and + is not one of the three. A group added after its reveal gets a warm-up on + the archive's newest day and its result an hour later, the only scheduled + message of that day (`docs/design.md` → "Groups"). - Posts write the reveal with the chat's zone, "20:00 (Kyiv)". A chat's zone is stored the first time maply needs it (`FixZone`), so a later change of language cannot move a reveal. A DM's stored this way is marked automatic @@ -99,10 +103,11 @@ player, and production-minded. - Free play (`internal/free`, `/play`, `/party/`; the archive and a challenge are screens inside `/play`) is outside the day: its own `free_*` tables, no place in the world, no stats shared with the - day, and no bot message in groups. Its rules are in `docs/design.md` → - "Free play". Records and friends need an account: a Telegram person (the - Mini App, or the site with an account that has Telegram, which plays as - the person and writes nothing to `core`) or an account with Google alone, + day, and no bot message in groups but a new group's warm-up result. Its + rules are in `docs/design.md` → "Free play". Records and friends need an + account: a Telegram person (the Mini App, or the site with an account + that has Telegram, which plays as the person and writes nothing to + `core`) or an account with Google alone, which plays as its own site player. A guest plays alone, without records. Its leaderboards (`/api/top`) count only games on a timer and never an attempt at a challenge, one row a person or an account with their best: diff --git a/CHANGELOG.md b/CHANGELOG.md index f7c109f..fcd26ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,15 @@ See [`docs/versioning.md`](docs/versioning.md) for what the numbers mean and result says, before the evening, whether you have answered and how long until the result, and after it your score and place in the world. The keyboard follows a language change; groups never get it. +- A group hears from maply the moment it is added: what maply is, when the + place and the answer come in the group's zone, and what comes next. A + group added after its 20:00 gets a warm-up on the newest day of the + archive, with its own result an hour later, so it has something to play + that evening. The warm-up counts nowhere: not in the day's tables, the + world, profiles, streaks or ratings. When maply may not pin in a + supergroup, the welcome asks the admins once, with a button that requests + just that right. `/start` in a group offers the warm-up while it runs. + For the operator: migration 031 adds the `warmup` tables and job kind. ## v0.0.1-alpha.20 - 2026-11-10 diff --git a/cmd/maply-dev/fakebot.go b/cmd/maply-dev/fakebot.go index 7f10f5a..b4a475c 100644 --- a/cmd/maply-dev/fakebot.go +++ b/cmd/maply-dev/fakebot.go @@ -1047,7 +1047,7 @@ func (f *fakeTelegram) run(ctx context.Context, e *Env) (func(), error) { tgc := telegram.New(client) tgc.Upload = &telegram.Uploader{Base: base, Token: BotToken} avatars := &avatar.Service{Store: e.Store, TG: tgc, Log: log, Now: e.Clock.Now} - opts := bot.Options{Username: botUsername, Version: "dev", AppURL: appURL, Zones: e.Zones, Now: e.Clock.Now} + opts := bot.Options{Payloads: e.Signer, Username: botUsername, Version: "dev", AppURL: appURL, Zones: e.Zones, Now: e.Clock.Now} sched := &schedule.Scheduler{ Store: e.Store, TG: tgc, Weather: standWeather{}, Payloads: e.Signer, Zones: e.Zones, Countries: e.Countries, ImagesDir: e.ImagesDir, Username: botUsername, AppURL: appURL, diff --git a/cmd/maply/main.go b/cmd/maply/main.go index 9b6aae5..660c586 100644 --- a/cmd/maply/main.go +++ b/cmd/maply/main.go @@ -110,7 +110,9 @@ func run(log *slog.Logger) error { log.Info("animated posts on", "ffmpeg", path) } } + signer := auth.NewSigner(cfg.TelegramBotToken) opts := bot.Options{ + Payloads: signer, Username: me.Username, Version: version, AppURL: cfg.AppURL, @@ -130,7 +132,6 @@ func run(log *slog.Logger) error { // The players' photos for the pins and tables of the results. avatars := &avatar.Service{Store: store, TG: tgc, Log: log} - signer := auth.NewSigner(cfg.TelegramBotToken) // Without a renderer the result goes out with the place's photo and the // Mini App shares through t.me/share, as before the card existed. var cards *card.Service diff --git a/docs/design.md b/docs/design.md index 382a549..89d72db 100644 --- a/docs/design.md +++ b/docs/design.md @@ -189,15 +189,20 @@ In a DM the intrigue arrives only if the person has not answered yet. The "Chat ## Groups -- **First day.** Right after being added, the bot runs a warm-up round on yesterday's place with the answer the same evening, so the group does not wait until tomorrow morning. -- **Permissions.** The game works without the right to pin messages. The bot tells the admins once that it is more fun with a pin. +- **First day.** The moment maply is added, the group gets one welcome: the group's home panel (Settings, Help, Close) with what maply is, when the place comes and when the answer does, "07:00" and "20:00 (Kyiv)" in the group's own post time and zone, and what comes next, which depends on where the group's day stands (decided in #57 on 16 November 2026): + - before the morning post: the first place comes at the post time today; + - between the post and the reveal: today's real round, whose post the scheduler sends within seconds of the welcome. A real round beats a warm-up, and two places at once would only confuse; + - after the reveal: a **warm-up**, since the group would otherwise wait until tomorrow morning. It plays the archive's newest day, normally yesterday's place: over in every zone, kept, and a panorama, as the free game's archive has it. Its button opens the Mini App with `startapp=w`, signed for the group and the day (version 3 of the payload), and membership is asked of Telegram as for a day's post. Each player's game is their own day from the archive (`free_archive`), so the warm-up counts in no day's table, no world, no profile, no streak and no rating, and someone who answered that day or had its place cannot take it, as in the archive. `warmup_game` only says which of those games came from the group. It takes answers for an hour (`schedule.WarmupFor`); then the `warmup` job sends its result: the place, the group's table and when the real game starts. Nobody played, no result. A group gets one warm-up ever; added back, it gets a welcome without one. The day's game for that date has no post and no result there. + + The welcome answers an admin adding maply, as a `/start` panel does, and is none of the day's three messages; the warm-up's result is the only scheduled message of a day the group has no round of. `/start` in a group shows the warm-up's button while it takes answers. +- **Permissions.** The game works without the right to pin messages. The bot tells the admins once that it is more fun with a pin: in the welcome, when maply joins a supergroup without being its admin, with a button `t.me/?startgroup=pin&admin=pin_messages` that asks Telegram for that one right; otherwise in the first post that could not be pinned. In a basic group every member may pin unless the admins said otherwise, so the welcome does not ask there. - **`/rival`.** Links two chats into a duel: a shared season score and the "Rival" intrigue. - **Seasons.** A calendar month. At the end the chat gets a champion of the month, and the ranking resets. - **Settings** through buttons in `/start`, as in quoto: morning post time, intrigue on/off, streak mentions on/off. ## Free play -Next to the day's game, which keeps every rule above, there is free play: alone or with up to eight friends, as many places as one likes, with no place in the world and no stats shared with the day. It is called "Free play" and opens at `/play`: from the menu, from the DM's `/start` panel and from a friend's invitation. It looks as the day's game does, the same header, panorama, globe, caption and bottom strip, and after an answer the same plates on a phone and the same side panel on a computer; only what is counted differs: the place of the game ("Place 2/5") where the day has its number, the place's clock where the day has its countdown, and the points. The menu's cards open the settings on a mode, `/play?mode=classic|blitz|streak|clock|archive`, and `/play?with=friends` opens a lobby; Blitz is the classic on 30 s. The bot writes nothing about it in groups, so the three messages a day stay three. +Next to the day's game, which keeps every rule above, there is free play: alone or with up to eight friends, as many places as one likes, with no place in the world and no stats shared with the day. It is called "Free play" and opens at `/play`: from the menu, from the DM's `/start` panel and from a friend's invitation. It looks as the day's game does, the same header, panorama, globe, caption and bottom strip, and after an answer the same plates on a phone and the same side panel on a computer; only what is counted differs: the place of the game ("Place 2/5") where the day has its number, the place's clock where the day has its countdown, and the points. The menu's cards open the settings on a mode, `/play?mode=classic|blitz|streak|clock|archive`, and `/play?with=friends` opens a lobby; Blitz is the classic on 30 s. The bot writes nothing about it in groups, so the three messages a day stay three; a group's warm-up on its first evening (see "Groups") is the one day of the archive a group hears about. Back goes one step up: from a place or the final to the mode's settings, from a day of the archive to the archive, from a game of a challenge to its table. The mode's settings, the archive and the lobby are pages of the top, as the days and the leaderboards are: on a phone's browser Back leads to the menu, on a computer they have no Back, the header is the way, and in Telegram Telegram's Back is the only one on every screen. Escape does what Back does. Between `/play` and `/party/` the free game keeps one entry of the browser's history, so the menu is the step before any of its pages. diff --git a/docs/mvp-plan.md b/docs/mvp-plan.md index 11ab0b8..4d33b78 100644 --- a/docs/mvp-plan.md +++ b/docs/mvp-plan.md @@ -119,7 +119,7 @@ maply calls them through `Client.Call` right away. Typed methods will be added t - `/start` in a group: - settings with buttons, as in voicy and branchy; - - a warm-up on yesterday's place with the answer the same evening; + - a welcome the moment maply is added, and a warm-up on the archive's newest day with its result an hour later when the group joins after its reveal (decided in #57, see `docs/design.md` → "Groups"); - one message to the admins if the bot has no right to pin. - 07:00 in the chat's time zone, or at the time the group chose: - a post with the photo and a button; diff --git a/internal/api/api.go b/internal/api/api.go index d13d088..dd521d1 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -70,6 +70,8 @@ type Store interface { AdoptDMZone(context.Context, int64, string) (bool, error) FixZone(context.Context, int64, string) error ChatActive(context.Context, int64) (bool, error) + WarmupOf(ctx context.Context, chatID int64) (db.Warmup, bool, error) + JoinWarmup(ctx context.Context, chatID, game int64) error DaysPage(context.Context, db.DaysQuery) (db.DaysPage, error) RoundNo(context.Context, int) (db.Round, bool, error) ClosedDay(context.Context, round.Date, round.Date) (db.ClosedDay, error) diff --git a/internal/api/free.go b/internal/api/free.go index b495c41..d26a828 100644 --- a/internal/api/free.go +++ b/internal/api/free.go @@ -94,6 +94,9 @@ type freeViewer struct { // site is a browser rather than the Mini App: its invitations are the // site's own links. site bool + // start is the Mini App's start_param, which Telegram signs with the rest + // of initData; empty on the site. + start string } // keeps is whether the viewer keeps records and may play with friends. An @@ -126,7 +129,7 @@ func (s *Server) freeViewer(w http.ResponseWriter, r *http.Request, lim *limiter if err != nil { return freeViewer{}, err } - return freeViewer{who: free.Who{UserID: data.User.ID}, user: data.User, lang: i18n.Resolve(lang)}, nil + return freeViewer{who: free.Who{UserID: data.User.ID}, user: data.User, lang: i18n.Resolve(lang), start: data.StartParam}, nil } if write && !ownJSON(r) { return freeViewer{}, apiError{http.StatusUnsupportedMediaType, "json_only"} diff --git a/internal/api/free_more.go b/internal/api/free_more.go index a2a5f0b..ba13eed 100644 --- a/internal/api/free_more.go +++ b/internal/api/free_more.go @@ -6,9 +6,11 @@ package api // keep records, a Telegram person or an account, as a party is. import ( + "context" "crypto/rand" "encoding/base64" "net/http" + "strings" "github.com/FreshLabDev/maply/internal/free" "github.com/FreshLabDev/maply/internal/i18n" @@ -37,11 +39,21 @@ func (s *Server) archiveTake(w http.ResponseWriter, r *http.Request) { } var b struct { N int `json:"n"` + // Warmup takes the day of the group's warm-up the app was opened + // on, in place of n. + Warmup bool `json:"warmup"` } if err := readBody(w, r, &b); err != nil { s.freeFail(w, r, err) return } + var chatID int64 + if b.Warmup { + if chatID, b.N, err = s.warmup(r.Context(), v); err != nil { + s.freeFail(w, r, err) + return + } + } if err := s.met(r.Context(), v); err != nil { s.freeFail(w, r, err) return @@ -51,9 +63,53 @@ func (s *Server) archiveTake(w http.ResponseWriter, r *http.Request) { s.freeFail(w, r, err) return } + if chatID != 0 { + if err := s.Store.JoinWarmup(r.Context(), chatID, g.ID); err != nil { + s.freeFail(w, r, err) + return + } + } writeJSON(w, http.StatusOK, g) } +// errWarmupOver is a warm-up whose result has gone out, or whose time has. +var errWarmupOver = apiError{http.StatusGone, "warmup_over"} + +// warmup is the group and the day of the warm-up the Mini App was opened on +// from a group's welcome: "w" and a payload signed for both, read from +// initData. As with the day's post, the payload only says where the link +// came from, so membership is asked of Telegram. A warm-up is a day of the +// archive, closed in every zone, played as any day of the archive is: the +// group only gets to see who of it played. +func (s *Server) warmup(ctx context.Context, v freeViewer) (int64, int, error) { + raw, ok := strings.CutPrefix(v.start, "w") + if !ok || v.who.UserID == 0 { + return 0, 0, errBadRequest + } + p, err := s.Payloads.VerifyWarmup(raw) + if err != nil { + return 0, 0, errUnauthorized + } + wu, ok, err := s.Store.WarmupOf(ctx, p.ChatID) + if err != nil { + return 0, 0, err + } + if !ok || wu.Day.String() != p.Date.String() { + return 0, 0, free.ErrNotFound + } + if !wu.Open(s.Now()) { + return 0, 0, errWarmupOver + } + member, err := s.Members.IsMember(ctx, p.Date, p.ChatID, v.who.UserID) + if err != nil { + return 0, 0, err + } + if !member { + return 0, 0, errNotMember + } + return p.ChatID, wu.DayNo, nil +} + func (s *Server) challengeMake(w http.ResponseWriter, r *http.Request) { v, err := s.freeViewer(w, r, s.makeLimit, true) if err != nil { diff --git a/internal/api/warmup_integration_test.go b/internal/api/warmup_integration_test.go new file mode 100644 index 0000000..392fec1 --- /dev/null +++ b/internal/api/warmup_integration_test.go @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: Apache-2.0 +//go:build integration + +package api + +import ( + "context" + "fmt" + "io" + "log/slog" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/FreshLabDev/tg" + + "github.com/FreshLabDev/maply/internal/auth" + "github.com/FreshLabDev/maply/internal/bot" + "github.com/FreshLabDev/maply/internal/db" + "github.com/FreshLabDev/maply/internal/free" + "github.com/FreshLabDev/maply/internal/round" + "github.com/FreshLabDev/maply/internal/schedule" + "github.com/FreshLabDev/maply/internal/telegram" +) + +// chatLog is every message maply sends, from the bot and from the +// scheduler, as a group would see them. +type chatLog struct { + msgs []chatMsg + cancel context.CancelFunc + batch []tg.Update + polled int +} + +type chatMsg struct { + kind string + chatID int64 + text string + markup telegram.Markup +} + +func (c *chatLog) add(kind string, chatID int64, text string, m telegram.Markup) (tg.Message, error) { + c.msgs = append(c.msgs, chatMsg{kind, chatID, text, m}) + msg := tg.Message{MessageID: int64(len(c.msgs)), Chat: tg.Chat{ID: chatID}, Text: text} + if kind == "photo" { + msg.Photo = []tg.Photo{{FileID: "warm-photo"}} + } + return msg, nil +} + +func (c *chatLog) in(chatID int64) []chatMsg { + var out []chatMsg + for _, m := range c.msgs { + if m.chatID == chatID { + out = append(out, m) + } + } + return out +} + +// The bot's side. +func (c *chatLog) DeleteWebhook(context.Context) error { return nil } +func (c *chatLog) GetUpdates(ctx context.Context, _ int64, _ int) ([]tg.Update, error) { + c.polled++ + if c.polled == 1 { + return c.batch, nil + } + c.cancel() + return nil, ctx.Err() +} +func (c *chatLog) SetMyCommandsForScope(context.Context, []tg.BotCommand, *tg.BotCommandScope) error { + return nil +} +func (c *chatLog) SendText(_ context.Context, chatID int64, text string, m telegram.Markup) (tg.Message, error) { + return c.add("text", chatID, text, m) +} +func (c *chatLog) SendTextIn(_ context.Context, chatID int64, _ int, text string, m telegram.Markup) (tg.Message, error) { + return c.add("text", chatID, text, m) +} +func (c *chatLog) SendKeyboard(_ context.Context, chatID int64, text string, _ telegram.Keyboard) (tg.Message, error) { + return c.add("keyboard", chatID, text, nil) +} +func (c *chatLog) EditText(context.Context, int64, int64, string, telegram.Markup) error { return nil } +func (c *chatLog) EditAnimation(context.Context, int64, int64, telegram.Animation, string, telegram.Markup) (tg.Message, error) { + return tg.Message{}, nil +} +func (c *chatLog) DeleteMessage(context.Context, int64, int64) error { return nil } +func (c *chatLog) AnswerCallbackQuery(context.Context, string, string) error { return nil } +func (c *chatLog) AnswerCallbackQueryAlert(context.Context, string, string) error { return nil } +func (c *chatLog) GetChatMember(_ context.Context, _, userID int64) (tg.ChatMember, error) { + return tg.ChatMember{Status: "administrator", User: tg.User{ID: userID}}, nil +} +func (c *chatLog) SetDescriptions(context.Context, string, string, string) error { return nil } + +// The scheduler's side. +func (c *chatLog) SendPhoto(_ context.Context, chatID int64, _ telegram.Photo, caption string, m telegram.Markup) (tg.Message, error) { + return c.add("photo", chatID, caption, m) +} +func (c *chatLog) SendAnimation(_ context.Context, chatID int64, _ telegram.Animation, caption string, m telegram.Markup) (tg.Message, error) { + return c.add("animation", chatID, caption, m) +} +func (c *chatLog) EditCaption(context.Context, int64, int64, string, telegram.Markup) error { + return nil +} +func (c *chatLog) Pin(_ context.Context, chatID, _ int64) error { + _, err := c.add("pin", chatID, "", nil) + return err +} +func (c *chatLog) Unpin(context.Context, int64, int64) error { return nil } + +// TestAGroupAddedInTheEveningWarmsUp adds maply to a group at 21:00 in Kyiv, +// after the group's reveal: the group gets its welcome with a warm-up on the +// archive's newest day, plays it from the Mini App, and an hour later gets +// the warm-up's result. The warm-up is a day of the archive: it is in no +// day's table, no world, no profile. +func TestAGroupAddedInTheEveningWarmsUp(t *testing.T) { + hs := freeSetup(t) + ctx := context.Background() + store := hs.srv.Store.(*db.Store) + const newGroup = int64(-1001900005599) + hs.person(1, "Oksana") + hs.person(2, "Ivan") + // Yesterday Ivan answered from his DM; the day is over everywhere. + yesterday := hs.seedPast(1, "JP", "asia", pastAnswer{user: 2, km: 2000, points: 900}) + worldBefore, err := store.World(ctx, yesterday) + if err != nil { + t.Fatal(err) + } + // 21:00 in Kyiv on 10 December: the group's 20:00 has passed. + hs.now = time.Date(2026, time.December, 10, 19, 0, 0, 0, time.UTC) + zones := hs.srv.Zones + hs.srv.Free.Zones = zones + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + group := tg.Chat{ID: newGroup, Type: "supergroup", Title: "Atlas"} + oksana := tg.User{ID: 1, FirstName: "Oksana", LanguageCode: "uk"} + + // The bot is added. + runCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + chats := &chatLog{cancel: cancel, batch: []tg.Update{{UpdateID: 1, MyChatMember: &tg.ChatMemberUpdated{ + Chat: group, From: oksana, OldChatMember: tg.ChatMember{Status: "left"}, NewChatMember: tg.ChatMember{Status: "administrator"}}}}} + b := bot.New(store, chats, log, bot.Options{Username: "maplyin_bot", Zones: zones, Payloads: hs.signer, + Now: func() time.Time { return hs.now }}) + if err := b.Run(runCtx); err != nil { + t.Fatal(err) + } + welcome := chats.in(newGroup) + if len(welcome) != 1 || welcome[0].kind != "text" || !strings.Contains(welcome[0].text, "22:00") { + t.Fatalf("welcome = %+v", welcome) + } + var link string + for _, row := range welcome[0].markup { + for _, btn := range row { + if strings.Contains(btn.URL, "startapp=w") { + link = btn.URL + } + } + } + u, err := url.Parse(link) + if err != nil || link == "" { + t.Fatalf("no warm-up button: %+v", welcome[0].markup) + } + start := u.Query().Get("startapp") + + // Oksana plays it from the welcome; Ivan answered that day and cannot; + // a stranger with a forwarded link is not in the group. + members := hs.srv.Members.(members) + members[[2]int64{newGroup, 1}] = true + members[[2]int64{newGroup, 2}] = true + inGroup := initData(1, "Oksana", "uk", start) + g := decode[free.SoloView](t, hs.expect("POST", "/api/free/archive", inGroup, `{"warmup":true}`, http.StatusOK)) + if g.Day == nil || g.Day.N != 99 || g.Current == nil { + t.Fatalf("warm-up game = %+v", g) + } + hs.expect("POST", fmt.Sprintf("/api/free/solo/%d/guess", g.ID), inGroup, `{"n":1,"lat":10.5,"lon":20.5}`, http.StatusOK) + if body := hs.expect("POST", "/api/free/archive", initData(2, "Ivan", "ru", start), `{"warmup":true}`, http.StatusConflict); !strings.Contains(body, "day_answered") { + t.Fatalf("Ivan took a day he answered: %s", body) + } + hs.expect("POST", "/api/free/archive", initData(3, "Alesia", "be", start), `{"warmup":true}`, http.StatusForbidden) + // The day's post payload is not a warm-up's, and a warm-up needs one. + day, err := hs.signer.Sign(auth.Payload{Date: yesterday, ChatID: newGroup}) + if err != nil { + t.Fatal(err) + } + hs.expect("POST", "/api/free/archive", initData(1, "Oksana", "uk", "w"+day), `{"warmup":true}`, http.StatusUnauthorized) + hs.expect("POST", "/api/free/archive", initData(1, "Oksana", "uk", ""), `{"warmup":true}`, http.StatusBadRequest) + + // The scheduler plans the group's day, which is over: no post and no + // result. An hour after the welcome the warm-up's result comes. + sched := &schedule.Scheduler{Store: store, TG: chats, Payloads: hs.signer, Zones: zones, Countries: hs.srv.Countries, + ImagesDir: hs.srv.ImagesDir, Username: "maplyin_bot", Log: log, Now: func() time.Time { return hs.now }} + sched.Step(ctx) + if got := chats.in(newGroup); len(got) != 1 { + t.Fatalf("before the warm-up's result the group got %+v", got[1:]) + } + hs.now = hs.now.Add(30 * time.Minute) + sched.Step(ctx) + if got := chats.in(newGroup); len(got) != 1 { + t.Fatalf("the warm-up's result came early: %+v", got[1:]) + } + // Too late for the warm-up: its result is about to come. + hs.now = hs.now.Add(30 * time.Minute) + hs.expect("POST", "/api/free/archive", initData(2, "Ivan", "ru", start), `{"warmup":true}`, http.StatusGone) + sched.Step(ctx) + sched.Step(ctx) + got := chats.in(newGroup) + if len(got) != 2 || got[1].kind != "photo" { + t.Fatalf("group messages = %+v", got) + } + result := got[1].text + for _, want := range []string{"maply #99", "Oksana", "Past", "07:00", "20:00"} { + if !strings.Contains(result, want) { + t.Fatalf("warm-up result = %q, missing %q", result, want) + } + } + if strings.Contains(result, "Ivan") { + t.Fatalf("warm-up result names Ivan, who did not play it: %q", result) + } + + // Nowhere else: no answer of the day, the day's world as it was, no day + // on Oksana's profile, nothing in the day's ranking of the group. + var guesses int + if err := hs.pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM maply.guess WHERE user_id = 1) + (SELECT count(*) FROM maply.site_guess)`).Scan(&guesses); err != nil { + t.Fatal(err) + } + if guesses != 0 { + t.Fatalf("the warm-up wrote %d answers of the day", guesses) + } + worldAfter, err := store.World(ctx, yesterday) + if err != nil { + t.Fatal(err) + } + median := func(w db.World) string { + if w.MedianKm == nil { + return "-" + } + return fmt.Sprint(*w.MedianKm) + } + if fmt.Sprint(worldAfter.Entries) != fmt.Sprint(worldBefore.Entries) || median(worldAfter) != median(worldBefore) { + t.Fatalf("the warm-up moved the world:\n%+v\n%+v", worldBefore, worldAfter) + } + if v := decode[ownView](t, hs.expect("GET", "/api/profile", initData(1, "Oksana", "uk", ""), "", http.StatusOK)); v.Ranked.Days != 0 { + t.Fatalf("Oksana's profile counts %d days", v.Ranked.Days) + } + if gs, err := store.ChatGuesses(ctx, round.DateIn(hs.now, time.UTC), newGroup); err != nil || len(gs) != 0 { + t.Fatalf("the group's day = %+v, %v", gs, err) + } + // One warm-up a group: added back, it gets a welcome without one. + chats.polled, chats.batch = 0, chats.batch[:1] + chats.batch[0].UpdateID = 2 + runCtx, cancel = context.WithTimeout(ctx, 10*time.Second) + defer cancel() + chats.cancel = cancel + if err := b.Run(runCtx); err != nil { + t.Fatal(err) + } + if again := chats.in(newGroup); len(again) != 3 || strings.Contains(fmt.Sprint(again[2].markup), "startapp=w") { + t.Fatalf("added back: %+v", again[2:]) + } +} diff --git a/internal/auth/payload.go b/internal/auth/payload.go index d712646..b308ffc 100644 --- a/internal/auth/payload.go +++ b/internal/auth/payload.go @@ -25,10 +25,13 @@ import ( // Posts already in chats carry this form. A new form gets a new version byte, // and this one keeps verifying. Version 2 has the same layout and signs a // result card's link: the startapp payload in a group post is visible to -// everyone who can read the post, so it must not open a card page. +// everyone who can read the post, so it must not open a card page. Version 3 +// has it too and opens a group's warm-up from its welcome, after a "w": the +// date is the day of the archive the warm-up plays, closed everywhere. const ( payloadVersion = 1 cardVersion = 2 + warmupVersion = 3 payloadBody = 1 + 2 + 8 payloadMAC = 16 ) @@ -62,6 +65,9 @@ func (s *Signer) Sign(p Payload) (string, error) { return s.sign(payloadVersion, // SignCard makes the token of a result card's link. func (s *Signer) SignCard(p Payload) (string, error) { return s.sign(cardVersion, p) } +// SignWarmup makes the startapp payload of a group's warm-up, without its "w". +func (s *Signer) SignWarmup(p Payload) (string, error) { return s.sign(warmupVersion, p) } + func (s *Signer) sign(version byte, p Payload) (string, error) { days := p.Date.DaysSince(payloadEpoch) if days < 0 || days > 0xFFFF { @@ -79,6 +85,8 @@ func (s *Signer) Verify(raw string) (Payload, error) { return s.verify(payloadVe func (s *Signer) VerifyCard(raw string) (Payload, error) { return s.verify(cardVersion, raw) } +func (s *Signer) VerifyWarmup(raw string) (Payload, error) { return s.verify(warmupVersion, raw) } + func (s *Signer) verify(version byte, raw string) (Payload, error) { buf, err := base64.RawURLEncoding.DecodeString(raw) if err != nil || len(buf) != payloadBody+payloadMAC || buf[0] != version { diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 6e44a99..71a2a34 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -11,6 +11,7 @@ import ( "github.com/FreshLabDev/tg" + "github.com/FreshLabDev/maply/internal/auth" "github.com/FreshLabDev/maply/internal/db" "github.com/FreshLabDev/maply/internal/round" "github.com/FreshLabDev/maply/internal/schedule" @@ -46,6 +47,11 @@ type Store interface { InsertGuess(ctx context.Context, g db.NewGuess) error GuessOf(ctx context.Context, d round.Date, userID int64) (db.Guess, bool, error) World(ctx context.Context, d round.Date) (db.World, error) + + SetPinWarned(ctx context.Context, chatID int64) error + PlanJob(ctx context.Context, kind string, chatID int64, d round.Date, runAt time.Time) error + StartWarmup(ctx context.Context, chatID int64, closed round.Date, resultAt time.Time) (db.Warmup, bool, error) + WarmupOf(ctx context.Context, chatID int64) (db.Warmup, bool, error) } type Telegram interface { @@ -78,6 +84,9 @@ type Options struct { // Profiles draws the statistics picture; nil shows the statistics as // text only. Profiles Profiles + // Payloads signs the link of a group's warm-up; nil leaves the warm-up + // without its button. + Payloads *auth.Signer // World refreshes the world picture of a DM's result; nil leaves its // Refresh button doing nothing. World WorldRefresher diff --git a/internal/bot/bot_test.go b/internal/bot/bot_test.go index 39b53b7..299cc9e 100644 --- a/internal/bot/bot_test.go +++ b/internal/bot/bot_test.go @@ -4,6 +4,7 @@ package bot import ( "context" "encoding/json" + "fmt" "io" "log/slog" "sync" @@ -38,11 +39,17 @@ type fakeStore struct { guesses []db.NewGuess scored map[int64]db.Guess world db.World + // warmDay is the archive's day a warm-up takes; zero has none. + warmDay round.Date + warmups map[int64]db.Warmup + jobs []string + pinWarned map[int64]bool } func newStore() *fakeStore { return &fakeStore{userLang: map[int64]string{}, chatLang: map[int64]string{}, zones: map[int64]string{}, - settings: map[int64]db.Settings{}, rounds: map[string]bool{}} + settings: map[int64]db.Settings{}, rounds: map[string]bool{}, + warmups: map[int64]db.Warmup{}, pinWarned: map[int64]bool{}} } func (f *fakeStore) Offset(context.Context) (int64, error) { @@ -164,6 +171,27 @@ func (f *fakeStore) InsertGuess(_ context.Context, g db.NewGuess) error { return nil } +func (f *fakeStore) SetPinWarned(_ context.Context, id int64) error { + f.pinWarned[id] = true + return nil +} +func (f *fakeStore) PlanJob(_ context.Context, kind string, chatID int64, d round.Date, runAt time.Time) error { + f.jobs = append(f.jobs, fmt.Sprintf("%s:%s:%d@%s", kind, d, chatID, runAt.UTC().Format(time.RFC3339))) + return nil +} +func (f *fakeStore) StartWarmup(_ context.Context, id int64, closed round.Date, at time.Time) (db.Warmup, bool, error) { + if _, ok := f.warmups[id]; ok || f.warmDay.IsZero() || closed.Before(f.warmDay) { + return db.Warmup{}, false, nil + } + w := db.Warmup{ChatID: id, Day: f.warmDay, DayNo: 41, ResultAt: at} + f.warmups[id] = w + return w, true, nil +} +func (f *fakeStore) WarmupOf(_ context.Context, id int64) (db.Warmup, bool, error) { + w, ok := f.warmups[id] + return w, ok, nil +} + type sent struct { chatID, messageID int64 text string diff --git a/internal/bot/menu.go b/internal/bot/menu.go index 45094dc..00b169e 100644 --- a/internal/bot/menu.go +++ b/internal/bot/menu.go @@ -189,11 +189,16 @@ func (v view) closeButton() telegram.Button { // home is two screens, with the reveal in the chat's zone (one of // round.ZoneChoices). The direct chat gets every tab: there the panel is the // whole bot. A group gets what a group acts on, and Settings only for an -// admin, who is the only one who can change them. -func (v view) home(appURL string, admin bool, zone string) (string, telegram.Markup) { +// admin, who is the only one who can change them. A group's warm-up, while +// it takes answers, is the first button there: warm is its link. +func (v view) home(appURL string, admin bool, zone, warm string) (string, telegram.Markup) { if v.sc == scopeGroup { text := panel(productName, "", v.t("home.hint"), quote(v.t("home.group", "time", i18n.At(v.lang, revealTime(), zone)))) var rows telegram.Markup + // A warm-up that still takes answers is the one thing to play here. + if warm != "" { + rows = append(rows, []telegram.Button{{Text: v.t("btn.warmup"), URL: warm, Style: tg.StylePrimary}}) + } if admin { rows = append(rows, []telegram.Button{v.button("btn.settings", actSettings)}) } diff --git a/internal/bot/menu_test.go b/internal/bot/menu_test.go index 7d3d7c8..acc11a8 100644 --- a/internal/bot/menu_test.go +++ b/internal/bot/menu_test.go @@ -45,7 +45,7 @@ func everyPanel(t *testing.T, v view) []drawn { median := 1234.4 var out []drawn add := func(name string, text string, m telegram.Markup) { out = append(out, drawn{name, text, m}) } - text, m := v.home("https://maply.example/", true, "Europe/Kyiv") + text, m := v.home("https://maply.example/", true, "Europe/Kyiv", "") add("home", text, m) text, m = v.help() add("help", text, m) @@ -137,18 +137,18 @@ func TestCloseOnlyInGroups(t *testing.T) { func TestHome(t *testing.T) { dm := view{lang: "en", owner: 1, sc: scopePrivate} - _, m := dm.home("https://maply.example/", false, "Europe/Kyiv") + _, m := dm.home("https://maply.example/", false, "Europe/Kyiv", "") play := m[0][0] if play.WebApp != "https://maply.example/" || play.Style != tg.StylePrimary { t.Fatalf("play = %+v", play) } - if _, m := dm.home("", false, "Europe/Kyiv"); m[0][0].WebApp != "" { + if _, m := dm.home("", false, "Europe/Kyiv", ""); m[0][0].WebApp != "" { t.Fatal("a home without APP_URL offered Play") } group := view{lang: "en", owner: 1, sc: scopeGroup} - _, member := group.home("https://maply.example/", false, "Europe/Kyiv") - _, admin := group.home("https://maply.example/", true, "Europe/Kyiv") + _, member := group.home("https://maply.example/", false, "Europe/Kyiv", "") + _, admin := group.home("https://maply.example/", true, "Europe/Kyiv", "") if has(member, actSettings) || !has(admin, actSettings) { t.Fatal("Settings must be on an admin's group home and only there") } diff --git a/internal/bot/panels.go b/internal/bot/panels.go index d62eb9a..02552a4 100644 --- a/internal/bot/panels.go +++ b/internal/bot/panels.go @@ -172,7 +172,11 @@ func (b *Bot) sendHome(ctx context.Context, m *tg.Message) error { b.log.Warn("admin check failed", "chat", m.Chat.ID, "error", err) } } - text, markup := v.home(b.opts.AppURL, admin, round.Name(zone, zoneLang)) + warm := "" + if v.sc == scopeGroup { + warm = b.openWarmup(ctx, m.Chat.ID) + } + text, markup := v.home(b.opts.AppURL, admin, round.Name(zone, zoneLang), warm) if _, err := b.tg.SendTextIn(ctx, m.Chat.ID, threadOf(*m), text, markup); err != nil { return fmt.Errorf("send home to %d: %w", m.Chat.ID, err) } @@ -346,7 +350,11 @@ func (b *Bot) runAction(ctx context.Context, cq *tg.CallbackQuery, owner int64, if err != nil { return "", err } - return edit(v.home(b.opts.AppURL, admin, round.Name(zone, zoneLang))) + warm := "" + if v.sc == scopeGroup { + warm = b.openWarmup(ctx, chat.ID) + } + return edit(v.home(b.opts.AppURL, admin, round.Name(zone, zoneLang), warm)) case actHelp: return edit(v.help()) case actAbout: @@ -512,7 +520,10 @@ func (b *Bot) onMembership(ctx context.Context, upd *tg.ChatMemberUpdated) error if err != nil { return err } - return b.adopt(ctx, upd.Chat.ID, chatLang, raw) + if err := b.adopt(ctx, upd.Chat.ID, chatLang, raw); err != nil { + return err + } + return b.welcome(ctx, upd, chatLang, raw) case !in(upd.NewChatMember.Status) && in(upd.OldChatMember.Status): return b.store.LeaveChat(ctx, upd.Chat.ID) } diff --git a/internal/bot/welcome.go b/internal/bot/welcome.go new file mode 100644 index 0000000..bd3e272 --- /dev/null +++ b/internal/bot/welcome.go @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: Apache-2.0 +package bot + +import ( + "context" + "fmt" + "net/url" + "time" + + "github.com/FreshLabDev/tg" + + "github.com/FreshLabDev/maply/internal/auth" + "github.com/FreshLabDev/maply/internal/db" + "github.com/FreshLabDev/maply/internal/i18n" + "github.com/FreshLabDev/maply/internal/round" + "github.com/FreshLabDev/maply/internal/schedule" + "github.com/FreshLabDev/maply/internal/telegram" +) + +// welcome greets a group maply has just been added to, so the group knows at +// once that maply works and when it speaks. It is the group's home panel with +// what comes next in it: the morning post when the group joins before it, +// today's post, which the scheduler sends within seconds, when it joins +// during the day, and a warm-up when the group's day is already over. One +// message, in answer to an admin adding maply: none of the day's three. +func (b *Bot) welcome(ctx context.Context, upd *tg.ChatMemberUpdated, chatLang, raw string) error { + chatID := upd.Chat.ID + lang := i18n.Resolve(raw) + zoneLang := raw + if chatLang != "" { + lang, zoneLang = i18n.Resolve(chatLang), chatLang + } + zone, err := b.store.ChatZone(ctx, chatID) + if err != nil { + return err + } + st, err := b.store.ChatSettings(ctx, chatID) + if err != nil { + return err + } + loc := b.opts.Zones.For(zone, zoneLang) + now := b.opts.Now() + d := round.DateIn(now, loc) + post := fmt.Sprintf("%02d:%02d", st.PostHour, st.PostMin) + v := view{lang: lang, owner: upd.From.ID, sc: scopeGroup} + + var next string + var warm string + switch { + case now.Before(d.At(st.PostHour, st.PostMin, loc)): + next = v.t("welcome.morning", "post", post) + case now.Before(d.Reveal(loc)): + next = v.t("welcome.today") + default: + w, ok, err := b.warmup(ctx, chatID, d, now) + if err != nil { + return err + } + if ok { + if warm, err = b.warmupLink(w); err != nil { + return err + } + next = v.t("welcome.warmup", "time", w.ResultAt.In(loc).Format("15:04")) + } else { + next = v.t("welcome.tomorrow", "post", post) + } + } + // A bot that is not an admin of a supergroup may not pin; in a basic + // group every member may, unless the admins said otherwise, and the + // morning post asks then. + askPin := upd.Chat.Type == "supergroup" && upd.NewChatMember.Status != "administrator" + text, markup := v.welcome(round.Name(zone, zoneLang), post, next, warm, askPin, b.pinLink()) + if _, err := b.tg.SendText(ctx, chatID, text, markup); err != nil { + return fmt.Errorf("welcome %d: %w", chatID, err) + } + if askPin { + // The admins have heard it: the morning post does not ask again. + if err := b.store.SetPinWarned(ctx, chatID); err != nil { + b.log.Warn("pin request not marked", "chat", chatID, "error", err) + } + } + return nil +} + +// warmup is the group's warm-up that still takes answers: the one it has, or +// a new one when the group has never played. A new one is the newest day of +// the archive, closed in every zone, and its result is planned for an hour +// on. date is the group's date now, which keys the result's job. +func (b *Bot) warmup(ctx context.Context, chatID int64, date round.Date, now time.Time) (db.Warmup, bool, error) { + w, ok, err := b.store.WarmupOf(ctx, chatID) + if err != nil { + return db.Warmup{}, false, err + } + if ok { + return w, w.Open(now), nil + } + closed, ok := closedBy(b.opts.Zones, now) + if !ok { + return db.Warmup{}, false, nil + } + if w, ok, err = b.store.StartWarmup(ctx, chatID, closed, now.Add(schedule.WarmupFor)); err != nil || !ok { + return db.Warmup{}, false, err + } + if err := b.store.PlanJob(ctx, schedule.JobWarmup, chatID, date, w.ResultAt); err != nil { + return db.Warmup{}, false, err + } + return w, true, nil +} + +// closedBy is the newest date over in every zone by now: the archive's +// newest day, which no chat anywhere still plays. +func closedBy(z round.Zones, now time.Time) (round.Date, bool) { + d := z.Newest(now) + if z.LastReveal(d).IsZero() { + return round.Date{}, false + } + for z.LastReveal(d).After(now) { + d = d.AddDays(-1) + } + return d, true +} + +// openWarmup is the link of the group's warm-up while it takes answers, else +// empty: the home panel of a group shows it as long as there is one to play. +func (b *Bot) openWarmup(ctx context.Context, chatID int64) string { + w, ok, err := b.store.WarmupOf(ctx, chatID) + if err != nil { + b.log.Warn("warm-up not read", "chat", chatID, "error", err) + return "" + } + if !ok || !w.Open(b.opts.Now()) { + return "" + } + link, err := b.warmupLink(w) + if err != nil { + b.log.Warn("warm-up link not signed", "chat", chatID, "error", err) + return "" + } + return link +} + +// warmupLink opens the Mini App on the warm-up: "w" and a payload signed for +// the group and the day, so a link from another group, or edited by hand, +// opens nothing. +func (b *Bot) warmupLink(w db.Warmup) (string, error) { + if b.opts.Payloads == nil { + return "", nil + } + payload, err := b.opts.Payloads.SignWarmup(auth.Payload{Date: w.Day, ChatID: w.ChatID}) + if err != nil { + return "", err + } + return "https://t.me/" + b.opts.Username + "/play?startapp=w" + payload, nil +} + +// pinLink asks Telegram to make maply an admin with the right to pin: the +// admin picks the group, and Telegram offers that one right ticked. +func (b *Bot) pinLink() string { + if b.opts.Username == "" { + return "" + } + return "https://t.me/" + b.opts.Username + "?" + url.Values{"startgroup": {"pin"}, "admin": {"pin_messages"}}.Encode() +} + +// welcome is the group's first panel: what maply is and when it speaks in +// the quote, then what comes next, and the admins' note when maply may not +// pin. Its buttons are the home panel's, after the warm-up and the right to +// pin when there are those. +func (v view) welcome(zone, post, next, warm string, askPin bool, pinLink string) (string, telegram.Markup) { + body := quote(v.t("welcome.body", "post", post, "time", i18n.At(v.lang, revealTime(), zone))) + text := panel(productName, "", v.t("welcome.hint"), body) + "\n\n" + next + if askPin { + text += "\n\n" + v.t("welcome.pin") + "" + } + var rows telegram.Markup + if warm != "" { + rows = append(rows, []telegram.Button{{Text: v.t("btn.warmup"), URL: warm, Style: tg.StylePrimary}}) + } + if askPin && pinLink != "" { + rows = append(rows, []telegram.Button{{Text: v.t("btn.pin_right"), URL: pinLink}}) + } + rows = append(rows, + []telegram.Button{v.button("btn.settings", actSettings), v.button("btn.help", actHelp)}, + []telegram.Button{v.closeButton()}, + ) + return text, rows +} diff --git a/internal/bot/welcome_test.go b/internal/bot/welcome_test.go new file mode 100644 index 0000000..6b98bf0 --- /dev/null +++ b/internal/bot/welcome_test.go @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: Apache-2.0 +package bot + +import ( + "context" + "io" + "log/slog" + "net/url" + "strings" + "testing" + "time" + + "github.com/FreshLabDev/tg" + + "github.com/FreshLabDev/maply/internal/auth" + "github.com/FreshLabDev/maply/internal/i18n" + "github.com/FreshLabDev/maply/internal/round" + "github.com/FreshLabDev/maply/internal/schedule" + "github.com/FreshLabDev/maply/internal/telegram" +) + +// welcomeBot is a bot whose clock the test moves, with a signer for the +// warm-up's link. +func welcomeBot(t *testing.T, now *time.Time) (*Bot, *fakeStore, *fakeTelegram, *auth.Signer) { + t.Helper() + store := newStore() + client := &fakeTelegram{members: map[int64]string{adminID: "administrator", userID: "member"}} + signer := auth.NewSigner("test-token") + b := New(store, client, slog.New(slog.NewTextHandler(io.Discard, nil)), Options{ + Username: "maplyin_bot", Version: "v0.1.0", AppURL: "https://maply.example/", + Zones: loadZones(t), Now: func() time.Time { return *now }, Payloads: signer, + }) + return b, store, client, signer +} + +func added(chat tg.Chat, by tg.User, status string) tg.Update { + return tg.Update{MyChatMember: &tg.ChatMemberUpdated{Chat: chat, From: by, + OldChatMember: tg.ChatMember{Status: "left"}, NewChatMember: tg.ChatMember{Status: status}}} +} + +func urlOf(m telegram.Markup, text string) string { + for _, b := range buttons(m) { + if b.Text == text { + return b.URL + } + } + return "" +} + +// A group hears from maply the moment it is added, and what it hears +// depends on where its day stands: before the morning post, during the day, +// and after the reveal, when it gets a warm-up instead. +func TestWelcomeFollowsTheGroupsDay(t *testing.T) { + ctx := context.Background() + // Kyiv is UTC+2 in December. + at := func(h, m int) time.Time { return time.Date(2026, time.December, 10, h, m, 0, 0, time.UTC) } + cases := []struct { + name string + now time.Time + next string + }{ + {"before the post", at(4, 30), i18n.T("uk", "welcome.morning", "post", "07:00")}, + {"during the day", at(12, 0), i18n.T("uk", "welcome.today")}, + {"after the reveal, nothing to play", at(19, 0), i18n.T("uk", "welcome.tomorrow", "post", "07:00")}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + now := c.now + b, store, client, _ := welcomeBot(t, &now) + b.handle(ctx, added(group, admin, "administrator")) + if len(client.sends) != 1 || client.sends[0].chatID != groupID { + t.Fatalf("sends = %+v", client.sends) + } + w := client.sends[0] + if !strings.Contains(w.text, c.next) || !strings.Contains(w.text, "20:00") { + t.Fatalf("welcome = %q, want %q", w.text, c.next) + } + if urlOf(w.markup, i18n.T("uk", "btn.warmup")) != "" || len(store.jobs) != 0 { + t.Fatalf("a warm-up with nothing to warm up on: %+v, jobs %v", w.markup, store.jobs) + } + if !has(w.markup, actSettings) || !has(w.markup, actClose) { + t.Fatalf("no settings in the welcome: %+v", w.markup) + } + }) + } +} + +// After its reveal a new group gets a warm-up on the archive's newest day, +// with a link signed for the group and the day, and its result an hour on. +func TestWelcomeAfterTheRevealWarmsUp(t *testing.T) { + ctx := context.Background() + now := time.Date(2026, time.December, 10, 19, 0, 0, 0, time.UTC) // 21:00 in Kyiv + b, store, client, signer := welcomeBot(t, &now) + store.warmDay = round.NewDate(2026, time.December, 9) + b.handle(ctx, added(group, admin, "administrator")) + + w := client.sends[0] + if !strings.Contains(w.text, i18n.T("uk", "welcome.warmup", "time", "22:00")) { + t.Fatalf("welcome = %q", w.text) + } + link := urlOf(w.markup, i18n.T("uk", "btn.warmup")) + u, err := url.Parse(link) + if err != nil || !strings.HasPrefix(link, "https://t.me/maplyin_bot/play?") { + t.Fatalf("warm-up link = %q", link) + } + raw, ok := strings.CutPrefix(u.Query().Get("startapp"), "w") + if !ok { + t.Fatalf("startapp = %q", u.Query().Get("startapp")) + } + p, err := signer.VerifyWarmup(raw) + if err != nil || p.ChatID != groupID || p.Date.String() != "2026-12-09" { + t.Fatalf("payload = %+v, %v", p, err) + } + // The day's post payload does not open a warm-up, nor the other way. + if _, err := signer.Verify(raw); err == nil { + t.Fatal("a warm-up payload opens a day") + } + want := schedule.JobWarmup + ":2026-12-10:-1001@2026-12-10T20:00:00Z" + if len(store.jobs) != 1 || store.jobs[0] != want { + t.Fatalf("jobs = %v, want %s", store.jobs, want) + } + + // /start in the group offers it while it takes answers. + b.handle(ctx, command(group, member, "/start")) + // The member reads it in their language: the group has none yet. + if urlOf(client.sends[1].markup, i18n.T("ru", "btn.warmup")) != link { + t.Fatalf("home = %+v", client.sends[1].markup) + } + // Removed and added back within the hour: the same warm-up, planned once. + b.handle(ctx, added(group, admin, "administrator")) + if urlOf(client.sends[2].markup, i18n.T("uk", "btn.warmup")) != link || len(store.jobs) != 1 { + t.Fatalf("second welcome = %+v, jobs %v", client.sends[2], store.jobs) + } + // Once it is over, home has no warm-up and a new welcome says tomorrow. + now = now.Add(time.Hour) + b.handle(ctx, command(group, member, "/start")) + if urlOf(client.sends[3].markup, i18n.T("ru", "btn.warmup")) != "" { + t.Fatalf("home after the warm-up = %+v", client.sends[3].markup) + } + b.handle(ctx, added(group, admin, "administrator")) + if !strings.Contains(client.sends[4].text, i18n.T("uk", "welcome.tomorrow", "post", "07:00")) { + t.Fatalf("welcome after the warm-up = %q", client.sends[4].text) + } +} + +// A supergroup where maply is not an admin hears once that maply would pin +// the post, with a link that asks for that one right; the morning post does +// not ask again. +func TestWelcomeAsksForThePinOnce(t *testing.T) { + ctx := context.Background() + now := time.Date(2026, time.December, 10, 12, 0, 0, 0, time.UTC) + b, store, client, _ := welcomeBot(t, &now) + b.handle(ctx, added(group, admin, "member")) + w := client.sends[0] + if !strings.Contains(w.text, i18n.T("uk", "welcome.pin")) || !store.pinWarned[groupID] { + t.Fatalf("welcome = %q, warned = %v", w.text, store.pinWarned[groupID]) + } + link := urlOf(w.markup, i18n.T("uk", "btn.pin_right")) + if link != "https://t.me/maplyin_bot?admin=pin_messages&startgroup=pin" { + t.Fatalf("pin link = %q", link) + } + // An admin, or a basic group where members pin, is not asked. + for _, u := range []tg.Update{added(group, admin, "administrator"), added(tg.Chat{ID: -7, Type: "group"}, admin, "member")} { + b.handle(ctx, u) + if last := client.sends[len(client.sends)-1]; strings.Contains(last.text, i18n.T("uk", "welcome.pin")) { + t.Fatalf("asked again: %q", last.text) + } + } +} diff --git a/internal/db/warmup.go b/internal/db/warmup.go new file mode 100644 index 0000000..395945a --- /dev/null +++ b/internal/db/warmup.go @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/jackc/pgx/v5" + + "github.com/FreshLabDev/maply/internal/round" +) + +// Warmup is a group's warm-up: a day of the archive played from the group's +// welcome, with its own result at ResultAt. +type Warmup struct { + ChatID int64 + Day round.Date + DayNo int + ResultAt time.Time + ResultMsgID int64 +} + +// Open is whether the warm-up still takes answers: its result has not gone +// out and its time has not come. +func (w Warmup) Open(now time.Time) bool { return w.ResultMsgID == 0 && now.Before(w.ResultAt) } + +// StartWarmup gives a group its warm-up on the newest day of the archive +// closed by closed: over in every zone, kept, and a panorama, as the archive +// has it. A group gets one only while it has had no morning post and no +// warm-up before; ok is false otherwise, and when no day is there to play. +func (s *Store) StartWarmup(ctx context.Context, chatID int64, closed round.Date, resultAt time.Time) (Warmup, bool, error) { + var day time.Time + var dayNo int + err := s.pool.QueryRow(ctx, ` + INSERT INTO warmup (chat_id, day, result_at) + SELECT $1, r.date, $3 FROM round r + JOIN day_closed dc ON dc.date = r.date + JOIN place p ON p.id = r.place_id AND p.kind = 'panorama' + WHERE r.skipped_at IS NULL AND dc.date <= $2 + AND NOT EXISTS (SELECT 1 FROM chat_round cr WHERE cr.chat_id = $1 AND cr.post_msg_id IS NOT NULL) + ORDER BY r.date DESC + LIMIT 1 + ON CONFLICT (chat_id) DO NOTHING + RETURNING day, (SELECT day_no FROM round WHERE date = warmup.day)`, + chatID, closed.Time(), resultAt).Scan(&day, &dayNo) + if errors.Is(err, pgx.ErrNoRows) { + return Warmup{}, false, nil + } + if err != nil { + return Warmup{}, false, fmt.Errorf("start warm-up of %d: %w", chatID, err) + } + return Warmup{ChatID: chatID, Day: round.DateIn(day, time.UTC), DayNo: dayNo, ResultAt: resultAt}, true, nil +} + +// WarmupOf is the group's warm-up, if it has had one. +func (s *Store) WarmupOf(ctx context.Context, chatID int64) (Warmup, bool, error) { + w := Warmup{ChatID: chatID} + var day time.Time + var msg *int64 + err := s.pool.QueryRow(ctx, ` + SELECT w.day, r.day_no, w.result_at, w.result_msg_id + FROM warmup w JOIN round r ON r.date = w.day + WHERE w.chat_id = $1`, chatID).Scan(&day, &w.DayNo, &w.ResultAt, &msg) + if errors.Is(err, pgx.ErrNoRows) { + return Warmup{}, false, nil + } + if err != nil { + return Warmup{}, false, fmt.Errorf("warm-up of %d: %w", chatID, err) + } + w.Day = round.DateIn(day, time.UTC) + if msg != nil { + w.ResultMsgID = *msg + } + return w, true, nil +} + +// JoinWarmup counts a game of the archive in the group's warm-up. +func (s *Store) JoinWarmup(ctx context.Context, chatID, game int64) error { + if _, err := s.pool.Exec(ctx, ` + INSERT INTO warmup_game (chat_id, game) VALUES ($1, $2) ON CONFLICT DO NOTHING`, chatID, game); err != nil { + return fmt.Errorf("join warm-up of %d: %w", chatID, err) + } + return nil +} + +// WarmupGuesses are the answers given in the group's warm-up, best first: +// each player's one place of the day, with the points the archive gave it. +// A game given up, or not answered yet, is not in it. +func (s *Store) WarmupGuesses(ctx context.Context, chatID int64) ([]Guess, error) { + rows, err := s.pool.Query(ctx, ` + SELECT COALESCE(fm.user_id, 0), fm.name, fg.lat, fg.lon, fg.answered_at, fg.km, fg.pts_km, fg.pts_bonus + FROM warmup_game wg + JOIN free_member fm ON fm.game = wg.game AND fm.m = 1 + JOIN free_guess fg ON fg.game = wg.game AND fg.n = 1 AND fg.m = 1 + WHERE wg.chat_id = $1 AND fg.lat IS NOT NULL + ORDER BY fg.pts_km + fg.pts_bonus DESC, fg.km, fg.answered_at`, chatID) + if err != nil { + return nil, fmt.Errorf("warm-up guesses of %d: %w", chatID, err) + } + return pgx.CollectRows(rows, func(row pgx.CollectableRow) (Guess, error) { + var g Guess + var km float64 + var ptsKm, ptsBonus int + err := row.Scan(&g.UserID, &g.FirstName, &g.Pin.Lat, &g.Pin.Lon, &g.AnsweredAt, &km, &ptsKm, &ptsBonus) + g.Km, g.PtsKm, g.PtsBonus = &km, &ptsKm, &ptsBonus + return g, err + }) +} + +// SetWarmupResult records the warm-up's result message. +func (s *Store) SetWarmupResult(ctx context.Context, chatID, msgID int64) error { + if _, err := s.pool.Exec(ctx, `UPDATE warmup SET result_msg_id = $2 WHERE chat_id = $1`, chatID, msgID); err != nil { + return fmt.Errorf("warm-up result of %d: %w", chatID, err) + } + return nil +} diff --git a/internal/i18n/translations.json b/internal/i18n/translations.json index dd223ec..1648555 100644 --- a/internal/i18n/translations.json +++ b/internal/i18n/translations.json @@ -4139,6 +4139,24 @@ "uk": "Гра майже закінчилась, приєднатися вже не можна.", "zh": "游戏快结束了,无法再加入。" }, + "app.free.error.warmup_over": { + "ar": "انتهى الإحماء. ذلك اليوم ما زال في الأرشيف.", + "be": "Размінка скончылася. Гэты дзень застаўся ў архіве.", + "ca": "L’escalfament s’ha acabat. Aquell dia continua a l’arxiu.", + "cs": "Rozcvička skončila. Ten den zůstal v archivu.", + "de": "Das Aufwärmen ist vorbei. Der Tag ist noch im Archiv.", + "en": "The warm-up is over. That day is still in the archive.", + "es": "El calentamiento terminó. Ese día sigue en el archivo.", + "fr": "L’échauffement est fini. Ce jour reste dans les archives.", + "it": "Il riscaldamento è finito. Quel giorno resta nell’archivio.", + "ja": "ウォームアップは終わりました。その日はアーカイブに残っています。", + "pl": "Rozgrzewka się skończyła. Ten dzień został w archiwum.", + "ru": "Разминка закончилась. Этот день остался в архиве.", + "sv": "Uppvärmningen är slut. Dagen finns kvar i arkivet.", + "tr": "Isınma bitti. O gün arşivde duruyor.", + "uk": "Розминка скінчилася. Цей день лишився в архіві.", + "zh": "热身结束了。那一天还在存档里。" + }, "app.free.exit_go": { "ar": "مغادرة", "be": "Выйсці", @@ -10079,6 +10097,24 @@ "uk": "Нагадувати про серію", "zh": "连续记录提醒" }, + "btn.pin_right": { + "ar": "اسمحوا بالتثبيت", + "be": "Даць права замацоўваць", + "ca": "Deixeu-me fixar", + "cs": "Povolit připínání", + "de": "Anheften erlauben", + "en": "Let me pin", + "es": "Dejadme fijar", + "fr": "Me laisser épingler", + "it": "Lasciami fissare", + "ja": "固定を許可", + "pl": "Pozwól przypinać", + "ru": "Дать право закреплять", + "sv": "Låt mig fästa", + "tr": "Sabitleme izni ver", + "uk": "Дати право закріплювати", + "zh": "允许置顶" + }, "btn.play": { "ar": "العب", "be": "Гуляць", @@ -10169,6 +10205,24 @@ "uk": "Статистика", "zh": "统计" }, + "btn.warmup": { + "ar": "إحماء", + "be": "Размяцца", + "ca": "Escalfar", + "cs": "Rozehřát se", + "de": "Aufwärmen", + "en": "Warm up", + "es": "Calentar", + "fr": "S’échauffer", + "it": "Riscaldarsi", + "ja": "ウォームアップ", + "pl": "Rozgrzewka", + "ru": "Размяться", + "sv": "Värm upp", + "tr": "Isın", + "uk": "Розім’ятися", + "zh": "热身" + }, "btn.zone": { "ar": "المنطقة الزمنية: {zone}", "be": "Часавы пояс: {zone}", @@ -12275,6 +12329,168 @@ "uk": "{m} хв", "zh": "{m} 分钟" }, + "warmup.after": { + "ar": "الإحماء لا يُحسب في أي مكان. اللعبة الحقيقية تبدأ في {post}، والجواب في {time}.", + "be": "Размінка нікуды не ідзе. Сапраўдная гульня з {post}, адказ у {time}.", + "ca": "L’escalfament no compta enlloc. La partida de debò comença a les {post}, la resposta a les {time}.", + "cs": "Rozcvička se nikam nepočítá. Opravdová hra začíná v {post}, odpověď v {time}.", + "de": "Das Aufwärmen zählt nirgends. Das echte Spiel beginnt um {post}, die Auflösung um {time}.", + "en": "The warm-up counts nowhere. The real game starts at {post}, the answer at {time}.", + "es": "El calentamiento no cuenta. La partida de verdad empieza a las {post}, la respuesta a las {time}.", + "fr": "L’échauffement ne compte nulle part. La vraie partie commence à {post}, la réponse à {time}.", + "it": "Il riscaldamento non conta. La partita vera inizia alle {post}, la risposta alle {time}.", + "ja": "ウォームアップはどこにも記録されません。本番は {post} から、答えは {time} に。", + "pl": "Rozgrzewka nigdzie się nie liczy. Prawdziwa gra od {post}, odpowiedź o {time}.", + "ru": "Разминка никуда не идёт. Настоящая игра с {post}, ответ в {time}.", + "sv": "Uppvärmningen räknas ingenstans. Det riktiga spelet börjar {post}, svaret kommer {time}.", + "tr": "Isınma hiçbir yere sayılmaz. Asıl oyun {post} saatinde başlar, cevap {time} saatinde.", + "uk": "Розминка нікуди не йде. Справжня гра з {post}, відповідь о {time}.", + "zh": "热身不计入任何成绩。正式游戏 {post} 开始,{time} 公布答案。" + }, + "warmup.title": { + "ar": "إحماء", + "be": "размінка", + "ca": "escalfament", + "cs": "rozcvička", + "de": "Aufwärmen", + "en": "warm-up", + "es": "calentamiento", + "fr": "échauffement", + "it": "riscaldamento", + "ja": "ウォームアップ", + "pl": "rozgrzewka", + "ru": "разминка", + "sv": "uppvärmning", + "tr": "ısınma", + "uk": "розминка", + "zh": "热身" + }, + "welcome.body": { + "ar": "كل صباح في {post} أرسل صورة من مكان ما على الأرض. يضع كل واحد دبوسه، ولكل واحد محاولة واحدة.\nفي {time} يأتي الجواب مع جدول المجموعة: من كان الأقرب، ومن أخطأ بقارة كاملة.", + "be": "Кожную раніцу ў {post} я дасылаю здымак з нейкага кутка Зямлі. Усе ставяць пін, у кожнага адна спроба.\nУ {time} прыходзіць адказ з табліцай групы: хто быў бліжэй за ўсіх, а хто прамахнуўся на кантынент.", + "ca": "Cada matí a les {post} envio una foto d’algun punt de la Terra. Cadascú hi posa el seu pin, un intent per cap.\nA les {time} arriba la resposta amb la taula del grup: qui s’hi ha acostat més i qui ha fallat per un continent.", + "cs": "Každé ráno v {post} pošlu fotku z nějakého místa na Zemi. Každý zapíchne špendlík, jeden pokus na hlavu.\nV {time} přijde odpověď s tabulkou skupiny: kdo byl nejblíž a kdo se netrefil o kontinent.", + "de": "Jeden Morgen um {post} schicke ich ein Foto von irgendwo auf der Erde. Alle setzen eine Nadel, jeder hat einen Versuch.\nUm {time} kommt die Auflösung mit der Tabelle der Gruppe: wer am nächsten dran war und wer einen Kontinent daneben lag.", + "en": "Every morning at {post} I post a photo from somewhere on Earth. Everyone drops a pin, one try each.\nAt {time} the answer comes with the group’s table: who was closest, and who missed by a continent.", + "es": "Cada mañana a las {post} mando una foto de algún punto de la Tierra. Cada uno pone su pin, un intento por cabeza.\nA las {time} llega la respuesta con la tabla del grupo: quién estuvo más cerca y quién falló por un continente.", + "fr": "Chaque matin à {post}, j’envoie une photo prise quelque part sur Terre. Chacun pose son repère, un seul essai.\nÀ {time}, la réponse arrive avec le classement du groupe : qui était le plus proche, et qui s’est trompé de continent.", + "it": "Ogni mattina alle {post} mando una foto da qualche punto della Terra. Ognuno mette il suo segnaposto, un tentativo a testa.\nAlle {time} arriva la risposta con la classifica del gruppo: chi ci è andato più vicino e chi ha sbagliato continente.", + "ja": "毎朝 {post} に、地球のどこかの写真を送ります。みんなでピンを1本ずつ、チャンスは1回。\n{time} に答えとグループの順位が届きます。いちばん近かったのは誰か、大陸ごと外したのは誰か。", + "pl": "Każdego ranka o {post} wysyłam zdjęcie z jakiegoś miejsca na Ziemi. Każdy stawia pinezkę, jedna próba na osobę.\nO {time} przychodzi odpowiedź z tabelą grupy: kto był najbliżej, a kto pomylił kontynent.", + "ru": "Каждое утро в {post} я присылаю снимок из какой-то точки Земли. Все ставят пин, у каждого одна попытка.\nВ {time} приходит ответ с таблицей группы: кто был ближе всех, а кто промахнулся на континент.", + "sv": "Varje morgon klockan {post} skickar jag ett foto från någonstans på jorden. Alla sätter en nål, ett försök var.\nKlockan {time} kommer svaret med gruppens tabell: vem som var närmast och vem som missade med en kontinent.", + "tr": "Her sabah {post} saatinde Dünya’nın bir yerinden bir fotoğraf atıyorum. Herkes bir iğne bırakır, herkesin tek hakkı var.\n{time} saatinde cevap grubun tablosuyla gelir: kim en yakındı, kim kıtayı ıskaladı.", + "uk": "Щоранку о {post} я надсилаю знімок з якоїсь точки Землі. Усі ставлять пін, у кожного одна спроба.\nО {time} приходить відповідь з таблицею групи: хто був найближче, а хто схибив на континент.", + "zh": "每天早上 {post},我会发一张来自地球某处的照片。每人插一枚图钉,只有一次机会。\n{time} 公布答案和群排行:谁最接近,谁差了一整个大洲。" + }, + "welcome.hint": { + "ar": "مكان واحد في اليوم للمجموعة كلها.", + "be": "Адно месца на дзень для ўсёй групы.", + "ca": "Un lloc al dia per a tot el grup.", + "cs": "Jedno místo denně pro celou skupinu.", + "de": "Ein Ort am Tag für die ganze Gruppe.", + "en": "A place a day for the whole group.", + "es": "Un lugar al día para todo el grupo.", + "fr": "Un lieu par jour pour tout le groupe.", + "it": "Un posto al giorno per tutto il gruppo.", + "ja": "グループみんなで、1日1か所。", + "pl": "Jedno miejsce dziennie dla całej grupy.", + "ru": "Одно место в день на всю группу.", + "sv": "En plats om dagen för hela gruppen.", + "tr": "Tüm grup için günde bir yer.", + "uk": "Одне місце на день для всієї групи.", + "zh": "全群每天一个地点。" + }, + "welcome.morning": { + "ar": "أول مكان يصل اليوم في {post}.", + "be": "Першае месца прыляціць сёння ў {post}.", + "ca": "El primer lloc arriba avui a les {post}.", + "cs": "První místo přiletí dnes v {post}.", + "de": "Der erste Ort kommt heute um {post}.", + "en": "The first place comes today at {post}.", + "es": "El primer lugar llega hoy a las {post}.", + "fr": "Le premier lieu arrive aujourd’hui à {post}.", + "it": "Il primo posto arriva oggi alle {post}.", + "ja": "最初の場所は今日 {post} に届きます。", + "pl": "Pierwsze miejsce przyleci dziś o {post}.", + "ru": "Первое место прилетит сегодня в {post}.", + "sv": "Första platsen kommer i dag klockan {post}.", + "tr": "İlk yer bugün {post} saatinde geliyor.", + "uk": "Перше місце прилетить сьогодні о {post}.", + "zh": "第一个地点今天 {post} 送到。" + }, + "welcome.pin": { + "ar": "إلى المشرفين: امنحوني صلاحية تثبيت الرسائل، فيبقى مكان اليوم في الأعلى.", + "be": "Адмінам: дайце мне права замацоўваць паведамленні, і месца дня будзе вісець зверху.", + "ca": "Admins: deixeu-me fixar missatges i el lloc del dia es quedarà a dalt.", + "cs": "Adminům: dejte mi právo připínat zprávy a místo dne zůstane nahoře.", + "de": "Admins: Lasst mich Nachrichten anheften, dann bleibt der Ort des Tages oben.", + "en": "Admins: let me pin messages, and the day’s place will stay on top.", + "es": "Admins: dejadme fijar mensajes y el lugar del día se quedará arriba.", + "fr": "Admins : laissez-moi épingler des messages, et le lieu du jour restera en haut.", + "it": "Admin: lasciatemi fissare i messaggi e il posto del giorno resterà in alto.", + "ja": "管理者の方へ:メッセージを固定する権限をください。その日の場所がいちばん上に残ります。", + "pl": "Adminom: dajcie mi prawo przypinania wiadomości, a miejsce dnia będzie wisieć na górze.", + "ru": "Админам: дайте мне право закреплять сообщения, и место дня будет висеть сверху.", + "sv": "Admins: låt mig fästa meddelanden, så stannar dagens plats högst upp.", + "tr": "Yöneticiler: mesaj sabitleme izni verin, günün yeri en üstte kalsın.", + "uk": "Адмінам: дайте мені право закріплювати повідомлення, і місце дня висітиме вгорі.", + "zh": "管理员:给我置顶消息的权限,每天的地点就会挂在最上面。" + }, + "welcome.today": { + "ar": "مكان اليوم في الطريق، تحت هذه الرسالة مباشرة.", + "be": "Сённяшняе месца ўжо ляціць, яно крыху ніжэй.", + "ca": "El lloc d’avui ja arriba, just a sota.", + "cs": "Dnešní místo už letí, hned pod tímhle.", + "de": "Der Ort von heute ist schon unterwegs, gleich darunter.", + "en": "Today’s place is already on its way, right below.", + "es": "El lugar de hoy ya viene, justo debajo.", + "fr": "Le lieu du jour arrive déjà, juste en dessous.", + "it": "Il posto di oggi sta già arrivando, qui sotto.", + "ja": "今日の場所はもう向かっています。すぐ下です。", + "pl": "Dzisiejsze miejsce już leci, zaraz pod spodem.", + "ru": "Сегодняшнее место уже летит, оно чуть ниже.", + "sv": "Dagens plats är redan på väg, strax nedanför.", + "tr": "Bugünün yeri yolda, hemen aşağıda.", + "uk": "Сьогоднішнє місце вже летить, воно трохи нижче.", + "zh": "今天的地点已经在路上了,就在下面。" + }, + "welcome.tomorrow": { + "ar": "انتهت لعبة اليوم هنا. أول مكان يصل غدًا في {post}.", + "be": "Сёння тут усё ўжо скончылася. Першае месца прыляціць заўтра ў {post}.", + "ca": "La partida d’avui aquí ja s’ha acabat. El primer lloc arriba demà a les {post}.", + "cs": "Dnešní hra tu už skončila. První místo přiletí zítra v {post}.", + "de": "Das Spiel von heute ist hier schon vorbei. Der erste Ort kommt morgen um {post}.", + "en": "Today’s game here is already over. The first place comes tomorrow at {post}.", + "es": "La partida de hoy aquí ya terminó. El primer lugar llega mañana a las {post}.", + "fr": "La partie du jour est déjà finie ici. Le premier lieu arrive demain à {post}.", + "it": "Qui la partita di oggi è già finita. Il primo posto arriva domani alle {post}.", + "ja": "今日のゲームはここではもう終わりました。最初の場所は明日 {post} に届きます。", + "pl": "Dzisiejsza gra już się tu skończyła. Pierwsze miejsce przyleci jutro o {post}.", + "ru": "Сегодня здесь всё уже закончилось. Первое место прилетит завтра в {post}.", + "sv": "Dagens spel är redan över här. Första platsen kommer i morgon klockan {post}.", + "tr": "Bugünkü oyun burada bitti. İlk yer yarın {post} saatinde geliyor.", + "uk": "Сьогодні тут усе вже скінчилося. Перше місце прилетить завтра о {post}.", + "zh": "今天这里的游戏已经结束了。第一个地点明天 {post} 送到。" + }, + "welcome.warmup": { + "ar": "انتهت لعبة اليوم هنا، فلنحمّ على مكان من يوم سابق حتى {time}. لا تُحسب في أي مكان، هي فقط للتعوّد.", + "be": "Сёння тут усё ўжо скончылася, дык вось размінка на месцы аднаго з мінулых дзён, да {time}. Яна нікуды не ідзе, проста размяць пальцы.", + "ca": "La partida d’avui aquí ja s’ha acabat, així que escalfeu amb el lloc d’un dia passat fins a les {time}. No compta enlloc, és per agafar-hi el truc.", + "cs": "Dnešní hra tu už skončila, tak se rozehřejte na místě z některého minulého dne, do {time}. Nikam se nepočítá, je jen na rozjezd.", + "de": "Das Spiel von heute ist hier schon vorbei, also wärmt euch bis {time} an einem Ort von neulich auf. Zählt nirgends, nur zum Reinkommen.", + "en": "Today’s game here is already over, so warm up on a past day’s place until {time}. It counts nowhere, it’s just to get the hang of it.", + "es": "La partida de hoy aquí ya terminó, así que calentad con el lugar de un día pasado hasta las {time}. No cuenta para nada, es para pillarle el truco.", + "fr": "La partie du jour est déjà finie ici, alors échauffez-vous sur le lieu d’un jour passé jusqu’à {time}. Ça ne compte nulle part, c’est pour prendre la main.", + "it": "Qui la partita di oggi è già finita, quindi scaldatevi su un posto di un giorno passato fino alle {time}. Non conta da nessuna parte, serve a prenderci la mano.", + "ja": "今日のゲームはここではもう終わりました。{time} まで、過去の日の場所でウォームアップをどうぞ。どこにも記録されません。手ならしです。", + "pl": "Dzisiejsza gra już się tu skończyła, więc rozgrzewka na miejscu z jednego z poprzednich dni, do {time}. Nigdzie się nie liczy, to tylko rozgrzanie palców.", + "ru": "Сегодня здесь всё уже закончилось, так что вот разминка на месте одного из прошлых дней, до {time}. Она никуда не идёт, просто размять пальцы.", + "sv": "Dagens spel är redan över här, så värm upp på en plats från en tidigare dag fram till {time}. Den räknas ingenstans, den är bara för att komma in i det.", + "tr": "Bugünkü oyun burada bitti, o yüzden {time} saatine kadar geçmiş bir günün yeriyle ısının. Hiçbir yere sayılmaz, sadece alışmak için.", + "uk": "Сьогодні тут усе вже скінчилося, тож ось розминка на місці одного з минулих днів, до {time}. Вона нікуди не йде, просто розім’яти пальці.", + "zh": "今天这里的游戏已经结束了,先用往日的一个地点热热身吧,到 {time} 为止。不计入任何成绩,只是练练手。" + }, "world.day": { "ar": "الخطأ المعتاد {km}، وأصاب {pct}% البلد.", "be": "У паловы промах меншы за {km}, краіну ўгадалі {pct}%.", diff --git a/internal/schedule/schedule.go b/internal/schedule/schedule.go index f132741..78bd882 100644 --- a/internal/schedule/schedule.go +++ b/internal/schedule/schedule.go @@ -87,6 +87,9 @@ type Store interface { LeaveChat(ctx context.Context, chatID int64) error MigrateChat(ctx context.Context, from, to int64) error FixZone(ctx context.Context, chatID int64, zone string) error + WarmupOf(ctx context.Context, chatID int64) (db.Warmup, bool, error) + WarmupGuesses(ctx context.Context, chatID int64) ([]db.Guess, error) + SetWarmupResult(ctx context.Context, chatID, msgID int64) error } type Telegram interface { @@ -422,6 +425,8 @@ func (s *Scheduler) do(ctx context.Context, j db.Job) (err error) { return s.result(ctx, j) case jobWorld: return s.worldFinal(ctx, j) + case JobWarmup: + return s.warmup(ctx, j.ChatID) } return errSkip } diff --git a/internal/schedule/warmup.go b/internal/schedule/warmup.go new file mode 100644 index 0000000..1af751d --- /dev/null +++ b/internal/schedule/warmup.go @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: Apache-2.0 +package schedule + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/FreshLabDev/maply/internal/card" + "github.com/FreshLabDev/maply/internal/db" + "github.com/FreshLabDev/maply/internal/i18n" +) + +// JobWarmup sends a group's warm-up result. The bot plans it when it welcomes +// a group that has no day left to play. +const JobWarmup = "warmup" + +// WarmupFor is how long a warm-up takes answers. It starts when maply joins +// a group after the group's reveal, so the result comes the same evening, or +// a little after midnight, and well before the next morning's post. +const WarmupFor = time.Hour + +// warmup sends the warm-up's result: the archive day's place and the +// group's table of it. The place is of a day over in every zone, which the +// days page shows to anyone, so it is no secret here. Nobody who played +// means nothing to say: the job ends without a message, and the group's +// next message is the morning post. +func (s *Scheduler) warmup(ctx context.Context, chatID int64) error { + c, ok, err := s.chatOf(ctx, chatID) + if err != nil || !ok { + return orSkip(err) + } + w, ok, err := s.Store.WarmupOf(ctx, c.ID) + if err != nil || !ok { + return orSkip(err) + } + if w.ResultMsgID != 0 { + return nil + } + if now := s.now(); now.Before(w.ResultAt) { + return laterError{w.ResultAt} + } + guesses, err := s.Store.WarmupGuesses(ctx, c.ID) + if err != nil { + return err + } + if len(guesses) == 0 { + return errSkip + } + rd, ok, err := s.Store.RoundOn(ctx, w.Day) + if err != nil || !ok { + return orSkip(err) + } + answer, err := s.Store.Answer(ctx, rd.PlaceID) + if err != nil { + return err + } + lang := i18n.Resolve(c.Lang) + msg, err := s.sendPhoto(ctx, c.ID, rd, warmupCaption(lang, rd.DayNo, answer, guesses, fmt.Sprintf("%02d:%02d", c.PostHour, c.PostMin), revealAt(lang, c)), nil) + if err != nil { + return err + } + return s.Store.SetWarmupResult(ctx, c.ID, msg.MessageID) +} + +// warmupCaption is the warm-up's result: the head of a day's result marked +// as the warm-up, the table, and when the real game begins. +func warmupCaption(lang string, dayNo int, answer db.Answer, guesses []db.Guess, post, at string) string { + head := card.Quoted(lang, dayNo, answer) + head = strings.Replace(head, "", " · "+i18n.T(lang, "warmup.title"), 1) + lines := table(lang, guesses, nil) + lines = append(lines, "", ""+i18n.T(lang, "warmup.after", "post", post, "time", at)+"") + return fitCaption(head, lines) +} diff --git a/internal/schedule/warmup_test.go b/internal/schedule/warmup_test.go new file mode 100644 index 0000000..67d4c5f --- /dev/null +++ b/internal/schedule/warmup_test.go @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: Apache-2.0 +package schedule + +import ( + "strings" + "testing" + + "github.com/FreshLabDev/maply/internal/db" + "github.com/FreshLabDev/maply/internal/i18n" +) + +func TestWarmupCaption(t *testing.T) { + km, pts, bonus := 120.0, 3000, 800 + answer := db.Answer{CountryISO: "PT", City: map[string]string{"en": "Lisbon", "ru": "Лиссабон"}} + got := warmupCaption("ru", 41, answer, []db.Guess{{UserID: 1, FirstName: "Оксана", Km: &km, PtsKm: &pts, PtsBonus: &bonus}}, + "07:00", "20:00 (Киев)") + for _, want := range []string{ + "maply #41 · " + i18n.T("ru", "warmup.title"), + "Лиссабон", + "🥇 Оксана", + i18n.T("ru", "warmup.after", "post", "07:00", "time", "20:00 (Киев)"), + } { + if !strings.Contains(got, want) { + t.Fatalf("caption = %q, missing %q", got, want) + } + } +} diff --git a/migrations/031_warmup.sql b/migrations/031_warmup.sql new file mode 100644 index 0000000..26e8301 --- /dev/null +++ b/migrations/031_warmup.sql @@ -0,0 +1,29 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- A group that adds maply after its reveal has no day left to play until the +-- next morning, so it gets a warm-up: the newest day of the archive, closed in +-- every zone, played from the group's welcome and summed up in the group an +-- hour later. A warm-up is a day of the free game's archive: every player's +-- game is their own free_archive game, outside the day's tables, the world, +-- the profiles, the streaks and the ratings. warmup_game only says which of +-- those games were started from the group's welcome. +-- +-- One warm-up a group, ever: a group that removes maply and adds it back +-- gets a welcome, not a second warm-up. +CREATE TABLE IF NOT EXISTS warmup ( + chat_id BIGINT PRIMARY KEY CHECK (chat_id < 0), + day DATE NOT NULL REFERENCES round(date), + result_at TIMESTAMPTZ NOT NULL, + result_msg_id BIGINT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS warmup_game ( + chat_id BIGINT NOT NULL REFERENCES warmup(chat_id) ON DELETE CASCADE, + game BIGINT NOT NULL REFERENCES free_game(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, game) +); + +-- The warm-up's result is a job of its own, keyed by the group and the date +-- the group joined on. +ALTER TABLE job DROP CONSTRAINT IF EXISTS job_kind_check; +ALTER TABLE job ADD CONSTRAINT job_kind_check CHECK (kind IN ('post', 'pin', 'intrigue', 'result', 'world', 'warmup')); diff --git a/web/app/free.js b/web/app/free.js index 6d645ab..d3164c6 100644 --- a/web/app/free.js +++ b/web/app/free.js @@ -1073,6 +1073,20 @@ const c = p[0] === "c" ? p.slice(1) : q; return CODE.test(c) ? c : ""; } + // A group's warm-up opens the archive's day it plays: "w" and a payload the server checks, once, as a challenge is. + let warmed = false; + const warmCode = () => !warmed && /^w[A-Za-z0-9_-]{36}$/.test(startParam()); + async function warmUp() { + const my = ++gen; liveGame = null; + top(T("free.archive"), ""); + wait(); + let g; + try { g = await req("/api/free/archive", { warmup: true }); } + catch (e) { if (my !== gen) return; toast(ferr(e)); archive(); return; } + if (my !== gen) return; + GAME = g; + haptic("medium"); continueGame(); + } // What the address asks of /play: a mode from the menu's cards, the archive, a game with friends. Read once and // taken off the address, so Back and a reload do not ask again; in Telegram the router would carry it on. function asked() { @@ -1091,9 +1105,10 @@ Router.screen("play", /^\/play$/, { open(m, from) { came(from); open(); - const h = first, c = dareCode(), a = asked(); first = null; dared = true; + const h = first, c = dareCode(), a = asked(), wu = warmCode(); first = null; dared = true; warmed = true; if (h) { HOME = h; if (!SET) SET = Object.assign({}, h.last); } if (c) return challenge(c); + if (wu) return warmUp(); if (a.mode === "archive") return archive(); if (a.friends) return withFriends(h); home(h, a.mode); @@ -1125,7 +1140,7 @@ }); window.Free = { // Whether the app opens on the free game rather than the day: once, before the day has started. - takes() { return !dayBoot && !opened && (!!invite() || !!dareCode() || /^\/play$/.test(location.pathname) || PARTY.test(location.pathname)); }, + takes() { return !dayBoot && !opened && (!!invite() || !!dareCode() || warmCode() || /^\/play$/.test(location.pathname) || PARTY.test(location.pathname)); }, // start opens it in place of the day; boot is the day's start, run when the free game is left. async start(boot) { dayBoot = boot; @@ -1138,7 +1153,7 @@ hideLoader(); const code = invite(); if (code && !PARTY.test(location.pathname)) Router.go("/party/" + code, { replace: true }); - else if (dareCode() && !/^\/play$/.test(location.pathname)) Router.go("/play", { replace: true }); + else if ((dareCode() || warmCode()) && !/^\/play$/.test(location.pathname)) Router.go("/play", { replace: true }); Router.start(); if (typeof accountReady === "function") accountReady(); },