180 lines
5.4 KiB
Go
180 lines
5.4 KiB
Go
package bot
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/slack-go/slack"
|
|
|
|
"slackerbot/internal/model"
|
|
)
|
|
|
|
const (
|
|
stopInterrupted = "interrupted"
|
|
shutdownGrace = 5 * time.Second
|
|
resumeWithin = time.Hour
|
|
maxResumes = 3
|
|
|
|
resumeNote = "(slackerbot restarted while you were working on the last message, so your turn was cut off. " +
|
|
"Carry on from where you stopped, without redoing work that's already done.)"
|
|
|
|
inFlightSlackLimit = 35000
|
|
)
|
|
|
|
func isInFlight(verb string) bool { return verb == "in-flight" || verb == "inflight" }
|
|
|
|
func (b *Bot) trackTurn(m incoming, root, replyTS string, prior *model.Turn) *model.Turn {
|
|
ownerID, _ := m.owner()
|
|
t := &model.Turn{
|
|
Channel: m.channel, ThreadTS: root, MessageTS: m.ts, ReplyTS: replyTS,
|
|
User: m.user, OwnerID: ownerID, DM: m.dm, Heard: m.heard, Text: m.text,
|
|
StartedAt: time.Now(),
|
|
}
|
|
for _, f := range m.files {
|
|
t.Files = append(t.Files, model.TurnFile{Name: f.Name, Mode: f.Mode, URL: f.URLPrivateDownload, Size: f.Size})
|
|
}
|
|
if prior != nil {
|
|
t.Prompted, t.Resumes, t.StartedAt = prior.Prompted, prior.Resumes+1, prior.StartedAt
|
|
}
|
|
b.saveTurn(t)
|
|
return t
|
|
}
|
|
|
|
func (b *Bot) saveTurn(t *model.Turn) {
|
|
if err := b.store.PutTurn(t); err != nil {
|
|
log.Printf("in-flight: saving %s/%s: %v", t.Channel, t.ThreadTS, err)
|
|
}
|
|
}
|
|
|
|
// A turn cut off by shutdown stays recorded, so the next start picks it back up.
|
|
func (b *Bot) untrackTurn(ctx context.Context, t *model.Turn) {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
if err := b.store.DeleteTurn(t.Channel, t.ThreadTS); err != nil {
|
|
log.Printf("in-flight: clearing %s/%s: %v", t.Channel, t.ThreadTS, err)
|
|
}
|
|
}
|
|
|
|
// waitForTurns gives running turns a moment to post their last edit before the process exits.
|
|
func (b *Bot) waitForTurns(grace time.Duration) {
|
|
done := make(chan struct{})
|
|
go func() {
|
|
b.turnsWG.Wait()
|
|
close(done)
|
|
}()
|
|
select {
|
|
case <-done:
|
|
case <-time.After(grace):
|
|
}
|
|
}
|
|
|
|
func turnMessage(t model.Turn) incoming {
|
|
m := incoming{user: t.User, channel: t.Channel, ts: t.MessageTS, text: t.Text, dm: t.DM, heard: t.Heard}
|
|
if t.ThreadTS != t.MessageTS {
|
|
m.threadTS = t.ThreadTS
|
|
}
|
|
for _, f := range t.Files {
|
|
m.files = append(m.files, slack.File{Name: f.Name, Mode: f.Mode, URLPrivateDownload: f.URL, Size: f.Size})
|
|
}
|
|
return m
|
|
}
|
|
|
|
func (b *Bot) resumeTurns(ctx context.Context) {
|
|
for _, t := range b.store.Turns() {
|
|
go b.resume(ctx, t)
|
|
}
|
|
}
|
|
|
|
func (b *Bot) resume(ctx context.Context, t model.Turn) {
|
|
if time.Since(t.StartedAt) > resumeWithin || t.Resumes >= maxResumes {
|
|
log.Printf("in-flight: giving up on %s/%s (started %s, resumed %d times)", t.Channel, t.ThreadTS, t.StartedAt.Format(time.RFC3339), t.Resumes)
|
|
b.say(ctx, t.Channel, t.ThreadTS, ":warning: slackerbot restarted while it was answering this, and it's too late to pick it back up. "+
|
|
"Send your message again if you still need it.")
|
|
b.unreact(ctx, t.Channel, t.MessageTS, "eyes")
|
|
b.react(ctx, t.Channel, t.MessageTS, "warning")
|
|
if err := b.store.DeleteTurn(t.Channel, t.ThreadTS); err != nil {
|
|
log.Printf("in-flight: clearing %s/%s: %v", t.Channel, t.ThreadTS, err)
|
|
}
|
|
return
|
|
}
|
|
log.Printf("in-flight: resuming %s/%s for %s after a restart (prompted %v, resume %d)", t.Channel, t.ThreadTS, t.User, t.Prompted, t.Resumes+1)
|
|
b.converse(ctx, turnMessage(t), &t)
|
|
}
|
|
|
|
// inFlightFor shows the in-flight files as they are on disk. They hold message
|
|
// text, so only super users and user managers may read them.
|
|
func (b *Bot) inFlightFor(m incoming, all, agent bool) string {
|
|
p := b.store.Permissions()
|
|
channel := m.channel
|
|
if all {
|
|
channel = ""
|
|
if !p.IsManager(m.user) && len(p.Default[m.user]) == 0 {
|
|
return ":lock: Only user managers and super users on the default list can see every channel's in-flight replies."
|
|
}
|
|
} else if !p.IsSuperUser(m.channel, m.user) {
|
|
return ":lock: Only super users here and user managers can see the in-flight replies."
|
|
}
|
|
files, err := b.store.InFlightFiles(channel)
|
|
if err != nil {
|
|
return ":warning: Couldn't read the in-flight files: " + err.Error()
|
|
}
|
|
if len(files) == 0 {
|
|
if all {
|
|
return "No replies are in flight anywhere."
|
|
}
|
|
return "No replies are in flight here."
|
|
}
|
|
limit := inFlightSlackLimit
|
|
if agent {
|
|
limit = maxReplyBytes / 2
|
|
}
|
|
names := make([]string, 0, len(files))
|
|
for name := range files {
|
|
names = append(names, name)
|
|
}
|
|
sort.Strings(names)
|
|
|
|
var sb strings.Builder
|
|
sb.WriteString("*In-flight replies* (what I'd pick back up after a restart):\n")
|
|
for i, name := range names {
|
|
data := strings.TrimSpace(string(files[name]))
|
|
room := limit - sb.Len() - len(name) - 20
|
|
if room <= 0 {
|
|
fmt.Fprintf(&sb, "_(%d more files not shown)_", len(names)-i)
|
|
break
|
|
}
|
|
if len(data) > room {
|
|
data = cutBytes(data, room) + fmt.Sprintf("\n… (cut off, %d bytes in total)", len(files[name]))
|
|
}
|
|
fmt.Fprintf(&sb, "`%s`\n```\n%s\n```\n", name, data)
|
|
}
|
|
return strings.TrimSpace(sb.String())
|
|
}
|
|
|
|
// The files hold other people's messages, so only the asker sees them.
|
|
func (b *Bot) whisper(ctx context.Context, m incoming, text string) {
|
|
opts := []slack.MsgOption{slack.MsgOptionText(text, false)}
|
|
if m.threadTS != "" {
|
|
opts = append(opts, slack.MsgOptionTS(m.threadTS))
|
|
}
|
|
if _, err := b.api.PostEphemeralContext(ctx, m.channel, m.user, opts...); err != nil {
|
|
log.Printf("slack ephemeral: %v", err)
|
|
}
|
|
}
|
|
|
|
func cutBytes(s string, n int) string {
|
|
if len(s) <= n {
|
|
return s
|
|
}
|
|
for n > 0 && !utf8.RuneStart(s[n]) {
|
|
n--
|
|
}
|
|
return s[:n]
|
|
}
|