-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.go
More file actions
1545 lines (1414 loc) · 47.6 KB
/
Copy pathapp.go
File metadata and controls
1545 lines (1414 loc) · 47.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"fmt"
"strings"
"time"
"github.com/charmbracelet/bubbles/progress"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
)
// screen is the current top-level view of the app.
type screen int
const (
scHome screen = iota
scConfigure
scChannels
scTypes
scConfirm
scRunning
)
// chanScope selects which channel set the shared tree selector (scChannels)
// drives: the message channels or the reaction channels.
type chanScope int
const (
scopeMessages chanScope = iota
scopeReactions
)
// runConfig holds every tunable, mirroring the CLI flags. The TUI edits these
// live; nothing here is required except (for a real run) a token.
type runConfig struct {
order string // "oldest" | "newest"
content string
afterSnow string // from --after (CLI only)
beforeSnow string // from --before (CLI only)
afterDate string
beforeDate string
last string
typeSel map[string]bool // selected message-type ids (nil/empty = any)
workers int
delay float64
jitter float64
maxRPS float64
token string
execute bool
ntfy string // ntfy topic or full URL for a completion ping ("" = off)
notifyEvery time.Duration // push a progress ntfy this often during a run (0 = completion only)
remember bool // persist the token locally (keychain / encrypted file)
// dual-mode: what to delete, from what the package contains
delMessages bool // run the message phase
delReactions bool // run the reaction phase
reactionsFirst bool // reaction phase runs before messages
reactionDelay float64 // per-channel spacing floor for reactions (seconds)
}
// appModel is the whole TUI: a small state machine over the screens above,
// sharing one loaded package and one live-filtered preview.
type appModel struct {
screen screen
raws []RawChannel
pkgName string
cfg runConfig
selected map[string]bool // channelID -> included
// live preview (recomputed whenever the filter changes)
jobs []ChannelJob
total int
perr string // filter/parse error to surface
// configure screen
fcursor int
editing bool
input textinput.Model
advanced bool
// token validation (async /users/@me probe)
tokenState tokenState
tokenUser string
tokenErr string
tokenID string // the token account's user id (for owner-match check)
tokenHandle string // unique @handle, for the mismatch note
// package owner (from account/user.json); "" if the package didn't record it
ownerID string
ownerName string
ownerHandle string // unique @handle, for the mismatch note
// update notice (async; see update.go)
updateCh <-chan string
updateLine string // "" until a newer version is found
// guild membership for the 403 rollup, fetched once per run
members map[string]bool
membersLoaded bool
// opt-in token storage (keychain / encrypted file), keyed per account
stateKey string // account key for the store (same as the resume-log key)
savedToken string // the token value currently persisted, to avoid re-saving
tokenFromStore bool
storeNote string // short status from the last save/forget, shown in Configure
// ntfy test ping: result of the notification sent when the topic is entered
ntfyNote string
// crash-safe resume: already-deleted message IDs from prior runs, and the
// per-package log the engine appends to during a real run.
done map[string]bool
progPath string
progLog *progressLog
resumed int // count of package messages already deleted in a prior run
// reactions (from Activity/reporting), parallel to the message fields
caps PackageCapabilities
reactions []Reaction
guildNames map[string]string
reactSelected map[string]bool // reaction channel ids -> included
reactGuilds []guildGroup // guild-grouped reaction channels for the selector
reactRaws []RawChannel // synthetic channels backing the reaction selector
reactJobs []ChannelJob
reactTotal int
reactDone map[string]bool // reaction keys removed in a prior run
reactProgPath string
// two-phase run state (messages phase, reactions phase)
runCtx context.Context
phases []phasePlan
phaseIdx int
phaseResults []opResult
// browser sign-in (async Chrome-launch capture)
browserActive bool
browserErr string
browserCancel context.CancelFunc
// channels screen (shared by the message and reaction selectors)
chanScope chanScope
guilds []guildGroup
ccursor int
search textinput.Model
// message-type screen
tcursor int
typeCounts map[string]int // static per-type message tallies
// running screen
stats *Stats
eng *Engine // live handle for pause/resume + pacing hotkeys
paused bool
cancel context.CancelFunc
prog progress.Model
started bool
rateHist []float64 // recent deletions/sec samples for the sparkline
logWarn string // resume-log failure notice; "" while the log is healthy
cfb *cfBudget // Cloudflare invalid-response window; one per process, not per phase
// ntfy progress + remote control (execute runs with ntfy set)
lastNotify time.Time // when the last progress ntfy went out
controlCh chan controlCmd // pause/resume/stop from the phone; nil = control off
controlOn bool
stopping bool // stop taken; finalize instead of advancing to the next phase
pausePend bool // pause taken at a phase boundary; applied to the next phase's engine
// end-of-run finalization (report file + optional ntfy ping), fired once
startedAt time.Time
reported bool
reportPath string // where the run report was written ("" = not yet / failed)
reportOverride string // --report path; "" = default alongside the resume log
notifyResult string // short outcome of the ntfy ping, shown on the final frame
openErr string // last failure from opening the report
width, height int
quitting bool
}
// guildGroup buckets channels under a server (or the synthetic DM group).
type guildGroup struct {
id string
name string
isDM bool
open bool
chans []int // indices into m.raws
msgSum int
}
func newAppModel(raws []RawChannel, cfg runConfig, sel map[string]bool, pkgName string) *appModel {
ti := textinput.New()
ti.Prompt = "› "
sr := textinput.New()
sr.Prompt = "/ "
sr.Placeholder = "filter channels…"
staticCursorForDemo(&ti)
staticCursorForDemo(&sr)
p := progress.New(progress.WithGradient(nord7, nord8), progress.WithWidth(50), progress.WithoutPercentage())
m := &appModel{
screen: scHome,
raws: raws,
pkgName: pkgName,
cfg: cfg,
selected: sel,
input: ti,
search: sr,
prog: p,
width: 90,
height: 30,
cfb: newCFBudget(),
}
// Messages are known at construction; reactions arrive later via setReactions.
m.caps.HasMessages = len(raws) > 0
m.typeCounts = countTypes(raws)
m.buildGuilds()
m.recompute()
return m
}
// Init validates a token supplied up front (via --token or DISCORD_TOKEN) so
// the home screen shows "logged in as X", and collects the update notice.
func (m *appModel) Init() tea.Cmd {
return tea.Batch(m.startTokenCheck(), awaitUpdateNotice(m.updateCh))
}
// updateNoticeMsg carries the update-check result to the home screen.
type updateNoticeMsg string
// awaitUpdateNotice delivers the update-check result, or nothing when no check
// was started (tests build the model directly).
func awaitUpdateNotice(ch <-chan string) tea.Cmd {
if ch == nil {
return nil
}
return func() tea.Msg { return updateNoticeMsg(<-ch) }
}
// --- preview ---------------------------------------------------------------
func (m *appModel) selectedSet() map[string]bool {
return selectionSet(m.raws, m.selected)
}
// reactSelectedSet is selectedSet for the reaction channel selector.
func (m *appModel) reactSelectedSet() map[string]bool {
return selectionSet(m.reactRaws, m.reactSelected)
}
// scopeRaws / scopeSelected / scopeGuilds return the channel set the tree
// selector currently operates on. The returned slices/maps are the model's own
// (not copies), so mutating an element (a guild's open flag, a selection bit)
// edits the live state.
func (m *appModel) scopeRaws() []RawChannel {
if m.chanScope == scopeReactions {
return m.reactRaws
}
return m.raws
}
func (m *appModel) scopeSelected() map[string]bool {
if m.chanScope == scopeReactions {
return m.reactSelected
}
return m.selected
}
func (m *appModel) scopeGuilds() []guildGroup {
if m.chanScope == scopeReactions {
return m.reactGuilds
}
return m.guilds
}
// scopeNoun labels the per-channel count in the current scope's tree.
func (m *appModel) scopeNoun() string {
if m.chanScope == scopeReactions {
return "reactions"
}
return "msgs"
}
// countSelected tallies how many of raws are selected.
func countSelected(raws []RawChannel, sel map[string]bool) (selected, total int) {
for _, rc := range raws {
total++
if sel[rc.ChannelID] {
selected++
}
}
return
}
// reactSelectionCounts is selectionCounts for the reaction channel selector.
func (m *appModel) reactSelectionCounts() (selected, total int) {
return countSelected(m.reactRaws, m.reactSelected)
}
// scopeSelectionCounts is selectionCounts for whichever tree is on screen.
func (m *appModel) scopeSelectionCounts() (selected, total int) {
return countSelected(m.scopeRaws(), m.scopeSelected())
}
// recompute refreshes both the message and reaction previews from the filters.
func (m *appModel) recompute() {
m.recomputeMessages()
m.recomputeReactions()
}
func (m *appModel) recomputeMessages() {
bounds, err := resolveBounds(m.cfg.afterSnow, m.cfg.beforeSnow, m.cfg.afterDate, m.cfg.beforeDate, m.cfg.last, time.Now())
if err != nil {
m.perr = err.Error()
m.jobs, m.total = nil, 0
return
}
substr, re, err := compileContentFilter(m.cfg.content)
if err != nil {
m.perr = err.Error()
m.jobs, m.total = nil, 0
return
}
m.perr = ""
f := Filter{
Content: substr,
ContentRe: re,
AfterID: bounds.AfterID,
BeforeID: bounds.BeforeID,
Order: m.cfg.order,
Channels: m.selectedSet(),
Types: typesMask(m.cfg.typeSel),
Done: m.done,
}
m.jobs, m.total = ApplyFilter(m.raws, f)
}
// recomputeReactions refreshes the reaction preview. Reactions share the date and
// order filters with messages, plus their own channel selection and resume set.
func (m *appModel) recomputeReactions() {
if !m.caps.HasReactions {
m.reactJobs, m.reactTotal = nil, 0
return
}
bounds, err := resolveBounds(m.cfg.afterSnow, m.cfg.beforeSnow, m.cfg.afterDate, m.cfg.beforeDate, m.cfg.last, time.Now())
if err != nil {
m.reactJobs, m.reactTotal = nil, 0
return
}
f := Filter{
AfterID: bounds.AfterID,
BeforeID: bounds.BeforeID,
Order: m.cfg.order,
Channels: m.reactSelectedSet(),
Done: m.reactDone,
}
m.reactJobs, m.reactTotal = ApplyReactionFilter(m.reactions, f, m.guildNames)
}
// setReactions installs the reaction data on the model and builds the reaction
// channel selector, then defaults the delete targets from what the package has.
func (m *appModel) setReactions(reactions []Reaction, guildNames map[string]string, caps PackageCapabilities, reactProgPath string) {
m.caps = caps
m.reactions = reactions
m.guildNames = guildNames
m.reactProgPath = reactProgPath
m.reactDone = loadProgressSet(reactProgPath)
m.reactRaws = reactionRawChannels(reactions, guildNames)
m.reactGuilds = groupGuilds(m.reactRaws)
m.reactSelected = map[string]bool{}
for _, rc := range m.reactRaws {
m.reactSelected[rc.ChannelID] = true
}
m.cfg.delMessages = caps.HasMessages
m.cfg.delReactions = caps.HasReactions && !caps.HasMessages
m.recompute()
}
// maybeSaveToken persists the current token to the OS keyring when "remember" is
// on and the token validated, deduping against what's already stored.
func (m *appModel) maybeSaveToken() {
tok := strings.TrimSpace(m.cfg.token)
if !m.cfg.remember || m.stateKey == "" || tok == "" || tok == m.savedToken {
return
}
if m.tokenState != tsValid {
return // only ever store a token we've confirmed works
}
backend, err := saveToken(m.stateKey, tok)
if err != nil {
m.storeNote = "not remembered: " + err.Error()
return
}
m.savedToken = tok
m.storeNote = "token remembered (" + backend + ")"
}
// forgetStoredToken removes any persisted token for this account.
func (m *appModel) forgetStoredToken() {
if m.stateKey == "" {
return
}
if err := forgetToken(m.stateKey); err != nil {
m.storeNote = "forget failed: " + err.Error()
return
}
m.savedToken, m.tokenFromStore = "", false
m.storeNote = "stored token forgotten"
}
// resetDefaults restores every config knob to its default and re-selects all
// channels, keeping the token (a credential, not config) and its check state.
func (m *appModel) resetDefaults() {
tok := m.cfg.token
m.cfg = defaultRunConfig()
m.cfg.token = tok
// Re-select everything in both trees, independent of which selector was last
// open, and restore the capability-derived delete targets.
for _, rc := range m.raws {
m.selected[rc.ChannelID] = true
}
for _, rc := range m.reactRaws {
m.reactSelected[rc.ChannelID] = true
}
m.cfg.delMessages = m.caps.HasMessages
m.cfg.delReactions = m.caps.HasReactions && !m.caps.HasMessages
m.fcursor = 0
m.perr = ""
m.recompute()
}
func (m *appModel) previewETA() time.Duration {
return estimate(m.jobs, m.cfg.workers, time.Duration(m.cfg.delay*float64(time.Second)))
}
// --- top-level Update ------------------------------------------------------
func (m *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
m.prog.Width = clampInt(msg.Width-20, 20, 70)
return m, nil
case tickMsg:
if m.screen == scRunning {
snap := m.stats.Snapshot()
m.rateHist = append(m.rateHist, snap.Rate)
if len(m.rateHist) > 120 {
m.rateHist = m.rateHist[len(m.rateHist)-120:]
}
m.noteLogErr()
if snap.Finished || snap.Aborted {
if m.reported {
return m, nil
}
// Record this phase's result. Then either advance to the next
// phase, or (on the last phase, an abort, or a stop) finalize
// once. A stop ends the whole run, not just the phase: the next
// phase would start on the already-cancelled context.
m.phaseResults = append(m.phaseResults, m.phaseResult(snap))
if m.progLog != nil {
m.progLog.close()
m.noteLogErr()
m.progLog = nil
}
if snap.Aborted || !snap.Completed || m.stopping || m.phaseIdx >= len(m.phases)-1 {
m.reported = true
return m, m.finalizeRun()
}
m.phaseIdx++
return m, m.startPhase(m.phaseIdx)
}
cmds := []tea.Cmd{doTick()}
if c := m.maybePeriodicNotify(); c != nil {
cmds = append(cmds, c)
}
return m, tea.Batch(cmds...)
}
return m, nil
case controlMsg:
return m.applyControl(msg.cmd)
case notifyDoneMsg:
if msg.err != nil {
m.notifyResult = "notify failed: " + msg.err.Error()
} else if strings.TrimSpace(m.cfg.ntfy) != "" {
m.notifyResult = "notified via ntfy"
}
return m, nil
case openDoneMsg:
if msg.err != nil {
m.openErr = "could not open " + msg.path + ": " + msg.err.Error()
}
return m, nil
case ntfyTestMsg:
if msg.err != nil {
m.ntfyNote = "test notification failed: " + msg.err.Error()
} else {
m.ntfyNote = "test notification sent; check your ntfy app"
}
return m, nil
case tokenCheckMsg:
m.applyTokenCheck(msg)
return m, nil
case updateNoticeMsg:
m.updateLine = string(msg)
return m, nil
case browserSigninMsg:
return m, m.applyBrowserSignin(msg)
}
switch m.screen {
case scHome:
return m.updateHome(msg)
case scConfigure:
return m.updateConfigure(msg)
case scChannels:
return m.updateChannels(msg)
case scTypes:
return m.updateTypes(msg)
case scConfirm:
return m.updateConfirm(msg)
case scRunning:
return m.updateRunning(msg)
}
return m, nil
}
func (m *appModel) View() string {
switch m.screen {
case scConfigure:
return m.viewConfigure()
case scChannels:
return m.viewChannels()
case scTypes:
return m.viewTypes()
case scConfirm:
return m.viewConfirm()
case scRunning:
frame, _ := m.viewRunning()
return frame
default:
return m.viewHome()
}
}
// --- home ------------------------------------------------------------------
func (m *appModel) updateHome(msg tea.Msg) (tea.Model, tea.Cmd) {
key, ok := msg.(tea.KeyMsg)
if !ok {
return m, nil
}
switch key.String() {
case "q", "ctrl+c":
m.quitting = true
return m, tea.Quit
case "c":
m.screen = scConfigure
return m, nil
case "e":
m.toggleExecute()
return m, nil
case "enter", "s":
return m.startRun()
}
return m, nil
}
// toggleExecute flips dry-run/execute, refusing execute without a token (or with
// one Discord has already told us is invalid).
func (m *appModel) toggleExecute() {
if !m.cfg.execute {
if reason := m.executeGuard(); reason != "" {
m.perr = reason
return
}
}
m.cfg.execute = !m.cfg.execute
m.perr = ""
}
func (m *appModel) startRun() (tea.Model, tea.Cmd) {
// Startable when ANY enabled phase has work; gating on the message count
// alone would make a reactions-only run unreachable.
msgWork := m.cfg.delMessages && m.total > 0
reactWork := m.cfg.delReactions && m.reactTotal > 0
if !msgWork && !reactWork {
m.perr = "Nothing matches the current filters."
return m, nil
}
if m.cfg.execute {
if reason := m.executeGuard(); reason != "" {
m.perr = reason
return m, nil
}
m.screen = scConfirm
return m, nil
}
return m.launchEngine()
}
// phasePlan is one phase of a run (messages or reactions), with its jobs, the
// per-channel floor, and the resume log it appends to.
type phasePlan struct {
kind string
jobs []ChannelJob
total int
floor time.Duration
logPath string
}
// buildPhases assembles the run's phases from the selected targets, in the
// configured order (messages first by default).
func (m *appModel) buildPhases() []phasePlan {
var msg, react *phasePlan
if m.cfg.delMessages && m.total > 0 {
msg = &phasePlan{
kind: "messages", jobs: m.jobs, total: m.total,
floor: time.Duration(m.cfg.delay * float64(time.Second)), logPath: m.progPath,
}
}
if m.cfg.delReactions && m.reactTotal > 0 {
react = &phasePlan{
kind: "reactions", jobs: m.reactJobs, total: m.reactTotal,
floor: time.Duration(m.cfg.reactionDelay * float64(time.Second)), logPath: m.reactProgPath,
}
}
first, second := msg, react
if m.cfg.reactionsFirst {
first, second = react, msg
}
var out []phasePlan
if first != nil {
out = append(out, *first)
}
if second != nil {
out = append(out, *second)
}
return out
}
// launchEngine starts the run: builds the phases and starts the first one, plus
// the ntfy remote-control subscriber for the whole run.
func (m *appModel) launchEngine() (tea.Model, tea.Cmd) {
m.phases = m.buildPhases()
if len(m.phases) == 0 {
m.perr = "Nothing selected to delete."
return m, nil
}
ctx, cancel := context.WithCancel(context.Background())
m.cancel = cancel
m.runCtx = ctx
m.phaseIdx = 0
m.phaseResults = nil
m.members, m.membersLoaded = nil, false // refetched once per run
m.started = true
m.startedAt = time.Now()
m.reported = false
m.stopping, m.pausePend = false, false
m.reportPath, m.notifyResult, m.logWarn = "", "", ""
m.openErr = ""
m.screen = scRunning
// Remote control (pause/resume/stop from the phone) rides the same ntfy
// topic, on a derived control sub-topic, for the whole run.
m.controlCh, m.controlOn = nil, false
var cmds []tea.Cmd
if target := resolveNtfyURL(m.cfg.ntfy); m.cfg.execute && target != "" {
if ctl := controlTarget(target); ctl != "" {
ch := make(chan controlCmd, 8)
m.controlCh, m.controlOn = ch, true
go subscribeControl(ctx, ctl, func(c controlCmd) {
select {
case ch <- c:
case <-ctx.Done():
}
})
cmds = append(cmds, waitControl(ch))
}
}
cmds = append(cmds, m.startPhase(0))
return m, tea.Batch(cmds...)
}
// startPhase spins up the engine for phase i, closing any previous phase's log.
func (m *appModel) startPhase(i int) tea.Cmd {
p := m.phases[i]
m.stats = NewStats(p.total, m.cfg.workers)
m.rateHist = nil // each phase gets its own sparkline history
if m.progLog != nil {
m.progLog.close()
m.progLog = nil
}
var onDeleted func(string)
if m.cfg.execute && p.logPath != "" {
if pl, err := openProgressLog(p.logPath); err == nil {
m.progLog = pl
onDeleted = pl.record
} else {
// executeGuard probed this log before the run, so this only happens
// on mid-run breakage; warn and carry on.
m.logWarn = "resume log unavailable (" + err.Error() + "): this phase's deletions will be re-attempted on the next run"
}
}
minInterval := time.Duration(float64(time.Second) / clampFloat(m.cfg.maxRPS, 1, 49))
m.eng = NewEngine(EngineConfig{
Token: strings.TrimSpace(m.cfg.token),
Workers: m.cfg.workers,
DeleteDelay: p.floor,
Jitter: m.cfg.jitter,
DryRun: !m.cfg.execute,
GlobalMinInterval: minInterval,
OnDeleted: onDeleted,
CF: m.cfb,
}, m.stats)
m.paused = m.pausePend && m.cfg.execute
m.pausePend = false
m.eng.setPaused(m.paused)
m.lastNotify = time.Now()
go m.eng.Run(m.runCtx, p.jobs)
if m.paused {
// The pause was taken at the boundary with no engine to hold it; confirm
// it to the phone now that one does.
return tea.Batch(doTick(), m.progressNotifyCmd(true))
}
return doTick()
}
// noteLogErr surfaces the resume log's first write failure on the running
// screen. bufio's error is sticky: nothing is recorded after it, so those
// deletions repeat on the next run while this one keeps going.
func (m *appModel) noteLogErr() {
if m.logWarn != "" || m.progLog == nil {
return
}
if err := m.progLog.writeErr(); err != nil {
m.logWarn = "resume log write failed (" + err.Error() + "): deletions from that point on will be re-attempted on the next run"
}
}
// phaseResult captures a finished phase's outcome, resolving its channels to
// servers for the undeletable rollup.
func (m *appModel) phaseResult(snap Snapshot) opResult {
kind := m.phases[m.phaseIdx].kind
meta := metaFromRaws(m.raws)
if kind == "reactions" {
meta = metaFromReactions(m.reactions, m.guildNames)
}
return opResult{
Kind: kind,
Snap: snap,
Collapsed: snap.ActiveLimit >= 1 && snap.ActiveLimit < len(snap.Workers),
Forbidden: m.forbiddenServers(snap, meta),
}
}
// controlMsg carries a remote command from the ntfy control topic into the
// Bubble Tea loop, so it's applied on the UI goroutine like a keypress.
type controlMsg struct{ cmd controlCmd }
// waitControl blocks on the control channel and delivers the next command. It's
// re-armed after each command so the stream keeps flowing while the run is live.
func waitControl(ch chan controlCmd) tea.Cmd {
return func() tea.Msg {
c, ok := <-ch
if !ok {
return nil
}
return controlMsg{cmd: c}
}
}
// rearmControl re-issues the control listener, or nil if control isn't active.
func (m *appModel) rearmControl() tea.Cmd {
if m.controlOn && m.controlCh != nil {
return waitControl(m.controlCh)
}
return nil
}
// applyControl handles a remote pause/resume/stop, mirroring the p/stop hotkeys,
// and re-arms the listener so more commands arrive.
func (m *appModel) applyControl(c controlCmd) (tea.Model, tea.Cmd) {
if m.screen != scRunning || m.eng == nil || m.reported {
return m, m.rearmControl()
}
// Between a phase finishing and the tick that starts the next one there is
// no live engine, so pause and stop are held for the next phase rather than
// dropped: the run would otherwise keep deleting past a stop the user
// believes took effect.
boundary := m.atPhaseBoundary()
var out tea.Cmd
switch c {
case cmdPause:
switch {
case !m.cfg.execute:
case boundary:
m.pausePend = true
case !m.eng.isPaused():
m.eng.setPaused(true)
m.paused = true
m.lastNotify = time.Now()
out = m.progressNotifyCmd(true)
}
case cmdResume:
switch {
case !m.cfg.execute:
case boundary:
m.pausePend = false
case m.eng.isPaused():
m.eng.setPaused(false)
m.paused = false
m.lastNotify = time.Now()
out = m.progressNotifyCmd(false)
}
case cmdStop:
// Wind the run down; the finished tick writes the report and fires the
// completion ping. The final frame stays until the user leaves.
m.stopping = true
if m.cancel != nil {
m.cancel()
}
}
return m, tea.Batch(out, m.rearmControl())
}
// atPhaseBoundary reports whether the phase's engine has wound down, leaving no
// live engine for a control command to act on.
func (m *appModel) atPhaseBoundary() bool {
if m.stats == nil {
return true
}
snap := m.stats.Snapshot()
return snap.Finished || snap.Aborted
}
// maybePeriodicNotify fires a progress ntfy once the interval has elapsed.
func (m *appModel) maybePeriodicNotify() tea.Cmd {
if !m.cfg.execute || m.cfg.notifyEvery <= 0 || resolveNtfyURL(m.cfg.ntfy) == "" {
return nil
}
if time.Since(m.lastNotify) < m.cfg.notifyEvery {
return nil
}
m.lastNotify = time.Now()
return m.progressNotifyCmd(m.eng != nil && m.eng.isPaused())
}
// progressNotifyCmd posts a live progress/pause notification in the background.
// It reports nothing back (nil msg), so the final-frame notify result is left to
// the completion ping.
func (m *appModel) progressNotifyCmd(paused bool) tea.Cmd {
target := resolveNtfyURL(m.cfg.ntfy)
if target == "" || !m.cfg.execute || m.stats == nil {
return nil
}
msg := runningNtfy(m.pkgName, m.stats.Snapshot(), paused, controlTarget(target))
return func() tea.Msg {
_ = postNtfy(context.Background(), target, msg)
return nil
}
}
// notifyExit sends a final "stopped" notification synchronously on a manual quit.
// tea.Quit won't run async commands, so this is bounded and best-effort:
// the quit never hangs on the network.
func (m *appModel) notifyExit() {
target := resolveNtfyURL(m.cfg.ntfy)
if target == "" || m.stats == nil {
return
}
// Report finished phases plus the in-flight one under its real kind, so a
// quit mid-reactions isn't pushed as "N messages deleted".
results := append([]opResult{}, m.phaseResults...)
kind := "messages"
if m.phaseIdx >= 0 && m.phaseIdx < len(m.phases) {
kind = m.phases[m.phaseIdx].kind
}
results = append(results, opResult{Kind: kind, Snap: m.stats.Snapshot()})
r := runReport{
Package: m.pkgName,
Execute: m.cfg.execute,
StartedAt: m.startedAt,
EndedAt: time.Now(),
Results: results,
}
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
_ = sendNtfy(ctx, target, r.notifyTitle(), r.notifyBody(), r.notifyPriority(), r.notifyTags())
}
// finalizeRun writes the end-of-run report and returns a command that fires the
// ntfy ping (async, so a slow network never freezes the final frame). Called
// exactly once, when the engine reports finished/aborted.
func (m *appModel) finalizeRun() tea.Cmd {
r := runReport{
Package: m.pkgName,
Execute: m.cfg.execute,
StartedAt: m.startedAt,
EndedAt: time.Now(),
Results: m.phaseResults,
Resumed: m.resumed,
}
cmds := []tea.Cmd{notifyCmd(resolveNtfyURL(m.cfg.ntfy), r)}
if path := r.destPath(m.reportOverride, m.reportProgPath()); path != "" {
if err := writeRunReport(path, r); err == nil {
m.reportPath = path
// Only now: during the run the terminal keeps the mouse, so
// selecting text works as usual.
cmds = append(cmds, tea.EnableMouseCellMotion)
}
}
return tea.Batch(cmds...)
}
// clickReport answers a plain click on the final frame's button, which the OSC 8
// link cannot: terminals reserve that for ctrl/cmd+click.
func (m *appModel) clickReport(msg tea.MouseMsg) tea.Cmd {
if msg.Action != tea.MouseActionPress || msg.Button != tea.MouseButtonLeft || m.reportPath == "" {
return nil
}
// Rendering again to find the button is sound because a paint follows every
// update, and the values still moving once a run has finished (elapsed, rate)
// sit in fixed-width cells, so the row the button lands on cannot shift.
if _, hit := m.viewRunning(); !hit.contains(msg.X, msg.Y) {
return nil
}
return m.openReportCmd()
}
// openReportCmd opens the report as a command rather than inline, so a handler
// that takes its time resolving cannot hold up the frame; the outcome arrives
// as openDoneMsg. The path is copied because the model may move on before the
// command runs.
func (m *appModel) openReportCmd() tea.Cmd {
m.openErr = ""
return openReport(m.reportPath)
}
// reportProgPath is the resume log the report path is derived from: the message
// log if a message phase ran, else the reaction log.
func (m *appModel) reportProgPath() string {
if m.progPath != "" {
return m.progPath
}
return m.reactProgPath
}
// forbiddenServers rolls undeletable (403) messages up to their servers for the
// report. When any exist on a real run, one guilds call (time-boxed) labels each
// server as left or still-joined; a dry run or a missing token skips the labels.
func (m *appModel) forbiddenServers(snap Snapshot, meta map[string]chanMeta) []forbiddenServer {
if len(snap.Forbidden) == 0 {
return nil
}
if tok := strings.TrimSpace(m.cfg.token); m.cfg.execute && tok != "" && !m.membersLoaded {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
m.members = fetchGuildMembership(ctx, tok)
cancel()
m.membersLoaded = true
}
return forbiddenByServer(snap.Forbidden, meta, m.members)
}
// notifyCmd posts the completion ping in the background, reporting the outcome
// back as a notifyDoneMsg.
func notifyCmd(target string, r runReport) tea.Cmd {
if target == "" {
return nil
}
return func() tea.Msg {
err := sendNtfy(context.Background(), target, r.notifyTitle(), r.notifyBody(), r.notifyPriority(), r.notifyTags())
return notifyDoneMsg{err: err}
}
}
type notifyDoneMsg struct{ err error }
// openDoneMsg carries the outcome of openReportCmd. It names the path it tried
// so a stale command reports the file the user actually clicked.
type openDoneMsg struct {
path string
err error
}
// finishRun closes the progress log and reloads the done-set so a subsequent
// run (or the returning home preview) reflects what this run deleted.
func (m *appModel) finishRun() {
if m.progLog != nil {
m.progLog.close()
if err := m.progLog.writeErr(); err != nil && m.perr == "" {
m.perr = "Resume log write failed (" + err.Error() + "). Deletions after the failure were not recorded and will be re-attempted on the next run."
}
m.progLog = nil
}
// A run only aborts on repeated 401, which means the token has almost
// certainly rotated. Drop the stored copy, but only when the rejected token