From af486df0e12ab84de6c414e694088448aeacb028 Mon Sep 17 00:00:00 2001 From: amtiYo Date: Mon, 16 Nov 2026 16:56:00 +0100 Subject: [PATCH] feat(bot): pause groups where nobody plays A group where nobody plays still got the morning post, the intrigue and the result every day: noise for the group, a reason to remove the bot, and wasted sends. After seven quiet days in a row (the morning post went out and nobody answered from the group; a warm-up is not an answer) the group gets one question in place of the eighth day's intrigue, so it still gets three messages that day. Any member can press "Keep playing", which starts the count again. Only an admin can press "Pause", and the bot checks admin rights with Telegram on each press. If nobody presses a button and nobody answers, the third morning after the question pauses the group: no post, intrigue or result, and the question is edited to say how to resume. /start in a paused group says so and shows Resume to admins. Places come back with the first morning post after the press. An answer from the group at any point resets the count. A paused group is left out of ActiveChats but stays active for its members' answer window. A pause is logged with its cause. A group that removes maply and adds it back starts with no pause and no quiet days. If the quiet check fails, the bot logs the error and sends the post or intrigue anyway: the pause comes a day late, but the group does not lose its message. Migration 032 adds the quiet and pause columns to chat_settings. Closes #94 Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- CHANGELOG.md | 9 ++ docs/design.md | 1 + internal/bot/bot.go | 5 + internal/bot/bot_test.go | 31 +++- internal/bot/menu.go | 3 +- internal/bot/panels.go | 34 ++++ internal/bot/quiet.go | 105 ++++++++++++ internal/bot/quiet_test.go | 59 +++++++ internal/db/quiet.go | 143 +++++++++++++++++ internal/db/schedule.go | 19 ++- internal/db/settings.go | 16 +- internal/i18n/translations.json | 144 +++++++++++++++++ internal/schedule/day.go | 22 ++- internal/schedule/quiet.go | 103 ++++++++++++ internal/schedule/quiet_integration_test.go | 169 ++++++++++++++++++++ internal/schedule/schedule.go | 46 +++++- migrations/032_quiet.sql | 21 +++ 18 files changed, 918 insertions(+), 16 deletions(-) create mode 100644 internal/bot/quiet.go create mode 100644 internal/bot/quiet_test.go create mode 100644 internal/db/quiet.go create mode 100644 internal/schedule/quiet.go create mode 100644 internal/schedule/quiet_integration_test.go create mode 100644 migrations/032_quiet.sql diff --git a/AGENTS.md b/AGENTS.md index 49c9368..c6337ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,9 @@ player, and production-minded. 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"). + message of that day (`docs/design.md` → "Groups"). A group quiet for + seven days gets its question to keep playing in place of the intrigue, + and a paused group gets nothing (`chat_settings.paused_at`). - 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index fcd26ed..bb880c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,15 @@ See [`docs/versioning.md`](docs/versioning.md) for what the numbers mean and 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. +- maply stops posting into a group where nobody plays. After seven days + with the morning post and no answer from the group, it asks once, in + place of that day's intrigue, whether to keep sending places: "Keep + playing" (any member) or "Pause" (admins). With no press and no answer + for three days the group pauses itself and gets nothing until an admin + presses Resume under `/start`; the places come back the next morning. + Any answer from the group resets the count. For the operator: migration + 032 adds the pause columns to `chat_settings`, and a pause is logged as + `group paused` with its cause. ## v0.0.1-alpha.20 - 2026-11-10 diff --git a/docs/design.md b/docs/design.md index 89d72db..99b3ae1 100644 --- a/docs/design.md +++ b/docs/design.md @@ -195,6 +195,7 @@ In a DM the intrigue arrives only if the person has not answered yet. The "Chat - 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. +- **A group where nobody plays** (#94, 16 November 2026). A quiet day is a day the group got its morning post and nobody answered from the group (`guess.chat_id`); a warm-up is free play and is no answer, and a day without a post neither counts nor breaks the run. After seven quiet days in a row the group gets, in place of the eighth day's intrigue, one question: "Nobody here has guessed a place for a week. Keep sending them?" with "Keep playing" and "Pause". The question takes the intrigue's slot, so the day still has three messages; a group with the intrigue turned off has the slot too, half an hour after the post when its post comes too late for 16:00–18:00. Any member may press "Keep playing", which counts the quiet days again from the day after the question; "Pause" is an admin's, checked with Telegram on the press. Any answer from the group, before or after the question, ends the run and takes the question back. With no press and no answer, the third morning after the question pauses the group: no post that morning, and the question is edited to say how to turn maply back on. A paused group gets nothing from the scheduler, no post, intrigue or result, and is not an active chat; it keeps maply and still counts for its members' answer window. `/start` there says maply is paused, with "Resume" for an admin; resuming starts with the first morning post after the press, so a group resumed after its post time waits for the next morning. The pause is logged with its cause (`paused_by`: admin or silence), and so are the question, a press of "Keep playing" and a resume. maply removed and added back starts afresh: no pause and no quiet days. Migration 032 adds the columns to `chat_settings`. - **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. diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 71a2a34..c715b6e 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -52,6 +52,11 @@ type Store interface { 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) + + Paused(ctx context.Context, chatID int64) (bool, error) + KeepPlaying(ctx context.Context, chatID int64) (bool, error) + PauseGroup(ctx context.Context, chatID int64, by string) (int64, bool, error) + ResumeGroup(ctx context.Context, chatID int64, at time.Time) (bool, error) } type Telegram interface { diff --git a/internal/bot/bot_test.go b/internal/bot/bot_test.go index 299cc9e..776c79b 100644 --- a/internal/bot/bot_test.go +++ b/internal/bot/bot_test.go @@ -44,12 +44,41 @@ type fakeStore struct { warmups map[int64]db.Warmup jobs []string pinWarned map[int64]bool + // paused is the groups maply is paused in; asked those with the quiet + // question out. + paused map[int64]bool + asked 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{}, - warmups: map[int64]db.Warmup{}, pinWarned: map[int64]bool{}} + warmups: map[int64]db.Warmup{}, pinWarned: map[int64]bool{}, + paused: map[int64]bool{}, asked: map[int64]bool{}} +} + +func (f *fakeStore) Paused(_ context.Context, id int64) (bool, error) { return f.paused[id], nil } + +func (f *fakeStore) KeepPlaying(_ context.Context, id int64) (bool, error) { + ok := f.asked[id] && !f.paused[id] + if ok { + f.asked[id] = false + } + return ok, nil +} + +func (f *fakeStore) PauseGroup(_ context.Context, id int64, _ string) (int64, bool, error) { + if f.paused[id] { + return 0, false, nil + } + f.paused[id], f.asked[id] = true, false + return 0, true, nil +} + +func (f *fakeStore) ResumeGroup(_ context.Context, id int64, _ time.Time) (bool, error) { + ok := f.paused[id] + f.paused[id] = false + return ok, nil } func (f *fakeStore) Offset(context.Context) (int64, error) { diff --git a/internal/bot/menu.go b/internal/bot/menu.go index 00b169e..ddc3364 100644 --- a/internal/bot/menu.go +++ b/internal/bot/menu.go @@ -53,6 +53,7 @@ const ( actGroupAuto = "glangauto" actPost = "post" actSwitch = "sw" + actResume = "resume" actClose = "close" ) @@ -62,7 +63,7 @@ var postSteps = map[int]bool{-60: true, -15: true, 15: true, 60: true} func adminOnly(action string) bool { head, _, _ := strings.Cut(action, ":") switch head { - case actSettings, actZone, actGroupLang, actGroupAuto, actPost, actSwitch: + case actSettings, actZone, actGroupLang, actGroupAuto, actPost, actSwitch, actResume: return true } return false diff --git a/internal/bot/panels.go b/internal/bot/panels.go index 02552a4..408d0d7 100644 --- a/internal/bot/panels.go +++ b/internal/bot/panels.go @@ -177,6 +177,9 @@ func (b *Bot) sendHome(ctx context.Context, m *tg.Message) error { warm = b.openWarmup(ctx, m.Chat.ID) } text, markup := v.home(b.opts.AppURL, admin, round.Name(zone, zoneLang), warm) + if v.sc == scopeGroup && b.groupPaused(ctx, m.Chat.ID) { + text, markup = v.paused(admin) + } 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) } @@ -221,6 +224,9 @@ func (b *Bot) onCallback(ctx context.Context, cq *tg.CallbackQuery) error { if d, ok := schedule.WorldCallback(cq.Data); ok { return b.onRefreshWorld(ctx, cq, d) } + if isQuietCB(cq.Data) { + return b.onQuiet(ctx, cq) + } owner, action, ok := parseMenuCB(cq.Data) if !ok { return b.tg.AnswerCallbackQuery(ctx, cq.ID, "") @@ -353,8 +359,36 @@ func (b *Bot) runAction(ctx context.Context, cq *tg.CallbackQuery, owner int64, warm := "" if v.sc == scopeGroup { warm = b.openWarmup(ctx, chat.ID) + if b.groupPaused(ctx, chat.ID) { + return edit(v.paused(admin)) + } } return edit(v.home(b.opts.AppURL, admin, round.Name(zone, zoneLang), warm)) + case actResume: + if v.sc != scopeGroup { + return "", nil + } + ok, err := b.store.ResumeGroup(ctx, chat.ID, b.opts.Now()) + if err != nil { + return "", err + } + if ok { + b.log.Info("group resumed", "chat", chat.ID) + } + zone, err := b.store.ChatZone(ctx, chat.ID) + if err != nil { + return "", err + } + st, err := b.store.ChatSettings(ctx, chat.ID) + if err != nil { + return "", err + } + // The home, saying when the next place comes: the first morning + // post after now (schedule's resting), which is today's only + // before its time. + _, markup := v.home(b.opts.AppURL, true, round.Name(zone, zoneLang), "") + text := panel(productName, "", v.t("home.hint"), quote(v.t("home.resumed", "post", fmt.Sprintf("%02d:%02d", st.PostHour, st.PostMin)))) + return edit(text, markup) case actHelp: return edit(v.help()) case actAbout: diff --git a/internal/bot/quiet.go b/internal/bot/quiet.go new file mode 100644 index 0000000..dcadd1d --- /dev/null +++ b/internal/bot/quiet.go @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: Apache-2.0 +package bot + +import ( + "context" + "fmt" + + "github.com/FreshLabDev/tg" + + "github.com/FreshLabDev/maply/internal/db" + "github.com/FreshLabDev/maply/internal/i18n" + "github.com/FreshLabDev/maply/internal/schedule" + "github.com/FreshLabDev/maply/internal/telegram" +) + +func isQuietCB(data string) bool { return data == schedule.QuietKeep || data == schedule.QuietPause } + +// onQuiet is a press under the question a quiet group gets (see +// schedule.askQuiet). Any member may keep the game going; only an admin may +// pause it, and the check runs on every press. +func (b *Bot) onQuiet(ctx context.Context, cq *tg.CallbackQuery) error { + m := cq.Message + if scopeOf(m.Chat) != scopeGroup || !isPanel(m) || !pressedHere(m, cq.Data) { + return b.tg.AnswerCallbackQuery(ctx, cq.ID, "") + } + raw, err := b.personLang(ctx, cq.From) + if err != nil { + _ = b.tg.AnswerCallbackQuery(ctx, cq.ID, "") + return err + } + _, lang, err := b.groupLang(ctx, m.Chat.ID, raw) + if err != nil { + _ = b.tg.AnswerCallbackQuery(ctx, cq.ID, "") + return err + } + text := "" + switch cq.Data { + case schedule.QuietKeep: + kept, err := b.store.KeepPlaying(ctx, m.Chat.ID) + if err != nil { + _ = b.tg.AnswerCallbackQuery(ctx, cq.ID, "") + return err + } + text = i18n.T(lang, "quiet.kept") + if kept { + b.log.Info("quiet group kept", "chat", m.Chat.ID) + } else if paused, err := b.store.Paused(ctx, m.Chat.ID); err != nil { + _ = b.tg.AnswerCallbackQuery(ctx, cq.ID, "") + return err + } else if paused { + // Too late: the group paused itself. /start turns it back on. + text = i18n.T(lang, "quiet.paused") + } + case schedule.QuietPause: + admin, err := b.isAdmin(ctx, m.Chat.ID, cq.From.ID) + if err != nil { + _ = b.tg.AnswerCallbackQuery(ctx, cq.ID, "") + return err + } + if !admin { + return b.tg.AnswerCallbackQueryAlert(ctx, cq.ID, i18n.T(i18n.Resolve(raw), "msg.admin_only")) + } + if _, ok, err := b.store.PauseGroup(ctx, m.Chat.ID, db.PausedByAdmin); err != nil { + _ = b.tg.AnswerCallbackQuery(ctx, cq.ID, "") + return err + } else if ok { + b.log.Info("group paused", "chat", m.Chat.ID, "by", db.PausedByAdmin) + } + text = i18n.T(lang, "quiet.paused") + } + err = b.tg.EditText(ctx, m.Chat.ID, m.MessageID, text, nil) + if err != nil && !tg.IsMessageNotModified(err) { + _ = b.tg.AnswerCallbackQuery(ctx, cq.ID, "") + return fmt.Errorf("edit quiet question in %d: %w", m.Chat.ID, err) + } + return b.tg.AnswerCallbackQuery(ctx, cq.ID, "") +} + +// paused is the home of a paused group: what happened, and Resume for an +// admin, who is the only one who can press it, over Settings. +func (v view) paused(admin bool) (string, telegram.Markup) { + text := panel(productName, "", v.t("home.hint"), quote(v.t("home.paused"))) + var rows telegram.Markup + if admin { + b := v.button("btn.resume", actResume) + b.Style = tg.StylePrimary + rows = append(rows, []telegram.Button{b}, []telegram.Button{v.button("btn.settings", actSettings)}) + } + rows = append(rows, + []telegram.Button{v.button("btn.help", actHelp), v.button("btn.about", actAbout)}, + []telegram.Button{v.closeButton()}, + ) + return text, rows +} + +// groupPaused reads whether the group is paused for its home. A failed read +// shows the usual home: Resume is only offered when the pause is known. +func (b *Bot) groupPaused(ctx context.Context, chatID int64) bool { + paused, err := b.store.Paused(ctx, chatID) + if err != nil { + b.log.Warn("pause not read", "chat", chatID, "error", err) + return false + } + return paused +} diff --git a/internal/bot/quiet_test.go b/internal/bot/quiet_test.go new file mode 100644 index 0000000..722f972 --- /dev/null +++ b/internal/bot/quiet_test.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +package bot + +import ( + "context" + "strings" + "testing" + + "github.com/FreshLabDev/maply/internal/i18n" + "github.com/FreshLabDev/maply/internal/schedule" +) + +// Pause and Resume are an admin's: a member's press is refused on the +// press itself, whatever the callback says, and changes nothing. +func TestOnlyAnAdminPausesOrResumes(t *testing.T) { + b, store, client := testBot(t) + ctx := context.Background() + refused := i18n.T("ru", "msg.admin_only") + + store.chatLang[groupID] = "en" + store.asked[groupID] = true + b.handle(ctx, press(group, member, schedule.QuietPause)) + if store.paused[groupID] || len(client.alerts) != 1 || client.alerts[0] != refused || len(client.edits) != 0 { + t.Fatalf("a member paused: paused %v, alerts %v, edits %d", store.paused[groupID], client.alerts, len(client.edits)) + } + // Keep playing is anyone's. + b.handle(ctx, press(group, member, schedule.QuietKeep)) + if store.asked[groupID] || len(client.edits) != 1 || client.edits[0].text != i18n.T("en", "quiet.kept") || len(client.edits[0].markup) != 0 { + t.Fatalf("keep playing: asked %v, edits %+v", store.asked[groupID], client.edits) + } + b.handle(ctx, press(group, admin, schedule.QuietPause)) + if !store.paused[groupID] || len(client.edits) != 2 || client.edits[1].text != i18n.T("en", "quiet.paused") { + t.Fatalf("an admin's pause: paused %v, edits %+v", store.paused[groupID], client.edits) + } + + // /start in the paused group says so; Resume is on the admin's panel only. + b.handle(ctx, command(group, member, "/start")) + text, markup := client.sends[len(client.sends)-1].text, client.sends[len(client.sends)-1].markup + if !strings.Contains(text, i18n.T("en", "home.paused")) || has(markup, actResume) { + t.Fatalf("member's /start in a paused group = %q, %+v", text, markup) + } + b.handle(ctx, command(group, admin, "/start")) + if markup := client.sends[len(client.sends)-1].markup; !has(markup, actResume) { + t.Fatalf("admin's /start in a paused group has no Resume: %+v", markup) + } + + // A member forging Resume into their own panel is refused. + b.handle(ctx, press(group, member, cb(userID, actResume))) + if !store.paused[groupID] || len(client.alerts) != 2 || client.alerts[1] != refused { + t.Fatalf("a member resumed: paused %v, alerts %v", store.paused[groupID], client.alerts) + } + b.handle(ctx, press(group, admin, cb(adminID, actResume))) + if store.paused[groupID] { + t.Fatal("an admin's Resume left the group paused") + } + if last := client.edits[len(client.edits)-1]; !strings.Contains(last.text, i18n.T("en", "home.resumed", "post", "07:00")) || has(last.markup, actResume) { + t.Fatalf("after Resume the panel = %q, %+v", last.text, last.markup) + } +} diff --git a/internal/db/quiet.go b/internal/db/quiet.go new file mode 100644 index 0000000..36ada16 --- /dev/null +++ b/internal/db/quiet.go @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: Apache-2.0 +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/jackc/pgx/v5" + + "github.com/FreshLabDev/maply/internal/round" +) + +// Quiet is where a group stands on the way to a pause. +type Quiet struct { + // Days is the group's quiet days in a row before the date: days it got + // the morning post and nobody answered from the group, since its last + // answer and since quiet_since. A day without a post neither counts nor + // breaks the run. + Days int + // Asked is whether the question is out, sent on AskedOn. + Asked bool + AskedOn round.Date + // Answered is whether someone answered from the group on or after + // AskedOn, which takes the question back. + Answered bool +} + +// QuietOf is the group's quiet days up to d, d itself not counted unless +// someone answered on it, which ends the run. +func (s *Store) QuietOf(ctx context.Context, chatID int64, d round.Date) (Quiet, error) { + var q Quiet + var asked *time.Time + err := s.pool.QueryRow(ctx, ` + WITH cs AS (SELECT quiet_since, quiet_asked_on FROM chat_settings WHERE chat_id = $1), + last AS (SELECT max(date) AS date FROM guess WHERE chat_id = $1 AND date <= $2) + SELECT (SELECT count(*) FROM chat_round cr + WHERE cr.chat_id = $1 AND cr.post_msg_id IS NOT NULL AND cr.date < $2 + AND (cs.quiet_since IS NULL OR cr.date >= cs.quiet_since) + AND (last.date IS NULL OR cr.date > last.date)), + cs.quiet_asked_on, + COALESCE(last.date >= cs.quiet_asked_on, false) + FROM cs, last`, chatID, d.Time()).Scan(&q.Days, &asked, &q.Answered) + if errors.Is(err, pgx.ErrNoRows) { + return Quiet{}, nil + } + if err != nil { + return Quiet{}, fmt.Errorf("quiet of %d: %w", chatID, err) + } + if asked != nil { + q.Asked, q.AskedOn = true, round.DateIn(*asked, time.UTC) + } + q.Answered = q.Answered && q.Asked + return q, nil +} + +// AskQuiet records the question sent to the group on d. +func (s *Store) AskQuiet(ctx context.Context, chatID int64, d round.Date, msgID int64) error { + if _, err := s.pool.Exec(ctx, ` + UPDATE chat_settings SET quiet_asked_on = $2, quiet_msg_id = $3, updated_at = now() WHERE chat_id = $1`, + chatID, d.Time(), msgID); err != nil { + return fmt.Errorf("ask quiet %d: %w", chatID, err) + } + return nil +} + +// ClearQuiet takes the question back: someone answered from the group. The +// answer itself ends the run of quiet days. +func (s *Store) ClearQuiet(ctx context.Context, chatID int64) error { + if _, err := s.pool.Exec(ctx, ` + UPDATE chat_settings SET quiet_asked_on = NULL, quiet_msg_id = NULL, updated_at = now() WHERE chat_id = $1`, + chatID); err != nil { + return fmt.Errorf("clear quiet %d: %w", chatID, err) + } + return nil +} + +// KeepPlaying is a press of "Keep playing": the question is answered and +// the quiet days count again from the day after it was asked. ok is false +// when there was no question to answer, or the group is paused. +func (s *Store) KeepPlaying(ctx context.Context, chatID int64) (bool, error) { + tag, err := s.pool.Exec(ctx, ` + UPDATE chat_settings SET quiet_since = quiet_asked_on + 1, quiet_asked_on = NULL, quiet_msg_id = NULL, + updated_at = now() + WHERE chat_id = $1 AND quiet_asked_on IS NOT NULL AND paused_at IS NULL`, chatID) + if err != nil { + return false, fmt.Errorf("keep playing %d: %w", chatID, err) + } + return tag.RowsAffected() == 1, nil +} + +// Pause reasons. +const ( + PausedByAdmin = "admin" + PausedBySilence = "silence" +) + +// PauseGroup stops the scheduler sending to the group. msgID is the question +// that was out, 0 for none; ok is false when the group was paused already. +func (s *Store) PauseGroup(ctx context.Context, chatID int64, by string) (msgID int64, ok bool, err error) { + var msg *int64 + err = s.pool.QueryRow(ctx, ` + UPDATE chat_settings cs SET paused_at = now(), paused_by = $2, quiet_asked_on = NULL, quiet_msg_id = NULL, + updated_at = now() + FROM (SELECT chat_id, quiet_msg_id FROM chat_settings WHERE chat_id = $1 FOR UPDATE) was + WHERE cs.chat_id = was.chat_id AND cs.kind = 'group' AND cs.paused_at IS NULL + RETURNING was.quiet_msg_id`, chatID, by).Scan(&msg) + if errors.Is(err, pgx.ErrNoRows) { + return 0, false, nil + } + if err != nil { + return 0, false, fmt.Errorf("pause %d: %w", chatID, err) + } + return deref(msg), true, nil +} + +// ResumeGroup turns a paused group back on at at. Its day starts with the +// first morning post after at, and only days from then count towards the +// next question. ok is false when it was not paused. +func (s *Store) ResumeGroup(ctx context.Context, chatID int64, at time.Time) (bool, error) { + tag, err := s.pool.Exec(ctx, ` + UPDATE chat_settings SET paused_at = NULL, paused_by = NULL, resumed_at = $2, quiet_since = $3, + updated_at = now() + WHERE chat_id = $1 AND paused_at IS NOT NULL`, chatID, at, round.DateIn(at, time.UTC).Time()) + if err != nil { + return false, fmt.Errorf("resume %d: %w", chatID, err) + } + return tag.RowsAffected() == 1, nil +} + +// Paused reports whether the group is paused. +func (s *Store) Paused(ctx context.Context, chatID int64) (bool, error) { + var paused bool + err := s.pool.QueryRow(ctx, `SELECT paused_at IS NOT NULL FROM chat_settings WHERE chat_id = $1`, chatID).Scan(&paused) + if errors.Is(err, pgx.ErrNoRows) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("paused %d: %w", chatID, err) + } + return paused, nil +} diff --git a/internal/db/schedule.go b/internal/db/schedule.go index 055c37a..aaae744 100644 --- a/internal/db/schedule.go +++ b/internal/db/schedule.go @@ -25,21 +25,26 @@ type Chat struct { PostMin int Intrigue bool Mentions bool + // ResumedAt is when a paused group was turned back on: its day starts + // with the first morning post after it. Zero for a DM. + ResumedAt time.Time } // ActiveChats lists every chat the day is sent to. A DM counts once the person -// has been seen there and until they block maply. +// has been seen there and until they block maply. A paused group is left out. func (s *Store) ActiveChats(ctx context.Context) ([]Chat, error) { rows, err := s.pool.Query(ctx, ` SELECT cs.chat_id, 'group', COALESCE(cs.timezone, ''), COALESCE(core.effective_language(0, cs.chat_id, 'chat'), ''), - (EXTRACT(HOUR FROM cs.post_time) * 60 + EXTRACT(MINUTE FROM cs.post_time))::int, cs.intrigue, cs.mentions + (EXTRACT(HOUR FROM cs.post_time) * 60 + EXTRACT(MINUTE FROM cs.post_time))::int, cs.intrigue, cs.mentions, + cs.resumed_at FROM chat_settings cs - WHERE cs.kind = 'group' AND cs.active + WHERE cs.kind = 'group' AND cs.active AND cs.paused_at IS NULL UNION ALL SELECT p.telegram_user_id, 'dm', COALESCE(cs.timezone, ''), COALESCE(core.effective_language(p.telegram_user_id, NULL, 'user'), ''), - (EXTRACT(HOUR FROM COALESCE(cs.post_time, '07:00')) * 60 + EXTRACT(MINUTE FROM COALESCE(cs.post_time, '07:00')))::int, COALESCE(cs.intrigue, true), COALESCE(cs.mentions, true) + (EXTRACT(HOUR FROM COALESCE(cs.post_time, '07:00')) * 60 + EXTRACT(MINUTE FROM COALESCE(cs.post_time, '07:00')))::int, COALESCE(cs.intrigue, true), COALESCE(cs.mentions, true), + NULL::timestamptz FROM core.maply_presence p LEFT JOIN chat_settings cs ON cs.chat_id = p.telegram_user_id WHERE p.chat_id = 0 AND COALESCE(cs.active, true)`) @@ -49,8 +54,12 @@ func (s *Store) ActiveChats(ctx context.Context) ([]Chat, error) { return pgx.CollectRows(rows, func(row pgx.CollectableRow) (Chat, error) { var c Chat var post int - err := row.Scan(&c.ID, &c.Kind, &c.Zone, &c.Lang, &post, &c.Intrigue, &c.Mentions) + var resumed *time.Time + err := row.Scan(&c.ID, &c.Kind, &c.Zone, &c.Lang, &post, &c.Intrigue, &c.Mentions, &resumed) c.PostHour, c.PostMin = post/60, post%60 + if resumed != nil { + c.ResumedAt = *resumed + } return c, err }) } diff --git a/internal/db/settings.go b/internal/db/settings.go index cd8d321..160aa34 100644 --- a/internal/db/settings.go +++ b/internal/db/settings.go @@ -122,7 +122,14 @@ func (s *Store) AdoptChatZone(ctx context.Context, chatID int64, zone string) er if _, err := s.pool.Exec(ctx, ` INSERT INTO chat_settings (chat_id, kind, timezone) VALUES ($1, $2, $3) ON CONFLICT (chat_id) DO UPDATE SET timezone = COALESCE(chat_settings.timezone, EXCLUDED.timezone), - active = true, left_at = NULL, updated_at = now()`, + active = true, left_at = NULL, updated_at = now(), + -- Added back, a group starts afresh: whoever added maply wants + -- the places, so a pause and the quiet days before it are gone. + paused_at = CASE WHEN chat_settings.active THEN chat_settings.paused_at END, + paused_by = CASE WHEN chat_settings.active THEN chat_settings.paused_by END, + quiet_asked_on = CASE WHEN chat_settings.active THEN chat_settings.quiet_asked_on END, + quiet_msg_id = CASE WHEN chat_settings.active THEN chat_settings.quiet_msg_id END, + quiet_since = CASE WHEN chat_settings.active THEN chat_settings.quiet_since ELSE CURRENT_DATE END`, chatID, kindOf(chatID), zone); err != nil { return fmt.Errorf("adopt zone of %d: %w", chatID, err) } @@ -186,12 +193,13 @@ func (s *Store) MigrateChat(ctx context.Context, from, to int64) error { } defer tx.Rollback(ctx) if _, err := tx.Exec(ctx, ` - INSERT INTO chat_settings (chat_id, kind, post_time, intrigue, mentions, active, timezone, zone_auto) - SELECT $2, 'group', post_time, intrigue, mentions, true, timezone, zone_auto + INSERT INTO chat_settings (chat_id, kind, post_time, intrigue, mentions, active, timezone, zone_auto, paused_at, paused_by) + SELECT $2, 'group', post_time, intrigue, mentions, true, timezone, zone_auto, paused_at, paused_by FROM chat_settings WHERE chat_id = $1 ON CONFLICT (chat_id) DO UPDATE SET post_time = EXCLUDED.post_time, intrigue = EXCLUDED.intrigue, mentions = EXCLUDED.mentions, timezone = COALESCE(EXCLUDED.timezone, chat_settings.timezone), - zone_auto = EXCLUDED.zone_auto, active = true, left_at = NULL, updated_at = now()`, from, to); err != nil { + zone_auto = EXCLUDED.zone_auto, paused_at = EXCLUDED.paused_at, paused_by = EXCLUDED.paused_by, + active = true, left_at = NULL, updated_at = now()`, from, to); err != nil { return fmt.Errorf("migrate chat %d settings: %w", from, err) } var lang *string diff --git a/internal/i18n/translations.json b/internal/i18n/translations.json index 1648555..ced85d0 100644 --- a/internal/i18n/translations.json +++ b/internal/i18n/translations.json @@ -10133,6 +10133,42 @@ "uk": "Грати", "zh": "开始玩" }, + "btn.quiet_keep": { + "ar": "نواصل اللعب", + "be": "Гуляем далей", + "ca": "Continuem jugant", + "cs": "Hrajeme dál", + "de": "Weiterspielen", + "en": "Keep playing", + "es": "Seguir jugando", + "fr": "Continuer", + "it": "Continuiamo", + "ja": "続ける", + "pl": "Gramy dalej", + "ru": "Играем дальше", + "sv": "Spela vidare", + "tr": "Oynamaya devam", + "uk": "Граємо далі", + "zh": "继续玩" + }, + "btn.quiet_pause": { + "ar": "إيقاف مؤقت", + "be": "На паўзу", + "ca": "Posa en pausa", + "cs": "Pozastavit", + "de": "Pausieren", + "en": "Pause", + "es": "Pausar", + "fr": "Mettre en pause", + "it": "Metti in pausa", + "ja": "一時停止", + "pl": "Wstrzymaj", + "ru": "На паузу", + "sv": "Pausa", + "tr": "Duraklat", + "uk": "На паузу", + "zh": "暂停" + }, "btn.refresh": { "ar": "تحديث", "be": "Абнавіць", @@ -10169,6 +10205,24 @@ "uk": "Відкрити підсумок", "zh": "查看结果" }, + "btn.resume": { + "ar": "استئناف", + "be": "Працягнуць", + "ca": "Reprèn", + "cs": "Pokračovat", + "de": "Fortsetzen", + "en": "Resume", + "es": "Reanudar", + "fr": "Reprendre", + "it": "Riprendi", + "ja": "再開", + "pl": "Wznów", + "ru": "Продолжить", + "sv": "Fortsätt", + "tr": "Devam et", + "uk": "Продовжити", + "zh": "恢复" + }, "btn.settings": { "ar": "الإعدادات", "be": "Налады", @@ -10781,6 +10835,42 @@ "uk": "Одне місце на день. Де це?", "zh": "每天一个地点。这是哪里?" }, + "home.paused": { + "ar": "maply متوقف مؤقتًا هنا ولا يرسل شيئًا. يمكن للمشرف الضغط على «استئناف»: تعود الأماكن من الصباح التالي.", + "be": "maply тут на паўзе і нічога не дасылае. Адмін можа націснуць «Працягнуць»: месцы вернуцца з наступнай раніцы.", + "ca": "maply està en pausa aquí i no envia res. Un admin pot prémer Reprèn: els llocs tornen a partir de l’endemà al matí.", + "cs": "maply je tu pozastavený a nic neposílá. Admin může stisknout Pokračovat: místa se vrátí od dalšího rána.", + "de": "maply pausiert hier und schickt nichts. Ein Admin kann auf Fortsetzen tippen: Die Orte kommen ab dem nächsten Morgen wieder.", + "en": "maply is paused here and sends nothing. An admin can press Resume: the places come back from the next morning.", + "es": "maply está en pausa aquí y no envía nada. Un admin puede pulsar Reanudar: los lugares vuelven desde la mañana siguiente.", + "fr": "maply est en pause ici et n’envoie rien. Un admin peut appuyer sur Reprendre : les lieux reviennent dès le lendemain matin.", + "it": "maply qui è in pausa e non manda nulla. Un admin può premere Riprendi: i luoghi tornano dalla mattina dopo.", + "ja": "maply はここで一時停止中で、何も送りません。管理者が「再開」を押すと、翌朝から場所が戻ります。", + "pl": "maply jest tu wstrzymany i nic nie wysyła. Admin może nacisnąć Wznów: miejsca wrócą od następnego ranka.", + "ru": "maply здесь на паузе и ничего не присылает. Админ может нажать «Продолжить»: места вернутся со следующего утра.", + "sv": "maply är pausad här och skickar ingenting. En admin kan trycka på Fortsätt: platserna kommer tillbaka från nästa morgon.", + "tr": "maply burada duraklatıldı ve hiçbir şey göndermiyor. Bir yönetici Devam et düğmesine basabilir: yerler ertesi sabahtan itibaren geri gelir.", + "uk": "maply тут на паузі й нічого не надсилає. Адмін може натиснути «Продовжити»: місця повернуться з наступного ранку.", + "zh": "maply 在这里已暂停,不会发送任何内容。管理员可以点击“恢复”:从下一个早上起地点会回来。" + }, + "home.resumed": { + "ar": "عاد maply! يصل المكان التالي مع منشور الصباح في {post}.", + "be": "maply вярнуўся! Наступнае месца прыйдзе з ранішнім пастом а {post}.", + "ca": "maply ha tornat! El proper lloc arriba amb la publicació del matí, a les {post}.", + "cs": "maply je zpátky! Další místo přijde s ranním příspěvkem v {post}.", + "de": "maply ist zurück! Der nächste Ort kommt mit dem Morgenpost um {post}.", + "en": "maply is back! The next place comes with the morning post at {post}.", + "es": "¡maply ha vuelto! El próximo lugar llega con la publicación de la mañana, a las {post}.", + "fr": "maply est de retour ! Le prochain lieu arrive avec le message du matin, à {post}.", + "it": "maply è tornato! Il prossimo luogo arriva con il post del mattino, alle {post}.", + "ja": "maply が戻ってきました!次の場所は {post} の朝の投稿で届きます。", + "pl": "maply wrócił! Następne miejsce przyjdzie z porannym postem o {post}.", + "ru": "maply вернулся! Следующее место придёт с утренним постом в {post}.", + "sv": "maply är tillbaka! Nästa plats kommer med morgoninlägget klockan {post}.", + "tr": "maply geri döndü! Sıradaki yer, saat {post} sabah gönderisiyle gelir.", + "uk": "maply повернувся! Наступне місце прийде з ранковим постом о {post}.", + "zh": "maply 回来了!下一个地点会在 {post} 的早间帖子里发来。" + }, "intrigue.all": { "ar": "أجاب الجميع. تبعد الدبابيس عن بعضها حتى {km} كم. النتيجة في الساعة {time}.", "be": "Адказалі ўсе. Шпількі раскіданыя на {km} км. Вынік у {time}.", @@ -11483,6 +11573,60 @@ "uk": "найкраще місце у світі", "zh": "最佳世界排名" }, + "quiet.ask": { + "ar": "ألو؟ هل من أحد هنا؟ 👀\nلم يخمّن أحد هنا مكانًا منذ أسبوع. هل أواصل إرسالها؟", + "be": "Агов, ёсць тут хто жывы? 👀\nТут ужо тыдзень ніхто не адгадвае месцы. Дасылаць іх далей?", + "ca": "Hola? Hi ha algú? 👀\nFa una setmana que ningú no endevina cap lloc aquí. Continuo enviant-los?", + "cs": "Haló? Je tu někdo? 👀\nUž týden tu nikdo nehádá žádné místo. Mám je posílat dál?", + "de": "Hallo? Jemand da? 👀\nHier hat seit einer Woche niemand einen Ort geraten. Soll ich weiter welche schicken?", + "en": "Hello? Anyone there? 👀\nNobody here has guessed a place for a week. Shall I keep sending them?", + "es": "¿Hola? ¿Hay alguien? 👀\nHace una semana que nadie adivina un lugar aquí. ¿Sigo enviándolos?", + "fr": "Allô ? Il y a quelqu’un ? 👀\nPersonne ici n’a deviné de lieu depuis une semaine. Je continue à les envoyer ?", + "it": "Pronto? C’è qualcuno? 👀\nQui nessuno indovina un luogo da una settimana. Continuo a mandarli?", + "ja": "もしもし?誰かいますか?👀\nここでは1週間、誰も場所を当てていません。このまま送り続けますか?", + "pl": "Halo? Jest tu kto? 👀\nOd tygodnia nikt tu nie zgaduje miejsc. Wysyłać je dalej?", + "ru": "Ау, есть кто живой? 👀\nЗдесь уже неделю никто не угадывает места. Продолжать их присылать?", + "sv": "Hallå? Är det någon här? 👀\nIngen här har gissat en plats på en vecka. Ska jag fortsätta skicka dem?", + "tr": "Alo? Kimse var mı? 👀\nBir haftadır burada kimse bir yer tahmin etmedi. Göndermeye devam edeyim mi?", + "uk": "Агов, є тут хтось живий? 👀\nТут уже тиждень ніхто не вгадує місця. Надсилати їх далі?", + "zh": "喂?有人吗?👀\n这里已经一周没人猜地点了。还要继续发吗?" + }, + "quiet.kept": { + "ar": "اتفقنا! ستواصل الأماكن الوصول كل صباح. 🌍", + "be": "Дамовіліся! Месцы і далей будуць прыходзіць кожную раніцу. 🌍", + "ca": "Fet! Els llocs continuaran arribant cada matí. 🌍", + "cs": "Platí! Místa budou dál chodit každé ráno. 🌍", + "de": "Abgemacht! Die Orte kommen weiter jeden Morgen. 🌍", + "en": "Deal! The places keep coming every morning. 🌍", + "es": "¡Trato hecho! Los lugares seguirán llegando cada mañana. 🌍", + "fr": "Marché conclu ! Les lieux continuent d’arriver chaque matin. 🌍", + "it": "Affare fatto! I luoghi continuano ad arrivare ogni mattina. 🌍", + "ja": "了解!これからも毎朝、場所を届けます。🌍", + "pl": "Umowa stoi! Miejsca dalej będą przychodzić co rano. 🌍", + "ru": "Договорились! Места и дальше будут приходить каждое утро. 🌍", + "sv": "Avgjort! Platserna fortsätter komma varje morgon. 🌍", + "tr": "Anlaştık! Yerler her sabah gelmeye devam edecek. 🌍", + "uk": "Домовилися! Місця й далі приходитимуть щоранку. 🌍", + "zh": "一言为定!每天早上照常发地点。🌍" + }, + "quiet.paused": { + "ar": "maply يأخذ قيلولة هنا 😴 لا منشورات حتى يوقظه أحد: يمكن للمشرف إرسال /start والضغط على «استئناف».", + "be": "maply тут прылёг падрамаць 😴 Пастоў не будзе, пакуль яго не разбудзяць: адмін можа даслаць /start і націснуць «Працягнуць».", + "ca": "maply fa la migdiada aquí 😴 No hi haurà publicacions fins que algú el desperti: un admin pot enviar /start i prémer Reprèn.", + "cs": "maply si tu dává šlofíka 😴 Žádné příspěvky, dokud ho někdo nevzbudí: admin může poslat /start a stisknout Pokračovat.", + "de": "maply macht hier ein Nickerchen 😴 Keine Posts, bis es jemand weckt: Ein Admin kann /start senden und auf Fortsetzen tippen.", + "en": "maply is taking a nap here 😴 No posts until someone wakes it up: an admin can send /start and press Resume.", + "es": "maply se echa una siesta aquí 😴 No habrá publicaciones hasta que alguien lo despierte: un admin puede enviar /start y pulsar Reanudar.", + "fr": "maply fait la sieste ici 😴 Plus de messages tant que personne ne le réveille : un admin peut envoyer /start et appuyer sur Reprendre.", + "it": "maply qui si fa un pisolino 😴 Niente post finché qualcuno non lo sveglia: un admin può inviare /start e premere Riprendi.", + "ja": "maply はここでひと休み中 😴 誰かが起こすまで投稿しません。管理者が /start を送って「再開」を押せます。", + "pl": "maply ucina sobie tu drzemkę 😴 Żadnych postów, dopóki ktoś go nie obudzi: admin może wysłać /start i nacisnąć Wznów.", + "ru": "maply здесь прилёг вздремнуть 😴 Постов не будет, пока его не разбудят: админ может отправить /start и нажать «Продолжить».", + "sv": "maply tar en tupplur här 😴 Inga inlägg förrän någon väcker den: en admin kan skicka /start och trycka på Fortsätt.", + "tr": "maply burada biraz kestiriyor 😴 Biri onu uyandırana kadar gönderi yok: bir yönetici /start gönderip Devam et düğmesine basabilir.", + "uk": "maply тут приліг подрімати 😴 Постів не буде, доки його не розбудять: адмін може надіслати /start і натиснути «Продовжити».", + "zh": "maply 在这里打个盹 😴 有人叫醒它之前不会再发帖:管理员可以发送 /start 并点击“恢复”。" + }, "result.answered_of": { "ar": "أجاب {n} من {total}.", "be": "Адказалі {n} з {total}.", diff --git a/internal/schedule/day.go b/internal/schedule/day.go index b95d7f6..f634bde 100644 --- a/internal/schedule/day.go +++ b/internal/schedule/day.go @@ -51,7 +51,7 @@ func (s *Scheduler) intrigue(ctx context.Context, j db.Job) error { if err != nil { return err } - if !ok || !c.Intrigue || !s.now().Before(j.Date.Reveal(s.location(c))) { + if !ok || !s.now().Before(j.Date.Reveal(s.location(c))) || resting(c, j.Date, s.location(c)) { return errSkip } cr, err := s.Store.ChatRound(ctx, c.ID, j.Date) @@ -64,6 +64,24 @@ func (s *Scheduler) intrigue(ctx context.Context, j db.Job) error { if cr.PostMsgID == 0 { return errSkip } + if c.Kind == "group" { + asked, err := s.askQuiet(ctx, c, j.Date) + if asked { + // Sent: a failure after it is only bookkeeping, and a retry + // would ask twice. + if err != nil { + s.Log.Error("quiet question not recorded", "chat", c.ID, "error", err) + } + return nil + } + if err != nil { + // The intrigue goes out as on any day; the question waits. + s.Log.Error("quiet check failed", "chat", c.ID, "error", err) + } + } + if !c.Intrigue || !intrigueFits(c, j.Date, s.location(c)) { + return errSkip + } rd, ok, err := s.Store.RoundOn(ctx, j.Date) if err != nil || !ok { return orSkip(err) @@ -267,7 +285,7 @@ func (s *Scheduler) streakLine(ctx context.Context, silent []db.Member, d round. func (s *Scheduler) result(ctx context.Context, j db.Job) error { c, ok, err := s.chatOf(ctx, j.ChatID) - if err != nil || !ok { + if err != nil || !ok || resting(c, j.Date, s.location(c)) { return orSkip(err) } rd, ok, err := s.Store.RoundOn(ctx, j.Date) diff --git a/internal/schedule/quiet.go b/internal/schedule/quiet.go new file mode 100644 index 0000000..e137283 --- /dev/null +++ b/internal/schedule/quiet.go @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: Apache-2.0 +package schedule + +import ( + "context" + "time" + + "github.com/FreshLabDev/tg" + + "github.com/FreshLabDev/maply/internal/db" + "github.com/FreshLabDev/maply/internal/i18n" + "github.com/FreshLabDev/maply/internal/round" + "github.com/FreshLabDev/maply/internal/telegram" +) + +// A group where nobody plays is asked, in place of an intrigue, whether to +// go on, and paused when nobody answers the question. See docs/design.md → +// "Groups". +const ( + // QuietDays is how many quiet days in a row bring the question. + QuietDays = 7 + // QuietWait is how many days the question waits for a press; the + // morning after, the group is paused. + QuietWait = 3 + + // The question's buttons. Any member may keep the game going; only an + // admin may pause it. + QuietKeep = "quiet:keep" + QuietPause = "quiet:pause" +) + +// QuietMarkup is the question's two buttons. +func QuietMarkup(lang string) telegram.Markup { + return telegram.Markup{{ + {Text: i18n.T(lang, "btn.quiet_keep"), CallbackData: QuietKeep, Style: tg.StylePrimary}, + {Text: i18n.T(lang, "btn.quiet_pause"), CallbackData: QuietPause}, + }} +} + +// resting is a resumed group's date that started before the resume: its +// day begins with the first morning post after it. +func resting(c db.Chat, d round.Date, loc *time.Location) bool { + return c.Kind == "group" && !c.ResumedAt.IsZero() && d.At(c.PostHour, c.PostMin, loc).Before(c.ResumedAt) +} + +// askQuiet sends the question in place of the day's intrigue when the group +// has had QuietDays quiet days in a row and has not been asked since. It +// reports whether it did; the question then is the day's second message. +func (s *Scheduler) askQuiet(ctx context.Context, c db.Chat, d round.Date) (bool, error) { + q, err := s.Store.QuietOf(ctx, c.ID, d) + if err != nil { + return false, err + } + if q.Answered { + return false, s.Store.ClearQuiet(ctx, c.ID) + } + if q.Asked || q.Days < QuietDays { + return false, nil + } + lang := i18n.Resolve(c.Lang) + msg, err := s.TG.SendText(ctx, c.ID, i18n.T(lang, "quiet.ask"), QuietMarkup(lang)) + if err != nil { + return false, err + } + s.Log.Info("quiet group asked", "chat", c.ID, "date", d, "days", q.Days) + if err := s.Store.AskQuiet(ctx, c.ID, d, msg.MessageID); err != nil { + return true, err + } + return true, s.Store.SetIntrigueSent(ctx, c.ID, d, "quiet", s.now()) +} + +// pauseIfIgnored pauses the group on the morning QuietWait days after the +// question when nobody pressed a button and nobody answered from the group +// since. It reports whether it paused; the morning post is then not sent. +func (s *Scheduler) pauseIfIgnored(ctx context.Context, c db.Chat, d round.Date) (bool, error) { + q, err := s.Store.QuietOf(ctx, c.ID, d) + if err != nil { + return false, err + } + if q.Answered { + return false, s.Store.ClearQuiet(ctx, c.ID) + } + if !q.Asked || d.Before(q.AskedOn.AddDays(QuietWait)) { + return false, nil + } + msgID, ok, err := s.Store.PauseGroup(ctx, c.ID, db.PausedBySilence) + if err != nil || !ok { + return ok, err + } + s.Log.Info("group paused", "chat", c.ID, "by", db.PausedBySilence, "asked_on", q.AskedOn) + s.chatsMu.Lock() + delete(s.chats, c.ID) + s.chatsMu.Unlock() + if msgID != 0 { + lang := i18n.Resolve(c.Lang) + if err := s.TG.EditText(ctx, c.ID, msgID, i18n.T(lang, "quiet.paused"), nil); err != nil && !tg.IsMessageNotModified(err) { + // The pause holds; the question just keeps its buttons, and a + // press on them finds the group paused. + s.Log.Info("quiet question not edited", "chat", c.ID, "error", err) + } + } + return true, nil +} diff --git a/internal/schedule/quiet_integration_test.go b/internal/schedule/quiet_integration_test.go new file mode 100644 index 0000000..647011e --- /dev/null +++ b/internal/schedule/quiet_integration_test.go @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: Apache-2.0 +//go:build integration + +package schedule + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/FreshLabDev/maply/internal/i18n" + "github.com/FreshLabDev/maply/internal/round" +) + +// messages is what the group got on the date, by kind: sends only, not +// edits or pins. +func (st *standing) messages(from int) []sent { + var out []sent + for _, m := range st.fake.log[from:] { + if m.chatID == group && (m.kind == "photo" || m.kind == "text" || m.kind == "animation") { + out = append(out, m) + } + } + return out +} + +// day runs the scheduler through one Kyiv date, 05:00 to 23:40, every +// twenty minutes, and returns what the group got. +func (st *standing) day(t *testing.T, d round.Date) []sent { + t.Helper() + from := len(st.fake.log) + for st.clock = d.At(5, 0, st.kyiv); st.clock.Before(d.At(23, 59, st.kyiv)); st.clock = st.clock.Add(20 * time.Minute) { + st.s.Step(context.Background()) + } + return st.messages(from) +} + +// A group where nobody plays: seven quiet days bring the question once, in +// place of the eighth day's intrigue; three days without a press pause the +// group, and while paused it gets nothing; an admin's Resume in the middle +// of a day starts it again with the next morning's post. +func TestQuietGroupIsAskedPausedAndResumed(t *testing.T) { + st := newStanding(t, 16) + ctx := context.Background() + ask := i18n.T("en", "quiet.ask") + asks := func(ms []sent) int { + n := 0 + for _, m := range ms { + if m.text == ask { + n++ + } + } + return n + } + + // Seven quiet days: the post and an intrigue each, no result since + // nobody answered anywhere, and no question. + for i := range QuietDays { + got := st.day(t, st.d.AddDays(i)) + if len(got) != 2 || asks(got) != 0 { + t.Fatalf("quiet day %d: the group got %d messages (%d questions), want the post and the intrigue: %+v", i+1, len(got), asks(got), got) + } + } + + // The eighth: the question takes the intrigue's place. + asked := st.d.AddDays(QuietDays) + got := st.day(t, asked) + if len(got) != 2 || asks(got) != 1 { + t.Fatalf("day 8: %d messages, %d questions, want the post and the question: %+v", len(got), asks(got), got) + } + q := got[1] + if len(q.buttons) != 1 || len(q.buttons[0]) != 2 || q.buttons[0][0].CallbackData != QuietKeep || q.buttons[0][1].CallbackData != QuietPause { + t.Fatalf("question's buttons = %+v", q.buttons) + } + + // Three more days without a press: the posts still come, the question + // does not come again. + for i := 1; i < QuietWait; i++ { + got := st.day(t, asked.AddDays(i)) + if len(got) != 2 || asks(got) != 0 { + t.Fatalf("day %d after the question: %d messages, %d questions: %+v", i, len(got), asks(got), got) + } + } + // The third morning after it, the group is paused: no post, and the + // question says how to turn maply back on. + pausedOn := asked.AddDays(QuietWait) + if got := st.day(t, pausedOn); len(got) != 0 { + t.Fatalf("the day of the pause sent %+v", got) + } + if edit := st.fake.last("edit_text", group); edit.text != i18n.T("en", "quiet.paused") || len(edit.buttons) != 0 { + t.Fatalf("the question became %q with %+v", edit.text, edit.buttons) + } + var by string + if err := st.pool.QueryRow(ctx, `SELECT paused_by FROM maply.chat_settings WHERE chat_id = $1`, group).Scan(&by); err != nil || by != "silence" { + t.Fatalf("paused_by = %q (%v)", by, err) + } + chats, err := st.store.ActiveChats(ctx) + if err != nil { + t.Fatal(err) + } + for _, c := range chats { + if c.ID == group { + t.Fatal("a paused group is an active chat") + } + } + + // Paused, nothing at all. + calls := len(st.fake.log) + resumedOn := pausedOn.AddDays(1) + from := len(st.fake.log) + for st.clock = resumedOn.At(5, 0, st.kyiv); st.clock.Before(resumedOn.At(12, 0, st.kyiv)); st.clock = st.clock.Add(20 * time.Minute) { + st.s.Step(ctx) + } + if len(st.fake.log) != calls { + t.Fatalf("a paused group got %+v", st.fake.log[calls:]) + } + // An admin resumes at noon: today's post time is gone, so today stays + // quiet, and the next morning's post goes out. + if ok, err := st.store.ResumeGroup(ctx, group, st.clock); err != nil || !ok { + t.Fatalf("resume = %v, %v", ok, err) + } + for ; st.clock.Before(resumedOn.At(23, 59, st.kyiv)); st.clock = st.clock.Add(20 * time.Minute) { + st.s.Step(ctx) + } + if got := st.messages(from); len(got) != 0 { + t.Fatalf("the day of the resume sent %+v", got) + } + got = st.day(t, resumedOn.AddDays(1)) + if len(got) != 2 || !strings.Contains(got[0].text, "maply #") || asks(got) != 0 { + t.Fatalf("the morning after the resume: %+v, want the post and the intrigue", got) + } +} + +// One answer from the group ends the run of quiet days, and an answer +// after the question takes it back: no pause. +func TestAnAnswerKeepsAQuietGroupGoing(t *testing.T) { + st := newStanding(t, 13) + ctx := context.Background() + for i := range QuietDays { + st.day(t, st.d.AddDays(i)) + } + asked := st.d.AddDays(QuietDays) + if got := st.day(t, asked); len(got) != 2 || got[1].text != i18n.T("en", "quiet.ask") { + t.Fatalf("day 8 = %+v, want the question", got) + } + // The next day someone answers from the group. + next := asked.AddDays(1) + st.clock = next.At(5, 0, st.kyiv) + for ; st.clock.Before(next.At(10, 0, st.kyiv)); st.clock = st.clock.Add(20 * time.Minute) { + st.s.Step(ctx) + } + exec(t, st.pool, `INSERT INTO maply.guess (date, user_id, context, chat_id, lat, lon, answered_at, deadline_at) + VALUES ($1, $2, 'group', $3, 40.4, -3.7, $4, $5)`, next.Time(), player, group, st.clock, next.Reveal(st.kyiv)) + for ; st.clock.Before(next.At(23, 59, st.kyiv)); st.clock = st.clock.Add(20 * time.Minute) { + st.s.Step(ctx) + } + for i := 2; i <= QuietWait+1; i++ { + if got := st.day(t, asked.AddDays(i)); len(got) < 2 || !strings.Contains(got[0].text, "maply #") { + t.Fatalf("day %d after the question: %+v, want the post", i, got) + } + } + if paused, err := st.store.Paused(ctx, group); err != nil || paused { + t.Fatalf("paused = %v, %v after an answer", paused, err) + } + if q, err := st.store.QuietOf(ctx, group, asked.AddDays(QuietWait+2)); err != nil || q.Asked || q.Days != QuietWait { + t.Fatalf("quiet = %+v, %v", q, err) + } +} diff --git a/internal/schedule/schedule.go b/internal/schedule/schedule.go index 78bd882..36b92e6 100644 --- a/internal/schedule/schedule.go +++ b/internal/schedule/schedule.go @@ -90,6 +90,10 @@ type Store interface { 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 + QuietOf(ctx context.Context, chatID int64, d round.Date) (db.Quiet, error) + AskQuiet(ctx context.Context, chatID int64, d round.Date, msgID int64) error + ClearQuiet(ctx context.Context, chatID int64) error + PauseGroup(ctx context.Context, chatID int64, by string) (int64, bool, error) } type Telegram interface { @@ -284,6 +288,26 @@ func intrigueAt(chatID int64, d round.Date, loc *time.Location) time.Time { return d.At(16, 0, loc).Add(time.Duration(h.Sum32()%120) * time.Minute) } +// intrigueSlot is when the chat's intrigue comes: a moment of 16:00–18:00 +// at least an hour after the post. ok is false when the post comes too +// late for one; a group then still has a slot half an hour after the post, +// used only by the quiet group's question. +func intrigueSlot(c db.Chat, d round.Date, loc *time.Location) (at time.Time, ok bool) { + post := d.At(c.PostHour, c.PostMin, loc) + if at := intrigueAt(c.ID, d, loc); at.After(post.Add(time.Hour)) { + return at, true + } + if c.Kind == "group" { + return post.Add(30 * time.Minute), true + } + return time.Time{}, false +} + +// intrigueFits is whether the chat's day has room for an intrigue proper. +func intrigueFits(c db.Chat, d round.Date, loc *time.Location) bool { + return intrigueAt(c.ID, d, loc).After(d.At(c.PostHour, c.PostMin, loc).Add(time.Hour)) +} + // plan queues the current date's three jobs for every chat. The queue's keys // make this idempotent; the map only spares the database a repeat. func (s *Scheduler) plan(ctx context.Context) error { @@ -326,17 +350,24 @@ func (s *Scheduler) plan(ctx context.Context) error { d := round.DateIn(now, loc) // The zone is in the mark: a chat that moves to another zone gets its // jobs moved the same minute, not after a restart. - mark := fmt.Sprintf("%s %s %02d:%02d %t", d, loc, c.PostHour, c.PostMin, c.Intrigue) + mark := fmt.Sprintf("%s %s %02d:%02d %t %d", d, loc, c.PostHour, c.PostMin, c.Intrigue, c.ResumedAt.Unix()) if s.planned[c.ID] == mark { continue } + // A group resumed after today's post time starts tomorrow morning. + if resting(c, d, loc) { + s.planned[c.ID] = mark + continue + } reveal := d.Reveal(loc) post := d.At(c.PostHour, c.PostMin, loc) if now.Before(reveal) { if err := s.Store.PlanJob(ctx, jobPost, c.ID, d, post); err != nil { return err } - if at := intrigueAt(c.ID, d, loc); c.Intrigue && at.After(post.Add(time.Hour)) { + // A group's slot is planned with the intrigue off as well: a + // quiet group's question takes it (see askQuiet). + if at, ok := intrigueSlot(c, d, loc); ok && (c.Intrigue || c.Kind == "group") { if err := s.Store.PlanJob(ctx, jobIntrigue, c.ID, d, at); err != nil { return err } @@ -505,6 +536,9 @@ func (s *Scheduler) post(ctx context.Context, j db.Job) error { if err != nil { return err } + if resting(c, j.Date, loc) { + return errSkip + } cr, err := s.Store.ChatRound(ctx, c.ID, j.Date) if err != nil { return err @@ -512,6 +546,14 @@ func (s *Scheduler) post(ctx context.Context, j db.Job) error { if cr.PostMsgID != 0 { return nil } + if c.Kind == "group" { + // A failed check costs the pause a day, not the group its post. + if paused, err := s.pauseIfIgnored(ctx, c, j.Date); err != nil { + s.Log.Error("quiet check failed", "chat", c.ID, "error", err) + } else if paused { + return errSkip + } + } lang := i18n.Resolve(c.Lang) line := "" if c.Kind == "group" { diff --git a/migrations/032_quiet.sql b/migrations/032_quiet.sql new file mode 100644 index 0000000..d2952c1 --- /dev/null +++ b/migrations/032_quiet.sql @@ -0,0 +1,21 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- A group where nobody plays is asked once whether to go on, and paused when +-- nobody answers the question. A quiet day is a day the group got its +-- morning post and nobody answered from the group (guess.chat_id); a +-- warm-up is free play and is no answer here. +-- +-- quiet_since: days before it do not count towards the next question. Set by +-- "Keep playing" and by a resume. +-- quiet_asked_on, quiet_msg_id: the question is out and waits for a press; +-- cleared by a press, by an answer from the group and by the pause. +-- paused_at, paused_by: the group gets nothing from the scheduler. A paused +-- group stays active: it still has maply, and its members' answer window +-- still counts it. +-- resumed_at: a resumed group's day starts with the first morning post after +-- this moment. +ALTER TABLE chat_settings ADD COLUMN IF NOT EXISTS quiet_since DATE; +ALTER TABLE chat_settings ADD COLUMN IF NOT EXISTS quiet_asked_on DATE; +ALTER TABLE chat_settings ADD COLUMN IF NOT EXISTS quiet_msg_id BIGINT; +ALTER TABLE chat_settings ADD COLUMN IF NOT EXISTS paused_at TIMESTAMPTZ; +ALTER TABLE chat_settings ADD COLUMN IF NOT EXISTS paused_by TEXT CHECK (paused_by IN ('admin', 'silence')); +ALTER TABLE chat_settings ADD COLUMN IF NOT EXISTS resumed_at TIMESTAMPTZ;