// Package bot wires Matrix command messages to the *arr clients. // // Commands take the form " " (e.g. "!movie dune"). The // dispatcher parses the message, picks the *arr client by command name, // performs a lookup, and adds the top hit. The reply is posted back into a // thread rooted at the request event so a busy room stays readable. package bot import ( "context" "fmt" "html" "log/slog" "strings" "time" "bellhop/internal/arr" "maunium.net/go/mautrix/id" ) // Replier sends a threaded reply into roomID under rootEventID. The ctx // governs cancellation/deadline so shutdown propagates through replies. type Replier interface { PostThreadedReply(ctx context.Context, roomID id.RoomID, rootEventID id.EventID, plain, htmlBody string) error } // Services holds the configured *arr clients. Any field may be nil; commands // that target an unconfigured service reply with "not configured". type Services struct { Radarr arr.Client Sonarr arr.Client Lidarr arr.Client } // Dispatcher routes parsed commands to services and posts replies. type Dispatcher struct { baseCtx context.Context prefix string services Services replier Replier timeout time.Duration } // New builds a Dispatcher. prefix is the leading character(s) on a command // (e.g. "!"); a zero value defaults to "!". baseCtx becomes the parent of // every per-command context so app shutdown cancels in-flight handlers. func New(baseCtx context.Context, prefix string, services Services, replier Replier) *Dispatcher { if prefix == "" { prefix = "!" } if baseCtx == nil { baseCtx = context.Background() } return &Dispatcher{ baseCtx: baseCtx, prefix: prefix, services: services, replier: replier, timeout: 60 * time.Second, } } // Handle is the matrix.MessageHandler entry point. It parses body, dispatches // the command, and posts a reply. Non-command messages are ignored silently. func (d *Dispatcher) Handle(roomID id.RoomID, eventID id.EventID, sender id.UserID, body string) { cmd, query, ok := parseCommand(d.prefix, body) if !ok { return } slog.Info("bot: command received", "room", roomID, "sender", sender, "cmd", cmd, "query", query) ctx, cancel := context.WithTimeout(d.baseCtx, d.timeout) defer cancel() plain, htmlBody := d.dispatch(ctx, cmd, query) if err := d.replier.PostThreadedReply(ctx, roomID, eventID, plain, htmlBody); err != nil { slog.Error("bot: reply failed", "room", roomID, "err", err) } } // parseCommand pulls (cmd, query) out of a body like "!movie dune". Returns // ok=false when the message is not a command for us. func parseCommand(prefix, body string) (cmd, query string, ok bool) { body = strings.TrimSpace(body) if !strings.HasPrefix(body, prefix) { return "", "", false } rest := strings.TrimSpace(body[len(prefix):]) if rest == "" { return "", "", false } parts := strings.SplitN(rest, " ", 2) cmd = strings.ToLower(parts[0]) if len(parts) == 2 { query = strings.TrimSpace(parts[1]) } return cmd, query, true } func (d *Dispatcher) dispatch(ctx context.Context, cmd, query string) (plain, htmlBody string) { switch cmd { case "help": return d.help() case "movie": return d.run(ctx, "movie", "Radarr", d.services.Radarr, query) case "tv": return d.run(ctx, "tv", "Sonarr", d.services.Sonarr, query) case "music": return d.run(ctx, "music", "Lidarr", d.services.Lidarr, query) default: msg := fmt.Sprintf("Unknown command %q. Try %shelp.", cmd, d.prefix) return msg, html.EscapeString(msg) } } func (d *Dispatcher) run(ctx context.Context, cmd, service string, client arr.Client, query string) (plain, htmlBody string) { if client == nil { msg := fmt.Sprintf("%s is not configured.", service) return msg, html.EscapeString(msg) } if query == "" { msg := fmt.Sprintf("Usage: %s%s ", d.prefix, cmd) return msg, html.EscapeString(msg) } results, err := client.Search(ctx, query) if err != nil { slog.Error("bot: search failed", "service", service, "query", query, "err", err) msg := fmt.Sprintf("%s search failed: %v", service, err) return msg, html.EscapeString(msg) } if len(results) == 0 { msg := fmt.Sprintf("No %s results for %q.", service, query) return msg, html.EscapeString(msg) } top := results[0] if top.Exists { msg := fmt.Sprintf("%s already has %s in the library.", service, formatTitle(top)) return msg, html.EscapeString(msg) } if err := client.Add(ctx, top); err != nil { slog.Error("bot: add failed", "service", service, "title", top.Title, "err", err) msg := fmt.Sprintf("%s: failed to add %s: %v", service, formatTitle(top), err) return msg, html.EscapeString(msg) } plain = fmt.Sprintf("Added to %s: %s", service, formatTitle(top)) htmlBody = fmt.Sprintf("Added to %s: %s", html.EscapeString(service), html.EscapeString(formatTitle(top))) return plain, htmlBody } func (d *Dispatcher) help() (string, string) { lines := []string{ "Bellhop commands:", fmt.Sprintf(" %smovie — add the top Radarr hit", d.prefix), fmt.Sprintf(" %stv — add the top Sonarr hit", d.prefix), fmt.Sprintf(" %smusic — add the top Lidarr hit", d.prefix), fmt.Sprintf(" %shelp — show this message", d.prefix), } plain := strings.Join(lines, "\n") htmlBody := "
" + html.EscapeString(plain) + "
" return plain, htmlBody } func formatTitle(r arr.Result) string { if r.Year > 0 { return fmt.Sprintf("%s (%d)", r.Title, r.Year) } return r.Title }