1
0

tgbot_broadcast_test.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. package tgbot
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/http/httptest"
  9. "slices"
  10. "strings"
  11. "sync"
  12. "testing"
  13. "time"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database"
  15. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  16. "github.com/mhsanaei/3x-ui/v3/internal/web/locale"
  17. telegoapi "github.com/mymmrac/telego/telegoapi"
  18. "github.com/mymmrac/telego"
  19. "github.com/nicksnyder/go-i18n/v2/i18n"
  20. "golang.org/x/text/language"
  21. )
  22. // newBroadcastMock serves ok:true and records per-method call counts and
  23. // bodies; copyMessages answers with an array of ids, as the real API does.
  24. func newBroadcastMock(t *testing.T) (url string, calls func(string) int, bodies func(string) []map[string]any) {
  25. t.Helper()
  26. var mu sync.Mutex
  27. counts := map[string]int{}
  28. sent := map[string][]map[string]any{}
  29. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  30. raw, _ := io.ReadAll(r.Body)
  31. payload := map[string]any{}
  32. _ = json.Unmarshal(raw, &payload)
  33. method := strings.TrimPrefix(r.URL.Path, "/bot"+testBotToken+"/")
  34. message := map[string]any{"message_id": 7, "date": 0, "chat": map[string]any{"id": 1, "type": "private"}}
  35. result := any(message)
  36. if method == "copyMessages" {
  37. result = []any{message, message}
  38. }
  39. mu.Lock()
  40. counts[method]++
  41. sent[method] = append(sent[method], payload)
  42. mu.Unlock()
  43. w.Header().Set("Content-Type", "application/json")
  44. _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "result": result})
  45. }))
  46. t.Cleanup(srv.Close)
  47. return srv.URL,
  48. func(method string) int {
  49. mu.Lock()
  50. defer mu.Unlock()
  51. return counts[method]
  52. },
  53. func(method string) []map[string]any {
  54. mu.Lock()
  55. defer mu.Unlock()
  56. return append([]map[string]any(nil), sent[method]...)
  57. }
  58. }
  59. func setBroadcastAdmins(t *testing.T, ids []int64) {
  60. t.Helper()
  61. tgBotMutex.Lock()
  62. orig := adminIds
  63. adminIds = ids
  64. tgBotMutex.Unlock()
  65. t.Cleanup(func() {
  66. tgBotMutex.Lock()
  67. adminIds = orig
  68. tgBotMutex.Unlock()
  69. })
  70. }
  71. func setBroadcastRunning(t *testing.T, running bool) {
  72. t.Helper()
  73. tgBotMutex.Lock()
  74. orig := isRunning
  75. isRunning = running
  76. tgBotMutex.Unlock()
  77. t.Cleanup(func() {
  78. tgBotMutex.Lock()
  79. isRunning = orig
  80. tgBotMutex.Unlock()
  81. })
  82. }
  83. func swapBroadcastSender(t *testing.T, sender func(int64, broadcastDraft) error, pause func(time.Duration)) {
  84. t.Helper()
  85. origSend, origPause := broadcastSender, broadcastPause
  86. t.Cleanup(func() {
  87. broadcastSender, broadcastPause = origSend, origPause
  88. })
  89. broadcastSender = sender
  90. if pause != nil {
  91. broadcastPause = pause
  92. }
  93. }
  94. // broadcastLocalizer renders the broadcast keys a test asserts on; without it
  95. // I18n returns the bare key instead of the template output.
  96. func broadcastLocalizer(t *testing.T) {
  97. t.Helper()
  98. bundle := i18n.NewBundle(language.MustParse("en-US"))
  99. bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
  100. _ = bundle.AddMessages(language.MustParse("en-US"),
  101. &i18n.Message{ID: "tgbot.messages.broadcastPreview", Other: "📤 This message will go to {{ .Count }} recipients. Send it?"},
  102. &i18n.Message{ID: "tgbot.messages.broadcastNotCopyable", Other: "❗ This message can't be copied for broadcast."},
  103. &i18n.Message{ID: "tgbot.messages.broadcastAskText", Other: "send the message"},
  104. &i18n.Message{ID: "tgbot.messages.broadcastAlreadyRunning", Other: "already running"},
  105. &i18n.Message{ID: "tgbot.messages.broadcastProgress", Other: "progress {{ .Sent }}/{{ .Total }} failed {{ .Failed }}"},
  106. &i18n.Message{ID: "tgbot.messages.broadcastFinished", Other: "finished"},
  107. &i18n.Message{ID: "tgbot.messages.broadcastCanceled", Other: "canceled"},
  108. &i18n.Message{ID: "tgbot.messages.broadcastUnreachable", Other: "ℹ️ {{ .Count }} recipients cannot be messaged — ask them to press Start."},
  109. )
  110. orig := locale.LocalizerBot
  111. t.Cleanup(func() { locale.LocalizerBot = orig })
  112. locale.LocalizerBot = i18n.NewLocalizer(bundle, "en-US")
  113. }
  114. func createBroadcastInbound(t *testing.T, tag, settings string) {
  115. t.Helper()
  116. inbound := &model.Inbound{Tag: tag, Settings: settings, Enable: true}
  117. if err := database.GetDB().Create(inbound).Error; err != nil {
  118. t.Fatalf("create inbound %s: %v", tag, err)
  119. }
  120. }
  121. // broadcastClientsJSON renders an inbound settings blob with the given tgIds.
  122. func broadcastClientsJSON(t *testing.T, tgIDs ...int64) string {
  123. t.Helper()
  124. clients := make([]string, 0, len(tgIDs))
  125. for i, tgID := range tgIDs {
  126. clients = append(clients, fmt.Sprintf(`{"email":"user%d@x","tgId":%d}`, i, tgID))
  127. }
  128. return `{"clients":[` + strings.Join(clients, ",") + `]}`
  129. }
  130. // resetBroadcastState clears the shared broadcast globals before a test
  131. // asserts on them: shuffled tests may inherit state from an earlier test.
  132. func resetBroadcastState(t *testing.T) {
  133. t.Helper()
  134. broadcastResetAll()
  135. userStateMgr.reset()
  136. }
  137. // composeBroadcast hands a message to the composition step the way the router
  138. // does: keyed by its sender, who is awaiting broadcast input.
  139. func composeBroadcast(tb *Tgbot, message telego.Message) {
  140. actor := messageActor(message)
  141. userStateMgr.set(actor, broadcastAwaitingText)
  142. tb.handleBroadcastInput(&message, actor)
  143. }
  144. func swapAlbumDebounce(t *testing.T, d time.Duration) {
  145. t.Helper()
  146. orig := broadcastAlbumDebounce
  147. t.Cleanup(func() { broadcastAlbumDebounce = orig })
  148. broadcastAlbumDebounce = d
  149. }
  150. // waitBroadcastPending polls until the debounce finalizer has stored a draft
  151. // and returns its ids and card token.
  152. func waitBroadcastPending(t *testing.T, actor chatUser) ([]int, string) {
  153. t.Helper()
  154. deadline := time.Now().Add(2 * time.Second)
  155. for time.Now().Before(deadline) {
  156. if ids, token, ok := broadcastPendingDraft(actor); ok {
  157. return ids, token
  158. }
  159. time.Sleep(2 * time.Millisecond)
  160. }
  161. t.Fatal("album draft was never finalized in time")
  162. return nil, ""
  163. }
  164. func TestCollectBroadcastRecipients(t *testing.T) {
  165. tb := newStaleButtonTgbot(t)
  166. setBroadcastAdmins(t, []int64{222})
  167. // 111 appears on both inbounds, 222 is an admin, 0 has no Telegram ID.
  168. createBroadcastInbound(t, "in-1", broadcastClientsJSON(t, 111, 111, 222))
  169. createBroadcastInbound(t, "in-2", broadcastClientsJSON(t, 111, 333, 0, 444))
  170. got := tb.collectBroadcastRecipients()
  171. slices.Sort(got)
  172. if !slices.Equal(got, []int64{111, 333, 444}) {
  173. t.Fatalf("collectBroadcastRecipients() = %v, want [111 333 444]", got)
  174. }
  175. }
  176. func assertBroadcastResult(t *testing.T, got, want broadcastResult) {
  177. t.Helper()
  178. got.Elapsed, want.Elapsed = 0, 0
  179. if got != want {
  180. t.Errorf("result = %+v, want %+v", got, want)
  181. }
  182. }
  183. func TestRunBroadcastCounters(t *testing.T) {
  184. broadcastLocalizer(t)
  185. url, _, _ := newBroadcastMock(t)
  186. swapTestBot(t, url)
  187. setBroadcastRunning(t, true)
  188. blocked := &telegoapi.Error{ErrorCode: 403, Description: "Forbidden: bot was blocked by the user"}
  189. tests := []struct {
  190. name string
  191. recipients []int64
  192. outcomes map[int64]error
  193. delivered int
  194. failed int
  195. skipped int
  196. unreachable int
  197. }{
  198. {"all delivered", []int64{1, 2, 3}, map[int64]error{1: nil, 2: nil, 3: nil}, 3, 0, 0, 0},
  199. {
  200. "a blocked chat is skipped and a transient error fails",
  201. []int64{1, 2, 3, 4},
  202. map[int64]error{1: nil, 2: blocked, 3: nil, 4: errors.New("connection reset")},
  203. 2, 1, 1, 1,
  204. },
  205. }
  206. for _, tt := range tests {
  207. t.Run(tt.name, func(t *testing.T) {
  208. swapBroadcastSender(t, func(chatID int64, _ broadcastDraft) error {
  209. return tt.outcomes[chatID]
  210. }, func(time.Duration) {})
  211. runner := &broadcastRunner{chatID: 100, messageID: 5}
  212. tb := &Tgbot{}
  213. tb.runBroadcast(runner, broadcastDraft{FromChatID: 100, MessageIDs: []int{7}}, tt.recipients)
  214. assertBroadcastResult(t, runner.getResult(), broadcastResult{
  215. Total: len(tt.recipients),
  216. Delivered: tt.delivered,
  217. Failed: tt.failed,
  218. Skipped: tt.skipped,
  219. Unreachable: tt.unreachable,
  220. })
  221. summary := tb.broadcastSummaryText(runner.getResult())
  222. if tt.unreachable == 0 {
  223. if strings.Contains(summary, "press Start") {
  224. t.Errorf("summary = %q, want no unreachable note", summary)
  225. }
  226. } else if !strings.Contains(summary, "1 recipients cannot be messaged") {
  227. t.Errorf("summary = %q, want the unreachable note with the count", summary)
  228. }
  229. })
  230. }
  231. }
  232. func TestRunBroadcastCancelsMidway(t *testing.T) {
  233. url, _, _ := newBroadcastMock(t)
  234. swapTestBot(t, url)
  235. setBroadcastRunning(t, true)
  236. runner := &broadcastRunner{chatID: 100, messageID: 5}
  237. swapBroadcastSender(t, func(chatID int64, _ broadcastDraft) error {
  238. if chatID == 1 {
  239. runner.cancel.Store(true)
  240. }
  241. return nil
  242. }, func(time.Duration) {})
  243. (&Tgbot{}).runBroadcast(runner, broadcastDraft{FromChatID: 100, MessageIDs: []int{7}}, []int64{1, 2, 3, 4, 5})
  244. assertBroadcastResult(t, runner.getResult(), broadcastResult{
  245. Total: 5,
  246. Delivered: 1,
  247. Failed: 0,
  248. Skipped: 4,
  249. Canceled: true,
  250. })
  251. if broadcastCurrentRunner() != nil {
  252. t.Errorf("broadcast slot still registered after the run finished")
  253. }
  254. }
  255. // Regression: a 403 left the progress counter where it was, so a streak of
  256. // unreachable chats at a multiple of broadcastProgressEvery edited the card per chat.
  257. func TestRunBroadcastUnreachableKeepsProgressThrottled(t *testing.T) {
  258. broadcastLocalizer(t)
  259. url, calls, _ := newBroadcastMock(t)
  260. swapTestBot(t, url)
  261. setBroadcastRunning(t, true)
  262. blocked := &telegoapi.Error{ErrorCode: 403, Description: "Forbidden: bot can't initiate conversation with a user"}
  263. swapBroadcastSender(t, func(int64, broadcastDraft) error { return blocked }, func(time.Duration) {})
  264. runner := &broadcastRunner{chatID: 100, messageID: 5}
  265. (&Tgbot{}).runBroadcast(runner, broadcastDraft{FromChatID: 100, MessageIDs: []int{7}}, []int64{1, 2, 3, 4, 5})
  266. // Five recipients sit under both throttle thresholds: only the summary edits the card.
  267. if got := calls("editMessageText"); got != 1 {
  268. t.Errorf("editMessageText calls = %d, want 1 (the summary alone)", got)
  269. }
  270. }
  271. // A long retry_after must not park the runner slot: the wait is slept in
  272. // slices and an abort between them ends the recipient immediately.
  273. func TestBroadcastFloodWaitSlicesLongWaits(t *testing.T) {
  274. flood := &telegoapi.Error{
  275. ErrorCode: 429,
  276. Description: "Too Many Requests: retry after 30",
  277. Parameters: &telegoapi.ResponseParameters{RetryAfter: 30},
  278. }
  279. tests := []struct {
  280. name string
  281. abortAfter int // abort checks answered false before aborting; -1 never aborts
  282. wantPauses int
  283. wantErr string
  284. }{
  285. {"a 30 s wait becomes six 5 s slices", -1, 30, `429 "Too Many Requests: retry after 30", migrate to chat ID: 0, retry after: 30`},
  286. {"an abort between slices ends the wait", 1, 1, errBroadcastAborted.Error()},
  287. }
  288. for _, tt := range tests {
  289. t.Run(tt.name, func(t *testing.T) {
  290. var mu sync.Mutex
  291. var pauses []time.Duration
  292. swapBroadcastSender(t, func(int64, broadcastDraft) error { return flood }, func(d time.Duration) {
  293. mu.Lock()
  294. defer mu.Unlock()
  295. pauses = append(pauses, d)
  296. })
  297. checks := 0
  298. aborted := func() bool {
  299. if tt.abortAfter < 0 {
  300. return false
  301. }
  302. checks++
  303. return checks > tt.abortAfter
  304. }
  305. err := broadcastDeliverOne(9, broadcastDraft{FromChatID: 100, MessageIDs: []int{7}}, aborted)
  306. mu.Lock()
  307. defer mu.Unlock()
  308. if err == nil || err.Error() != tt.wantErr {
  309. t.Errorf("broadcastDeliverOne() error = %v, want %q", err, tt.wantErr)
  310. }
  311. if len(pauses) != tt.wantPauses {
  312. t.Fatalf("pauses = %d slices, want %d", len(pauses), tt.wantPauses)
  313. }
  314. for i, p := range pauses {
  315. if p != broadcastFloodWaitSlice {
  316. t.Errorf("pauses[%d] = %v, want %v", i, p, broadcastFloodWaitSlice)
  317. }
  318. }
  319. })
  320. }
  321. }
  322. // Regression: broadcast state used to survive a stop, leaving an armed album
  323. // timer, a confirmable token and a held runner slot behind.
  324. func TestStopBotResetsBroadcastState(t *testing.T) {
  325. broadcastLocalizer(t)
  326. url, calls, _ := newBroadcastMock(t)
  327. swapTestBot(t, url)
  328. swapAlbumDebounce(t, 20*time.Millisecond)
  329. setBroadcastAdmins(t, []int64{5000})
  330. const chatID = int64(9116)
  331. resetBroadcastState(t)
  332. origRunning := isRunning
  333. t.Cleanup(func() {
  334. tgBotMutex.Lock()
  335. isRunning = origRunning
  336. tgBotMutex.Unlock()
  337. })
  338. composeBroadcast(&Tgbot{}, telego.Message{
  339. Chat: telego.Chat{ID: chatID},
  340. From: &telego.User{ID: 5000},
  341. MessageID: 1,
  342. MediaGroupID: "grpR",
  343. })
  344. runner := broadcastRegisterRunner(chatID)
  345. if runner == nil {
  346. t.Fatal("broadcastRegisterRunner() = nil before the stop")
  347. }
  348. StopBot()
  349. if broadcastCurrentRunner() != nil {
  350. t.Errorf("broadcast slot survived StopBot")
  351. }
  352. if !runner.cancel.Load() {
  353. t.Errorf("the active run was not cancelled on stop")
  354. }
  355. if _, _, ok := broadcastPendingDraft(chatUser{chatID: chatID, userID: 5000}); ok {
  356. t.Errorf("a composition survived StopBot")
  357. }
  358. time.Sleep(60 * time.Millisecond)
  359. if got := calls("copyMessage") + calls("sendMessage"); got != 0 {
  360. t.Errorf("an armed album timer fired after StopBot (%d calls)", got)
  361. }
  362. }
  363. // The per-recipient pause scales with the copied batch size so an album does
  364. // not multiply the messages per second on the wire.
  365. func TestRunBroadcastAlbumPacing(t *testing.T) {
  366. url, _, _ := newBroadcastMock(t)
  367. swapTestBot(t, url)
  368. setBroadcastRunning(t, true)
  369. var pauses []time.Duration
  370. swapBroadcastSender(t, func(int64, broadcastDraft) error { return nil }, func(d time.Duration) {
  371. pauses = append(pauses, d)
  372. })
  373. runner := &broadcastRunner{chatID: 100, messageID: 5}
  374. (&Tgbot{}).runBroadcast(runner, broadcastDraft{FromChatID: 100, MessageIDs: []int{1, 2, 3}}, []int64{1, 2})
  375. if len(pauses) != 1 || pauses[0] != 3*broadcastSendDelay {
  376. t.Errorf("pauses = %v, want one pause of %v for a three-message album", pauses, 3*broadcastSendDelay)
  377. }
  378. }
  379. func TestBroadcastDeliverOneRetries429(t *testing.T) {
  380. flood := func(after int) error {
  381. return &telegoapi.Error{
  382. ErrorCode: 429,
  383. Description: "Too Many Requests: retry after " + fmt.Sprint(after),
  384. Parameters: &telegoapi.ResponseParameters{RetryAfter: after},
  385. }
  386. }
  387. tests := []struct {
  388. name string
  389. responses []error
  390. canceled bool
  391. wantErr string
  392. wantCalls int
  393. wantPauses []time.Duration
  394. }{
  395. {
  396. name: "flood control waits and retries the same recipient",
  397. responses: []error{flood(2), nil},
  398. wantCalls: 2,
  399. wantPauses: []time.Duration{2 * time.Second},
  400. },
  401. {
  402. name: "gives up after the retry budget",
  403. responses: []error{flood(1), flood(1), flood(1), flood(1), flood(1), flood(1), nil},
  404. wantErr: `429 "Too Many Requests: retry after 1", migrate to chat ID: 0, retry after: 1`,
  405. wantCalls: 6,
  406. wantPauses: []time.Duration{time.Second, time.Second, time.Second, time.Second, time.Second},
  407. },
  408. {
  409. name: "non-429 errors are returned without retrying",
  410. responses: []error{errors.New("connection reset")},
  411. wantErr: "connection reset",
  412. wantCalls: 1,
  413. },
  414. {
  415. name: "a cancel during a flood wait abandons the recipient",
  416. responses: []error{flood(2), nil},
  417. canceled: true,
  418. wantErr: errBroadcastAborted.Error(),
  419. wantCalls: 1,
  420. },
  421. }
  422. for _, tt := range tests {
  423. t.Run(tt.name, func(t *testing.T) {
  424. var mu sync.Mutex
  425. callNum := 0
  426. var pauses []time.Duration
  427. swapBroadcastSender(t, func(int64, broadcastDraft) error {
  428. mu.Lock()
  429. defer mu.Unlock()
  430. callNum++
  431. if callNum > len(tt.responses) {
  432. return nil
  433. }
  434. return tt.responses[callNum-1]
  435. }, func(d time.Duration) {
  436. mu.Lock()
  437. defer mu.Unlock()
  438. pauses = append(pauses, d)
  439. })
  440. canceled := func() bool { return tt.canceled }
  441. err := broadcastDeliverOne(9, broadcastDraft{FromChatID: 100, MessageIDs: []int{7}}, canceled)
  442. mu.Lock()
  443. defer mu.Unlock()
  444. if tt.wantErr != "" {
  445. if err == nil || err.Error() != tt.wantErr {
  446. t.Errorf("broadcastDeliverOne() error = %v, want %q", err, tt.wantErr)
  447. }
  448. } else if err != nil {
  449. t.Errorf("broadcastDeliverOne() error = %v, want nil", err)
  450. }
  451. if callNum != tt.wantCalls {
  452. t.Errorf("sender calls = %d, want %d", callNum, tt.wantCalls)
  453. }
  454. if len(pauses) != len(tt.wantPauses) {
  455. t.Fatalf("pauses = %v, want %v", pauses, tt.wantPauses)
  456. }
  457. for i, p := range tt.wantPauses {
  458. if pauses[i] != p {
  459. t.Errorf("pauses[%d] = %v, want %v", i, pauses[i], p)
  460. }
  461. }
  462. })
  463. }
  464. }
  465. func TestBroadcastRegisterRunnerSingleSlot(t *testing.T) {
  466. first := broadcastRegisterRunner(1)
  467. if first == nil {
  468. t.Fatal("broadcastRegisterRunner() = nil for an idle bot")
  469. }
  470. t.Cleanup(func() { broadcastUnregisterRunner(first) })
  471. if second := broadcastRegisterRunner(2); second != nil {
  472. t.Fatalf("broadcastRegisterRunner() = %v while a broadcast is running, want nil", second)
  473. }
  474. broadcastUnregisterRunner(first)
  475. if broadcastCurrentRunner() != nil {
  476. t.Fatalf("slot still registered after unregister")
  477. }
  478. }
  479. func TestStartBroadcastRefusesWhileRunning(t *testing.T) {
  480. broadcastLocalizer(t)
  481. const chatID = int64(9102)
  482. resetBroadcastState(t)
  483. runner := broadcastRegisterRunner(chatID)
  484. t.Cleanup(func() {
  485. broadcastUnregisterRunner(runner)
  486. })
  487. admin := chatUser{chatID: chatID, userID: chatID}
  488. (&Tgbot{}).startBroadcast(admin)
  489. if state, ok := userStateMgr.get(admin); ok {
  490. t.Fatalf("state = %q while a broadcast is running, want none", state)
  491. }
  492. }
  493. func TestBroadcastCommandRequiresAdmin(t *testing.T) {
  494. const chatID = int64(9101)
  495. resetBroadcastState(t)
  496. message := &telego.Message{Chat: telego.Chat{ID: chatID}, From: &telego.User{ID: chatID}, Text: "/broadcast"}
  497. (&Tgbot{}).answerCommand(message, chatID, false)
  498. if state, ok := userStateMgr.get(messageActor(*message)); ok {
  499. t.Fatalf("non-admin /broadcast set state %q", state)
  500. }
  501. if _, _, ok := broadcastPendingDraft(messageActor(*message)); ok {
  502. t.Fatalf("non-admin /broadcast produced a draft")
  503. }
  504. if broadcastCurrentRunner() != nil {
  505. t.Fatalf("non-admin /broadcast started a runner")
  506. }
  507. }
  508. func TestBroadcastStartCommandSetsState(t *testing.T) {
  509. broadcastLocalizer(t)
  510. const chatID = int64(9103)
  511. resetBroadcastState(t)
  512. defer func() {
  513. userStateMgr.reset()
  514. broadcastResetAll()
  515. }()
  516. (&Tgbot{}).answerCommand(&telego.Message{Chat: telego.Chat{ID: chatID}, From: &telego.User{ID: chatID}, Text: "/broadcast"}, chatID, true)
  517. state, ok := userStateMgr.get(chatUser{chatID: chatID, userID: chatID})
  518. if !ok || state != broadcastAwaitingText {
  519. t.Fatalf("state = %q (ok=%v), want %q", state, ok, broadcastAwaitingText)
  520. }
  521. }
  522. func TestDeliverBroadcastCopy(t *testing.T) {
  523. tests := []struct {
  524. name string
  525. draft broadcastDraft
  526. wantMethods map[string]int
  527. check func(t *testing.T, bodies func(string) []map[string]any)
  528. }{
  529. {
  530. name: "a single message rides copyMessage",
  531. draft: broadcastDraft{FromChatID: 55, MessageIDs: []int{7}},
  532. wantMethods: map[string]int{"copyMessage": 1},
  533. check: func(t *testing.T, bodies func(string) []map[string]any) {
  534. body := bodies("copyMessage")[0]
  535. if fmt.Sprint(body["from_chat_id"]) != "55" || fmt.Sprint(body["message_id"]) != "7" {
  536. t.Errorf("copy body = %v, want from 55 message 7", body)
  537. }
  538. },
  539. },
  540. {
  541. name: "an album rides one copyMessages call",
  542. draft: broadcastDraft{FromChatID: 55, MessageIDs: []int{1, 2, 3}},
  543. wantMethods: map[string]int{"copyMessages": 1, "copyMessage": 0},
  544. check: func(t *testing.T, bodies func(string) []map[string]any) {
  545. if fmt.Sprint(bodies("copyMessages")[0]["message_ids"]) != "[1 2 3]" {
  546. t.Errorf("message_ids = %v, want [1 2 3]", bodies("copyMessages")[0]["message_ids"])
  547. }
  548. },
  549. },
  550. }
  551. for _, tt := range tests {
  552. t.Run(tt.name, func(t *testing.T) {
  553. // A fresh mock per case keeps the per-method counts independent.
  554. url, calls, bodies := newBroadcastMock(t)
  555. swapTestBot(t, url)
  556. if err := deliverBroadcastCopy(66, tt.draft); err != nil {
  557. t.Fatalf("deliverBroadcastCopy() error = %v", err)
  558. }
  559. for method, want := range tt.wantMethods {
  560. if got := calls(method); got != want {
  561. t.Errorf("%s calls = %d, want %d", method, got, want)
  562. }
  563. }
  564. if tt.check != nil {
  565. tt.check(t, bodies)
  566. }
  567. })
  568. }
  569. }
  570. // Regression: a media group used to produce one draft per photo, so three
  571. // photos meant three previews and only the last tapped one was delivered.
  572. func TestHandleBroadcastInputMediaGroup(t *testing.T) {
  573. broadcastLocalizer(t)
  574. url, calls, bodies := newBroadcastMock(t)
  575. swapTestBot(t, url)
  576. setBroadcastRunning(t, true)
  577. swapAlbumDebounce(t, 20*time.Millisecond)
  578. tb := newStaleButtonTgbot(t)
  579. setBroadcastAdmins(t, []int64{5000})
  580. const chatID = int64(9109)
  581. resetBroadcastState(t)
  582. createBroadcastInbound(t, "in-1", broadcastClientsJSON(t, 601))
  583. // Updates of one album arrive out of order and copyMessages demands
  584. // strictly increasing ids, so the draft must sort them.
  585. for _, id := range []int{103, 101, 102} {
  586. composeBroadcast(tb, telego.Message{
  587. Chat: telego.Chat{ID: chatID},
  588. From: &telego.User{ID: 5000},
  589. MessageID: id,
  590. MediaGroupID: "grp9",
  591. Photo: []telego.PhotoSize{{FileID: "unused"}},
  592. })
  593. }
  594. ids, token := waitBroadcastPending(t, chatUser{chatID: chatID, userID: 5000})
  595. if !slices.Equal(ids, []int{101, 102, 103}) {
  596. t.Fatalf("album draft ids = %v, want [101 102 103]", ids)
  597. }
  598. if token == "" {
  599. t.Fatalf("album draft has no confirmation token")
  600. }
  601. if state, ok := userStateMgr.get(chatUser{chatID: chatID, userID: 5000}); ok {
  602. t.Errorf("state = %q after the album was accepted, want cleared", state)
  603. }
  604. if got := calls("copyMessages"); got != 1 {
  605. t.Errorf("copyMessages calls = %d, want 1 self-copy of the whole album", got)
  606. }
  607. // copyMessages rejects ids that are not strictly increasing.
  608. if got := fmt.Sprint(bodies("copyMessages")[0]["message_ids"]); got != "[101 102 103]" {
  609. t.Errorf("self-copy message_ids = %v, want [101 102 103]", got)
  610. }
  611. deadline := time.Now().Add(2 * time.Second)
  612. for time.Now().Before(deadline) && calls("sendMessage") == 0 {
  613. time.Sleep(2 * time.Millisecond)
  614. }
  615. if calls("sendMessage") != 1 {
  616. t.Errorf("sendMessage calls = %d, want 1 confirmation card", calls("sendMessage"))
  617. }
  618. }
  619. func TestHandleBroadcastInputSingleMessage(t *testing.T) {
  620. broadcastLocalizer(t)
  621. url, calls, bodies := newBroadcastMock(t)
  622. swapTestBot(t, url)
  623. setBroadcastRunning(t, true)
  624. tb := newStaleButtonTgbot(t)
  625. setBroadcastAdmins(t, []int64{5000})
  626. const chatID = int64(9104)
  627. resetBroadcastState(t)
  628. createBroadcastInbound(t, "in-1", broadcastClientsJSON(t, 602))
  629. composeBroadcast(tb, telego.Message{
  630. Chat: telego.Chat{ID: chatID},
  631. From: &telego.User{ID: 5000},
  632. MessageID: 42,
  633. Text: "hello all",
  634. })
  635. ids, token := waitBroadcastPending(t, chatUser{chatID: chatID, userID: 5000})
  636. if !slices.Equal(ids, []int{42}) {
  637. t.Fatalf("draft ids = %v, want a reference to message 42", ids)
  638. }
  639. if got := calls("copyMessage"); got != 1 {
  640. t.Errorf("copyMessage calls = %d, want 1 self-copy preview", got)
  641. }
  642. card := bodies("sendMessage")[0]
  643. confirmData := card["reply_markup"].(map[string]any)["inline_keyboard"].([]any)[0].([]any)[0].(map[string]any)["callback_data"]
  644. if confirmData != "broadcast_confirm "+token {
  645. t.Errorf("card button = %v, want a confirm bound to the pending token %q", confirmData, token)
  646. }
  647. }
  648. // Regression: tapping Send on a superseded preview card delivered whatever
  649. // draft happened to be pending instead of the card's own composition.
  650. func TestBroadcastConfirmStaleTokenRejected(t *testing.T) {
  651. broadcastLocalizer(t)
  652. url, calls, _ := newBroadcastMock(t)
  653. swapTestBot(t, url)
  654. setBroadcastRunning(t, true)
  655. tb := newStaleButtonTgbot(t)
  656. setBroadcastAdmins(t, []int64{5000})
  657. const chatID = int64(9112)
  658. resetBroadcastState(t)
  659. createBroadcastInbound(t, "in-1", broadcastClientsJSON(t, 603))
  660. composeBroadcast(tb, telego.Message{Chat: telego.Chat{ID: chatID}, From: &telego.User{ID: 5000}, MessageID: 11, Text: "first"})
  661. _, staleToken := waitBroadcastPending(t, chatUser{chatID: chatID, userID: 5000})
  662. // A second composition replaces the first, so the first card goes stale.
  663. composeBroadcast(tb, telego.Message{Chat: telego.Chat{ID: chatID}, From: &telego.User{ID: 5000}, MessageID: 12, Text: "second"})
  664. ids, liveToken := waitBroadcastPending(t, chatUser{chatID: chatID, userID: 5000})
  665. if !slices.Equal(ids, []int{12}) {
  666. t.Fatalf("draft ids = %v, want only the second message", ids)
  667. }
  668. previewCopies := calls("copyMessage")
  669. tb.answerCallback(&telego.CallbackQuery{
  670. ID: "stale",
  671. From: telego.User{ID: 5000},
  672. Data: "broadcast_confirm " + staleToken,
  673. Message: &telego.Message{Chat: telego.Chat{ID: chatID}, MessageID: 5},
  674. }, true)
  675. if calls("copyMessage") != previewCopies {
  676. t.Fatalf("a stale token started deliveries")
  677. }
  678. if broadcastCurrentRunner() != nil {
  679. t.Fatalf("a stale token started a runner")
  680. }
  681. tb.answerCallback(&telego.CallbackQuery{
  682. ID: "live",
  683. From: telego.User{ID: 5000},
  684. Data: "broadcast_confirm " + liveToken,
  685. Message: &telego.Message{Chat: telego.Chat{ID: chatID}, MessageID: 6},
  686. }, true)
  687. waitBroadcastFinished(t)
  688. if calls("copyMessage") != previewCopies+1 {
  689. t.Errorf("copyMessage calls = %d, want %d (the live draft delivered once)", calls("copyMessage"), previewCopies+1)
  690. }
  691. }
  692. // Regression: composition stayed keyed by chat after the state moved to the
  693. // admin, so a second admin's draft in a group dropped the first admin's.
  694. func TestBroadcastComposesArePerAdmin(t *testing.T) {
  695. broadcastLocalizer(t)
  696. url, _, bodies := newBroadcastMock(t)
  697. swapTestBot(t, url)
  698. setBroadcastRunning(t, true)
  699. tb := newStaleButtonTgbot(t)
  700. const groupChat, adminA, adminB = int64(-1009113), int64(5000), int64(5001)
  701. setBroadcastAdmins(t, []int64{adminA, adminB})
  702. resetBroadcastState(t)
  703. createBroadcastInbound(t, "in-1", broadcastClientsJSON(t, 604))
  704. composeBroadcast(tb, telego.Message{Chat: telego.Chat{ID: groupChat}, From: &telego.User{ID: adminA}, MessageID: 21, Text: "from A"})
  705. composeBroadcast(tb, telego.Message{Chat: telego.Chat{ID: groupChat}, From: &telego.User{ID: adminB}, MessageID: 22, Text: "from B"})
  706. cards := bodies("sendMessage")
  707. if len(cards) != 2 {
  708. t.Fatalf("sendMessage calls = %d, want one preview card per admin", len(cards))
  709. }
  710. // Each admin confirms their own card, A first; each run must deliver its own draft.
  711. for i, admin := range []int64{adminA, adminB} {
  712. confirm := cards[i]["reply_markup"].(map[string]any)["inline_keyboard"].([]any)[0].([]any)[0].(map[string]any)["callback_data"].(string)
  713. tb.answerCallback(&telego.CallbackQuery{
  714. ID: "q",
  715. From: telego.User{ID: admin},
  716. Data: confirm,
  717. Message: &telego.Message{Chat: telego.Chat{ID: groupChat}, MessageID: 30 + i},
  718. }, true)
  719. waitBroadcastFinished(t)
  720. }
  721. var delivered []string
  722. for _, body := range bodies("copyMessage") {
  723. if fmt.Sprint(body["chat_id"]) == "604" {
  724. delivered = append(delivered, fmt.Sprint(body["message_id"]))
  725. }
  726. }
  727. if !slices.Equal(delivered, []string{"21", "22"}) {
  728. t.Errorf("messages delivered to the client = %v, want [21 22]: each admin's own draft", delivered)
  729. }
  730. }
  731. func waitBroadcastFinished(t *testing.T) {
  732. t.Helper()
  733. deadline := time.Now().Add(2 * time.Second)
  734. for time.Now().Before(deadline) {
  735. if broadcastCurrentRunner() == nil {
  736. return
  737. }
  738. time.Sleep(2 * time.Millisecond)
  739. }
  740. t.Fatal("broadcast did not finish in time")
  741. }
  742. func TestConfirmBroadcastEndToEnd(t *testing.T) {
  743. broadcastLocalizer(t)
  744. url, calls, _ := newBroadcastMock(t)
  745. swapTestBot(t, url)
  746. setBroadcastRunning(t, true)
  747. tb := newStaleButtonTgbot(t)
  748. setBroadcastAdmins(t, []int64{5000})
  749. const chatID = int64(9105)
  750. resetBroadcastState(t)
  751. createBroadcastInbound(t, "in-1", broadcastClientsJSON(t, 501, 502))
  752. composeBroadcast(tb, telego.Message{Chat: telego.Chat{ID: chatID}, From: &telego.User{ID: 5000}, MessageID: 9, Text: "hi"})
  753. _, token := waitBroadcastPending(t, chatUser{chatID: chatID, userID: 5000})
  754. tb.answerCallback(&telego.CallbackQuery{
  755. ID: "q1",
  756. From: telego.User{ID: 5000},
  757. Data: "broadcast_confirm " + token,
  758. Message: &telego.Message{Chat: telego.Chat{ID: chatID}, MessageID: 5},
  759. }, true)
  760. waitBroadcastFinished(t)
  761. // One preview self-copy plus two deliveries; the card is edited into the
  762. // progress card and then into the summary, so nothing is sent twice.
  763. if got := calls("copyMessage"); got != 3 {
  764. t.Errorf("copyMessage calls = %d, want 3 (preview + 2 deliveries)", got)
  765. }
  766. if got := calls("sendMessage"); got != 1 {
  767. t.Errorf("sendMessage calls = %d, want 1 confirmation card", got)
  768. }
  769. if got := calls("editMessageText"); got != 2 {
  770. t.Errorf("editMessageText calls = %d, want 2 (progress + summary)", got)
  771. }
  772. if got := calls("answerCallbackQuery"); got != 1 {
  773. t.Errorf("answerCallbackQuery calls = %d, want 1", got)
  774. }
  775. }
  776. func TestConfirmBroadcastWithoutDraftAnswersError(t *testing.T) {
  777. url, calls, _ := newBroadcastMock(t)
  778. swapTestBot(t, url)
  779. tb := newStaleButtonTgbot(t)
  780. const chatID = int64(9106)
  781. resetBroadcastState(t)
  782. tb.answerCallback(&telego.CallbackQuery{
  783. ID: "q1",
  784. From: telego.User{ID: chatID},
  785. Data: "broadcast_confirm sometoken",
  786. Message: &telego.Message{Chat: telego.Chat{ID: chatID}, MessageID: 5},
  787. }, true)
  788. if calls("answerCallbackQuery") != 1 {
  789. t.Errorf("answerCallbackQuery calls = %d, want 1 error answer", calls("answerCallbackQuery"))
  790. }
  791. if broadcastCurrentRunner() != nil {
  792. t.Errorf("a confirm without a draft must not start a broadcast")
  793. }
  794. }
  795. func TestBroadcastCancelCallbackClearsDraft(t *testing.T) {
  796. url, calls, _ := newBroadcastMock(t)
  797. swapTestBot(t, url)
  798. tb := newStaleButtonTgbot(t)
  799. const chatID = int64(9107)
  800. resetBroadcastState(t)
  801. admin := chatUser{chatID: chatID, userID: chatID}
  802. userStateMgr.set(admin, broadcastAwaitingText)
  803. broadcastComposes[admin] = &broadcastCompose{messageIDs: []int{9}, token: "tok9"}
  804. tb.answerCallback(&telego.CallbackQuery{
  805. ID: "q1",
  806. From: telego.User{ID: chatID},
  807. Data: "broadcast_cancel",
  808. Message: &telego.Message{Chat: telego.Chat{ID: chatID}, MessageID: 9},
  809. }, true)
  810. if _, ok := userStateMgr.get(admin); ok {
  811. t.Errorf("state survived the cancel tap")
  812. }
  813. if _, _, ok := broadcastPendingDraft(admin); ok {
  814. t.Errorf("draft survived the cancel tap")
  815. }
  816. if got := calls("deleteMessage"); got != 1 {
  817. t.Errorf("deleteMessage calls = %d, want 1", got)
  818. }
  819. if got := calls("answerCallbackQuery"); got != 1 {
  820. t.Errorf("answerCallbackQuery calls = %d, want 1", got)
  821. }
  822. }
  823. func TestBroadcastCallbacksDeniedToNonAdmin(t *testing.T) {
  824. url, calls, _ := newBroadcastMock(t)
  825. swapTestBot(t, url)
  826. tb := newStaleButtonTgbot(t)
  827. const chatID = int64(9108)
  828. resetBroadcastState(t)
  829. for _, data := range []string{"broadcast_confirm sometoken", "broadcast_cancel"} {
  830. tb.answerCallback(&telego.CallbackQuery{
  831. ID: "q1",
  832. From: telego.User{ID: 999999},
  833. Data: data,
  834. Message: &telego.Message{Chat: telego.Chat{ID: chatID}, MessageID: 5},
  835. }, false)
  836. if calls("answerCallbackQuery") != 0 {
  837. t.Fatalf("%s answered a non-admin callback", data)
  838. }
  839. if broadcastCurrentRunner() != nil {
  840. t.Fatalf("%s started a broadcast for a non-admin", data)
  841. }
  842. }
  843. }