package bot import ( "context" "encoding/json" "fmt" "net/http" "net/url" "os" "strings" "time" "lchat/internal/e2ee" ) // Announcer is the engine behind a recipe's `changelog` rule // (docs/bot-recipes.md): it polls the instance's embedded changelog // (/api/changelog) and posts entries it hasn't announced yet into every // group/DM the bot has been added to. It powered the retired default // "Announcer" identity; today the app announces its own updates server-side // (announce.go — a push to admins + the Admin app's update stream), and this // engine stays for operators whose custom bots explicitly opt into posting // release notes to groups. // // Deliberately write-only: it never fetches or decrypts a single message — it // unwraps thread keys only to *encrypt* what it posts, and it calls no model // API. "This bot is in the group" means "it can post here", not "it reads // this room". // // State (which entries have been announced) lives at .state.json // ({"announced":[ids]}), so a restart never replays entries. type Announcer struct { Base string Session *Session // StatePath defaults to .state.json via StatePathFor. StatePath string // Logf receives progress lines ("announced 2 entries to 3/3 threads"). Logf func(format string, args ...any) client *http.Client kindDeclared bool } // StatePathFor mirrors the Node announcer's convention. func StatePathFor(sessionPath string) string { return sessionPath + ".state.json" } type announcerState struct { Announced []string `json:"announced"` } // Tick runs one poll: declare our kind (once, best-effort), fetch the // changelog, and post anything new to every thread we're in. On the very first // run it baselines to the current changelog without posting, so a fresh // announcer announces what ships *after* it, not history. func (a *Announcer) Tick() error { if a.client == nil { // Marked like all sidecar-to-instance traffic (sidecarmark.go), so a // recipe's announce poller can't hold a hibernating instance awake. a.client = &http.Client{Timeout: 30 * time.Second, Transport: markTransport{}} } a.declareKind() var cl struct { Entries []struct { ID string `json:"id"` Text string `json:"text"` } `json:"entries"` } if err := a.get("/api/changelog", &cl); err != nil { return fmt.Errorf("changelog: %w", err) } raw, err := os.ReadFile(a.StatePath) if os.IsNotExist(err) { ids := make([]string, 0, len(cl.Entries)) for _, e := range cl.Entries { ids = append(ids, e.ID) } a.logf("baselined at %d entries", len(ids)) return a.saveState(announcerState{Announced: ids}) } if err != nil { return err } var state announcerState if err := json.Unmarshal(raw, &state); err != nil { return fmt.Errorf("bad state file %s: %w", a.StatePath, err) } seen := make(map[string]bool, len(state.Announced)) for _, id := range state.Announced { seen[id] = true } var fresh []string // entry texts, oldest first (changelog order) for _, e := range cl.Entries { if e.ID != "" && e.Text != "" && !seen[e.ID] { fresh = append(fresh, e.Text) state.Announced = append(state.Announced, e.ID) } } if len(fresh) == 0 { return nil } text := "🚀 Just shipped:\n\n" + strings.Join(fresh, "\n\n") var tl struct { Threads []struct { ID string `json:"id"` Kind string `json:"kind"` Wrapped string `json:"wrapped"` } `json:"threads"` } if err := a.get("/api/threads", &tl); err != nil { return fmt.Errorf("threads: %w", err) } posted, targets := 0, 0 for _, t := range tl.Threads { if t.Wrapped == "" || (t.Kind != "group" && t.Kind != "dm") { continue } targets++ if err := a.post(t.ID, t.Wrapped, text); err != nil { a.logf("thread %s: %v", t.ID, err) continue } posted++ } // Mark announced even with zero targets: entries shipped while the bot sat // in no groups are old news by the time someone adds it — don't replay them. if err := a.saveState(state); err != nil { return err } a.logf("announced %d entries to %d/%d threads", len(fresh), posted, targets) return nil } // Run is the poll loop, until ctx is cancelled. Tick errors are logged and // retried next tick. func (a *Announcer) Run(ctx context.Context, interval time.Duration) { for { if err := a.Tick(); err != nil { a.logf("tick failed: %v", err) } select { case <-time.After(interval): case <-ctx.Done(): return } } } // post encrypts one message under the thread's key and posts it — the only // thing the announcer ever does with a thread key. func (a *Announcer) post(threadID, wrapped, text string) error { keyB64, err := e2ee.UnwrapThreadKey(wrapped, a.Session.UserPriv) if err != nil { return err } key, err := e2ee.ImportKey(keyB64) if err != nil { return err } blob, err := e2ee.EncryptJSON(key, map[string]any{ "name": a.Session.Name, "text": text, "ts": time.Now().UnixMilli(), }) if err != nil { return err } body, _ := json.Marshal(map[string]string{"thread_id": threadID, "blob": blob}) resp, err := a.client.Post(a.Base+"/api/messages?token="+url.QueryEscape(a.Session.Token), "application/json", strings.NewReader(string(body))) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("server %d", resp.StatusCode) } return nil } // declareKind self-reports "bot" (deterministic — no model) so the UI badges // us BOT, not AI. Best-effort; retried on a later tick if it fails. func (a *Announcer) declareKind() { if a.kindDeclared { return } body, _ := json.Marshal(map[string]string{"token": a.Session.Token, "kind": "bot"}) resp, err := a.client.Post(a.Base+"/api/bot-config", "application/json", strings.NewReader(string(body))) if err != nil { a.logf("declare kind: %v", err) return } resp.Body.Close() a.kindDeclared = resp.StatusCode == http.StatusOK } func (a *Announcer) get(path string, out any) error { resp, err := a.client.Get(a.Base + path + "?token=" + url.QueryEscape(a.Session.Token)) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("%s: server %d", path, resp.StatusCode) } return json.NewDecoder(resp.Body).Decode(out) } func (a *Announcer) saveState(s announcerState) error { raw, err := json.Marshal(s) if err != nil { return err } return os.WriteFile(a.StatePath, raw, 0o600) } func (a *Announcer) logf(format string, args ...any) { if a.Logf != nil { a.Logf("announcer: "+format, args...) } }