diff --git a/docs/community-plugins.md b/docs/community-plugins.md index b68b24805..64d7f8594 100644 --- a/docs/community-plugins.md +++ b/docs/community-plugins.md @@ -20,3 +20,4 @@ These plugins are maintained by the community. To add a plugin, open a PR. | [cliamp-plugin-save-song](https://github.com/dorobica/cliamp-plugin-save-song) | One key saves the playing song, including the live title on radio streams, to a dated list you can search and replay | [@dorobica](https://github.com/dorobica) | | [cliamp-plugin-mac-notify](https://github.com/dbarrerap/cliamp-plugin-mac-notify) | macOS Now Playing desktop notifications with local cover art and YouTube thumbnails | [@dbarrerap](https://github.com/dbarrerap) | | [cliamp-plugin-hanami](https://github.com/niteover/cliamp-plugin-hanami) | Pixel cherry blossom visualizer: petals pile up in drifts that glow with the spectrum and jump on the beat | [@niteover](https://github.com/niteover) | +| [cliamp-plugin-deezload](https://github.com/cartudev/cliamp-plugin-deezload) | DeezLoad music bot for the Telegram provider: command palette, inline search, covers and reply history | [@cartudev](https://github.com/cartudev) | diff --git a/docs/keybindings.md b/docs/keybindings.md index 5c492df2b..4b1364b99 100644 --- a/docs/keybindings.md +++ b/docs/keybindings.md @@ -44,6 +44,7 @@ entries, a status message tells you which key to press. | `Ctrl+Z` | Undo the last playlist or queue change | | `o` | Open file browser | | `b` `Esc` | Back to provider | +| `!` | Plugin actions for the active provider | In full and compact playback layouts, the first `Tab` from the playlist focuses Source (`SRC`); `Shift+Tab` starts at Speed when it is visible. Source is skipped diff --git a/docs/plugins.md b/docs/plugins.md index 07f38674e..0ef29a5a1 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -291,6 +291,35 @@ The callback can return a string. The CLI client prints it. Invoke commands from List registered commands with `cliamp plugins commands`. A command can run for up to 5 minutes before it times out. cliamp also stops a command when its IPC job is canceled and when cliamp quits. +### `p:action{...}` - plugin action pane (requires `permissions = {"ui"}`) + +The `!` key opens a pane with the actions the loaded plugins registered for the +active provider. An action can run immediately or ask for one line of text +first. `provider` limits it to a provider, by name. + +```lua +p:action{ + key = "!", -- optional, default "!" + id = "send", -- unique per plugin + label = "Send message", + description = "Ask the bot for a track", + provider = "Telegram", -- optional + context = "chat", -- optional: "chat" or "chats" + prompt = "Message", -- optional: ask for text first + on_submit = function(text) ... end, +} +``` + +Actions are namespaced by plugin, so two plugins can use the same `id`. +`p:action` returns `true`, or `false, reason` when the UI permission is missing +or the id is already registered. The action pane filters by provider and by the +text typed in the pane. An action with `prompt` runs `on_submit` with the text; +without it, `on_submit` gets an empty string. + +`context` narrows the action to the provider list or to open content: +`"chats"` shows it only while the provider list has no open playlist, and +`"chat"` only while one is open. Leave it out to show the action in both. + ## Lua API All APIs are in the global `cliamp` table. @@ -358,13 +387,14 @@ cliamp.queue.has_next() --> true when a playable track follows in play order -- mutate (requires "control") cliamp.queue.add(path) -- resolve a file/dir/URL and append +cliamp.queue.insert(index, track) --> true | nil, err -- insert at index cliamp.queue.add(track) --> true | nil, err -- append a track table as given cliamp.queue.jump(index) -- make index current and play it cliamp.queue.remove(index) -- remove the track at index cliamp.queue.move(from, to) -- swap the tracks at from and to ``` -`add`, `remove`, and `move` follow the rules of the `Shift+Up`, `Shift+Down`, +`add`, `insert`, `remove`, and `move` follow the rules of the `Shift+Up`, `Shift+Down`, and `x` keys and of IPC: - While shuffle is on, `move` changes nothing. @@ -372,7 +402,7 @@ and `x` keys and of IPC: that playlist. `remove` removes the track from it too. When that save fails, the edit changes nothing. Favorites is not a playlist file, so an edit of a loaded Favorites list changes only the queue. -- `add`, `move`, and `remove` record no undo. After one of them, `Ctrl+Z` does +- `add`, `insert`, `move`, and `remove` record no undo. After one of them, `Ctrl+Z` does not undo the last TUI edit, because that undo would drop the new change. - While the queue mirrors a saved local playlist, `remove` does not remove a track that a directory source of that playlist supplies. A removal of the @@ -405,6 +435,66 @@ It returns `true`, or `nil` and an error message when the table is invalid (for example, a missing path or a title that is not a string) or when the plugin lacks the `control` permission. An HTTP URL is always marked as a stream. +### cliamp.provider (requires permissions) + +`cliamp.provider.current()` returns the provider and the playlist context: + +```lua +{ + name = "Telegram", + playlist_id = "u:1:2", playlist_name = "DeezLoad", + playlist_section = "Bots", + selection_id = "u:1:2", selection_name = "DeezLoad", + selection_section = "Bots", +} +``` + +`playlist_id` is the playlist open in the pane; `selection_id` is the row under +the cursor. Either can be empty. `playlist_section` and `selection_section` are +the headings the provider uses, such as `Bots` or `Groups`. `name` is the same +string the provider uses in the UI. + +`cliamp.provider.call(action, params[, options])` calls a provider action. +Reads need `permissions = {"provider"}`; actions that change the remote account +need `permissions = {"provider-send"}`. The provider must implement +`provider.ChatCommander`; a provider without it returns an error. + +```lua +-- block until the bot replies, or return the error +local reply, err = cliamp.provider.call("telegram.ask", { + chat = chat, + text = "/search daft punk", + timeout = 60, +}) + +-- keep the UI responsive while a bot takes its time +cliamp.provider.call("telegram.ask", {chat = chat, text = text}, { + on_reply = function(reply, err) ... end, + timeout = 90, +}) +``` + +Options are `on_reply = function(result, err)` and `timeout = seconds` (default +60). With `on_reply` the call runs off the UI goroutine and delivers the result +to the callback; use it for calls that wait for a bot. Without it the call +blocks the Lua hook and returns the result. A key binding has a five-second +budget, so a waiting call from a key binding needs `on_reply`. + +Telegram actions at this layer are `telegram.commands` (the commands a bot +advertises), `telegram.send` (send text and return the message id), +`telegram.ask` (send and wait for the reply), `telegram.reply` (wait for the +next message after an id), `telegram.callback` (press an inline button), +`telegram.message` (re-read one message), `telegram.inline` (ask an inline bot +for results), `telegram.send_inline` (send one of those results), +`telegram.resolve` (turn a username or `t.me` link into a playlist id) and +`telegram.add_chat` (add a chat to the provider's `chats` filter when one is +set). + +`cliamp.provider.open{provider, playlist_id, playlist_name, playlist_section}` +asks the UI to load a playlist that the plugin resolved, such as a bot chat it +just created. It returns true, or an error when the provider is not active or +the UI is not available. + ### cliamp.http ```lua @@ -669,8 +759,13 @@ panes. ```lua cliamp.ui.select{ - title = "Which visualizer?", - options = { "Bars", "Scatter", "None" }, + title = "Track", + body = "2:34 ยท 7 options", -- optional text above the list + options = { + "Bars", -- title only + {title = "Get Lucky", subtitle = "Daft Punk", description = "3:09", + image = "/tmp/cover.png"}, -- optional image path or URL + }, cursor = 2, -- optional, 1-based on_select = function(index) ... end, on_cancel = function() ... end, -- optional, Esc @@ -679,7 +774,52 @@ cliamp.ui.select{ Returns true when the request was accepted. With no interactive UI (headless mode) it returns an error. Closing the selector calls `on_cancel` when given, or -`on_select(-1)` otherwise. +`on_select(-1)` otherwise. A table row can carry `title`, `subtitle`, +`description` and `image`; the image is rendered with the terminal's image +protocol when it supports one, and ignored otherwise. + +```lua +cliamp.ui.input{ + title = "Message", + placeholder = "song, artist or link", + value = "", -- optional + suggestions = { -- optional, same row shape as select + {title = "/start", description = "Start the bot"}, + }, + on_change = function(text) ... end, -- optional, every edit + on_select = function(index) ... end, -- optional, Enter on a live row + on_submit = function(text) ... end, + on_cancel = function() ... end, -- optional, Esc +} +``` + +`ui.input` asks for one line of text. `Enter` calls `on_submit` with the text; +`Esc` calls `on_cancel` when given. `on_change` runs on every edit and +`on_select` runs when `Enter` picks a live suggestion. It returns `true, token` +when the request was accepted; keep that token for `cliamp.ui.suggestions`. +Headless mode returns an error. + +While an input is open, `cliamp.ui.suggestions(options, {live = true})` replaces +the list under it. This is how a plugin turns the input into a live search or a +command palette. `live = true` (the default) marks the rows as results: `Enter` +selects one and calls `on_select` instead of submitting the typed text. +`live = false` makes them plain suggestions again, so `Enter` submits the text. +Pass `query = "..."` with the text the results belong to and `token` from the +matching `ui.input` call; cliamp drops a result for a query or input that has +already been replaced. An empty `query` is compared too: only omit it when the +results are not tied to the text. Without `token`, newer results apply to the +most recent input from that plugin. + +```lua +cliamp.ui.text{ + title = "Bot reply", + text = "long text ...", + on_close = function() ... end, -- optional +} +``` + +`ui.text` opens a scrollable read-only panel. `โ†‘`/`โ†“`, `PageUp`/`PageDown`, +`Home`/`End` scroll it; `Esc` or `q` closes it and calls `on_close`. ### cliamp.vis diff --git a/docs/telegram.md b/docs/telegram.md index ca6182095..705b5459a 100644 --- a/docs/telegram.md +++ b/docs/telegram.md @@ -107,6 +107,22 @@ screen, desktop widgets) as a `data:` URL. | `buffer_mb` | no | Megabytes buffered before playback (default 1) | | `session_file` | no | Session path (default `~/.local/share/cliamp/telegram.session`) | +## Bot chats + +A chat with a bot is a normal playlist: the provider lists its audio documents +and plays them. A plugin can also write into that chat: send a command as the +signed-in user, wait for the bot's reply, press an inline button, or ask an +inline bot for results and send one. The write actions live in the plugin API +(`cliamp.provider.call`), not in a fixed key, so the plugin decides the prompt +and how to show the reply. A plugin can also resolve a bot username, add the +chat to the `chats` filter, and ask the UI to open it. See [Plugins](plugins.md) +and the bundled `telegram-bot.lua`. + +Writes use the same MTProto session as reads and act as the signed-in user. A +bot sees a normal message from you; a command sent to a group is visible to +every member. Keep the session file private: it can send messages and press +buttons on your behalf. + ## Limits - One account: the provider browses the dialogs of the signed-in user. diff --git a/external/telegram/provider.go b/external/telegram/provider.go index c20a5929a..b7d3fcfd3 100644 --- a/external/telegram/provider.go +++ b/external/telegram/provider.go @@ -32,6 +32,7 @@ var ( _ provider.CustomStreamer = (*Provider)(nil) _ provider.TrackPager = (*Provider)(nil) _ provider.CodeAuthenticator = (*Provider)(nil) + _ provider.ChatCommander = (*Provider)(nil) ) const ( @@ -77,6 +78,7 @@ type Provider struct { cfg config.TelegramConfig client *tgclient.Client api *tg.Client + write writeAPI // tests inject a fake; production uses api authReq chan authRequest mu sync.Mutex // guards state and connectErr state provState @@ -259,7 +261,19 @@ func (p *Provider) currentState() provState { // wait returns once the connection is usable. playlist.ErrNeedsAuth means the // pane must collect the login code; other errors keep the call retryable. func (p *Provider) wait() error { + return p.waitContext(context.Background()) +} + +// waitContext is wait with a caller that can give up. The provider can spend +// up to connectWait settling, and a canceled UI action should not stay blocked +// in the polling loop until that deadline. +func (p *Provider) waitContext(ctx context.Context) error { + if ctx == nil { + ctx = context.Background() + } deadline := time.Now().Add(connectWait) + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() for { switch p.currentState() { case provReady: @@ -275,7 +289,11 @@ func (p *Provider) wait() error { if time.Now().After(deadline) { return errors.New("telegram: still connecting, try again") } - time.Sleep(100 * time.Millisecond) + select { + case <-ctx.Done(): + return ctx.Err() + case <-ticker.C: + } } } diff --git a/external/telegram/write.go b/external/telegram/write.go new file mode 100644 index 000000000..3d043742d --- /dev/null +++ b/external/telegram/write.go @@ -0,0 +1,684 @@ +package telegram + +import ( + "context" + "crypto/rand" + "encoding/binary" + "errors" + "fmt" + "strings" + "time" + "unicode/utf16" + "unicode/utf8" + + "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/provider" + "github.com/gotd/td/tg" +) + +// writeAPI is the part of *tg.Client that the write side uses. Tests inject a +// fake so the provider never needs a real account. +type writeAPI interface { + MessagesSendMessage(ctx context.Context, request *tg.MessagesSendMessageRequest) (tg.UpdatesClass, error) + MessagesGetHistory(ctx context.Context, request *tg.MessagesGetHistoryRequest) (tg.MessagesMessagesClass, error) + UsersGetFullUser(ctx context.Context, id tg.InputUserClass) (*tg.UsersUserFull, error) + MessagesGetBotCallbackAnswer(ctx context.Context, request *tg.MessagesGetBotCallbackAnswerRequest) (*tg.MessagesBotCallbackAnswer, error) + MessagesGetInlineBotResults(ctx context.Context, request *tg.MessagesGetInlineBotResultsRequest) (*tg.MessagesBotResults, error) + MessagesSendInlineBotResult(ctx context.Context, request *tg.MessagesSendInlineBotResultRequest) (tg.UpdatesClass, error) +} + +// resolveChatID accepts a peer id or a username and returns the input peer +// plus the canonical peer id. The canonical id goes into track paths, so a +// profile that names a bot by username still produces a playable URI. +func (p *Provider) resolveChatID(ctx context.Context, chat string) (tg.InputPeerClass, string, error) { + if peer, err := parsePeerID(chat); err == nil { + return peer, chat, nil + } + info, err := p.resolveChatCached(ctx, chat) + if err != nil { + return nil, "", err + } + peer, err := parsePeerID(info.ID) + if err != nil { + return nil, "", err + } + return peer, info.ID, nil +} + +// writer returns the API the write side calls. Production leaves write nil and +// uses the connected client; tests set write to a fake. +func (p *Provider) writer() writeAPI { + if p.write != nil { + return p.write + } + return p.api +} + +// BotCommands returns the commands the bot of a user chat advertises. Groups, +// channels and users that are not bots return none. +func (p *Provider) BotCommands(ctx context.Context, chatID string) ([]provider.BotCommand, error) { + if err := p.waitContext(ctx); err != nil { + return nil, err + } + peer, _, err := p.resolveChatID(ctx, chatID) + if err != nil { + return nil, err + } + user, ok := peer.(*tg.InputPeerUser) + if !ok { + return nil, nil + } + full, err := p.writer().UsersGetFullUser(ctx, &tg.InputUser{ + UserID: user.UserID, + AccessHash: user.AccessHash, + }) + if err != nil { + return nil, fmt.Errorf("telegram: commands of %q: %w", chatID, err) + } + info, ok := full.FullUser.GetBotInfo() + if !ok { + return nil, nil + } + out := make([]provider.BotCommand, 0, len(info.Commands)) + for _, command := range info.Commands { + name := strings.TrimSpace(command.Command) + if name == "" { + continue + } + if !strings.HasPrefix(name, "/") { + name = "/" + name + } + out = append(out, provider.BotCommand{Command: name, Description: command.Description}) + } + return out, nil +} + +// SendCommand sends text to chatID as the signed-in user and returns the id +// of the message Telegram created. +func (p *Provider) SendCommand(ctx context.Context, chatID, text string) (int, error) { + if err := p.waitContext(ctx); err != nil { + return 0, err + } + text = strings.TrimSpace(text) + if text == "" { + return 0, errors.New("telegram: empty message") + } + peer, _, err := p.resolveChatID(ctx, chatID) + if err != nil { + return 0, err + } + randomID, err := randomMessageID() + if err != nil { + return 0, err + } + updates, err := p.writer().MessagesSendMessage(ctx, &tg.MessagesSendMessageRequest{ + Peer: peer, + Message: text, + RandomID: randomID, + NoWebpage: true, + }) + if err != nil { + return 0, fmt.Errorf("telegram: send to %q: %w", chatID, err) + } + id := sentMessageID(updates) + if id == 0 { + return 0, errors.New("telegram: send returned no message id") + } + return id, nil +} + +// BotCallback presses an inline button on a bot message. +func (p *Provider) BotCallback(ctx context.Context, chatID string, messageID int, data []byte) error { + if err := p.waitContext(ctx); err != nil { + return err + } + peer, _, err := p.resolveChatID(ctx, chatID) + if err != nil { + return err + } + _, err = p.writer().MessagesGetBotCallbackAnswer(ctx, &tg.MessagesGetBotCallbackAnswerRequest{ + Peer: peer, + MsgID: messageID, + Data: data, + }) + if err != nil { + // DeezLoad starts the download after the callback and can take longer + // than Telegram's callback answer window. The button was pressed, so + // the caller waits for the audio instead of reporting a failure. + if strings.Contains(err.Error(), "BOT_RESPONSE_TIMEOUT") { + return nil + } + return fmt.Errorf("telegram: callback on %q: %w", chatID, err) + } + return nil +} + +// Message reads one message by id. It is used after a callback that edits a +// menu in place: the id stays the same, so WaitReply cannot see the change. +func (p *Provider) Message(ctx context.Context, chatID string, messageID int) (provider.ChatReply, error) { + if err := p.waitContext(ctx); err != nil { + return provider.ChatReply{}, err + } + peer, canonicalID, err := p.resolveChatID(ctx, chatID) + if err != nil { + return provider.ChatReply{}, err + } + history, err := p.writer().MessagesGetHistory(ctx, &tg.MessagesGetHistoryRequest{ + Peer: peer, + OffsetID: messageID + 1, + MinID: messageID - 1, + MaxID: messageID + 1, + Limit: 1, + }) + if err != nil { + return provider.ChatReply{}, fmt.Errorf("telegram: message %d of %q: %w", messageID, chatID, err) + } + for _, entity := range messagesOf(history) { + msg, ok := entity.(*tg.Message) + if !ok || msg.ID != messageID { + continue + } + if reply, ok := replyFromMessage(canonicalID, msg); ok { + return reply, nil + } + } + return provider.ChatReply{Kind: "none"}, nil +} + +// replyFromMessage turns one message into a ChatReply. +func replyFromMessage(chatID string, msg *tg.Message) (provider.ChatReply, bool) { + if media, ok := msg.Media.(*tg.MessageMediaDocument); ok { + if doc, ok := media.Document.(*tg.Document); ok { + if info, ok := audioInfo(doc); ok { + track := playlist.Track{ + Path: fmt.Sprintf("%s%s:%d", uriPrefix, chatID, msg.ID), + Title: info.title, + Artist: info.performer, + DurationSecs: info.duration, + ProviderMeta: map[string]string{"telegram.id": fmt.Sprint(msg.ID)}, + } + return provider.ChatReply{ + Kind: "audio", + Track: track, + Text: strings.TrimSpace(msg.Message), + From: senderOf(msg), + MessageID: msg.ID, + Buttons: buttonsOf(msg), + Links: linksOf(msg), + }, true + } + } + } + buttons := buttonsOf(msg) + if text := strings.TrimSpace(msg.Message); text != "" || len(buttons) > 0 { + return provider.ChatReply{ + Kind: "text", + Text: text, + From: senderOf(msg), + MessageID: msg.ID, + Buttons: buttons, + Links: linksOf(msg), + }, true + } + return provider.ChatReply{}, false +} + +// WaitReply polls chatID until an audio message newer than afterID arrives or a +// text reply sits unanswered for replyGrace. It returns Kind "none" when the +// timeout ends with nothing new. The caller owns the timeout. +func (p *Provider) WaitReply(ctx context.Context, chatID string, afterID int, timeout time.Duration) (provider.ChatReply, error) { + return p.waitReply(ctx, chatID, afterID, timeout, false) +} + +// WaitAudio is WaitReply for a bot that first sends text and then downloads +// the audio. It ignores text and keyboards until an audio arrives or the +// timeout ends. +func (p *Provider) WaitAudio(ctx context.Context, chatID string, afterID int, timeout time.Duration) (provider.ChatReply, error) { + return p.waitReply(ctx, chatID, afterID, timeout, true) +} + +// replyGrace is how long a text reply waits for a newer message before it is +// returned as the final answer. It is a var so tests can shorten it. +var replyGrace = 3 * time.Second + +func (p *Provider) waitReply(ctx context.Context, chatID string, afterID int, timeout time.Duration, audioOnly bool) (provider.ChatReply, error) { + if err := p.waitContext(ctx); err != nil { + return provider.ChatReply{}, err + } + peer, canonicalID, err := p.resolveChatID(ctx, chatID) + if err != nil { + return provider.ChatReply{}, err + } + if timeout <= 0 { + timeout = 20 * time.Second + } + deadline := time.Now().Add(timeout) + pollCtx, cancel := context.WithDeadline(ctx, deadline) + defer cancel() + var ( + pending provider.ChatReply + hasPending bool + textUntil time.Time + ) + for { + history, err := p.writer().MessagesGetHistory(pollCtx, &tg.MessagesGetHistoryRequest{ + Peer: peer, + MinID: afterID, + Limit: 20, + }) + if err != nil { + if ctx.Err() != nil { + return provider.ChatReply{}, ctx.Err() + } + if pollCtx.Err() != nil { + if hasPending { + return pending, nil + } + return provider.ChatReply{Kind: "none"}, nil + } + return provider.ChatReply{}, fmt.Errorf("telegram: reply of %q: %w", chatID, err) + } + if audio, ok := audioReply(canonicalID, afterID, messagesOf(history)); ok { + return audio, nil + } + if !audioOnly { + if newest, ok := newestReplyWithButtons(afterID, messagesOf(history)); ok { + return newest, nil + } + } + if value, ok := textReply(afterID, messagesOf(history)); ok { + changed := !hasPending || value.Text != pending.Text || value.MessageID != pending.MessageID + pending, hasPending = value, true + if !audioOnly && changed { + textUntil = time.Now().Add(replyGrace) + } + } + now := time.Now() + if !audioOnly && hasPending && now.After(textUntil) { + return pending, nil + } + if now.After(deadline) { + if hasPending { + return pending, nil + } + return provider.ChatReply{Kind: "none"}, nil + } + wait := time.Until(deadline) + if !audioOnly && hasPending { + wait = min(wait, time.Until(textUntil)) + } + wait = min(wait, time.Second) + if wait < 50*time.Millisecond { + wait = 50 * time.Millisecond + } + select { + case <-ctx.Done(): + return provider.ChatReply{}, ctx.Err() + case <-time.After(wait): + } + } +} + +// audioReply returns the newest audio message newer than afterID. Telegram +// returns history newest first, so the first match is the newest. +func audioReply(chatID string, afterID int, messages []tg.MessageClass) (provider.ChatReply, bool) { + for _, entity := range messages { + msg, ok := entity.(*tg.Message) + if !ok || msg.ID <= afterID || msg.Out { + continue + } + media, ok := msg.Media.(*tg.MessageMediaDocument) + if !ok { + continue + } + doc, ok := media.Document.(*tg.Document) + if !ok { + continue + } + info, ok := audioInfo(doc) + if !ok { + continue + } + track := playlist.Track{ + Path: fmt.Sprintf("%s%s:%d", uriPrefix, chatID, msg.ID), + Title: info.title, + Artist: info.performer, + DurationSecs: info.duration, + ProviderMeta: map[string]string{"telegram.id": fmt.Sprint(msg.ID)}, + } + return provider.ChatReply{ + Kind: "audio", + Track: track, + Text: strings.TrimSpace(msg.Message), + From: senderOf(msg), + MessageID: msg.ID, + Buttons: buttonsOf(msg), + Links: linksOf(msg), + }, true + } + return provider.ChatReply{}, false +} + +// newestReplyWithButtons returns the newest text/keyboard message only when +// it carries buttons. A newer text reply without a keyboard supersedes an +// older menu, so WaitReply reports the newer failure instead of the stale +// options. +func newestReplyWithButtons(afterID int, messages []tg.MessageClass) (provider.ChatReply, bool) { + for _, entity := range messages { + msg, ok := entity.(*tg.Message) + if !ok || msg.ID <= afterID || msg.Out { + continue + } + buttons := buttonsOf(msg) + text := strings.TrimSpace(msg.Message) + if text == "" && len(buttons) == 0 { + continue + } + if len(buttons) == 0 { + return provider.ChatReply{}, false + } + return provider.ChatReply{ + Kind: "text", + Text: text, + From: senderOf(msg), + MessageID: msg.ID, + Buttons: buttons, + Links: linksOf(msg), + }, true + } + return provider.ChatReply{}, false +} + +// textReply returns the newest text message newer than afterID, with the +// inline buttons attached to it. +func textReply(afterID int, messages []tg.MessageClass) (provider.ChatReply, bool) { + for _, entity := range messages { + msg, ok := entity.(*tg.Message) + if !ok || msg.ID <= afterID || msg.Out { + continue + } + if text := strings.TrimSpace(msg.Message); text != "" { + return provider.ChatReply{ + Kind: "text", + Text: text, + From: senderOf(msg), + MessageID: msg.ID, + Buttons: buttonsOf(msg), + Links: linksOf(msg), + }, true + } + } + return provider.ChatReply{}, false +} + +// linksOf returns the URLs the message text points to, both explicit text +// links and bare URLs. +func linksOf(msg *tg.Message) []string { + if len(msg.Entities) == 0 { + return nil + } + // Telegram entity offsets and lengths count UTF-16 code units. A rune + // slice counts code points, so an emoji before a URL would make the end + // index too large and drop the link. + units := utf16.Encode([]rune(msg.Message)) + var out []string + for _, entity := range msg.Entities { + switch value := entity.(type) { + case *tg.MessageEntityTextURL: + if value.URL != "" { + out = append(out, value.URL) + } + case *tg.MessageEntityURL: + start, end := value.Offset, value.Offset+value.Length + if start >= 0 && end <= len(units) && start < end { + out = append(out, string(utf16.Decode(units[start:end]))) + } + } + } + return out +} + +// buttonsOf reads the inline keyboard of a message. Link buttons carry a URL; +// callback buttons carry the data the bot expects back. +func buttonsOf(msg *tg.Message) []provider.ChatButton { + switch markup := msg.ReplyMarkup.(type) { + case *tg.ReplyInlineMarkup: + var out []provider.ChatButton + for _, row := range markup.Rows { + for _, button := range row.Buttons { + item := provider.ChatButton{Text: button.Text} + switch kind := button.Type.(type) { + case *tg.InlineButtonTypeCallback: + item.Kind = "callback" + item.Data = kind.Data + if utf8.Valid(kind.Data) { + item.DataText = string(kind.Data) + } + case *tg.InlineButtonTypeURL: + item.Kind = "url" + item.URL = kind.URL + case *tg.InlineButtonTypeWebView: + item.Kind = "url" + item.URL = kind.URL + case *tg.InlineButtonTypeDisabled: + item.Kind = "disabled" + case *tg.InlineButtonTypeSwitchInline: + item.Kind = "switch_inline" + item.Query = kind.Query + case *tg.InlineButtonTypeCopy: + item.Kind = "copy" + default: + item.Kind = strings.TrimPrefix(fmt.Sprintf("%T", button.Type), "*tg.") + } + out = append(out, item) + } + } + return out + case *tg.ReplyKeyboardMarkup: + var out []provider.ChatButton + for _, row := range markup.Rows { + for _, button := range row.Buttons { + out = append(out, provider.ChatButton{Text: button.Text, Kind: "text", SendText: true}) + } + } + return out + default: + return nil + } +} + +// senderOf describes who sent a message, when Telegram reports it. +func senderOf(msg *tg.Message) string { + switch peer := msg.FromID.(type) { + case *tg.PeerUser: + return fmt.Sprintf("u:%d", peer.UserID) + case *tg.PeerChat: + return fmt.Sprintf("c:%d", peer.ChatID) + case *tg.PeerChannel: + return fmt.Sprintf("ch:%d", peer.ChannelID) + default: + return "" + } +} + +// sentMessageID walks the updates Telegram returns for a send. The id may come +// as updateMessageID, updateNewMessage, updateNewChannelMessage or, for a +// short update, on the update itself. +func sentMessageID(updates tg.UpdatesClass) int { + switch value := updates.(type) { + case *tg.Updates: + return idInUpdates(value.Updates) + case *tg.UpdatesCombined: + return idInUpdates(value.Updates) + case *tg.UpdateShortSentMessage: + return value.ID + default: + return 0 + } +} + +func idInUpdates(updates []tg.UpdateClass) int { + for _, entity := range updates { + switch value := entity.(type) { + case *tg.UpdateMessageID: + return value.ID + case *tg.UpdateNewMessage: + return value.Message.GetID() + case *tg.UpdateNewChannelMessage: + return value.Message.GetID() + } + } + return 0 +} + +func randomMessageID() (int64, error) { + var buf [8]byte + if _, err := rand.Read(buf[:]); err != nil { + return 0, fmt.Errorf("telegram: random id: %w", err) + } + id := int64(binary.LittleEndian.Uint64(buf[:]) & (1<<63 - 1)) + if id == 0 { + id = 1 + } + return id, nil +} + +// ResolveChat resolves a username or t.me link into the playlist description +// the dialog list uses. It also creates the peer without sending a message. +func (p *Provider) ResolveChat(ctx context.Context, username string) (playlist.PlaylistInfo, error) { + if err := p.waitContext(ctx); err != nil { + return playlist.PlaylistInfo{}, err + } + return p.resolveChatCached(ctx, username) +} + +// InlineResults asks a bot for the inline results of query. This is the flow +// behind a switch_inline button: the user picks one result, and +// SendInlineResult sends it as a normal message. +func (p *Provider) InlineResults(ctx context.Context, chatID, botID, query, offset string) (provider.InlineResults, error) { + if err := p.waitContext(ctx); err != nil { + return provider.InlineResults{}, err + } + peer, _, err := p.resolveChatID(ctx, chatID) + if err != nil { + return provider.InlineResults{}, err + } + botPeer, _, err := p.resolveChatID(ctx, botID) + if err != nil { + return provider.InlineResults{}, err + } + botUser, ok := botPeer.(*tg.InputPeerUser) + if !ok { + return provider.InlineResults{}, fmt.Errorf("telegram: %q is not a bot", botID) + } + response, err := p.writer().MessagesGetInlineBotResults(ctx, &tg.MessagesGetInlineBotResultsRequest{ + Bot: &tg.InputUser{ + UserID: botUser.UserID, + AccessHash: botUser.AccessHash, + }, + Peer: peer, + Query: query, + Offset: offset, + }) + if err != nil { + return provider.InlineResults{}, fmt.Errorf("telegram: inline results of %q: %w", botID, err) + } + out := provider.InlineResults{ + QueryID: response.QueryID, + NextOffset: response.NextOffset, + } + for _, entity := range response.Results { + switch result := entity.(type) { + case *tg.BotInlineResult: + out.Results = append(out.Results, provider.InlineResult{ + ID: result.ID, + Type: result.Type, + Kind: inlineMessageKind(result.SendMessage), + Title: result.Title, + Description: result.Description, + URL: result.URL, + ThumbURL: webDocumentURL(result.Thumb), + }) + case *tg.BotInlineMediaResult: + kind := inlineMessageKind(result.SendMessage) + if doc, ok := result.Document.(*tg.Document); ok { + if _, audio := audioInfo(doc); audio { + kind = "audio" + } + } + out.Results = append(out.Results, provider.InlineResult{ + ID: result.ID, + Type: result.Type, + Kind: kind, + Title: result.Title, + Description: result.Description, + }) + } + } + return out, nil +} + +// webDocumentURL returns the public URL of an inline result thumbnail. +func webDocumentURL(document tg.WebDocumentClass) string { + switch value := document.(type) { + case *tg.WebDocument: + return value.URL + case *tg.WebDocumentNoProxy: + return value.URL + default: + return "" + } +} + +// inlineMessageKind says what sending the result creates. A media auto +// message is usually an audio or a document; the plugin can prefer it over an +// article. +func inlineMessageKind(message tg.BotInlineMessageClass) string { + switch message.(type) { + case *tg.BotInlineMessageMediaAuto: + return "media" + case *tg.BotInlineMessageText: + return "text" + case *tg.BotInlineMessageMediaContact: + return "contact" + case *tg.BotInlineMessageMediaGeo, *tg.BotInlineMessageMediaVenue: + return "geo" + case *tg.BotInlineMessageMediaWebPage: + return "webpage" + default: + return "text" + } +} + +// SendInlineResult sends one result of an inline query to the chat. +func (p *Provider) SendInlineResult(ctx context.Context, chatID, botID string, queryID int64, resultID string) (int, error) { + if err := p.waitContext(ctx); err != nil { + return 0, err + } + peer, _, err := p.resolveChatID(ctx, chatID) + if err != nil { + return 0, err + } + // Resolve the bot so a bad id fails before Telegram creates the message. + if _, _, err := p.resolveChatID(ctx, botID); err != nil { + return 0, err + } + randomID, err := randomMessageID() + if err != nil { + return 0, err + } + updates, err := p.writer().MessagesSendInlineBotResult(ctx, &tg.MessagesSendInlineBotResultRequest{ + Peer: peer, + QueryID: queryID, + ID: resultID, + RandomID: randomID, + }) + if err != nil { + return 0, fmt.Errorf("telegram: send inline result: %w", err) + } + id := sentMessageID(updates) + if id == 0 { + return 0, errors.New("telegram: send inline result returned no message id") + } + return id, nil +} diff --git a/external/telegram/write_test.go b/external/telegram/write_test.go new file mode 100644 index 000000000..e6e5e23a8 --- /dev/null +++ b/external/telegram/write_test.go @@ -0,0 +1,480 @@ +package telegram + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/gotd/td/tg" +) + +type fakeWriteAPI struct { + sent *tg.MessagesSendMessageRequest + sendResp tg.UpdatesClass + sendErr error + + history []tg.MessagesMessagesClass + histErr error + histReqs []*tg.MessagesGetHistoryRequest + histTimes []time.Time + + full *tg.UsersUserFull + fullErr error + fullID tg.InputUserClass + + callback *tg.MessagesGetBotCallbackAnswerRequest + callbackErr error + + inline *tg.MessagesBotResults + inlineErr error + inlineReq *tg.MessagesGetInlineBotResultsRequest + sendInline *tg.MessagesSendInlineBotResultRequest + sendInlineResp tg.UpdatesClass + sendInlineErr error +} + +func (f *fakeWriteAPI) MessagesSendMessage(_ context.Context, request *tg.MessagesSendMessageRequest) (tg.UpdatesClass, error) { + f.sent = request + return f.sendResp, f.sendErr +} + +func (f *fakeWriteAPI) MessagesGetHistory(_ context.Context, request *tg.MessagesGetHistoryRequest) (tg.MessagesMessagesClass, error) { + f.histReqs = append(f.histReqs, request) + f.histTimes = append(f.histTimes, time.Now()) + if f.histErr != nil { + return nil, f.histErr + } + if len(f.history) == 0 { + return &tg.MessagesMessages{}, nil + } + next := f.history[0] + if len(f.history) > 1 { + f.history = f.history[1:] + } + return next, nil +} + +func (f *fakeWriteAPI) UsersGetFullUser(_ context.Context, id tg.InputUserClass) (*tg.UsersUserFull, error) { + f.fullID = id + return f.full, f.fullErr +} + +func (f *fakeWriteAPI) MessagesGetBotCallbackAnswer(_ context.Context, request *tg.MessagesGetBotCallbackAnswerRequest) (*tg.MessagesBotCallbackAnswer, error) { + f.callback = request + return &tg.MessagesBotCallbackAnswer{}, f.callbackErr +} + +func (f *fakeWriteAPI) MessagesGetInlineBotResults(_ context.Context, request *tg.MessagesGetInlineBotResultsRequest) (*tg.MessagesBotResults, error) { + f.inlineReq = request + return f.inline, f.inlineErr +} + +func (f *fakeWriteAPI) MessagesSendInlineBotResult(_ context.Context, request *tg.MessagesSendInlineBotResultRequest) (tg.UpdatesClass, error) { + f.sendInline = request + return f.sendInlineResp, f.sendInlineErr +} + +func readyProvider(api writeAPI) *Provider { + p := &Provider{write: api} + p.state = provReady + return p +} + +func TestSendCommand(t *testing.T) { + api := &fakeWriteAPI{sendResp: &tg.Updates{Updates: []tg.UpdateClass{&tg.UpdateMessageID{ID: 42}}}} + p := readyProvider(api) + + id, err := p.SendCommand(context.Background(), "u:100:200", " /start ") + if err != nil { + t.Fatalf("SendCommand: %v", err) + } + if id != 42 { + t.Fatalf("id = %d, want 42", id) + } + if api.sent == nil { + t.Fatal("no message sent") + } + if api.sent.Message != "/start" { + t.Errorf("message = %q, want %q", api.sent.Message, "/start") + } + if api.sent.RandomID == 0 { + t.Error("RandomID = 0") + } + peer, ok := api.sent.Peer.(*tg.InputPeerUser) + if !ok || peer.UserID != 100 || peer.AccessHash != 200 { + t.Errorf("peer = %#v, want user 100/200", api.sent.Peer) + } +} + +func TestSendCommandShortUpdate(t *testing.T) { + api := &fakeWriteAPI{sendResp: &tg.UpdateShortSentMessage{ID: 7}} + p := readyProvider(api) + + id, err := p.SendCommand(context.Background(), "ch:1:2", "/play") + if err != nil { + t.Fatalf("SendCommand: %v", err) + } + if id != 7 { + t.Fatalf("id = %d, want 7", id) + } +} + +func TestSendCommandRejectsEmpty(t *testing.T) { + p := readyProvider(&fakeWriteAPI{}) + if _, err := p.SendCommand(context.Background(), "u:1:2", " "); err == nil { + t.Fatal("expected an error for an empty message") + } +} + +func TestSendCommandPropagatesError(t *testing.T) { + api := &fakeWriteAPI{sendErr: errors.New("FLOOD_WAIT_30")} + p := readyProvider(api) + if _, err := p.SendCommand(context.Background(), "u:1:2", "/start"); err == nil { + t.Fatal("expected the send error") + } +} + +func TestBotCommands(t *testing.T) { + full := &tg.UserFull{} + full.SetBotInfo(tg.BotInfo{Commands: []tg.BotCommand{ + {Command: "search", Description: "Find a track"}, + {Command: "/start", Description: "Start"}, + {Command: "", Description: "ignored"}, + }}) + api := &fakeWriteAPI{full: &tg.UsersUserFull{FullUser: *full}} + p := readyProvider(api) + + commands, err := p.BotCommands(context.Background(), "u:100:200") + if err != nil { + t.Fatalf("BotCommands: %v", err) + } + if len(commands) != 2 { + t.Fatalf("commands = %#v, want 2", commands) + } + if commands[0].Command != "/search" || commands[0].Description != "Find a track" { + t.Errorf("command 0 = %#v", commands[0]) + } + if commands[1].Command != "/start" { + t.Errorf("command 1 = %#v", commands[1]) + } + user, ok := api.fullID.(*tg.InputUser) + if !ok || user.UserID != 100 || user.AccessHash != 200 { + t.Errorf("full user id = %#v", api.fullID) + } +} + +func TestBotCommandsGroupIsEmpty(t *testing.T) { + p := readyProvider(&fakeWriteAPI{}) + commands, err := p.BotCommands(context.Background(), "c:123") + if err != nil { + t.Fatalf("BotCommands: %v", err) + } + if len(commands) != 0 { + t.Fatalf("commands = %#v, want none", commands) + } +} + +func TestWaitReplyAudio(t *testing.T) { + msg := &tg.Message{ + ID: 10, + Media: &tg.MessageMediaDocument{Document: &tg.Document{ + MimeType: "audio/flac", + Attributes: []tg.DocumentAttributeClass{ + &tg.DocumentAttributeAudio{Title: "Walk", Performer: "Foo Fighters", Duration: 260}, + }, + }}, + } + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{msg}}, + }} + p := readyProvider(api) + + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, time.Second) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.Kind != "audio" { + t.Fatalf("kind = %q, want audio", reply.Kind) + } + if reply.Track.Title != "Walk" || reply.Track.Artist != "Foo Fighters" { + t.Errorf("track = %#v", reply.Track) + } + if reply.Track.Path != "telegram:u:1:2:10" { + t.Errorf("path = %q", reply.Track.Path) + } + if len(api.histReqs) != 1 || api.histReqs[0].MinID != 5 { + t.Errorf("history requests = %#v", api.histReqs) + } +} + +func TestWaitReplyText(t *testing.T) { + msg := &tg.Message{ID: 8, Message: "Track not found"} + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{msg}}, + }} + p := readyProvider(api) + + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 100*time.Millisecond) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.Kind != "text" || reply.Text != "Track not found" { + t.Fatalf("reply = %#v", reply) + } +} + +func TestWaitReplyNone(t *testing.T) { + p := readyProvider(&fakeWriteAPI{}) + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 50*time.Millisecond) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.Kind != "none" { + t.Fatalf("reply = %#v, want none", reply) + } +} + +func TestWaitReplyIgnoresOldAndOutgoing(t *testing.T) { + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{ + &tg.Message{ID: 4, Message: "old"}, + &tg.Message{ID: 6, Out: true, Message: "mine"}, + }}, + }} + p := readyProvider(api) + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 50*time.Millisecond) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.Kind != "none" { + t.Fatalf("reply = %#v, want none", reply) + } +} + +func TestBotCallback(t *testing.T) { + api := &fakeWriteAPI{} + p := readyProvider(api) + if err := p.BotCallback(context.Background(), "u:1:2", 77, []byte("data")); err != nil { + t.Fatalf("BotCallback: %v", err) + } + if api.callback == nil || api.callback.MsgID != 77 || string(api.callback.Data) != "data" { + t.Fatalf("callback = %#v", api.callback) + } +} + +func TestInlineResults(t *testing.T) { + api := &fakeWriteAPI{inline: &tg.MessagesBotResults{ + QueryID: 9, + Results: []tg.BotInlineResultClass{ + &tg.BotInlineResult{ID: "1", Type: "audio", Title: "Get Lucky", Description: "Daft Punk"}, + }, + }} + p := readyProvider(api) + results, err := p.InlineResults(context.Background(), "u:1:2", "u:1:2", "get lucky", "") + if err != nil { + t.Fatalf("InlineResults: %v", err) + } + if results.QueryID != 9 || len(results.Results) != 1 { + t.Fatalf("results = %#v", results) + } + if results.Results[0].Title != "Get Lucky" || results.Results[0].Description != "Daft Punk" { + t.Errorf("result = %#v", results.Results[0]) + } + if api.inlineReq == nil || api.inlineReq.Query != "get lucky" { + t.Errorf("request = %#v", api.inlineReq) + } +} + +func TestSendInlineResult(t *testing.T) { + api := &fakeWriteAPI{sendInlineResp: &tg.Updates{Updates: []tg.UpdateClass{&tg.UpdateMessageID{ID: 88}}}} + p := readyProvider(api) + id, err := p.SendInlineResult(context.Background(), "u:1:2", "u:1:2", 9, "1") + if err != nil { + t.Fatalf("SendInlineResult: %v", err) + } + if id != 88 { + t.Fatalf("id = %d", id) + } + if api.sendInline == nil || api.sendInline.QueryID != 9 || api.sendInline.ID != "1" { + t.Errorf("request = %#v", api.sendInline) + } +} + +func TestSentMessageIDFromNewMessage(t *testing.T) { + updates := &tg.Updates{Updates: []tg.UpdateClass{ + &tg.UpdateNewMessage{Message: &tg.Message{ID: 33}}, + }} + if got := sentMessageID(updates); got != 33 { + t.Fatalf("sentMessageID = %d, want 33", got) + } +} + +func TestMessageReadsEditedMenu(t *testing.T) { + msg := &tg.Message{ + ID: 7, + Message: "Settings", + ReplyMarkup: &tg.ReplyInlineMarkup{Rows: []tg.KeyboardInlineButtonRow{{ + Buttons: []tg.KeyboardInlineButton{{ + Text: "FLAC", + Type: &tg.InlineButtonTypeCallback{Data: []byte("flac")}, + }}, + }}}, + } + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{msg}}, + }} + p := readyProvider(api) + + reply, err := p.Message(context.Background(), "u:1:2", 7) + if err != nil { + t.Fatalf("Message: %v", err) + } + if reply.Kind != "text" || reply.Text != "Settings" { + t.Fatalf("reply = %#v", reply) + } + if len(reply.Buttons) != 1 || reply.Buttons[0].Text != "FLAC" || string(reply.Buttons[0].Data) != "flac" { + t.Fatalf("buttons = %#v", reply.Buttons) + } +} + +func TestLinksOfUsesUTF16Offsets(t *testing.T) { + msg := &tg.Message{ + Message: "๐Ÿ˜€ https://example.com", + Entities: []tg.MessageEntityClass{ + &tg.MessageEntityURL{Offset: 3, Length: 19}, + }, + } + links := linksOf(msg) + if len(links) != 1 || links[0] != "https://example.com" { + t.Fatalf("links = %#v, want the URL after the emoji", links) + } +} + +func TestAudioReplyKeepsButtonsAndCaption(t *testing.T) { + msg := &tg.Message{ + ID: 9, + Message: "Here is the track", + Media: &tg.MessageMediaDocument{Document: &tg.Document{ + MimeType: "audio/flac", + Attributes: []tg.DocumentAttributeClass{ + &tg.DocumentAttributeAudio{Title: "Walk", Performer: "Foo Fighters", Duration: 260}, + }, + }}, + ReplyMarkup: &tg.ReplyInlineMarkup{Rows: []tg.KeyboardInlineButtonRow{{ + Buttons: []tg.KeyboardInlineButton{{ + Text: "FLAC", + Type: &tg.InlineButtonTypeCallback{Data: []byte("flac")}, + }}, + }}}, + } + reply, ok := replyFromMessage("u:1:2", msg) + if !ok { + t.Fatal("replyFromMessage returned false") + } + if reply.Kind != "audio" || reply.Text != "Here is the track" { + t.Fatalf("reply = %#v", reply) + } + if len(reply.Buttons) != 1 || reply.Buttons[0].Text != "FLAC" { + t.Fatalf("buttons = %#v", reply.Buttons) + } +} + +func TestWaitContextHonorsCancellation(t *testing.T) { + p := &Provider{} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := p.waitContext(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("waitContext = %v, want context.Canceled", err) + } +} + +func TestWaitAudioKeepsTheLatestText(t *testing.T) { + first := &tg.Message{ID: 6, Message: "Searching"} + second := &tg.Message{ID: 7, Message: "Track not found"} + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{first}}, + &tg.MessagesMessages{Messages: []tg.MessageClass{second}}, + }} + p := readyProvider(api) + + reply, err := p.WaitAudio(context.Background(), "u:1:2", 5, 1300*time.Millisecond) + if err != nil { + t.Fatalf("WaitAudio: %v", err) + } + if reply.Kind != "text" || reply.Text != "Track not found" { + t.Fatalf("reply = %#v, want the latest text", reply) + } +} + +func TestMessageWindowStartsAtTheRequestedID(t *testing.T) { + msg := &tg.Message{ID: 7, Message: "Settings"} + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{msg}}, + }} + p := readyProvider(api) + + if _, err := p.Message(context.Background(), "u:1:2", 7); err != nil { + t.Fatalf("Message: %v", err) + } + if len(api.histReqs) != 1 { + t.Fatalf("history requests = %d, want 1", len(api.histReqs)) + } + if got := api.histReqs[0].OffsetID; got != 8 { + t.Fatalf("OffsetID = %d, want 8", got) + } +} + +func TestWaitReplyRestartsGraceForANewMessageWithTheSameText(t *testing.T) { + oldGrace := replyGrace + replyGrace = 50 * time.Millisecond + t.Cleanup(func() { replyGrace = oldGrace }) + + first := &tg.Message{ID: 6, Message: "Searching"} + second := &tg.Message{ID: 7, Message: "Searching"} + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{first}}, + &tg.MessagesMessages{Messages: []tg.MessageClass{second}}, + }} + p := readyProvider(api) + + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 500*time.Millisecond) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.MessageID != 7 { + t.Fatalf("message id = %d, want the newer message", reply.MessageID) + } + if len(api.histTimes) < 2 { + t.Fatalf("history calls = %d, want at least 2", len(api.histTimes)) + } + if since := time.Since(api.histTimes[1]); since < 40*time.Millisecond { + t.Fatalf("returned %v after the newer message, want a restarted grace period", since) + } +} + +func TestWaitReplyPrefersNewerTextOverOlderKeyboard(t *testing.T) { + keyboard := &tg.Message{ + ID: 7, + Message: "Menu", + ReplyMarkup: &tg.ReplyInlineMarkup{Rows: []tg.KeyboardInlineButtonRow{{ + Buttons: []tg.KeyboardInlineButton{{ + Text: "FLAC", + Type: &tg.InlineButtonTypeCallback{Data: []byte("flac")}, + }}, + }}}, + } + text := &tg.Message{ID: 8, Message: "Track not found"} + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{text, keyboard}}, + }} + p := readyProvider(api) + + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 100*time.Millisecond) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.Kind != "text" || reply.Text != "Track not found" { + t.Fatalf("reply = %#v, want the newer text", reply) + } +} diff --git a/lua_wiring.go b/lua_wiring.go index c9474ebf6..d7a88a889 100644 --- a/lua_wiring.go +++ b/lua_wiring.go @@ -1,7 +1,12 @@ package main import ( + "context" + "encoding/base64" + "fmt" + "strings" "sync" + "sync/atomic" "time" tea "charm.land/bubbletea/v2" @@ -9,6 +14,7 @@ import ( "github.com/bjarneo/cliamp/internal/playback" "github.com/bjarneo/cliamp/luaplugin" "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/provider" "github.com/bjarneo/cliamp/ui/model" ) @@ -84,6 +90,13 @@ func luaControlProvider(send func(tea.Msg)) luaplugin.ControlProvider { QueueMove: func(from, to int) { send(model.PluginQueueMsg{Op: "move", Index: from, To: to}) }, + QueueInsert: func(index int, t luaplugin.Track) { + send(model.PluginQueueMsg{Op: "insert", Index: index, Track: playlist.Track{ + Path: t.Path, Title: t.Title, Artist: t.Artist, Album: t.Album, + Genre: t.Genre, Year: t.Year, DurationSecs: t.Duration, Stream: t.Stream, + AlbumArtURL: t.ArtURL, + }}) + }, } } @@ -132,11 +145,15 @@ func newOrderedSender(send func(tea.Msg)) (queue func(tea.Msg), stop func()) { // luaUIProvider lets Lua plugins show a status message. func luaUIProvider(send func(tea.Msg), headless bool) luaplugin.UIProvider { + var inputSeq atomic.Uint64 return luaplugin.UIProvider{ ShowMessage: func(text string, duration time.Duration) { send(model.ShowStatusMsg{Text: text, Duration: duration}) }, - ShowSelect: showSelectFor(send, headless), + ShowSelect: showSelectFor(send, headless), + ShowInput: showInputFor(send, headless, &inputSeq), + UpdateInput: updateInputFor(send, headless), + ShowText: showTextFor(send, headless), SetVis: func(name string) { send(model.SetVisMsg{Name: name}) }, @@ -146,11 +163,342 @@ func luaUIProvider(send func(tea.Msg), headless bool) luaplugin.UIProvider { // showSelectFor returns nil in headless mode: there is no UI to answer a // selector, and the API reports it as unavailable instead of accepting a // request nobody can complete. -func showSelectFor(send func(tea.Msg), headless bool) func(string, []string, int, func(int), func()) { +func showTextFor(send func(tea.Msg), headless bool) func(string, string, func()) { + if headless { + return nil + } + return func(title, text string, onClose func()) { + send(model.LuaTextMsg{Title: title, Text: text, OnClose: onClose}) + } +} + +func showInputFor(send func(tea.Msg), headless bool, seq *atomic.Uint64) func(string, string, string, []luaplugin.SelectOption, func(string), func(string), func(int), func()) uint64 { + if headless { + return nil + } + return func(title, placeholder, value string, suggestions []luaplugin.SelectOption, onChange, onSubmit func(string), onSelect func(int), onCancel func()) uint64 { + token := seq.Add(1) + send(model.LuaInputMsg{ + Token: token, + Title: title, + Placeholder: placeholder, + Value: value, + Suggestions: suggestions, + OnChange: onChange, + OnSubmit: onSubmit, + OnSelect: onSelect, + OnCancel: onCancel, + }) + return token + } +} + +func updateInputFor(send func(tea.Msg), headless bool) func([]luaplugin.SelectOption, bool, string, bool, uint64) { + if headless { + return nil + } + return func(options []luaplugin.SelectOption, live bool, query string, querySet bool, token uint64) { + send(model.LuaInputSuggestionsMsg{ + Token: token, + Options: options, + Live: live, + Query: query, + QuerySet: querySet, + }) + } +} + +func showSelectFor(send func(tea.Msg), headless bool) func(string, string, []luaplugin.SelectOption, int, func(int), func()) { if headless { return nil } - return func(title string, options []string, cursor int, onDone func(index int), onCancel func()) { - send(model.LuaSelectMsg{Title: title, Options: options, Cursor: cursor, OnDone: onDone, OnCancel: onCancel}) + return func(title, body string, options []luaplugin.SelectOption, cursor int, onDone func(index int), onCancel func()) { + send(model.LuaSelectMsg{Title: title, Body: body, Options: options, Cursor: cursor, OnDone: onDone, OnCancel: onCancel}) + } +} + +// luaProviderProvider exposes the provider context and the chat actions a +// provider supports. The dispatcher keeps the Lua API generic: a plugin asks +// for "telegram.send" and the provider that implements ChatCommander runs it. +// The provider call runs on the caller's goroutine, so a blocking reply never +// holds the UI. +func luaProviderProvider(entries []provider.Entry, load func() model.PluginState, send func(tea.Msg)) luaplugin.ProviderProvider { + var addChatMu sync.Mutex + return luaplugin.ProviderProvider{ + Current: func() luaplugin.ProviderInfo { return load().Provider }, + Open: func(info luaplugin.ProviderInfo) error { + if send == nil { + return fmt.Errorf("ui: not available") + } + if current := load().Provider.Name; current != "" && info.Name != "" && !strings.EqualFold(current, info.Name) { + return fmt.Errorf("provider.open: switch to %s first", info.Name) + } + send(model.PluginOpenProviderMsg{ + ProviderName: info.Name, + Playlist: playlist.PlaylistInfo{ + ID: info.PlaylistID, + Name: info.PlaylistName, + Section: info.PlaylistSection, + }, + }) + return nil + }, + Call: func(ctx context.Context, action string, params map[string]any) (map[string]any, error) { + name, verb, ok := strings.Cut(action, ".") + if !ok || name == "" || verb == "" { + return nil, fmt.Errorf("unknown provider action %q", action) + } + var prov playlist.Provider + for _, entry := range entries { + if strings.EqualFold(entry.Name, name) || strings.EqualFold(entry.Key, name) { + prov = entry.Provider + break + } + } + if prov == nil { + return nil, fmt.Errorf("provider %q is not available", name) + } + chat, _ := params["chat"].(string) + if chat == "" && verb != "resolve" { + return nil, fmt.Errorf("%s: chat is required", action) + } + commander, ok := prov.(provider.ChatCommander) + if !ok { + return nil, fmt.Errorf("provider %q does not support chat actions", name) + } + switch verb { + case "commands": + commands, err := commander.BotCommands(ctx, chat) + if err != nil { + return nil, err + } + rows := make([]any, 0, len(commands)) + for _, command := range commands { + rows = append(rows, map[string]any{ + "command": command.Command, + "description": command.Description, + }) + } + return map[string]any{"commands": rows}, nil + case "send": + text, _ := params["text"].(string) + id, err := commander.SendCommand(ctx, chat, text) + if err != nil { + return nil, err + } + return map[string]any{"id": id}, nil + case "ask": + text, _ := params["text"].(string) + id, err := commander.SendCommand(ctx, chat, text) + if err != nil { + return nil, err + } + return waitReplyResult(ctx, commander, chat, id, params) + case "reply": + return waitReplyResult(ctx, commander, chat, intParam(params, "after"), params) + case "resolve": + info, err := commander.ResolveChat(ctx, stringParam(params, "username")) + if err != nil { + return nil, err + } + return map[string]any{ + "id": info.ID, + "name": info.Name, + "section": info.Section, + }, nil + case "add_chat": + addChatMu.Lock() + defer addChatMu.Unlock() + filter, ok := prov.(provider.ChatFilter) + if !ok { + return nil, fmt.Errorf("provider %q has no chat filter", name) + } + chat := stringParam(params, "chat") + chats := filter.Chats() + found := false + for _, existing := range chats { + if existing == chat { + found = true + break + } + } + added := false + if !found && len(chats) > 0 { + chats = append(chats, chat) + if err := filter.SetChats(chats); err != nil { + return nil, err + } + added = true + } + return map[string]any{"added": added, "filtered": len(chats) > 0}, nil + case "inline": + bot := stringParam(params, "bot") + if bot == "" { + bot = chat + } + inline, err := commander.InlineResults(ctx, chat, bot, stringParam(params, "query"), stringParam(params, "offset")) + if err != nil { + return nil, err + } + rows := make([]any, 0, len(inline.Results)) + for _, result := range inline.Results { + rows = append(rows, map[string]any{ + "id": result.ID, + "type": result.Type, + "kind": result.Kind, + "title": result.Title, + "description": result.Description, + "url": result.URL, + "thumb_url": result.ThumbURL, + }) + } + return map[string]any{ + // Lua 5.1 numbers are float64 and cannot hold a 64-bit + // query id exactly. Keep it a string across the boundary. + "query_id": fmt.Sprintf("%d", inline.QueryID), + "next_offset": inline.NextOffset, + "results": rows, + }, nil + case "send_inline": + bot := stringParam(params, "bot") + if bot == "" { + bot = chat + } + id, err := commander.SendInlineResult(ctx, chat, bot, int64Param(params, "query_id"), stringParam(params, "result_id")) + if err != nil { + return nil, err + } + return map[string]any{"id": id}, nil + case "message": + reply, err := commander.Message(ctx, chat, intParam(params, "message_id")) + if err != nil { + return nil, err + } + return replyResult(reply), nil + case "callback": + data, err := base64.StdEncoding.DecodeString(stringParam(params, "data_b64")) + if err != nil { + return nil, fmt.Errorf("%s: data_b64: %w", action, err) + } + if err := commander.BotCallback(ctx, chat, intParam(params, "message_id"), data); err != nil { + return nil, err + } + return map[string]any{"ok": true}, nil + default: + return nil, fmt.Errorf("unknown provider action %q", action) + } + }, + } +} + +func replyResult(reply provider.ChatReply) map[string]any { + out := map[string]any{ + "kind": reply.Kind, + "text": reply.Text, + "from": reply.From, + "message_id": reply.MessageID, + } + if reply.Kind == "audio" { + out["track"] = luaplugin.TrackData(pluginTrackFromPlaylist(reply.Track)) + } + if len(reply.Links) > 0 { + out["links"] = reply.Links + } + if len(reply.Buttons) > 0 { + buttons := make([]any, 0, len(reply.Buttons)) + for _, button := range reply.Buttons { + row := map[string]any{"text": button.Text, "kind": button.Kind} + if len(button.Data) > 0 { + row["data_b64"] = base64.StdEncoding.EncodeToString(button.Data) + } + if button.DataText != "" { + row["data_text"] = button.DataText + } + if button.URL != "" { + row["url"] = button.URL + } + if button.SendText { + row["send_text"] = true + } + if button.Query != "" { + row["query"] = button.Query + } + buttons = append(buttons, row) + } + out["buttons"] = buttons + } + return out +} + +func waitReplyResult(ctx context.Context, commander provider.ChatCommander, chat string, after int, params map[string]any) (map[string]any, error) { + timeout := 20 * time.Second + if seconds, ok := params["timeout"].(float64); ok && seconds > 0 { + timeout = time.Duration(seconds * float64(time.Second)) + } else if deadline, ok := ctx.Deadline(); ok { + timeout = time.Until(deadline) + if timeout <= 0 { + timeout = time.Millisecond + } + } + var ( + reply provider.ChatReply + err error + ) + if audioOnly, _ := params["audio_only"].(bool); audioOnly { + reply, err = commander.WaitAudio(ctx, chat, after, timeout) + } else { + reply, err = commander.WaitReply(ctx, chat, after, timeout) + } + if err != nil { + return nil, err + } + out := replyResult(reply) + out["id"] = after + return out, nil +} + +func pluginTrackFromPlaylist(track playlist.Track) luaplugin.Track { + return luaplugin.Track{ + Title: track.Title, + Artist: track.Artist, + Album: track.Album, + Genre: track.Genre, + Path: track.Path, + Year: track.Year, + Number: track.TrackNumber, + Duration: track.DurationSecs, + Stream: track.Stream, + ArtURL: track.AlbumArtURL, + } +} + +func stringParam(params map[string]any, key string) string { + value, _ := params[key].(string) + return value +} + +func int64Param(params map[string]any, key string) int64 { + switch value := params[key].(type) { + case float64: + return int64(value) + case int64: + return value + case int: + return int64(value) + case string: + var out int64 + fmt.Sscan(value, &out) + return out + } + return 0 +} + +func intParam(params map[string]any, key string) int { + switch value := params[key].(type) { + case float64: + return int(value) + case int: + return value } + return 0 } diff --git a/lua_wiring_test.go b/lua_wiring_test.go index 887149142..c5e797210 100644 --- a/lua_wiring_test.go +++ b/lua_wiring_test.go @@ -1,6 +1,7 @@ package main import ( + "context" "reflect" "testing" "time" @@ -10,6 +11,7 @@ import ( "github.com/bjarneo/cliamp/internal/playback" "github.com/bjarneo/cliamp/luaplugin" "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/provider" "github.com/bjarneo/cliamp/ui/model" ) @@ -194,3 +196,64 @@ func TestLuaStateProviderReadsPublishedState(t *testing.T) { t.Errorf("queue of a state with no Queue = %#v, want nil", got) } } + +type fakeChatCommander struct { + provider.ChatCommander + replyCalled bool + audioCalled bool + timeout time.Duration +} + +func (f *fakeChatCommander) WaitReply(_ context.Context, _ string, _ int, timeout time.Duration) (provider.ChatReply, error) { + f.replyCalled = true + f.timeout = timeout + return provider.ChatReply{Kind: "text"}, nil +} + +func (f *fakeChatCommander) WaitAudio(_ context.Context, _ string, _ int, timeout time.Duration) (provider.ChatReply, error) { + f.audioCalled = true + f.timeout = timeout + return provider.ChatReply{Kind: "audio"}, nil +} + +func TestWaitReplyResultHonorsAudioOnly(t *testing.T) { + f := &fakeChatCommander{} + out, err := waitReplyResult(context.Background(), f, "u:1:2", 5, map[string]any{"audio_only": true}) + if err != nil { + t.Fatalf("waitReplyResult: %v", err) + } + if f.replyCalled || !f.audioCalled { + t.Fatalf("reply=%v audio=%v, want only WaitAudio", f.replyCalled, f.audioCalled) + } + if out["kind"] != "audio" { + t.Fatalf("kind = %v", out["kind"]) + } +} + +func TestWaitReplyResultUsesContextDeadline(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + f := &fakeChatCommander{} + if _, err := waitReplyResult(ctx, f, "u:1:2", 5, nil); err != nil { + t.Fatalf("waitReplyResult: %v", err) + } + if f.timeout < time.Second || f.timeout > 2*time.Second { + t.Fatalf("timeout = %v, want the remaining context deadline", f.timeout) + } +} + +func TestReplyResultIncludesButtonQuery(t *testing.T) { + out := replyResult(provider.ChatReply{Buttons: []provider.ChatButton{{ + Text: "Switch", + Kind: "switch_inline", + Query: "daft punk", + }}}) + buttons, ok := out["buttons"].([]any) + if !ok || len(buttons) != 1 { + t.Fatalf("buttons = %#v", out["buttons"]) + } + row, ok := buttons[0].(map[string]any) + if !ok || row["query"] != "daft punk" { + t.Fatalf("row = %#v, want query", buttons[0]) + } +} diff --git a/luaplugin/api_action.go b/luaplugin/api_action.go new file mode 100644 index 000000000..bdb5fe30e --- /dev/null +++ b/luaplugin/api_action.go @@ -0,0 +1,147 @@ +package luaplugin + +import ( + "errors" + "strings" + + lua "github.com/yuin/gopher-lua" +) + +// errActionExists is returned when a plugin registers the same action id +// twice. +var errActionExists = errors.New("p:action: id already registered") + +// Action is one entry a plugin contributes to the "!" action pane. Prompt is +// the label of the text input; when it is empty the action runs without +// asking for text. Run calls the plugin callback with the typed text. +type Action struct { + ID string + Plugin string + Label string + Description string + Provider string + Key string + Prompt string + Context string // "chat", "chats" or empty for both + + run func(text string) +} + +// Run invokes the action callback. It is safe to call from the UI goroutine: +// the manager queues the Lua call. +func (a Action) Run(text string) { + if a.run != nil { + a.run(text) + } +} + +// registerActionAPI adds p:action() to the plugin object. +func (m *Manager) registerActionAPI(L *lua.LState, obj *lua.LTable, p *Plugin) { + L.SetField(obj, "action", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermUI, "p:action") { + L.Push(lua.LFalse) + L.Push(lua.LString("ui permission required")) + return 2 + } + // p:action{...} passes the plugin object first. + opts, ok := L.Get(2).(*lua.LTable) + if !ok { + L.Push(lua.LFalse) + L.Push(lua.LString("p:action: options table required")) + return 2 + } + id := strings.TrimSpace(rawString(L, opts, "id")) + label := strings.TrimSpace(rawString(L, opts, "label")) + fn, ok := opts.RawGetString("on_submit").(*lua.LFunction) + if !ok { + L.Push(lua.LFalse) + L.Push(lua.LString("p:action: on_submit is required")) + return 2 + } + if id == "" { + id = label + } + if id == "" { + L.Push(lua.LFalse) + L.Push(lua.LString("p:action: id or label is required")) + return 2 + } + if label == "" { + label = id + } + key := strings.TrimSpace(rawString(L, opts, "key")) + if key == "" { + key = "!" + } + action := Action{ + ID: id, + Plugin: p.installName, + Label: label, + Description: strings.TrimSpace(rawString(L, opts, "description")), + Provider: strings.TrimSpace(rawString(L, opts, "provider")), + Key: key, + Prompt: strings.TrimSpace(rawString(L, opts, "prompt")), + Context: strings.TrimSpace(rawString(L, opts, "context")), + run: func(text string) { + label := "action " + id + m.mu.RLock() + defer m.mu.RUnlock() + if m.closing { + return + } + m.enqueue(p, label, func() { + m.call(p, label, hookTimeout, 0, fixedArgs(fn, lua.LString(text))) + }) + }, + } + if err := m.addAction(action); err != nil { + L.Push(lua.LFalse) + L.Push(lua.LString(err.Error())) + return 2 + } + L.Push(lua.LTrue) + return 1 + })) +} + +// addAction stores an action. The plugin install name namespaces the ID so two +// plugins can use the same local id. +func (m *Manager) addAction(action Action) error { + m.mu.Lock() + defer m.mu.Unlock() + key := action.Plugin + "\x00" + action.ID + if m.actions == nil { + m.actions = make(map[string]Action) + } + if _, exists := m.actions[key]; exists { + return errActionExists + } + m.actions[key] = action + return nil +} + +// Actions returns the actions registered for key. The slice is a copy and the +// order is unspecified; the caller sorts or filters it. +func (m *Manager) Actions(key string) []Action { + m.mu.RLock() + defer m.mu.RUnlock() + out := make([]Action, 0, len(m.actions)) + for _, action := range m.actions { + if key == "" || action.Key == key { + out = append(out, action) + } + } + return out +} + +// removeActions drops every action of a plugin. It runs when a plugin is +// closed, so the pane never shows a callback into a dead VM. +func (m *Manager) removeActions(installName string) { + m.mu.Lock() + defer m.mu.Unlock() + for key, action := range m.actions { + if action.Plugin == installName { + delete(m.actions, key) + } + } +} diff --git a/luaplugin/api_action_test.go b/luaplugin/api_action_test.go new file mode 100644 index 000000000..6c40a1b60 --- /dev/null +++ b/luaplugin/api_action_test.go @@ -0,0 +1,30 @@ +package luaplugin + +import "testing" + +func TestActionRegisters(t *testing.T) { + m := newTestManager() + loadTestPlugin(t, m, "action-test", ` + local p = plugin.register({name = "action-test", type = "hook", permissions = {"ui"}}) + p:action{key = "!", id = "say", label = "Say", prompt = "Message", on_submit = function(text) end} + `) + actions := m.Actions("!") + if len(actions) != 1 { + t.Fatalf("actions = %#v", actions) + } + if actions[0].ID != "say" || actions[0].Label != "Say" || actions[0].Prompt != "Message" { + t.Fatalf("action = %#v", actions[0]) + } +} + +func TestFailedPluginActionsRemoved(t *testing.T) { + m := newTestManager() + loadTestPluginExpectError(t, m, "bad-action", ` + local p = plugin.register({name = "bad-action", type = "hook", permissions = {"ui"}}) + p:action{key = "!", id = "ghost", label = "Ghost", on_submit = function() end} + error("boom") + `) + if got := m.Actions("!"); len(got) != 0 { + t.Fatalf("actions = %#v, want none after a failed load", got) + } +} diff --git a/luaplugin/api_provider.go b/luaplugin/api_provider.go new file mode 100644 index 000000000..2456dc524 --- /dev/null +++ b/luaplugin/api_provider.go @@ -0,0 +1,193 @@ +package luaplugin + +import ( + "context" + "strings" + "time" + + lua "github.com/yuin/gopher-lua" +) + +// ProviderInfo is the provider and playlist context a plugin sees. The +// playlist is the one open in the provider pane; selection is the row under +// the cursor in the provider list. Either id may be empty. +type ProviderInfo struct { + Name string + PlaylistID string + PlaylistName string + PlaylistSection string + SelectionID string + SelectionName string + SelectionSection string +} + +// ProviderProvider exposes the active provider context and the chat actions a +// provider supports. Call returns a JSON-compatible map. +type ProviderProvider struct { + Current func() ProviderInfo + Call func(ctx context.Context, action string, params map[string]any) (map[string]any, error) + // Open asks the UI to load a playlist the plugin resolved, such as a bot + // chat that was just created. + Open func(info ProviderInfo) error +} + +// providerWrites reports whether an action changes the remote account. Write +// actions need permissions = {"provider-send"}; reads need "provider". The +// check looks at the verb, so "Telegram.send" and "telegram.SEND" cannot +// bypass the permission by changing the provider or verb case. +func providerWrites(action string) bool { + _, verb, ok := strings.Cut(action, ".") + if !ok { + return false + } + switch strings.ToLower(verb) { + case "send", "ask", "callback", "send_inline", "add_chat": + return true + } + return false +} + +// registerProviderAPI adds cliamp.provider.* to the cliamp table. +// +// cliamp.provider.current() -> {name, playlist_id, playlist_name, +// selection_id, selection_name} +// cliamp.provider.call(action, params[, {on_reply = fn, timeout = secs}]) +func (m *Manager) registerProviderAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin) { + tbl := L.NewTable() + + L.SetField(tbl, "current", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermProvider, "cliamp.provider.current") { + return pushErr(L, "provider permission required") + } + pp := m.provider.Load() + if pp == nil || pp.Current == nil { + return pushErr(L, "provider: not available") + } + info := pp.Current() + L.Push(dataToTable(L, map[string]any{ + "name": info.Name, + "playlist_id": info.PlaylistID, + "playlist_name": info.PlaylistName, + "playlist_section": info.PlaylistSection, + "selection_id": info.SelectionID, + "selection_name": info.SelectionName, + "selection_section": info.SelectionSection, + })) + return 1 + })) + + // cliamp.provider.open{provider, playlist_id, playlist_name, playlist_section} + L.SetField(tbl, "open", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermProvider, "cliamp.provider.open") { + return pushErr(L, "provider permission required") + } + opts := L.CheckTable(1) + info := ProviderInfo{ + Name: strings.TrimSpace(rawString(L, opts, "provider")), + PlaylistID: strings.TrimSpace(rawString(L, opts, "playlist_id")), + PlaylistName: strings.TrimSpace(rawString(L, opts, "playlist_name")), + PlaylistSection: strings.TrimSpace(rawString(L, opts, "playlist_section")), + } + pp := m.provider.Load() + if pp == nil || pp.Open == nil { + return pushErr(L, "provider: not available") + } + if info.Name == "" && pp.Current != nil { + info.Name = pp.Current().Name + } + if info.PlaylistID == "" { + return pushErr(L, "cliamp.provider.open: playlist_id is required") + } + if err := pp.Open(info); err != nil { + return pushErr(L, err.Error()) + } + L.Push(lua.LTrue) + return 1 + })) + + L.SetField(tbl, "call", L.NewFunction(func(L *lua.LState) int { + action := strings.TrimSpace(L.CheckString(1)) + if action == "" { + return pushErr(L, "cliamp.provider.call: action is required") + } + if providerWrites(action) { + if !p.permitted(PermProviderSend, "cliamp.provider.call") { + return pushErr(L, "provider-send permission required") + } + } else if !p.permitted(PermProvider, "cliamp.provider.call") { + return pushErr(L, "provider permission required") + } + params := map[string]any{} + if value := L.Get(2); value != lua.LNil { + table, ok := value.(*lua.LTable) + if !ok { + return pushErr(L, "cliamp.provider.call: params must be a table") + } + converted, ok := luaToGo(table).(map[string]any) + if !ok { + return pushErr(L, "cliamp.provider.call: params must be a table with string keys") + } + params = converted + } + pp := m.provider.Load() + if pp == nil || pp.Call == nil { + return pushErr(L, "provider: not available") + } + + var opts *lua.LTable + if value := L.Get(3); value != lua.LNil { + opts, _ = value.(*lua.LTable) + } + var onReply *lua.LFunction + timeout := 60 * time.Second + if opts != nil { + onReply, _ = opts.RawGetString("on_reply").(*lua.LFunction) + if seconds := optFloatField(L, opts, "timeout"); seconds > 0 { + timeout = time.Duration(seconds * float64(time.Second)) + } + } + + if onReply != nil { + go m.runProviderCall(p, pp.Call, action, params, timeout, onReply) + L.Push(lua.LTrue) + return 1 + } + + ctx, cancel := context.WithTimeout(callContext(L), timeout) + defer cancel() + result, err := pp.Call(ctx, action, params) + if err != nil { + return pushErr(L, err.Error()) + } + L.Push(dataToTable(L, result)) + return 1 + })) + + L.SetField(cliamp, "provider", tbl) +} + +// runProviderCall runs a provider action off the Lua VM and delivers the +// result to the plugin callback. A key bind has a five-second hook budget, so +// a plugin that waits for a bot must use on_reply instead of blocking. +func (m *Manager) runProviderCall(p *Plugin, call func(context.Context, string, map[string]any) (map[string]any, error), action string, params map[string]any, timeout time.Duration, fn *lua.LFunction) { + ctx, cancel := context.WithTimeout(m.ctx, timeout) + defer cancel() + result, err := call(ctx, action, params) + label := "provider.call " + action + m.enqueueCompletion(p, label, func() { + m.call(p, label, hookTimeout, 0, func(L *lua.LState) (*lua.LFunction, []lua.LValue) { + if err != nil { + return fn, []lua.LValue{lua.LNil, lua.LString(err.Error())} + } + return fn, []lua.LValue{dataToTable(L, result)} + }) + }) +} + +// optFloatField reads a number field from a Lua options table. +func optFloatField(L *lua.LState, table *lua.LTable, key string) float64 { + if value, ok := table.RawGetString(key).(lua.LNumber); ok { + return float64(value) + } + return 0 +} diff --git a/luaplugin/api_provider_test.go b/luaplugin/api_provider_test.go new file mode 100644 index 000000000..cca8b07d4 --- /dev/null +++ b/luaplugin/api_provider_test.go @@ -0,0 +1,217 @@ +package luaplugin + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + lua "github.com/yuin/gopher-lua" +) + +func TestProviderCurrent(t *testing.T) { + m := newTestManager() + m.SetProviderProvider(ProviderProvider{ + Current: func() ProviderInfo { + return ProviderInfo{ + Name: "Telegram", + PlaylistID: "u:1:2", + PlaylistName: "DeezLoad", + PlaylistSection: "Bots", + SelectionID: "u:3:4", + SelectionName: "Other", + SelectionSection: "Chats", + } + }, + }) + loadTestPlugin(t, m, "provider-current", ` + local p = plugin.register({name = "provider-current", type = "hook", permissions = {"provider"}}) + local c = cliamp.provider.current() + _G.name = c.name + _G.playlist = c.playlist_name + _G.playlist_section = c.playlist_section + _G.selection = c.selection_name + _G.selection_section = c.selection_section + `) + + p := m.plugins[0] + if got := p.L.GetGlobal("name").String(); got != "Telegram" { + t.Errorf("name = %q", got) + } + if got := p.L.GetGlobal("playlist").String(); got != "DeezLoad" { + t.Errorf("playlist = %q", got) + } + if got := p.L.GetGlobal("selection").String(); got != "Other" { + t.Errorf("selection = %q", got) + } + if got := p.L.GetGlobal("playlist_section").String(); got != "Bots" { + t.Errorf("playlist_section = %q", got) + } + if got := p.L.GetGlobal("selection_section").String(); got != "Chats" { + t.Errorf("selection_section = %q", got) + } +} + +func TestProviderCallRead(t *testing.T) { + m := newTestManager() + var gotAction string + m.SetProviderProvider(ProviderProvider{ + Current: func() ProviderInfo { return ProviderInfo{Name: "Telegram"} }, + Call: func(_ context.Context, action string, params map[string]any) (map[string]any, error) { + gotAction = action + if params["chat"] != "u:1:2" { + t.Errorf("chat = %v", params["chat"]) + } + return map[string]any{"commands": []any{ + map[string]any{"command": "/search", "description": "Find"}, + }}, nil + }, + }) + loadTestPlugin(t, m, "provider-read", ` + local p = plugin.register({name = "provider-read", type = "hook", permissions = {"provider"}}) + local res = cliamp.provider.call("telegram.commands", {chat = "u:1:2"}) + _G.command = res.commands[1].command + _G.description = res.commands[1].description + `) + if gotAction != "telegram.commands" { + t.Errorf("action = %q", gotAction) + } + p := m.plugins[0] + if got := p.L.GetGlobal("command").String(); got != "/search" { + t.Errorf("command = %q", got) + } + if got := p.L.GetGlobal("description").String(); got != "Find" { + t.Errorf("description = %q", got) + } +} + +func TestProviderCallWriteNeedsPermission(t *testing.T) { + m := newTestManager() + m.SetProviderProvider(ProviderProvider{ + Call: func(context.Context, string, map[string]any) (map[string]any, error) { + t.Fatal("the call should not run without provider-send") + return nil, nil + }, + }) + loadTestPlugin(t, m, "provider-denied", ` + local p = plugin.register({name = "provider-denied", type = "hook", permissions = {"provider"}}) + local ok, err = cliamp.provider.call("telegram.send", {chat = "u:1:2", text = "/start"}) + _G.ok = ok + _G.err = err + `) + p := m.plugins[0] + if p.L.GetGlobal("ok") != lua.LNil { + t.Error("call should return nil") + } + if got := p.L.GetGlobal("err").String(); !strings.Contains(got, "provider-send") { + t.Errorf("err = %q", got) + } +} + +func TestProviderCallAsyncReply(t *testing.T) { + m := newTestManager() + messages := make(chan string, 1) + m.SetUIProvider(UIProvider{ + ShowMessage: func(text string, _ time.Duration) { messages <- text }, + }) + m.SetProviderProvider(ProviderProvider{ + Call: func(ctx context.Context, action string, params map[string]any) (map[string]any, error) { + if action != "telegram.ask" { + return nil, errors.New("unexpected action " + action) + } + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(30 * time.Millisecond): + } + return map[string]any{ + "id": 10, + "kind": "audio", + "track": map[string]any{ + "title": "Walk", "artist": "Foo Fighters", "path": "telegram:u:1:2:10", + }, + }, nil + }, + }) + loadTestPlugin(t, m, "provider-async", ` + local p = plugin.register({name = "provider-async", type = "hook", permissions = {"provider", "provider-send"}}) + cliamp.provider.call("telegram.ask", {chat = "u:1:2", text = "/search walk"}, { + on_reply = function(reply) + cliamp.message(reply.kind .. ":" .. reply.track.title) + end, + }) + `) + select { + case got := <-messages: + if got != "audio:Walk" { + t.Fatalf("message = %q", got) + } + case <-time.After(2 * time.Second): + t.Fatal("the on_reply callback never ran") + } +} + +func TestProviderCallWriteRejectsMixedCaseAction(t *testing.T) { + m := newTestManager() + m.SetProviderProvider(ProviderProvider{ + Call: func(context.Context, string, map[string]any) (map[string]any, error) { + t.Fatal("the call should not run without provider-send") + return nil, nil + }, + }) + loadTestPlugin(t, m, "provider-mixed", ` + local p = plugin.register({name = "provider-mixed", type = "hook", permissions = {"provider"}}) + local ok, err = cliamp.provider.call("Telegram.send", {chat = "u:1:2", text = "/start"}) + _G.ok = ok + _G.err = err + `) + p := m.plugins[0] + if p.L.GetGlobal("ok") != lua.LNil { + t.Error("call should return nil") + } + if got := p.L.GetGlobal("err").String(); !strings.Contains(got, "provider-send") { + t.Errorf("err = %q", got) + } +} + +func TestProviderCallSyncUsesTimeout(t *testing.T) { + m := newTestManager() + m.SetProviderProvider(ProviderProvider{ + Call: func(ctx context.Context, action string, params map[string]any) (map[string]any, error) { + <-ctx.Done() + return nil, ctx.Err() + }, + }) + loadTestPlugin(t, m, "provider-timeout", ` + local p = plugin.register({name = "provider-timeout", type = "hook", permissions = {"provider"}}) + local res, err = cliamp.provider.call("telegram.commands", {chat = "u:1:2"}, {timeout = 0.05}) + _G.err = err + `) + p := m.plugins[0] + if got := p.L.GetGlobal("err").String(); !strings.Contains(got, "deadline exceeded") { + t.Errorf("err = %q", got) + } +} + +func TestProviderCallReplyIsRead(t *testing.T) { + m := newTestManager() + called := false + m.SetProviderProvider(ProviderProvider{ + Call: func(context.Context, string, map[string]any) (map[string]any, error) { + called = true + return map[string]any{"kind": "text"}, nil + }, + }) + loadTestPlugin(t, m, "provider-reply", ` + local p = plugin.register({name = "provider-reply", type = "hook", permissions = {"provider"}}) + local res = cliamp.provider.call("telegram.reply", {chat = "u:1:2", after = 5}) + _G.kind = res.kind + `) + if !called { + t.Fatal("telegram.reply should be callable with only the provider permission") + } + if got := m.plugins[0].L.GetGlobal("kind").String(); got != "text" { + t.Errorf("kind = %q", got) + } +} diff --git a/luaplugin/api_queue.go b/luaplugin/api_queue.go index 88f9d2023..2243eee32 100644 --- a/luaplugin/api_queue.go +++ b/luaplugin/api_queue.go @@ -120,6 +120,31 @@ func registerQueueAPI(L *lua.LState, cliamp *lua.LTable, loadState func() *State return 0 })) + // cliamp.queue.insert(index, track) -> true | nil, err โ€” insert a track at + // index. The core remaps the play order, the play-next queue and the + // current position. + L.SetField(tbl, "insert", L.NewFunction(func(L *lua.LState) int { + ctrl := loadCtrl() + index := L.CheckInt(1) + table, ok := L.Get(2).(*lua.LTable) + if !ok { + return pushErr(L, "queue.insert: track table required") + } + if !guard("insert") { + return pushErr(L, "queue.insert: requires permissions = {\"control\"}") + } + if ctrl.QueueInsert == nil { + return pushErr(L, "queue.insert: unavailable") + } + track, err := trackFromTable(table) + if err != nil { + return pushErr(L, "queue.insert: "+err.Error()) + } + ctrl.QueueInsert(index, track) + L.Push(lua.LTrue) + return 1 + })) + // cliamp.queue.move(from, to) โ€” reorder a track. L.SetField(tbl, "move", L.NewFunction(func(L *lua.LState) int { ctrl := loadCtrl() diff --git a/luaplugin/api_ui.go b/luaplugin/api_ui.go index c0fd7e574..7304ce29a 100644 --- a/luaplugin/api_ui.go +++ b/luaplugin/api_ui.go @@ -7,12 +7,49 @@ import ( lua "github.com/yuin/gopher-lua" ) +// parseSelectOptions reads a list of select rows. A row is a string (title +// only) or a table with title, subtitle and description. The same shape works +// for select options and input suggestions. +func parseSelectOptions(L *lua.LState, value lua.LValue) []SelectOption { + list, ok := value.(*lua.LTable) + if !ok { + return nil + } + var out []SelectOption + list.ForEach(func(_, value lua.LValue) { + switch item := value.(type) { + case lua.LString: + if text := strings.TrimSpace(string(item)); text != "" { + out = append(out, SelectOption{Title: text}) + } + case *lua.LTable: + title := strings.TrimSpace(rawString(L, item, "title")) + if title == "" { + title = strings.TrimSpace(rawString(L, item, "label")) + } + if title == "" { + title = strings.TrimSpace(rawString(L, item, "value")) + } + if title != "" { + out = append(out, SelectOption{ + Title: title, + Subtitle: strings.TrimSpace(rawString(L, item, "subtitle")), + Description: strings.TrimSpace(rawString(L, item, "description")), + Image: rawString(L, item, "image"), + }) + } + } + }) + return out +} + // registerUIAPI adds cliamp.ui.select. It lets a plugin ask the user to pick // one of several strings, which is the piece a plugin needs to build its own // settings menu: choose a visualizer, a weight, a layout pane, and so on. // Gated on permissions = {"ui"}. func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { tbl := L.NewTable() + var inputToken uint64 // cliamp.ui.select{title = "...", options = {"a", "b"}, on_select = fn} L.SetField(tbl, "select", L.NewFunction(func(L *lua.LState) int { @@ -25,12 +62,7 @@ func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { if !ok { return pushErr(L, "cliamp.ui.select: on_select is required") } - var options []string - if list, ok := opts.RawGetString("options").(*lua.LTable); ok { - list.ForEach(func(_, value lua.LValue) { - options = append(options, value.String()) - }) - } + options := parseSelectOptions(L, opts.RawGetString("options")) if len(options) == 0 { return pushErr(L, "cliamp.ui.select: options is empty") } @@ -48,7 +80,8 @@ func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { }) } } - up.ShowSelect(title, options, cursor, func(index int) { + body := rawString(L, opts, "body") + up.ShowSelect(title, body, options, cursor, func(index int) { if index < 0 { return } @@ -62,6 +95,123 @@ func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { return 1 })) + // cliamp.ui.input{title = "...", placeholder = "...", value = "...", + // on_submit = fn, on_cancel = fn} + L.SetField(tbl, "input", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermUI, "cliamp.ui.input") { + return pushErr(L, "ui permission required") + } + opts := L.CheckTable(1) + fn, ok := opts.RawGetString("on_submit").(*lua.LFunction) + if !ok { + return pushErr(L, "cliamp.ui.input: on_submit is required") + } + up := m.ui.Load() + if up == nil || up.ShowInput == nil { + return pushErr(L, "ui: not available") + } + title := strings.TrimSpace(rawString(L, opts, "title")) + placeholder := strings.TrimSpace(rawString(L, opts, "placeholder")) + value := rawString(L, opts, "value") + suggestions := parseSelectOptions(L, opts.RawGetString("suggestions")) + cancelFn, _ := opts.RawGetString("on_cancel").(*lua.LFunction) + onCancel := func() {} + if cancelFn != nil { + onCancel = func() { + m.enqueue(p, "ui.input cancel", func() { + m.call(p, "ui.input cancel", hookTimeout, 0, fixedArgs(cancelFn)) + }) + } + } + onChangeFn, _ := opts.RawGetString("on_change").(*lua.LFunction) + onChange := func(text string) {} + if onChangeFn != nil { + onChange = func(text string) { + m.enqueue(p, "ui.input change", func() { + m.call(p, "ui.input change", hookTimeout, 0, fixedArgs(onChangeFn, lua.LString(text))) + }) + } + } + onSelectFn, _ := opts.RawGetString("on_select").(*lua.LFunction) + onSelect := func(index int) {} + if onSelectFn != nil { + onSelect = func(index int) { + m.enqueue(p, "ui.input select", func() { + m.call(p, "ui.input select", hookTimeout, 0, fixedArgs(onSelectFn, lua.LNumber(index+1))) + }) + } + } + inputToken = up.ShowInput(title, placeholder, value, suggestions, onChange, func(text string) { + m.enqueue(p, "ui.input", func() { + m.call(p, "ui.input", hookTimeout, 0, fixedArgs(fn, lua.LString(text))) + }) + }, onSelect, onCancel) + L.Push(lua.LTrue) + L.Push(lua.LNumber(inputToken)) + return 2 + })) + + // cliamp.ui.suggestions(options, {live = true}) replaces the list under the + // open input. live rows are results: Enter selects one instead of + // submitting the text. + L.SetField(tbl, "suggestions", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermUI, "cliamp.ui.suggestions") { + return pushErr(L, "ui permission required") + } + options := parseSelectOptions(L, L.Get(1)) + live := true + query := "" + querySet := false + token := inputToken + if opts, ok := L.Get(2).(*lua.LTable); ok { + if value, ok := opts.RawGetString("live").(lua.LBool); ok { + live = bool(value) + } + if value := opts.RawGetString("query"); value != lua.LNil { + querySet = true + query = strings.TrimSpace(value.String()) + } + if value, ok := opts.RawGetString("token").(lua.LNumber); ok { + token = uint64(value) + } + } + up := m.ui.Load() + if up == nil || up.UpdateInput == nil { + return pushErr(L, "ui: not available") + } + up.UpdateInput(options, live, query, querySet, token) + L.Push(lua.LTrue) + return 1 + })) + + // cliamp.ui.text{title = "...", text = "...", on_close = fn} + L.SetField(tbl, "text", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermUI, "cliamp.ui.text") { + return pushErr(L, "ui permission required") + } + opts := L.CheckTable(1) + text := rawString(L, opts, "text") + if strings.TrimSpace(text) == "" { + return pushErr(L, "cliamp.ui.text: text is required") + } + up := m.ui.Load() + if up == nil || up.ShowText == nil { + return pushErr(L, "ui: not available") + } + closeFn, _ := opts.RawGetString("on_close").(*lua.LFunction) + onClose := func() {} + if closeFn != nil { + onClose = func() { + m.enqueue(p, "ui.text close", func() { + m.call(p, "ui.text close", hookTimeout, 0, fixedArgs(closeFn)) + }) + } + } + up.ShowText(strings.TrimSpace(rawString(L, opts, "title")), text, onClose) + L.Push(lua.LTrue) + return 1 + })) + vis := L.NewTable() // cliamp.vis.set("Scatter") L.SetField(vis, "set", L.NewFunction(func(L *lua.LState) int { diff --git a/luaplugin/api_ui_test.go b/luaplugin/api_ui_test.go new file mode 100644 index 000000000..af1456218 --- /dev/null +++ b/luaplugin/api_ui_test.go @@ -0,0 +1,99 @@ +package luaplugin + +import "testing" + +func TestUIInputPassesSuggestions(t *testing.T) { + m := newTestManager() + var got []SelectOption + m.SetUIProvider(UIProvider{ + ShowInput: func(_ string, _, _ string, suggestions []SelectOption, _ func(string), onSubmit func(string), _ func(int), _ func()) uint64 { + got = suggestions + onSubmit("x") + return 1 + }, + }) + loadTestPlugin(t, m, "input-suggestions", ` + local p = plugin.register({name = "input-suggestions", type = "hook", permissions = {"ui"}}) + cliamp.ui.input{ + title = "Message", + suggestions = {"/start", {value = "/help", description = "How to use"}}, + on_submit = function(text) end, + } + `) + if len(got) != 2 { + t.Fatalf("suggestions = %#v", got) + } + if got[0].Title != "/start" || got[0].Description != "" { + t.Errorf("suggestion 0 = %#v", got[0]) + } + if got[1].Title != "/help" || got[1].Description != "How to use" { + t.Errorf("suggestion 1 = %#v", got[1]) + } +} + +func TestUITextPassesBody(t *testing.T) { + m := newTestManager() + var gotTitle, gotText string + m.SetUIProvider(UIProvider{ + ShowText: func(title, text string, _ func()) { + gotTitle, gotText = title, text + }, + }) + loadTestPlugin(t, m, "ui-text", ` + local p = plugin.register({name = "ui-text", type = "hook", permissions = {"ui"}}) + cliamp.ui.text{title = "Reply", text = "line one\nline two"} + `) + if gotTitle != "Reply" || gotText != "line one\nline two" { + t.Fatalf("title = %q text = %q", gotTitle, gotText) + } +} + +func TestUISelectPassesStructuredOptions(t *testing.T) { + m := newTestManager() + var got []SelectOption + m.SetUIProvider(UIProvider{ + ShowSelect: func(_, _ string, options []SelectOption, _ int, onDone func(int), _ func()) { + got = options + onDone(0) + }, + }) + loadTestPlugin(t, m, "ui-select", ` + local p = plugin.register({name = "ui-select", type = "hook", permissions = {"ui"}}) + cliamp.ui.select{ + title = "Results", + options = { + "/start", + {title = "Get Lucky", subtitle = "Artist: Daft Punk", description = "Album: Random Access Memories"}, + }, + on_select = function(index) end, + } + `) + if len(got) != 2 { + t.Fatalf("options = %#v", got) + } + if got[0].Title != "/start" { + t.Errorf("option 0 = %#v", got[0]) + } + if got[1].Title != "Get Lucky" || got[1].Subtitle != "Artist: Daft Punk" || got[1].Description != "Album: Random Access Memories" { + t.Errorf("option 1 = %#v", got[1]) + } +} + +func TestUISuggestionsPassesImage(t *testing.T) { + m := newTestManager() + var got []SelectOption + m.SetUIProvider(UIProvider{ + UpdateInput: func(options []SelectOption, live bool, query string, querySet bool, token uint64) { + got = options + }, + }) + loadTestPlugin(t, m, "ui-suggestions", ` + local p = plugin.register({name = "ui-suggestions", type = "hook", permissions = {"ui"}}) + cliamp.ui.suggestions({ + {title = "Get Lucky", subtitle = "Artist: Daft Punk", image = "IMAGE"}, + }, {live = true}) + `) + if len(got) != 1 || got[0].Image != "IMAGE" { + t.Fatalf("options = %#v", got) + } +} diff --git a/luaplugin/hooks.go b/luaplugin/hooks.go index 8ccbf7b8e..545b26fb8 100644 --- a/luaplugin/hooks.go +++ b/luaplugin/hooks.go @@ -43,12 +43,14 @@ const ( // Permission strings declared via plugin.register({ permissions = {...} }). // Kept as named constants so the guard call sites and docs don't drift. const ( - PermControl = "control" - PermExec = "exec" - PermImage = "image" - PermLayout = "layout" - PermUI = "ui" - PermKeymap = "keymap" + PermControl = "control" + PermExec = "exec" + PermImage = "image" + PermLayout = "layout" + PermUI = "ui" + PermKeymap = "keymap" + PermProvider = "provider" + PermProviderSend = "provider-send" ) // luaHook is a single event callback registered by a plugin. @@ -202,6 +204,34 @@ func (m *Manager) enqueue(p *Plugin, label string, fn func()) bool { } } +// enqueueCompletion delivers an asynchronous provider completion without +// dropping it when the plugin queue is full. It holds m.mu only for the +// non-blocking send, so Close cannot close the queue underneath the send. The +// caller already returned true to Lua, so losing the completion would leave a +// plugin waiting forever. +func (m *Manager) enqueueCompletion(p *Plugin, label string, fn func()) bool { + for { + m.mu.RLock() + if m.closing { + m.mu.RUnlock() + return false + } + select { + case p.queue <- fn: + p.dropping.Store(false) + m.mu.RUnlock() + return true + default: + m.mu.RUnlock() + } + select { + case <-m.ctx.Done(): + return false + case <-time.After(50 * time.Millisecond): + } + } +} + // runQueue runs the queued calls of p one at a time until Close closes the // queue. Thus the events and key presses of one plugin keep their order. When // Close sets dropQueued, it drops the calls that still wait. diff --git a/luaplugin/hooks_test.go b/luaplugin/hooks_test.go new file mode 100644 index 000000000..3185db174 --- /dev/null +++ b/luaplugin/hooks_test.go @@ -0,0 +1,30 @@ +package luaplugin + +import ( + "testing" + "time" +) + +func TestEnqueueCompletionWaitsForQueueSpace(t *testing.T) { + m := newTestManager() + p := &Plugin{installName: "completion", queue: make(chan func(), 1)} + p.queue <- func() {} + done := make(chan bool, 1) + go func() { done <- m.enqueueCompletion(p, "completion", func() {}) }() + + select { + case <-done: + t.Fatal("enqueueCompletion delivered while the queue was full") + case <-time.After(100 * time.Millisecond): + } + + <-p.queue + select { + case ok := <-done: + if !ok { + t.Fatal("enqueueCompletion did not deliver the completion") + } + case <-time.After(time.Second): + t.Fatal("enqueueCompletion did not retry after the queue had space") + } +} diff --git a/luaplugin/luaplugin.go b/luaplugin/luaplugin.go index 72150d9e7..a3934246f 100644 --- a/luaplugin/luaplugin.go +++ b/luaplugin/luaplugin.go @@ -117,11 +117,24 @@ type ControlProvider struct { SetEQPreset func(name string, bands *[10]float64) Next func() Prev func() - QueueAdd func(path string) // resolve path/URL and append - QueueAddTrack func(track Track) // append a track table as given, without resolving its path - QueueJump func(index int) // make index current and play it - QueueRemove func(index int) // remove track at index - QueueMove func(from, to int) // reorder + QueueAdd func(path string) // resolve path/URL and append + QueueAddTrack func(track Track) // append a track table as given, without resolving its path + QueueJump func(index int) // make index current and play it + QueueRemove func(index int) // remove track at index + QueueMove func(from, to int) // reorder + QueueInsert func(index int, track Track) // insert a track at index +} + +// SelectOption is one row of cliamp.ui.select. A plain string option uses +// Title only; a table can add the subtitle and description lines Telegram uses +// for a track: title, artist and album. +type SelectOption struct { + Title string + Subtitle string + Description string + // Image is a pre-rendered ANSI block, one image line per row. The plugin + // downloads and converts it; the core only lays it out. + Image string } // UIProvider supplies callbacks that surface plugin output in the TUI. @@ -132,7 +145,17 @@ type UIProvider struct { // ShowSelect opens a selector with options and calls onDone with the chosen // index, or -1 when the user cancels. It must return at once; onDone runs on // the UI goroutine and the manager turns it into a plugin callback. - ShowSelect func(title string, options []string, cursor int, onDone func(index int), onCancel func()) + ShowSelect func(title, body string, options []SelectOption, cursor int, onDone func(index int), onCancel func()) + // ShowInput opens a text input. It must return at once; onSubmit and + // onCancel run on the UI goroutine and the manager turns them into plugin + // callbacks. + ShowInput func(title, placeholder, value string, suggestions []SelectOption, onChange func(text string), onSubmit func(text string), onSelect func(index int), onCancel func()) uint64 + // UpdateInput replaces the suggestions of the open input. live means the + // rows are search results that Enter selects, not command completions. + // query is the text the results belong to, when the plugin reports it. + UpdateInput func(options []SelectOption, live bool, query string, querySet bool, token uint64) + // ShowText opens a scrollable text panel. It must return at once. + ShowText func(title, text string, onClose func()) // SetVis switches the active visualizer by name. It must return at once: the // UI applies the change on its own goroutine. SetVis func(name string) @@ -152,14 +175,16 @@ type Manager struct { keyBindDescs map[string]KeyBinding // key string -> UI overlay entry (only for binds that supplied a description) reservedKeys map[string]bool // core-reserved keys; plugins may not bind these commands map[string]map[string]*luaHook // plugin name -> command name -> handler + actions map[string]Action // plugin name + id -> action pane entry visPlugs []*luaVis // Lua visualizers in registration order visMap map[string]*luaVis // name -> Lua visualizer namespaces map[string]string // event namespace -> owning plugin name layoutProvider LayoutProvider - names map[string]*Plugin // display name -> plugin that registered it - state atomic.Pointer[StateProvider] // see SetStateProvider - control atomic.Pointer[ControlProvider] // see SetControlProvider - ui atomic.Pointer[UIProvider] // see SetUIProvider + names map[string]*Plugin // display name -> plugin that registered it + state atomic.Pointer[StateProvider] // see SetStateProvider + control atomic.Pointer[ControlProvider] // see SetControlProvider + ui atomic.Pointer[UIProvider] // see SetUIProvider + provider atomic.Pointer[ProviderProvider] // see SetProviderProvider publisher EventPublisher timers *timerManager execs *execManager @@ -393,6 +418,11 @@ func (m *Manager) cleanupPlugin(p *Plugin) { delete(m.names, name) } } + for key, action := range m.actions { + if action.Plugin == p.installName { + delete(m.actions, key) + } + } for event, hooks := range m.hooks { m.hooks[event] = filterOutPlugin(hooks, p) } @@ -511,6 +541,7 @@ func (m *Manager) registerPluginAPI(L *lua.LState, p *Plugin) { m.registerPublishAPI(L, obj, p) m.registerKeymapAPI(L, obj, p) m.registerCommandAPI(L, obj, p) + m.registerActionAPI(L, obj, p) // For visualizer plugins, add init/render registration. if p.Type == "visualizer" { @@ -535,6 +566,7 @@ func (m *Manager) registerCliampAPI(L *lua.LState, p *Plugin) { registerImageAPI(L, cliamp, p) registerLayoutAPI(L, cliamp, p, m) registerUIAPI(L, cliamp, p, m) + m.registerProviderAPI(L, cliamp, p) registerHTTPAPI(L, cliamp) loadState, loadCtrl := loadProvider(&m.state), loadProvider(&m.control) registerPlayerAPI(L, cliamp, loadState) @@ -654,6 +686,12 @@ func (m *Manager) SetStateProvider(sp StateProvider) { m.state.Store(&sp) } +// SetProviderProvider sets the active provider context and the chat actions +// that cliamp.provider.call exposes. It is safe to call while plugins run. +func (m *Manager) SetProviderProvider(pp ProviderProvider) { + m.provider.Store(&pp) +} + // SetControlProvider sets the function pointers for player control. // Only plugins with permissions = {"control"} can use these. It is safe to // call while plugins run. @@ -727,6 +765,7 @@ func (m *Manager) Close() { // Close each VM under its lock. A timer or exec callback that runs now // finishes first, and each later call sees closed and returns errClosed. for _, p := range m.plugins { + m.removeActions(p.installName) p.mu.Lock() p.closed = true p.L.Close() diff --git a/luaplugin/metadata.go b/luaplugin/metadata.go index 8a50d0e60..75e27e585 100644 --- a/luaplugin/metadata.go +++ b/luaplugin/metadata.go @@ -24,7 +24,7 @@ type Metadata struct { // knownPermissions holds the names that plugin.register() accepts in // permissions. -var knownPermissions = map[string]bool{PermControl: true, PermExec: true, PermImage: true, PermLayout: true, PermUI: true, PermKeymap: true} +var knownPermissions = map[string]bool{PermControl: true, PermExec: true, PermImage: true, PermLayout: true, PermUI: true, PermKeymap: true, PermProvider: true, PermProviderSend: true} // errRegisteredTwice is the error of a second plugin.register() call. A // later call could otherwise replace the permissions that install and trust diff --git a/main.go b/main.go index bc9397391..e14a3260d 100644 --- a/main.go +++ b/main.go @@ -230,6 +230,7 @@ func run(overrides config.Overrides, positional []string, headless, visualizer60 defer stopLuaSend() luaMgr.SetControlProvider(luaControlProvider(luaSend)) luaMgr.SetUIProvider(luaUIProvider(luaSend, headless)) + luaMgr.SetProviderProvider(luaProviderProvider(providers.entries, m.PluginStateLoader(), luaSend)) } stopIPC, err := startIPC(prog.Send, pluginBroker, luaMgr, headless) diff --git a/playlist/playlist.go b/playlist/playlist.go index bdbc0baca..7eccb4521 100644 --- a/playlist/playlist.go +++ b/playlist/playlist.go @@ -210,6 +210,57 @@ func (p *Playlist) Add(tracks ...Track) { p.revision++ } +// Insert puts track at index in the list. Every index in the play order, +// the play-next queue and the current position moves with its track. In +// shuffle mode the new track plays next; otherwise it keeps the list +// position. +func (p *Playlist) Insert(index int, track Track) { + p.mu.Lock() + defer p.mu.Unlock() + if index < 0 { + index = 0 + } + if index > len(p.tracks) { + index = len(p.tracks) + } + track = cloneTrack(track) + p.tracks = append(p.tracks, Track{}) + copy(p.tracks[index+1:], p.tracks[index:]) + p.tracks[index] = track + + for i, idx := range p.order { + if idx >= index { + p.order[i] = idx + 1 + } + } + insertAt := index + if p.shuffle { + insertAt = p.pos + 1 + if insertAt < 0 { + insertAt = 0 + } + if insertAt > len(p.order) { + insertAt = len(p.order) + } + } + p.order = append(p.order, 0) + copy(p.order[insertAt+1:], p.order[insertAt:]) + p.order[insertAt] = index + if !p.shuffle && len(p.tracks) > 1 && index <= p.pos { + p.pos++ + } + for i, idx := range p.queue { + if idx >= index { + p.queue[i] = idx + 1 + } + } + if p.queuedIdx >= index { + p.queuedIdx++ + } + p.rebuildQueuePositions() + p.revision++ +} + // Len returns the number of tracks. func (p *Playlist) Len() int { p.mu.Lock() diff --git a/playlist/playlist_test.go b/playlist/playlist_test.go index 546ce3b95..b863ff81c 100644 --- a/playlist/playlist_test.go +++ b/playlist/playlist_test.go @@ -787,3 +787,68 @@ func TestReverseShuffledKeepsPlayOrder(t *testing.T) { t.Errorf("pos = %d, want %d", p.pos, pos) } } + +func TestInsertAtTopKeepsTheCurrentTrack(t *testing.T) { + p := makePlaylist(3, false) // A B C + p.SetIndex(1) // B + + p.Insert(0, Track{Title: "X"}) + + if got, want := titles(p), []string{"X", "A", "B", "C"}; !sliceEq(got, want) { + t.Fatalf("titles = %v, want %v", got, want) + } + current, index := p.Current() + if current.Title != "B" || index != 2 { + t.Fatalf("current = %q index %d, want B index 2", current.Title, index) + } +} + +func TestInsertAtMiddleKeepsOrder(t *testing.T) { + p := makePlaylist(3, false) // A B C + + p.Insert(1, Track{Title: "X"}) + + if got, want := titles(p), []string{"A", "X", "B", "C"}; !sliceEq(got, want) { + t.Fatalf("titles = %v, want %v", got, want) + } + current, index := p.Current() + if current.Title != "A" || index != 0 { + t.Fatalf("current = %q index %d, want A index 0", current.Title, index) + } +} + +func TestInsertShufflePlaysNext(t *testing.T) { + p := makePlaylist(3, true) + p.pos = 0 + + p.Insert(0, Track{Title: "X"}) + + next, ok := p.Next() + if !ok || next.Title != "X" { + t.Fatalf("next = %q, %v; want X", next.Title, ok) + } +} + +func TestInsertRemapsThePlayNextQueue(t *testing.T) { + p := makePlaylist(3, false) // A B C + p.Queue(2) // C + + p.Insert(0, Track{Title: "X"}) + + entries := p.QueueEntries() + if len(entries) != 1 { + t.Fatalf("queue = %#v", entries) + } + if entries[0].Track.Title != "C" || entries[0].TrackIndex != 3 { + t.Fatalf("queue entry = %#v, want C at 3", entries[0]) + } +} + +func TestInsertIntoEmptyPlaylistKeepsCurrentAtZero(t *testing.T) { + p := New() + p.ReplaceAt(nil, 0) + p.Insert(0, Track{Title: "A"}) + if _, idx := p.Current(); idx != 0 { + t.Fatalf("current index = %d, want 0", idx) + } +} diff --git a/plugins/telegram-bot.lua b/plugins/telegram-bot.lua new file mode 100644 index 000000000..db2f51d2c --- /dev/null +++ b/plugins/telegram-bot.lua @@ -0,0 +1,256 @@ +-- telegram-bot.lua โ€” send a message to the Telegram chat you are browsing +-- and add the audio the bot replies with to the current playlist. +-- +-- The core owns the MTProto session and the send/reply calls. This plugin +-- only draws the prompt and decides what to do with the reply, so any bot +-- that answers a text command with an audio document works without code +-- changes. +-- +-- The action appears under "!" when the Telegram provider is open. +-- A plain text query keeps waiting for the audio after an interim +-- "downloading" reply. Slash commands are treated as menu commands and do not +-- wait for delayed audio; use a plain query if the bot sends the audio after a +-- slash-command reply. +-- +-- The p:command("ask") form is for scripts and the MCP: +-- +-- cliamp plugins call telegram-bot ask /search daft punk + +local p = plugin.register({ + name = "telegram-bot", + type = "hook", + version = "0.1.0", + description = "Send a message to a Telegram bot and add its audio to the playlist", + permissions = {"ui", "provider", "provider-send", "control"}, +}) + +local function current_chat() + local ctx = cliamp.provider.current() + if ctx.name ~= "Telegram" then + return nil, nil + end + local chat = ctx.playlist_id + local name = ctx.playlist_name + if chat == "" then + chat = ctx.selection_id + name = ctx.selection_name + end + if chat == "" then + return nil, nil + end + return chat, name +end + +local busy = {} +local requestSeq = 0 + +local function is_busy(chat) + local entry = busy[chat] + if not entry then + return false + end + if entry.untilTime <= os.time() then + busy[chat] = nil + return false + end + return true +end + +local function reserve(chat) + if is_busy(chat) then + return nil + end + requestSeq = requestSeq + 1 + -- Longer than the 60s ask plus the 30s audio follow-up. A canceled + -- command cannot run its cleanup, so the deadline is the safety net. + busy[chat] = {token = requestSeq, untilTime = os.time() + 180} + return requestSeq +end + +local function finish(chat, token) + local entry = busy[chat] + if not entry then + return + end + if token and entry.token ~= token then + return + end + busy[chat] = nil +end + +local function insert_audio(reply) + if reply and reply.kind == "audio" and reply.track then + local ok, err = cliamp.queue.insert(0, reply.track) + if not ok then + cliamp.message("Telegram: " .. tostring(err or "could not queue the track"), 8) + return false + end + cliamp.message("Added: " .. reply.track.title, 5) + return true + end + return false +end + +local function wait_audio(chat, afterID, token) + cliamp.provider.call("telegram.reply", { + chat = chat, + after = afterID, + timeout = 20, + audio_only = true, + }, { + on_reply = function(reply, err) + if reply and reply.kind == "audio" then + insert_audio(reply) + elseif err then + cliamp.message("Telegram: " .. tostring(err), 8) + elseif reply and reply.kind == "text" and reply.text and reply.text ~= "" then + cliamp.message(reply.text, 8) + else + cliamp.message("No audio yet. Ctrl+R to reload.", 5) + end + finish(chat, token) + end, + timeout = 30, + }) +end + +local function add_reply(chat, reply, err, waitForAudio, token) + if not reply then + cliamp.message("Telegram: " .. tostring(err or "no reply"), 8) + finish(chat, token) + return + end + if reply.kind == "audio" then + insert_audio(reply) + finish(chat, token) + return + end + if reply.kind == "text" then + cliamp.message(reply.text, 8) + if waitForAudio and reply.message_id and reply.message_id > 0 then + -- The bot often sends "Downloading..." first and the audio after + -- WaitReply's grace period. Keep waiting for the audio. + wait_audio(chat, reply.message_id, token) + else + finish(chat, token) + end + return + end + cliamp.message("No reply yet. Ctrl+R to reload.", 5) + finish(chat, token) +end + +p:action{ + key = "!", + id = "send", + label = "Send message to this chat", + description = "Ask the bot for a track", + provider = "Telegram", + context = "chat", + on_submit = function() + local chat, name = current_chat() + if not chat then + cliamp.message("Open a Telegram chat first.", 3) + return + end + cliamp.ui.input{ + title = "Message โ†’ " .. (name or chat), + placeholder = "/search ...", + on_submit = function(text) + local token = reserve(chat) + if not token then + cliamp.message("Wait for the bot to finish this chat first.", 6) + return + end + cliamp.message("Sent. Waiting for the botโ€ฆ", 3) + local waitForAudio = text:sub(1, 1) ~= "/" + local ok, err = cliamp.provider.call("telegram.ask", { + chat = chat, + text = text, + timeout = 60, + }, { + on_reply = function(reply, replyErr) + add_reply(chat, reply, replyErr, waitForAudio, token) + end, + timeout = 90, + }) + if not ok then + finish(chat, token) + cliamp.message("Send failed: " .. tostring(err), 8) + end + end, + } + end, +} + +p:command("commands", function(args) + local chat = args[1] + if not chat or chat == "" then + return "usage: commands " + end + local res, err = cliamp.provider.call("telegram.commands", {chat = chat}) + if not res then + return "error: " .. tostring(err) + end + local out = {} + for _, command in ipairs(res.commands) do + out[#out+1] = command.command .. " โ€” " .. command.description + end + return table.concat(out, "\n") +end) + +local function canonical_chat(chat) + if chat:match("^u:") or chat:match("^c:") or chat:match("^ch:") then + return chat + end + local info = cliamp.provider.call("telegram.resolve", {username = chat}) + if info and info.id and info.id ~= "" then + return info.id + end + return chat +end + +p:command("ask", function(args) + local chat = args[1] + local text = table.concat(args, " ", 2) + if not chat or chat == "" or text == "" then + return "usage: ask " + end + chat = canonical_chat(chat) + local token = reserve(chat) + if not token then + return "busy: wait for the bot to finish this chat" + end + local reply, err = cliamp.provider.call("telegram.ask", { + chat = chat, + text = text, + timeout = 60, + }) + if reply and reply.kind == "text" and text:sub(1, 1) ~= "/" and reply.message_id and reply.message_id > 0 then + -- A plain query can return "Downloading..." before the audio. Keep + -- the reservation until the audio arrives or the follow-up times out. + local audio = cliamp.provider.call("telegram.reply", { + chat = chat, + after = reply.message_id, + timeout = 20, + audio_only = true, + }) + if audio and audio.kind == "audio" then + reply = audio + end + end + finish(chat, token) + if not reply then + return "error: " .. tostring(err) + end + if reply.kind == "audio" and reply.track then + return "audio: " .. reply.track.title + end + local out = {reply.kind .. ": " .. tostring(reply.text)} + if reply.buttons then + for i, button in ipairs(reply.buttons) do + out[#out+1] = string.format(" %d. %s kind=%s data=%s", i, button.text, tostring(button.kind), tostring(button.data_b64 or button.url)) + end + end + return table.concat(out, "\n") +end) diff --git a/provider/interfaces.go b/provider/interfaces.go index 38b9e85ab..55802101b 100644 --- a/provider/interfaces.go +++ b/provider/interfaces.go @@ -468,3 +468,68 @@ type ChatFilter interface { Chats() []string SetChats(chats []string) error } + +// BotCommand is one command a chat bot advertises. +type BotCommand struct { + Command string // includes the leading slash, e.g. "/search" + Description string +} + +// ChatButton is one inline button attached to a bot message. Data is the +// callback payload; URL is set for link buttons. A button has one or the +// other. +type ChatButton struct { + Text string + Data []byte + DataText string // Data as text when it is valid UTF-8, e.g. a Deezer URL + URL string + Query string // switch_inline: the inline query the button opens + Kind string // "callback", "url", "text", "switch_inline", ... + SendText bool // reply keyboard: sending Text is the button press +} + +// InlineResult is one result an inline bot returns for a query. +type InlineResult struct { + ID string + Type string + Kind string // "audio", "media", "photo", "text" + Title string + Description string + URL string + ThumbURL string +} + +// InlineResults is the answer to an inline query. QueryID must be sent back +// with the chosen result. +type InlineResults struct { + QueryID int64 + NextOffset string + Results []InlineResult +} + +// ChatReply is what arrived in a chat after a command. Kind is "audio", +// "text" or "none". MessageID is the reply message, so a callback can target +// its inline keyboard. +type ChatReply struct { + Kind string + Track playlist.Track + Text string + From string + MessageID int + Buttons []ChatButton + Links []string +} + +// ChatCommander is implemented by providers that can write into a chat as the +// signed-in user and read the reply. The chat id is a provider playlist id. +type ChatCommander interface { + BotCommands(ctx context.Context, chatID string) ([]BotCommand, error) + SendCommand(ctx context.Context, chatID, text string) (int, error) + WaitReply(ctx context.Context, chatID string, afterID int, timeout time.Duration) (ChatReply, error) + WaitAudio(ctx context.Context, chatID string, afterID int, timeout time.Duration) (ChatReply, error) + BotCallback(ctx context.Context, chatID string, messageID int, data []byte) error + Message(ctx context.Context, chatID string, messageID int) (ChatReply, error) + ResolveChat(ctx context.Context, username string) (playlist.PlaylistInfo, error) + InlineResults(ctx context.Context, chatID, botID, query, offset string) (InlineResults, error) + SendInlineResult(ctx context.Context, chatID, botID string, queryID int64, resultID string) (int, error) +} diff --git a/ui/model/action_pane.go b/ui/model/action_pane.go new file mode 100644 index 000000000..5a2f5679d --- /dev/null +++ b/ui/model/action_pane.go @@ -0,0 +1,209 @@ +package model + +import ( + "fmt" + "sort" + "strings" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + + "github.com/bjarneo/cliamp/luaplugin" +) + +// actionPaneState is the "!" pane: every plugin action registered for this +// key, filtered by the text the user types. +type actionPaneState struct { + visible bool + entries []luaplugin.Action + filtered []luaplugin.Action + cursor int + scroll int + query string + height int +} + +// openActionPane collects the actions registered for "!" and shows them. +func (m *Model) openActionPane() { + if m.luaMgr == nil { + m.status.Warning("No plugin actions. Install a plugin that registers p:action.", statusTTLDefault) + return + } + entries := m.luaMgr.Actions("!") + providerName := "" + if m.provider != nil { + providerName = m.provider.Name() + } + chatOpen := m.activeProviderPlaylistID != "" && m.focus != focusProvider + available := make([]luaplugin.Action, 0, len(entries)) + for _, action := range entries { + if action.Provider != "" && !strings.EqualFold(action.Provider, providerName) { + continue + } + switch action.Context { + case "chat": + if !chatOpen { + continue + } + case "chats": + if chatOpen { + continue + } + } + available = append(available, action) + } + entries = available + if len(entries) == 0 { + m.status.Warning("No plugin actions for !. Install a plugin that registers p:action.", statusTTLDefault) + return + } + sort.SliceStable(entries, func(i, j int) bool { + if entries[i].Plugin != entries[j].Plugin { + return entries[i].Plugin < entries[j].Plugin + } + return entries[i].Label < entries[j].Label + }) + m.actionPane = actionPaneState{ + visible: true, + entries: entries, + filtered: entries, + height: m.height, + } +} + +// handleActionPaneKey owns the keys while the action pane is open. +func (m *Model) handleActionPaneKey(msg tea.KeyPressMsg) tea.Cmd { + pane := &m.actionPane + switch msg.String() { + case "esc": + m.actionPane = actionPaneState{} + return nil + case "up": + if pane.cursor > 0 { + pane.cursor-- + } else { + pane.cursor = max(0, len(pane.filtered)-1) + } + pane.adjustScroll() + return nil + case "down": + if pane.cursor < len(pane.filtered)-1 { + pane.cursor++ + } else { + pane.cursor = 0 + } + pane.adjustScroll() + return nil + case "enter": + if len(pane.filtered) == 0 { + return nil + } + action := pane.filtered[pane.cursor] + m.actionPane = actionPaneState{} + if action.Prompt != "" { + m.openLuaInput(action.Prompt, "", "", nil, nil, func(text string) { + action.Run(text) + }, nil, nil) + return nil + } + action.Run("") + return nil + default: + if m.editText("action-pane", &pane.query, msg) { + m.filterActions() + } + } + return nil +} + +func (p *actionPaneState) adjustScroll() { + visible := max(1, p.visibleRows()) + if p.cursor < p.scroll { + p.scroll = p.cursor + } + if p.cursor >= p.scroll+visible { + p.scroll = p.cursor - visible + 1 + } +} + +func (p *actionPaneState) visibleRows() int { + if p.height <= 0 { + return 10 + } + const chrome = 9 // heading, query, footer, blanks and borders + return max(1, min(10, p.height-chrome)) +} + +// filterActions keeps the actions whose label, description or plugin contains +// the query. +func (m *Model) filterActions() { + pane := &m.actionPane + query := strings.ToLower(strings.TrimSpace(pane.query)) + if query == "" { + pane.filtered = pane.entries + } else { + filtered := make([]luaplugin.Action, 0, len(pane.entries)) + for _, action := range pane.entries { + text := strings.ToLower(action.Label + " " + action.Description + " " + action.Plugin) + if strings.Contains(text, query) { + filtered = append(filtered, action) + } + } + pane.filtered = filtered + } + pane.cursor = 0 + pane.scroll = 0 +} + +// renderActionPane draws the action list as a centered box. +func (m Model) renderActionPane() string { + pane := m.actionPane + if !pane.visible { + return "" + } + width := max(40, m.layout.frameWidth/2) + width = min(width, max(28, m.layout.frameWidth-4)) + + var b strings.Builder + b.WriteString("Actions") + b.WriteString("\n\n") + b.WriteString("> " + truncate(pane.query, width-4)) + b.WriteString("\n\n") + if len(pane.filtered) == 0 { + b.WriteString(dimStyle.Render(" no matches")) + } else { + visible := min(m.actionPane.visibleRows(), len(pane.filtered)) + start := pane.scroll + if start > len(pane.filtered)-visible { + start = max(0, len(pane.filtered)-visible) + } + end := min(start+visible, len(pane.filtered)) + for i := start; i < end; i++ { + action := pane.filtered[i] + prefix := " " + if i == pane.cursor { + prefix = "โ–ธ " + } + line := prefix + action.Label + if action.Plugin != "" && action.Plugin != action.Label { + line += dimStyle.Render(" " + action.Plugin) + } + b.WriteString(truncate(line, width-4)) + if i < end-1 { + b.WriteString("\n") + } + } + if end < len(pane.filtered) { + b.WriteString("\n" + dimStyle.Render(fmt.Sprintf(" โ†“ %d more", len(pane.filtered)-end))) + } + } + b.WriteString("\n\n") + b.WriteString(dimStyle.Render(" type to filter enter run esc cancel")) + + return lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(lipgloss.Color("240")). + Padding(0, 1). + Width(width). + Render(b.String()) +} diff --git a/ui/model/action_pane_test.go b/ui/model/action_pane_test.go new file mode 100644 index 000000000..4b370edb4 --- /dev/null +++ b/ui/model/action_pane_test.go @@ -0,0 +1,241 @@ +package model + +import ( + "os" + "path/filepath" + "sync" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/bjarneo/cliamp/internal/plugintrust" + "github.com/bjarneo/cliamp/luaplugin" +) + +func TestActionPaneRunsPluginActionWithInput(t *testing.T) { + configDir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", configDir) + pluginDir := filepath.Join(configDir, "plugins") + if err := os.MkdirAll(pluginDir, 0o755); err != nil { + t.Fatal(err) + } + pluginPath := filepath.Join(pluginDir, "action-spy.lua") + script := ` +local p = plugin.register({ + name = "action-spy", + type = "hook", + permissions = {"ui"}, +}) +p:action{ + key = "!", + id = "say", + label = "Say something", + prompt = "Message", + on_submit = function(text) + cliamp.message("got:" .. text) + end, +} +` + if err := os.WriteFile(pluginPath, []byte(script), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugintrust.Approve(pluginDir, "action-spy", pluginPath); err != nil { + t.Fatal(err) + } + mgr, err := luaplugin.New(nil, nil, ReservedKeys()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(sync.OnceFunc(mgr.Close)) + + messages := make(chan string, 1) + mgr.SetUIProvider(luaplugin.UIProvider{ + ShowMessage: func(text string, _ time.Duration) { messages <- text }, + }) + + t.Logf("actions: %#v", mgr.Actions("!")) + m := Model{luaMgr: mgr} + m.openActionPane() + if !m.actionPane.visible || len(m.actionPane.filtered) != 1 { + t.Fatalf("pane = %#v", m.actionPane) + } + m.handleActionPaneKey(tea.KeyPressMsg{Code: tea.KeyEnter}) + if m.luaInput == nil { + t.Fatal("enter did not open the prompt") + } + m.luaInput.value = "hello" + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyEnter}) + + select { + case got := <-messages: + if got != "got:hello" { + t.Fatalf("message = %q", got) + } + case <-time.After(2 * time.Second): + t.Fatal("the action callback never ran") + } +} + +func TestActionPaneFiltersByLabel(t *testing.T) { + configDir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", configDir) + pluginDir := filepath.Join(configDir, "plugins") + if err := os.MkdirAll(pluginDir, 0o755); err != nil { + t.Fatal(err) + } + pluginPath := filepath.Join(pluginDir, "action-list.lua") + script := ` +local p = plugin.register({name = "action-list", type = "hook", permissions = {"ui"}}) +for _, label in ipairs({"DeezLoad", "Other bot"}) do + p:action{key = "!", label = label, on_submit = function() end} +end +` + if err := os.WriteFile(pluginPath, []byte(script), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugintrust.Approve(pluginDir, "action-list", pluginPath); err != nil { + t.Fatal(err) + } + mgr, err := luaplugin.New(nil, nil, ReservedKeys()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(sync.OnceFunc(mgr.Close)) + + m := Model{luaMgr: mgr} + m.openActionPane() + if got := len(m.actionPane.filtered); got != 2 { + t.Fatalf("filtered = %d, want 2", got) + } + m.actionPane.query = "deez" + m.filterActions() + if got := len(m.actionPane.filtered); got != 1 || m.actionPane.filtered[0].Label != "DeezLoad" { + t.Fatalf("filtered = %#v", m.actionPane.filtered) + } +} + +func TestActionPaneFilterKeepsEntries(t *testing.T) { + m := Model{} + m.actionPane = actionPaneState{ + entries: []luaplugin.Action{ + {Label: "Alpha"}, + {Label: "Beta"}, + {Label: "Gamma"}, + }, + } + m.actionPane.filtered = m.actionPane.entries + m.actionPane.query = "beta" + m.filterActions() + if len(m.actionPane.filtered) != 1 || m.actionPane.filtered[0].Label != "Beta" { + t.Fatalf("filtered = %#v", m.actionPane.filtered) + } + m.actionPane.query = "" + m.filterActions() + if len(m.actionPane.filtered) != 3 || m.actionPane.filtered[0].Label != "Alpha" { + t.Fatalf("cleared filter = %#v", m.actionPane.filtered) + } +} + +func TestActionPaneVisibleRowsFitsHeight(t *testing.T) { + cases := map[int]int{0: 10, 10: 1, 15: 6, 55: 10} + for height, want := range cases { + pane := actionPaneState{height: height} + if got := pane.visibleRows(); got != want { + t.Fatalf("height %d: visibleRows = %d, want %d", height, got, want) + } + } +} + +func TestActionPaneResizeClampsScroll(t *testing.T) { + m := Model{} + m.actionPane = actionPaneState{ + visible: true, + entries: []luaplugin.Action{{Label: "One"}, {Label: "Two"}, {Label: "Three"}}, + filtered: []luaplugin.Action{{Label: "One"}, {Label: "Two"}, {Label: "Three"}}, + cursor: 2, + height: 55, + } + next, _ := m.Update(tea.WindowSizeMsg{Width: 80, Height: 10}) + got := next.(Model) + if got.actionPane.height != 10 { + t.Fatalf("height = %d, want 10", got.actionPane.height) + } + if got.actionPane.scroll != 2 { + t.Fatalf("scroll = %d, want 2", got.actionPane.scroll) + } +} + +func TestActionPaneFiltersByChatContext(t *testing.T) { + configDir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", configDir) + pluginDir := filepath.Join(configDir, "plugins") + if err := os.MkdirAll(pluginDir, 0o755); err != nil { + t.Fatal(err) + } + pluginPath := filepath.Join(pluginDir, "action-context.lua") + script := ` +local p = plugin.register({name = "action-context", type = "hook", permissions = {"ui"}}) +p:action{key = "!", id = "chat", label = "Chat action", context = "chat", on_submit = function() end} +p:action{key = "!", id = "chats", label = "Chats action", context = "chats", on_submit = function() end} +` + if err := os.WriteFile(pluginPath, []byte(script), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugintrust.Approve(pluginDir, "action-context", pluginPath); err != nil { + t.Fatal(err) + } + mgr, err := luaplugin.New(nil, nil, ReservedKeys()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(sync.OnceFunc(mgr.Close)) + + m := Model{luaMgr: mgr} + m.openActionPane() + if len(m.actionPane.filtered) != 1 || m.actionPane.filtered[0].Label != "Chats action" { + t.Fatalf("chats pane = %#v", m.actionPane.filtered) + } + + m.actionPane = actionPaneState{} + m.activeProviderPlaylistID = "u:1:2" + m.openActionPane() + if len(m.actionPane.filtered) != 1 || m.actionPane.filtered[0].Label != "Chat action" { + t.Fatalf("chat pane = %#v", m.actionPane.filtered) + } +} + +func TestActionPaneUsesVisibleProviderListForContext(t *testing.T) { + m := Model{luaMgr: nil} + // Use a manager so the pane has actions to filter. + configDir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", configDir) + pluginDir := filepath.Join(configDir, "plugins") + if err := os.MkdirAll(pluginDir, 0o755); err != nil { + t.Fatal(err) + } + pluginPath := filepath.Join(pluginDir, "action-visible.lua") + script := ` +local p = plugin.register({name = "action-visible", type = "hook", permissions = {"ui"}}) +p:action{key = "!", id = "chat", label = "Chat action", context = "chat", on_submit = function() end} +p:action{key = "!", id = "chats", label = "Chats action", context = "chats", on_submit = function() end} +` + if err := os.WriteFile(pluginPath, []byte(script), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugintrust.Approve(pluginDir, "action-visible", pluginPath); err != nil { + t.Fatal(err) + } + mgr, err := luaplugin.New(nil, nil, ReservedKeys()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(sync.OnceFunc(mgr.Close)) + m.luaMgr = mgr + m.activeProviderPlaylistID = "u:1:2" + m.focus = focusProvider + m.openActionPane() + if len(m.actionPane.filtered) != 1 || m.actionPane.filtered[0].Label != "Chats action" { + t.Fatalf("provider list pane = %#v", m.actionPane.filtered) + } +} diff --git a/ui/model/command_registry.go b/ui/model/command_registry.go index ab6ffae32..c80f5fb95 100644 --- a/ui/model/command_registry.go +++ b/ui/model/command_registry.go @@ -200,6 +200,7 @@ var commandRegistry = []commandSpec{ {Mode: commandModeMain, Keys: []string{"/"}, KeyLabel: "/", Label: "Filter/search list", Keymap: true, ContextHelp: true}, {Mode: commandModeMain, Keys: []string{"ctrl+f"}, KeyLabel: "Ctrl+F", Label: "Search active provider or YouTube", Keymap: true, ContextHelp: true}, {Mode: commandModeMain, Keys: []string{"u"}, KeyLabel: "u", Label: "Load URL (stream/playlist)", Keymap: true}, + {Mode: commandModeMain | commandModeProvider, Keys: []string{"!"}, KeyLabel: "!", Label: "Plugin actions", Keymap: true, ContextHelp: true}, {Mode: commandModeMain, Keys: []string{"d"}, KeyLabel: "d", Label: "Audio device picker", Keymap: true}, {Mode: commandModeMain, Keys: []string{"y"}, KeyLabel: "y", Label: "Show lyrics", Keymap: true}, {Mode: commandModeMain | commandModeProvider | commandModeProviderPill | commandModeVolume | commandModeEQ | commandModeShuffle | commandModeRepeat | commandModeSpeed, Keys: []string{"tab", "shift+tab"}, KeyLabel: "Tab/Shift+Tab", Label: "Focus", Keymap: true, ContextHelp: true}, diff --git a/ui/model/image_pulse.go b/ui/model/image_pulse.go new file mode 100644 index 000000000..1f750f44c --- /dev/null +++ b/ui/model/image_pulse.go @@ -0,0 +1,16 @@ +package model + +// imagePulse alternates the invisible reset at the end of an image +// placeholder line. Bubble Tea redraws only the lines whose bytes changed; +// a static kitty placeholder would stop being re-emitted and the terminal +// would drop the image. The plugin panes solve this inside cliamp.image.block; +// the selector receives a pre-rendered block, so the core has to keep it +// alive on each frame. +var imagePulse bool + +func imageResetSuffix() string { + if imagePulse { + return "\x1b[0m" + } + return "\x1b[0;0m" +} diff --git a/ui/model/keymap_test.go b/ui/model/keymap_test.go index ba37bffd4..622a968bd 100644 --- a/ui/model/keymap_test.go +++ b/ui/model/keymap_test.go @@ -19,7 +19,10 @@ var mainKeyPath = []string{"handleKey", "handleGlobalKey", "handleMainKey"} // modalKeyHandlers own the keys while their modal is open. They are not part of // a command mode, so the registry drift guard does not apply to them. var modalKeyHandlers = map[string]bool{ - "handleLuaSelectKey": true, + "handleLuaSelectKey": true, + "handleLuaInputKey": true, + "handleLuaTextKey": true, + "handleActionPaneKey": true, } // focusKeyHandlers maps the handlers that handleKey calls for a focused area diff --git a/ui/model/keys.go b/ui/model/keys.go index e5db50e94..ffdd2c2ab 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -190,10 +190,27 @@ func normalizeShiftedLetter(msg tea.KeyPressMsg) tea.KeyPressMsg { func (m *Model) handleKey(msg tea.KeyPressMsg) tea.Cmd { msg = normalizeShiftedLetter(msg) + // Ctrl+C quits over every plugin modal too. The modal handlers below own + // the keyboard, so the global handler never sees the key otherwise. + if msg.String() == "ctrl+c" { + return m.quit() + } + + if m.luaText != nil { + m.handleLuaTextKey(msg) + return nil + } + if m.luaInput != nil { + m.handleLuaInputKey(msg) + return nil + } if m.luaSelect != nil { m.handleLuaSelectKey(msg) return nil } + if m.actionPane.visible { + return m.handleActionPaneKey(msg) + } if cmd, ok := m.handleGlobalKey(msg); ok { return cmd @@ -418,6 +435,8 @@ func (m *Model) handleProviderPaneKey(msg tea.KeyPressMsg) tea.Cmd { if _, ok := m.provider.(provider.ChatFilter); ok { return m.startChatPicker() } + case "!": + m.openActionPane() } return nil } @@ -834,6 +853,9 @@ func (m *Model) handleMainKey(msg tea.KeyPressMsg) tea.Cmd { case "?": m.openKeymap() + case "!": + m.openActionPane() + default: if m.luaMgr != nil { m.luaMgr.EmitKey(msg.String()) @@ -1028,6 +1050,15 @@ func (m *Model) handlePaste(content string) tea.Cmd { if content == "" { return nil } + if m.luaText != nil { + return nil + } + if m.luaInput != nil { + m.insertText("lua-input", &m.luaInput.value, content) + m.luaInput.cursor = m.textInput.cursor + m.luaInput.afterEdit() + return nil + } if spec, ok := m.topOverlay(); ok { if spec.paste != nil { spec.paste(m, content) diff --git a/ui/model/lua_input.go b/ui/model/lua_input.go new file mode 100644 index 000000000..24c53a527 --- /dev/null +++ b/ui/model/lua_input.go @@ -0,0 +1,364 @@ +package model + +import ( + "strings" + "unicode/utf8" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + + "github.com/bjarneo/cliamp/luaplugin" +) + +// LuaInputMsg asks the UI to show a text input requested by a plugin. +// OnSubmit runs with the text the user typed; OnSelect runs with the 0-based +// index of a live result; OnCancel runs on Esc. +type LuaInputMsg struct { + Token uint64 + Title string + Placeholder string + Value string + Suggestions []luaplugin.SelectOption + OnChange func(text string) + OnSubmit func(text string) + OnSelect func(index int) + OnCancel func() +} + +// LuaInputSuggestionsMsg replaces the suggestions under the open input. +// Live rows are search results: Enter selects one instead of submitting the +// text. +type LuaInputSuggestionsMsg struct { + Token uint64 + Options []luaplugin.SelectOption + Live bool + // Query is the text the results belong to. QuerySet distinguishes an + // omitted query from an explicitly empty one. + Query string + QuerySet bool +} + +// luaInputState is the open plugin input. +type luaInputState struct { + token uint64 + title string + placeholder string + value string + cursor int + suggestions []luaplugin.SelectOption + filtered []luaplugin.SelectOption + live bool + choice int + onChange func(string) + onSubmit func(string) + onSelect func(int) + onCancel func() +} + +func (m *Model) openLuaInput(title, placeholder, value string, suggestions []luaplugin.SelectOption, onChange, onSubmit func(string), onSelect func(int), onCancel func()) { + m.luaInput = &luaInputState{ + title: title, + placeholder: placeholder, + value: value, + cursor: len(value), + suggestions: suggestions, + onChange: onChange, + onSubmit: onSubmit, + onSelect: onSelect, + onCancel: onCancel, + } + m.luaInput.filter() + m.textInput.begin("lua-input", value) + m.textInput.cursor = len(value) +} + +// filter keeps command suggestions that match a prefix. Live search results +// are already for the current text, so they are never filtered locally. +func (input *luaInputState) filter() { + if input.live { + input.filtered = input.suggestions + } else { + value := strings.TrimSpace(input.value) + input.filtered = nil + switch { + case value == "": + input.filtered = input.suggestions + case strings.HasPrefix(value, "/") && !strings.ContainsAny(value, " \t"): + prefix := strings.ToLower(value) + for _, suggestion := range input.suggestions { + if strings.HasPrefix(strings.ToLower(suggestion.Title), prefix) { + input.filtered = append(input.filtered, suggestion) + } + } + } + } + if input.choice >= len(input.filtered) { + input.choice = max(0, len(input.filtered)-1) + } + if input.choice < 0 { + input.choice = 0 + } +} + +// handleLuaInputKey drives the open input. It returns true when the key was +// consumed. +func (m *Model) handleLuaInputKey(msg tea.KeyPressMsg) bool { + input := m.luaInput + if input == nil { + return false + } + switch msg.String() { + case "esc": + m.luaInput = nil + if input.onCancel != nil { + input.onCancel() + } + case "up": + if len(input.filtered) > 0 { + input.choice = (input.choice - 1 + len(input.filtered)) % len(input.filtered) + } + case "down": + if len(input.filtered) > 0 { + input.choice = (input.choice + 1) % len(input.filtered) + } + case "tab": + if !input.live && len(input.filtered) > 0 { + input.value = input.filtered[input.choice].Title + if strings.HasPrefix(input.value, "/") && !strings.HasSuffix(input.value, " ") { + input.value += " " + } + input.cursor = len(input.value) + m.textInput.begin("lua-input", input.value) + m.textInput.cursor = input.cursor + input.afterEdit() + } + case "enter": + if input.live && len(input.filtered) > 0 { + index := input.choice + m.luaInput = nil + if input.onSelect != nil { + input.onSelect(index) + } + return true + } + text := strings.TrimSpace(input.value) + if text == "" && len(input.filtered) > 0 { + text = input.filtered[input.choice].Title + } + if text == "" { + return true + } + m.luaInput = nil + if input.onSubmit != nil { + input.onSubmit(text) + } + default: + before := input.value + if m.editText("lua-input", &input.value, msg) { + input.cursor = m.textInput.cursor + if input.value != before { + input.afterEdit() + } + } + } + return true +} + +// afterEdit applies the state changes that every edit shares, whether it came +// from a key or a paste. +func (input *luaInputState) afterEdit() { + // A live result belongs to the previous text. Clear it until the plugin + // sends the results for this query. + if input.live { + input.live = false + input.suggestions = nil + input.filtered = nil + input.choice = 0 + } else { + input.filter() + } + if input.onChange != nil { + input.onChange(input.value) + } +} + +// inputWindow shows the part of value around cursor that fits in width cells. +// The cursor marker takes one cell, so the text budget is width-1. +func inputWindow(value string, cursor, width int) string { + if width < 1 { + width = 1 + } + runes := []rune(value) + cursorRune := utf8.RuneCountInString(value[:min(cursor, len(value))]) + if cursorRune > len(runes) { + cursorRune = len(runes) + } + budget := width - 1 + start, used := cursorRune, 0 + for start > 0 { + w := lipgloss.Width(string(runes[start-1])) + if used+w > budget { + break + } + start-- + used += w + } + end := cursorRune + for end < len(runes) { + w := lipgloss.Width(string(runes[end])) + if used+w > budget { + break + } + end++ + used += w + } + var b strings.Builder + b.WriteString(string(runes[start:cursorRune])) + b.WriteString("โ–") + b.WriteString(string(runes[cursorRune:end])) + return b.String() +} + +// inputRows is the number of lines one option needs in the input. +func imageLines(image string) []string { + if strings.TrimSpace(image) == "" { + return nil + } + return strings.Split(strings.TrimRight(image, "\n"), "\n") +} + +func inputRows(option luaplugin.SelectOption) int { + rows := len(imageLines(option.Image)) + 1 + if option.Subtitle != "" { + rows++ + } + if option.Description != "" { + rows++ + } + return rows +} + +// renderLuaInput draws the input and its command menu or live results as a +// centered box. +func (m Model) renderLuaInput() string { + input := m.luaInput + if input == nil { + return "" + } + width := max(40, lipgloss.Width(input.title)+4) + width = max(width, lipgloss.Width(input.placeholder)+8) + for _, suggestion := range input.filtered { + width = max(width, lipgloss.Width(oneLine(suggestion.Title))+6) + width = max(width, lipgloss.Width(oneLine(suggestion.Subtitle))+6) + width = max(width, lipgloss.Width(oneLine(suggestion.Description))+6) + for _, line := range imageLines(suggestion.Image) { + width = max(width, lipgloss.Width(line)+4) + } + } + width = min(width, max(20, m.layout.frameWidth-4)) + + shown := inputWindow(input.value, input.cursor, width-4) + if strings.TrimSpace(input.value) == "" && input.placeholder != "" { + shown = dimStyle.Render(truncate(input.placeholder, width-4)) + } + + var b strings.Builder + b.WriteString(truncate(input.title, width-2)) + b.WriteString("\n\n") + b.WriteString("> " + truncate(shown, width-4)) + if len(input.filtered) > 0 { + b.WriteString("\n") + if input.live { + m.renderLiveInputRows(&b, input, width) + } else { + visible := min(5, len(input.filtered)) + start := 0 + if input.choice >= visible { + start = input.choice - visible + 1 + } + for i := start; i < start+visible; i++ { + suggestion := input.filtered[i] + prefix := " " + if i == input.choice { + prefix = "โ–ธ " + } + line := prefix + suggestion.Title + if suggestion.Description != "" { + line += " " + dimStyle.Render(suggestion.Description) + } + b.WriteString("\n" + truncate(line, width-4)) + } + if start+visible < len(input.filtered) { + b.WriteString("\n" + dimStyle.Render(" โ†“ more")) + } + } + } + b.WriteString("\n\n") + if input.live { + b.WriteString(dimStyle.Render(truncate(" enter select esc cancel", width-4))) + } else { + b.WriteString(dimStyle.Render(truncate(" tab complete enter esc", width-4))) + } + + return lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(lipgloss.Color("240")). + Padding(0, 1). + Width(width). + Render(b.String()) +} + +// renderLiveInputRows writes the search rows under the input. The window +// keeps the selected row visible and counts the lines each row occupies. +func (m Model) renderLiveInputRows(b *strings.Builder, input *luaInputState, width int) { + maxRows := max(3, m.height-14) + start := max(0, min(input.choice, len(input.filtered)-1)) + rows := inputRows(input.filtered[start]) + for start > 0 && rows+inputRows(input.filtered[start-1]) <= maxRows { + start-- + rows += inputRows(input.filtered[start]) + } + end := start + rows = 0 + for end < len(input.filtered) && rows+inputRows(input.filtered[end]) <= maxRows { + rows += inputRows(input.filtered[end]) + end++ + } + if end <= input.choice { + end = min(len(input.filtered), input.choice+1) + if start > input.choice { + start = input.choice + } + } + if start > 0 { + b.WriteString(dimStyle.Render(" โ†‘ more")) + b.WriteString("\n") + } + for i := start; i < end; i++ { + option := input.filtered[i] + if i > start { + b.WriteString("\n") + } + lines := imageLines(option.Image) + if budget := maxRows - (inputRows(option) - len(lines)); len(lines) > budget { + lines = lines[:max(0, budget)] + } + for _, line := range lines { + b.WriteString(" " + line + imageResetSuffix() + "\n") + } + marker := " " + if i == input.choice { + marker = "โ–ธ " + } + b.WriteString(marker + truncate(oneLine(option.Title), width-6)) + if option.Subtitle != "" { + b.WriteString("\n " + dimStyle.Render(truncate(oneLine(option.Subtitle), width-6))) + } + if option.Description != "" { + b.WriteString("\n " + dimStyle.Render(truncate(oneLine(option.Description), width-6))) + } + } + if end < len(input.filtered) { + b.WriteString("\n" + dimStyle.Render(" โ†“ more")) + } +} diff --git a/ui/model/lua_input_test.go b/ui/model/lua_input_test.go new file mode 100644 index 000000000..4dc8113d2 --- /dev/null +++ b/ui/model/lua_input_test.go @@ -0,0 +1,261 @@ +package model + +import ( + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + + "github.com/bjarneo/cliamp/luaplugin" +) + +func TestLuaInputFiltersAndCompletesCommands(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", []luaplugin.SelectOption{ + {Title: "/start", Description: "Start"}, + {Title: "/settings", Description: "Settings"}, + {Title: "/help", Description: "Help"}, + }, nil, nil, nil, nil) + + if got := len(m.luaInput.filtered); got != 3 { + t.Fatalf("filtered = %d, want 3", got) + } + m.luaInput.value = "/s" + m.luaInput.filter() + if got := len(m.luaInput.filtered); got != 2 { + t.Fatalf("filtered for /s = %d, want 2", got) + } + m.luaInput.choice = 1 + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyTab}) + if got := m.luaInput.value; got != "/settings " { + t.Fatalf("value after Tab = %q, want %q", got, "/settings ") + } +} + +func TestLuaInputHidesMenuForPlainText(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", []luaplugin.SelectOption{{Title: "/start"}}, nil, nil, nil, nil) + m.luaInput.value = "get lucky" + m.luaInput.filter() + if got := len(m.luaInput.filtered); got != 0 { + t.Fatalf("filtered = %d, want 0", got) + } +} + +func TestLuaInputSelectsLiveResult(t *testing.T) { + m := Model{} + selected := -1 + m.openLuaInput("Message", "", "", nil, nil, nil, func(index int) { selected = index }, nil) + m.luaInput.suggestions = []luaplugin.SelectOption{ + {Title: "Get Lucky", Subtitle: "Artist: Daft Punk", Description: "Album: Random Access Memories"}, + } + m.luaInput.live = true + m.luaInput.filter() + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyEnter}) + if selected != 0 { + t.Fatalf("selected = %d, want 0", selected) + } +} + +func TestLuaInputRendersImageLines(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + m.luaInput.live = true + m.luaInput.suggestions = []luaplugin.SelectOption{{Title: "Get Lucky", Image: "IMG\nART"}} + m.luaInput.filter() + box := m.renderLuaInput() + if !strings.Contains(box, "IMG") || !strings.Contains(box, "ART") { + t.Fatalf("box does not contain the image lines:\n%s", box) + } +} + +func TestLuaInputSuggestionsKeepImage(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + next, _ := m.Update(LuaInputSuggestionsMsg{ + Options: []luaplugin.SelectOption{{Title: "Get Lucky", Image: "IMG\nART"}}, + Live: true, + }) + got := next.(Model) + if len(got.luaInput.filtered) != 1 || got.luaInput.filtered[0].Image != "IMG\nART" { + t.Fatalf("input = %#v", got.luaInput) + } + box := got.renderLuaInput() + if !strings.Contains(box, "IMG") || !strings.Contains(box, "ART") { + t.Fatalf("box does not contain the image lines:\n%s", box) + } +} + +func TestPasteGoesToOpenLuaInput(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + m.handlePaste("daft punk") + if m.luaInput == nil || m.luaInput.value != "daft punk" { + t.Fatalf("input = %#v, want pasted text", m.luaInput) + } +} + +func TestLuaInputCursorAfterTab(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", []luaplugin.SelectOption{{Title: "/help", Description: "Help"}}, nil, nil, nil, nil) + m.luaInput.value = "/h" + m.luaInput.filter() + m.luaInput.choice = 0 + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyTab}) + m.handleLuaInputKey(tea.KeyPressMsg{Code: 'x', Text: "x"}) + if got := m.luaInput.value; got != "/help x" { + t.Fatalf("value = %q, want %q", got, "/help x") + } +} + +func TestLuaInputCursorOnPrefilledValue(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "abc", nil, nil, nil, nil, nil) + m.handleLuaInputKey(tea.KeyPressMsg{Code: 'd', Text: "d"}) + if got := m.luaInput.value; got != "abcd" { + t.Fatalf("value = %q, want %q", got, "abcd") + } +} + +func TestPasteIgnoredUnderTextPanel(t *testing.T) { + m := Model{} + m.openLuaText("Reply", "body", nil) + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + m.handlePaste("hidden") + if got := m.luaInput.value; got != "" { + t.Fatalf("value = %q, want empty", got) + } +} + +func TestLuaInputLiveRowsAreOneLine(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + m.luaInput.live = true + m.luaInput.suggestions = []luaplugin.SelectOption{{Title: "one\ntwo"}} + m.luaInput.filter() + box := m.renderLuaInput() + if strings.Contains(box, "one\ntwo") { + t.Fatalf("live row kept a newline:\n%s", box) + } +} + +func TestLuaInputTabNotifiesChange(t *testing.T) { + var got string + m := Model{} + m.openLuaInput("Message", "", "", []luaplugin.SelectOption{{Title: "/help", Description: "Help"}}, func(text string) { + got = text + }, nil, nil, nil) + m.luaInput.value = "/h" + m.luaInput.filter() + m.luaInput.choice = 0 + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyTab}) + if got != "/help " { + t.Fatalf("onChange = %q, want %q", got, "/help ") + } +} + +func TestLuaInputCapsTallResultImage(t *testing.T) { + m := Model{height: 24} + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + lines := make([]string, 20) + for i := range lines { + lines[i] = "IMG" + } + m.luaInput.live = true + m.luaInput.suggestions = []luaplugin.SelectOption{{Title: "Title", Image: strings.Join(lines, "\n")}} + m.luaInput.filter() + var b strings.Builder + m.renderLiveInputRows(&b, m.luaInput, 40) + out := b.String() + if strings.Count(out, "IMG") > 9 { + t.Fatalf("image was not capped:\n%s", out) + } + if !strings.Contains(out, "Title") { + t.Fatalf("selected title missing:\n%s", out) + } +} + +func TestLuaInputCursorMoveKeepsLiveResults(t *testing.T) { + changed := 0 + m := Model{} + m.openLuaInput("Message", "", "abc", nil, func(string) { changed++ }, nil, nil, nil) + m.luaInput.live = true + m.luaInput.suggestions = []luaplugin.SelectOption{{Title: "Get Lucky"}} + m.luaInput.filter() + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyLeft}) + if changed != 0 { + t.Fatalf("onChange ran %d times on a cursor move", changed) + } + if len(m.luaInput.filtered) != 1 { + t.Fatalf("live results cleared on a cursor move: %#v", m.luaInput.filtered) + } +} + +func TestLuaInputWindowFollowsCursor(t *testing.T) { + m := Model{width: 80} + value := strings.Repeat("a", 80) + "z" + m.openLuaInput("Message", "", value, nil, nil, nil, nil, nil) + box := m.renderLuaInput() + if !strings.Contains(box, "zโ–") { + t.Fatalf("cursor is not visible at the end of a long value:\n%s", box) + } +} + +func TestLuaInputIgnoresSuggestionsForAnOldQuery(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "new", nil, nil, nil, nil, nil) + m.Update(LuaInputSuggestionsMsg{ + Query: "old", + QuerySet: true, + Options: []luaplugin.SelectOption{{Title: "Stale"}}, + Live: true, + }) + if len(m.luaInput.suggestions) != 0 { + t.Fatalf("stale suggestions were installed: %#v", m.luaInput.suggestions) + } + m.Update(LuaInputSuggestionsMsg{ + Query: "new", + QuerySet: true, + Options: []luaplugin.SelectOption{{Title: "Fresh"}}, + Live: true, + }) + if len(m.luaInput.suggestions) != 1 || m.luaInput.suggestions[0].Title != "Fresh" { + t.Fatalf("fresh suggestions were not installed: %#v", m.luaInput.suggestions) + } +} + +func TestLuaInputIgnoresSuggestionsForAnOldToken(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "new", nil, nil, nil, nil, nil) + m.luaInput.token = 2 + m.Update(LuaInputSuggestionsMsg{ + Token: 1, + Options: []luaplugin.SelectOption{{Title: "Stale"}}, + Live: true, + }) + if len(m.luaInput.suggestions) != 0 { + t.Fatalf("suggestions from an old input were installed: %#v", m.luaInput.suggestions) + } + m.Update(LuaInputSuggestionsMsg{ + Token: 2, + Options: []luaplugin.SelectOption{{Title: "Fresh"}}, + Live: true, + }) + if len(m.luaInput.suggestions) != 1 || m.luaInput.suggestions[0].Title != "Fresh" { + t.Fatalf("suggestions = %#v", m.luaInput.suggestions) + } +} + +func TestLuaInputExplicitEmptyQueryRejectsStaleResults(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "new", nil, nil, nil, nil, nil) + m.Update(LuaInputSuggestionsMsg{ + Query: "", + QuerySet: true, + Options: []luaplugin.SelectOption{{Title: "Stale"}}, + Live: true, + }) + if len(m.luaInput.suggestions) != 0 { + t.Fatalf("explicit empty query was treated as omitted: %#v", m.luaInput.suggestions) + } +} diff --git a/ui/model/lua_modal.go b/ui/model/lua_modal.go index d5e72b569..86c127b31 100644 --- a/ui/model/lua_modal.go +++ b/ui/model/lua_modal.go @@ -7,13 +7,16 @@ import ( tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" + + "github.com/bjarneo/cliamp/luaplugin" ) // LuaSelectMsg asks the UI to show a selector requested by a plugin. OnDone // runs with the chosen index, or -1 when the user cancels. type LuaSelectMsg struct { Title string - Options []string + Body string + Options []luaplugin.SelectOption // Cursor is the 1-based option to start on; 0 starts at the first one. Cursor int OnDone func(index int) @@ -29,7 +32,8 @@ type SetVisMsg struct { // luaSelectState is the open plugin selector. type luaSelectState struct { title string - options []string + body string + options []luaplugin.SelectOption cursor int onDone func(index int) onCancel func() @@ -66,60 +70,106 @@ func (m *Model) handleLuaSelectKey(msg tea.KeyPressMsg) bool { return true } -// renderLuaSelect draws the selector as a centered box over the frame. +// renderLuaSelect draws the selector as a centered box over the frame. An +// option can be one line or three: title, subtitle and description. func (m Model) renderLuaSelect() string { sel := m.luaSelect - if sel == nil { + if sel == nil || len(sel.options) == 0 { return "" } width := 0 for _, option := range sel.options { - width = max(width, lipgloss.Width(option)) + width = max(width, lipgloss.Width(oneLine(option.Title))) + width = max(width, lipgloss.Width(oneLine(option.Subtitle))) + width = max(width, lipgloss.Width(oneLine(option.Description))) + for _, line := range imageLines(option.Image) { + width = max(width, lipgloss.Width(line)+4) + } + } + for _, line := range wrapBlock(sel.body, 40) { + width = max(width, lipgloss.Width(line)) } - width = min(max(width+6, 24), max(20, m.layout.frameWidth-4)) + width = min(max(width+8, 40), max(20, m.layout.frameWidth-4)) title := truncate(sel.title, width-2) - // The list can be longer than the screen (the visualizer picker lists every - // mode). Show a window around the cursor so the selected option is always - // visible, with markers when there is more above or below. - // Title, blank line, options, up to two "more" indicators, blank line, - // footer and the box borders: keep the whole box inside the terminal. - visible := len(sel.options) - if maxRows := max(1, m.height-8); visible > maxRows { - visible = maxRows - } - start := 0 - if sel.cursor >= visible { - start = sel.cursor - visible + 1 - } - if end := start + visible; end > len(sel.options) { - start = max(0, len(sel.options)-visible) - } - end := min(start+visible, len(sel.options)) + bodyLines := wrapBlock(sel.body, width-4) + if maxBody := max(1, (m.height-10)/2); len(bodyLines) > maxBody { + bodyLines = append(bodyLines[:maxBody], "โ€ฆ") + } + + linesOf := func(option luaplugin.SelectOption) int { + lines := len(imageLines(option.Image)) + 1 + if option.Subtitle != "" { + lines++ + } + if option.Description != "" { + lines++ + } + return lines + } + maxRows := max(3, m.height-8-len(bodyLines)) + start := max(0, min(sel.cursor, len(sel.options)-1)) + rows := linesOf(sel.options[start]) + for start > 0 && rows+linesOf(sel.options[start-1]) <= maxRows { + start-- + rows += linesOf(sel.options[start]) + } + end := start + rows = 0 + for end < len(sel.options) && rows+linesOf(sel.options[end]) <= maxRows { + rows += linesOf(sel.options[end]) + end++ + } + if end <= sel.cursor { + end = min(len(sel.options), sel.cursor+1) + if start > sel.cursor { + start = sel.cursor + } + } var b strings.Builder b.WriteString(title) b.WriteString("\n\n") + for _, line := range bodyLines { + b.WriteString(truncate(line, width-4)) + b.WriteString("\n") + } + if len(bodyLines) > 0 { + b.WriteString("\n") + } if start > 0 { b.WriteString(dimStyle.Render(" โ†‘ ") + truncate(fmt.Sprintf("%d more", start), width-6)) b.WriteString("\n") } for i := start; i < end; i++ { - option := truncate(sel.options[i], width-4) - line := " " + option + option := sel.options[i] + if i > start { + b.WriteString("\n") + } + lines := imageLines(option.Image) + if budget := maxRows - (linesOf(option) - len(lines)); len(lines) > budget { + lines = lines[:max(0, budget)] + } + for _, line := range lines { + b.WriteString(" " + line + imageResetSuffix() + "\n") + } + marker := " " if i == sel.cursor { - line = "โ–ธ " + option + marker = "โ–ธ " } - b.WriteString(line) - if i < end-1 || end < len(sel.options) { - b.WriteString("\n") + b.WriteString(marker + truncate(oneLine(option.Title), width-6)) + if option.Subtitle != "" { + b.WriteString("\n " + dimStyle.Render(truncate(oneLine(option.Subtitle), width-6))) + } + if option.Description != "" { + b.WriteString("\n " + dimStyle.Render(truncate(oneLine(option.Description), width-6))) } } if end < len(sel.options) { - b.WriteString(dimStyle.Render(" โ†“ ") + truncate(fmt.Sprintf("%d more", len(sel.options)-end), width-6)) + b.WriteString("\n" + dimStyle.Render(" โ†“ ") + truncate(fmt.Sprintf("%d more", len(sel.options)-end), width-6)) } b.WriteString("\n\n") - b.WriteString(dimStyle.Render(" โ†‘/โ†“ move enter select esc cancel")) + b.WriteString(dimStyle.Render(" โ†‘/โ†“ move enter esc")) box := lipgloss.NewStyle(). Border(lipgloss.RoundedBorder()). @@ -130,6 +180,18 @@ func (m Model) renderLuaSelect() string { return box } +// oneLine folds the line breaks a plugin may put in an option. A selector +// counts options, not rendered lines, so an embedded newline would make the +// box taller than the terminal and hide the rows below. +func oneLine(s string) string { + return strings.Map(func(r rune) rune { + if r == '\n' || r == '\r' || r == '\t' { + return ' ' + } + return r + }, s) +} + // overlayCentered places box over frame, centered. Whole frame lines are // replaced inside the box's band, so the underlay styling cannot leak into it. func overlayCentered(frame, box string, width, height int) string { diff --git a/ui/model/lua_text.go b/ui/model/lua_text.go new file mode 100644 index 000000000..bd6ab6e79 --- /dev/null +++ b/ui/model/lua_text.go @@ -0,0 +1,140 @@ +package model + +import ( + "fmt" + "strings" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" +) + +// LuaTextMsg asks the UI to show a scrollable text block requested by a +// plugin. OnClose runs when the user dismisses it with Esc. +type LuaTextMsg struct { + Title string + Text string + OnClose func() +} + +// luaTextState is the open text panel. +type luaTextState struct { + title string + lines []string + scroll int + onClose func() +} + +func (m *Model) openLuaText(title, text string, onClose func()) { + width := m.luaTextWidth() + m.luaText = &luaTextState{ + title: title, + lines: wrapBlock(strings.TrimSpace(text), width-4), + onClose: onClose, + } +} + +// wrapBlock wraps each source line separately, so the lists and paragraphs a +// bot sends keep their shape. +func wrapBlock(text string, width int) []string { + if strings.TrimSpace(text) == "" { + return nil + } + var out []string + for _, line := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") { + if strings.TrimSpace(line) == "" { + out = append(out, "") + continue + } + out = append(out, wrapText(line, width)...) + } + return out +} + +func (m Model) luaTextWidth() int { + width := max(40, m.layout.frameWidth-8) + return min(width, max(20, m.layout.frameWidth-4)) +} + +func (m Model) luaTextVisible() int { + if m.luaText == nil { + return 0 + } + return min(len(m.luaText.lines), max(3, m.height-10)) +} + +// handleLuaTextKey drives the open text panel. It returns true when the key +// was consumed. +func (m *Model) handleLuaTextKey(msg tea.KeyPressMsg) bool { + text := m.luaText + if text == nil { + return false + } + visible := m.luaTextVisible() + maxScroll := max(0, len(text.lines)-visible) + page := max(1, visible-1) + switch msg.String() { + case "esc", "q": + m.luaText = nil + if text.onClose != nil { + text.onClose() + } + case "up", "k": + text.scroll = max(0, text.scroll-1) + case "down", "j": + text.scroll = min(maxScroll, text.scroll+1) + case "pgup", "ctrl+u": + text.scroll = max(0, text.scroll-page) + case "pgdown", "ctrl+d": + text.scroll = min(maxScroll, text.scroll+page) + case "home", "g": + text.scroll = 0 + case "end", "G": + text.scroll = maxScroll + } + return true +} + +// renderLuaText draws the text panel as a centered box. +func (m Model) renderLuaText() string { + text := m.luaText + if text == nil { + return "" + } + width := m.luaTextWidth() + visible := m.luaTextVisible() + start := min(text.scroll, max(0, len(text.lines)-visible)) + end := min(start+visible, len(text.lines)) + + var b strings.Builder + b.WriteString(truncate(text.title, width-2)) + b.WriteString("\n\n") + for i := start; i < end; i++ { + b.WriteString(truncate(text.lines[i], width-4)) + if i < end-1 { + b.WriteString("\n") + } + } + if len(text.lines) > visible { + b.WriteString("\n") + if start > 0 { + b.WriteString(dimStyle.Render(" โ†‘ more")) + } + if end < len(text.lines) { + if start > 0 { + b.WriteString(" ") + } else { + b.WriteString(" ") + } + b.WriteString(dimStyle.Render(fmt.Sprintf("โ†“ %d more", len(text.lines)-end))) + } + } + b.WriteString("\n\n") + b.WriteString(dimStyle.Render(truncate(" โ†‘/โ†“ scroll esc close", width-4))) + + return lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(lipgloss.Color("240")). + Padding(0, 1). + Width(width). + Render(b.String()) +} diff --git a/ui/model/lua_text_test.go b/ui/model/lua_text_test.go new file mode 100644 index 000000000..7a638fbcd --- /dev/null +++ b/ui/model/lua_text_test.go @@ -0,0 +1,32 @@ +package model + +import ( + "strings" + "testing" + + tea "charm.land/bubbletea/v2" +) + +func TestLuaTextKeepsLinesAndScrolls(t *testing.T) { + m := Model{height: 12} + m.openLuaText("Reply", "line one\nline two\nline three\nline four\nline five", nil) + if got := m.luaText.lines[0]; got != "line one" { + t.Fatalf("first line = %q", got) + } + m.handleLuaTextKey(tea.KeyPressMsg{Code: tea.KeyDown}) + m.handleLuaTextKey(tea.KeyPressMsg{Code: tea.KeyDown}) + if m.luaText.scroll != 2 { + t.Fatalf("scroll = %d, want 2", m.luaText.scroll) + } + m.handleLuaTextKey(tea.KeyPressMsg{Code: tea.KeyEscape}) + if m.luaText != nil { + t.Fatal("esc did not close the panel") + } +} + +func TestWrapBlockKeepsBlankLines(t *testing.T) { + lines := wrapBlock("one\n\ntwo", 20) + if strings.Join(lines, "|") != "one||two" { + t.Fatalf("lines = %#v", lines) + } +} diff --git a/ui/model/model.go b/ui/model/model.go index ef254a628..6d8059dc9 100644 --- a/ui/model/model.go +++ b/ui/model/model.go @@ -319,6 +319,9 @@ type Model struct { panes *ui.PaneSet paneCache *paneCache luaSelect *luaSelectState + luaInput *luaInputState + luaText *luaTextState + actionPane actionPaneState artRef *artRef slotVis *slotVisualizers downloadsDirectory string @@ -460,6 +463,11 @@ type Model struct { // from a non-local provider (Spotify, Navidrome, โ€ฆ). Used to highlight that // row in the provider browser. Empty when no provider playlist is active. activeProviderPlaylistID string + // providerOpenPrevID is the playlist that was open before a provider row + // started loading. It restores the highlight and action context when the + // load fails. + providerOpenPrevID string + providerOpenPrevSet bool // radioListeners holds live listener counts per cliamp radio channel slug. // Nil means unknown: the fetch never ran or failed, and rows show no diff --git a/ui/model/plugin_modal_quit_test.go b/ui/model/plugin_modal_quit_test.go new file mode 100644 index 000000000..38ac371ed --- /dev/null +++ b/ui/model/plugin_modal_quit_test.go @@ -0,0 +1,33 @@ +package model + +import ( + "testing" + + tea "charm.land/bubbletea/v2" + + "github.com/bjarneo/cliamp/luaplugin" + "github.com/bjarneo/cliamp/playlist" +) + +func TestCtrlCQuitsOverPluginModals(t *testing.T) { + cases := []struct { + name string + open func(*Model) + }{ + {"action pane", func(m *Model) { m.actionPane.visible = true }}, + {"lua text", func(m *Model) { m.openLuaText("Reply", "body", nil) }}, + {"lua input", func(m *Model) { m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) }}, + {"lua select", func(m *Model) { + m.luaSelect = &luaSelectState{title: "Pick", options: []luaplugin.SelectOption{{Title: "One"}}} + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + m := Model{player: &playbackFakeEngine{}, playlist: playlist.New()} + tc.open(&m) + if cmd := m.handleKey(tea.KeyPressMsg{Code: 'c', Mod: tea.ModCtrl}); cmd == nil || !m.quitting { + t.Fatal("Ctrl+C did not quit") + } + }) + } +} diff --git a/ui/model/plugin_open.go b/ui/model/plugin_open.go new file mode 100644 index 000000000..4a0385051 --- /dev/null +++ b/ui/model/plugin_open.go @@ -0,0 +1,45 @@ +package model + +import ( + "strings" + + tea "charm.land/bubbletea/v2" +) + +// handlePluginOpenProvider loads a playlist that a plugin resolved, such as a +// bot chat created from the chat list. The provider pane may not contain the +// row yet, so the row is added before the tracks are fetched. +func (m *Model) handlePluginOpenProvider(msg PluginOpenProviderMsg) tea.Cmd { + if m.provider == nil || msg.Playlist.ID == "" { + return nil + } + if msg.ProviderName != "" && !strings.EqualFold(m.provider.Name(), msg.ProviderName) { + m.status.Warningf(statusTTLDefault, "Switch to %s first.", msg.ProviderName) + return nil + } + found := false + for i, row := range m.provPane.lists { + if row.ID == msg.Playlist.ID { + m.provPane.lists[i] = msg.Playlist + m.provPane.cursor = i + found = true + break + } + } + if !found { + m.provPane.lists = append(m.provPane.lists, msg.Playlist) + m.provPane.cursor = len(m.provPane.lists) - 1 + } + m.provPane.loading = true + if !m.providerOpenPrevSet { + m.providerOpenPrevID = m.activeProviderPlaylistID + m.providerOpenPrevSet = true + } + m.activeProviderPlaylistID = msg.Playlist.ID + m.focus = focusPlaylist + m.applyHeightMode() + m.adjustScroll() + m.recomputeLayout() + m.status.Activityf(statusTTLShort, "Loading %sโ€ฆ", msg.Playlist.Name) + return m.fetchProviderTracks(msg.Playlist.ID) +} diff --git a/ui/model/plugin_queue.go b/ui/model/plugin_queue.go index f98da95cd..0a0d41e1b 100644 --- a/ui/model/plugin_queue.go +++ b/ui/model/plugin_queue.go @@ -11,6 +11,13 @@ import ( // Mutations are routed through the Update loop rather than applied directly // from the plugin goroutine so the model's derived state (cursor, current // index, playback) stays consistent. Indices are 0-based. +// PluginOpenProviderMsg asks the UI to load a provider playlist the plugin +// resolved, such as a bot chat that was just created. +type PluginOpenProviderMsg struct { + ProviderName string + Playlist playlist.PlaylistInfo +} + type PluginQueueMsg struct { Op string // "add" | "add_track" | "jump" | "remove" | "move" Path string // add @@ -49,6 +56,17 @@ func (m *Model) handlePluginQueue(msg PluginQueueMsg) tea.Cmd { case "move": cmd, _ := m.moveTrack(msg.Index, msg.To) return cmd + + case "insert": + msg.Track.Stream = msg.Track.Stream || playlist.IsURL(msg.Track.Path) + if m.plCursor >= 0 && msg.Index <= m.plCursor && m.plCursor < m.playlist.Len() { + m.plCursor++ + } + m.playlist.Insert(msg.Index, msg.Track) + m.recountHeaderState(m.playlist.Tracks()) + m.normalizeQueueOverlay() + m.adjustScroll() + return m.rearmStalePreload() } return nil } diff --git a/ui/model/plugin_queue_test.go b/ui/model/plugin_queue_test.go index e32782910..ad8208fed 100644 --- a/ui/model/plugin_queue_test.go +++ b/ui/model/plugin_queue_test.go @@ -94,3 +94,27 @@ func TestAppendsCountAlbumHeaders(t *testing.T) { }) } } + +func TestPluginQueueInsertNormalizesStream(t *testing.T) { + p := playlist.New() + m := Model{player: &playbackFakeEngine{}, playlist: p} + m.Update(PluginQueueMsg{Op: "insert", Index: 0, Track: playlist.Track{Path: "https://example.com/live"}}) + tracks := p.Tracks() + if len(tracks) != 1 || !tracks[0].Stream { + t.Fatalf("tracks = %#v, want one stream track", tracks) + } +} + +func TestPluginQueueInsertKeepsSelectionAndHeaderState(t *testing.T) { + p := playlist.New() + p.Replace([]playlist.Track{{Title: "A", Path: "a.mp3"}, {Title: "B", Path: "b.mp3"}}) + m := Model{player: &playbackFakeEngine{}, playlist: p, plCursor: 1} + next, _ := m.Update(PluginQueueMsg{Op: "insert", Index: 0, Track: playlist.Track{Title: "X", Path: "x.mp3"}}) + got := next.(Model) + if got.plCursor != 2 { + t.Fatalf("plCursor = %d, want 2", got.plCursor) + } + if got.headerTracks != 3 { + t.Fatalf("headerTracks = %d, want 3", got.headerTracks) + } +} diff --git a/ui/model/plugin_state.go b/ui/model/plugin_state.go index 4c0f05d1b..d35ce3053 100644 --- a/ui/model/plugin_state.go +++ b/ui/model/plugin_state.go @@ -31,6 +31,8 @@ type PluginState struct { // the rows until the playlist changes, so a caller must not change // them. A state from PluginStateLoader always has a Queue. Queue func() []luaplugin.QueueEntry + // Provider is the provider and playlist context for cliamp.provider.current. + Provider luaplugin.ProviderInfo revision uint64 // the playlist revision at publish } @@ -51,6 +53,30 @@ func (m *Model) PluginStateLoader() func() PluginState { } } +// providerInfo describes the provider the user is browsing and the row under +// the cursor. The playlist is the one open in the provider pane, not the track +// that happens to play. +func (m *Model) providerInfo() luaplugin.ProviderInfo { + info := luaplugin.ProviderInfo{PlaylistID: m.activeProviderPlaylistID} + if m.provider != nil { + info.Name = m.provider.Name() + } + for _, row := range m.provPane.lists { + if row.ID == info.PlaylistID { + info.PlaylistName = row.Name + info.PlaylistSection = row.Section + break + } + } + if m.provPane.cursor >= 0 && m.provPane.cursor < len(m.provPane.lists) { + row := m.provPane.lists[m.provPane.cursor] + info.SelectionID = row.ID + info.SelectionName = row.Name + info.SelectionSection = row.Section + } + return info +} + // publishPluginState stores the state that Lua plugins read. It makes a new // Queue only when the playlist revision changed. func (m *Model) publishPluginState() { @@ -70,6 +96,7 @@ func (m *Model) publishPluginState() { Count: m.playlist.Len(), Index: m.playlist.Index(), HasNext: m.playlist.HasNext(), + Provider: m.providerInfo(), revision: m.playlist.Revision(), } state.Track.Artist, state.Track.Title = m.resolveTrackDisplay(track) diff --git a/ui/model/providers.go b/ui/model/providers.go index 1b257303c..0ab8c8fdb 100644 --- a/ui/model/providers.go +++ b/ui/model/providers.go @@ -60,6 +60,7 @@ func (m *Model) switchProvider(idx int) tea.Cmd { m.provPane.signIn = false m.catalogBatch = catalogBatchState{} m.activeProviderPlaylistID = "" + m.providerOpenPrevSet = false m.resetProviderNav() m.focus = focusProvider // The Local source shows the playlist manager instead of the old @@ -639,6 +640,7 @@ func (m *Model) openProviderList(index int) tea.Cmd { } if entry, ok := providerBrowseEntryForID(m.provider, item.ID); ok { m.activeProviderPlaylistID = "" + m.providerOpenPrevSet = false cmd := m.openNavBrowserEntry(m.provider, entry) if m.navBrowser.visible { m.navBrowser.fromProvList = true @@ -646,6 +648,10 @@ func (m *Model) openProviderList(index int) tea.Cmd { return cmd } m.provPane.loading = true + if !m.providerOpenPrevSet { + m.providerOpenPrevID = m.activeProviderPlaylistID + m.providerOpenPrevSet = true + } m.activeProviderPlaylistID = item.ID cmd := m.fetchProviderTracks(item.ID) if _, ok := m.provider.(*radio.ChannelProvider); ok { diff --git a/ui/model/update.go b/ui/model/update.go index d6e1ecacf..5d7a47268 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -106,6 +106,7 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { } m.luaSelect = &luaSelectState{ title: msg.Title, + body: msg.Body, options: msg.Options, cursor: cursor, onDone: msg.OnDone, @@ -113,9 +114,40 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { } return m, nil + case LuaTextMsg: + m.openLuaText(msg.Title, msg.Text, msg.OnClose) + return m, nil + + case LuaInputMsg: + if prev := m.luaInput; prev != nil && prev.onCancel != nil { + prev.onCancel() + } + m.openLuaInput(msg.Title, msg.Placeholder, msg.Value, msg.Suggestions, msg.OnChange, msg.OnSubmit, msg.OnSelect, msg.OnCancel) + m.luaInput.token = msg.Token + return m, nil + + case LuaInputSuggestionsMsg: + if m.luaInput == nil || msg.Token != m.luaInput.token { + return m, nil + } + if msg.QuerySet && msg.Query != m.luaInput.value { + return m, nil + } + if len(msg.Options) != len(m.luaInput.suggestions) { + m.luaInput.choice = 0 + } + m.luaInput.suggestions = msg.Options + m.luaInput.live = msg.Live + m.luaInput.filter() + return m, nil + case tea.WindowSizeMsg: m.width = msg.Width m.height = msg.Height + if m.actionPane.visible { + m.actionPane.height = msg.Height + m.actionPane.adjustScroll() + } m.recomputeLayout() m.normalizeMainFocus() m.clampActiveScrollState() @@ -368,6 +400,9 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { m.setCustomEQBand(msg.Band, msg.Gain) return m, nil + case PluginOpenProviderMsg: + return m, m.handlePluginOpenProvider(msg) + case PluginQueueMsg: cmd := m.handlePluginQueue(msg) return m, cmd diff --git a/ui/model/update_provider.go b/ui/model/update_provider.go index aa966579c..f71da4aaf 100644 --- a/ui/model/update_provider.go +++ b/ui/model/update_provider.go @@ -75,6 +75,10 @@ func (m *Model) handleTracksLoaded(msg tracksLoadedMsg) tea.Cmd { m.provPane.loading = false m.tracksPaging = msg.err == nil && msg.next > 0 if msg.err != nil { + if msg.offset == 0 && m.providerOpenPrevSet { + m.activeProviderPlaylistID = m.providerOpenPrevID + m.providerOpenPrevSet = false + } if errors.Is(msg.err, playlist.ErrNeedsAuth) { m.provPane.signIn = true m.err = nil @@ -91,6 +95,9 @@ func (m *Model) handleTracksLoaded(msg tracksLoadedMsg) tea.Cmd { m.err = withRetryHint(msg.err) return nil } + if msg.offset == 0 { + m.providerOpenPrevSet = false + } if msg.offset > 0 { m.playlist.Add(msg.tracks...) m.normalizeQueueOverlay() diff --git a/ui/model/view.go b/ui/model/view.go index bed74e09f..944936b47 100644 --- a/ui/model/view.go +++ b/ui/model/view.go @@ -263,14 +263,27 @@ func (m Model) View() tea.View { content = strings.Join(m.mainSections(body, true, contentFirst), "\n") } + // Keep image placeholder lines changing every frame so the terminal + // re-emits them and kitty does not drop the images. + imagePulse = !imagePulse + // Every screen now renders within the main frame, so frame and center // uniformly. rendered := m.centerFrame(m.layout.frameStyle().Render(content)) rendered = ui.FitRect(rendered, m.layout.frameWidth, max(1, m.height)) + if box := m.renderActionPane(); box != "" { + rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) + } if box := m.renderLuaSelect(); box != "" { rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) } + if box := m.renderLuaInput(); box != "" { + rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) + } + if box := m.renderLuaText(); box != "" { + rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) + } view := tea.NewView(rendered) view.BackgroundColor = ui.ColorBackground if ui.ColorBackground != nil {