fix: CLI poll loop used UUID instead of queue cursor (last_id)

The poll loop was storing msg.ID (UUID string) as afterID, but the server
expects the integer queue cursor from last_id. This caused the CLI to
re-fetch ALL messages on every poll cycle.

- Change PollMessages to accept int64 afterID and return PollResult with LastID
- Track lastQID (queue cursor) instead of lastMsgID (UUID)
- Parse the wrapped MessagesResponse properly
This commit is contained in:
clawbot
2026-02-10 18:22:08 -08:00
committed by user
parent fbeede563d
commit eff44e5d32
3 changed files with 234 additions and 590 deletions

View File

@@ -1,31 +1,15 @@
// Package chatapi provides a client for the chat server HTTP API. package api
package chatapi
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"strconv"
"time" "time"
) )
const (
httpTimeout = 30 * time.Second
pollExtraDelay = 5
httpErrThreshold = 400
)
// ErrHTTP is returned for non-2xx responses.
var ErrHTTP = errors.New("http error")
// ErrUnexpectedFormat is returned when the response format is
// not recognised.
var ErrUnexpectedFormat = errors.New("unexpected format")
// Client wraps HTTP calls to the chat server API. // Client wraps HTTP calls to the chat server API.
type Client struct { type Client struct {
BaseURL string BaseURL string
@@ -38,32 +22,59 @@ func NewClient(baseURL string) *Client {
return &Client{ return &Client{
BaseURL: baseURL, BaseURL: baseURL,
HTTPClient: &http.Client{ HTTPClient: &http.Client{
Timeout: httpTimeout, Timeout: 30 * time.Second,
}, },
} }
} }
func (c *Client) do(method, path string, body interface{}) ([]byte, error) {
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal: %w", err)
}
bodyReader = bytes.NewReader(data)
}
req, err := http.NewRequest(method, c.BaseURL+path, bodyReader)
if err != nil {
return nil, fmt.Errorf("request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
if c.Token != "" {
req.Header.Set("Authorization", "Bearer "+c.Token)
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("http: %w", err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)
}
if resp.StatusCode >= 400 {
return data, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(data))
}
return data, nil
}
// CreateSession creates a new session on the server. // CreateSession creates a new session on the server.
func (c *Client) CreateSession( func (c *Client) CreateSession(nick string) (*SessionResponse, error) {
nick string, data, err := c.do("POST", "/api/v1/session", &SessionRequest{Nick: nick})
) (*SessionResponse, error) {
data, err := c.do(
"POST", "/api/v1/session",
&SessionRequest{Nick: nick},
)
if err != nil { if err != nil {
return nil, err return nil, err
} }
var resp SessionResponse var resp SessionResponse
if err := json.Unmarshal(data, &resp); err != nil {
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, fmt.Errorf("decode session: %w", err) return nil, fmt.Errorf("decode session: %w", err)
} }
c.Token = resp.Token c.Token = resp.Token
return &resp, nil return &resp, nil
} }
@@ -73,113 +84,72 @@ func (c *Client) GetState() (*StateResponse, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
var resp StateResponse var resp StateResponse
if err := json.Unmarshal(data, &resp); err != nil {
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, fmt.Errorf("decode state: %w", err) return nil, fmt.Errorf("decode state: %w", err)
} }
return &resp, nil return &resp, nil
} }
// SendMessage sends a message (any IRC command). // SendMessage sends a message (any IRC command).
func (c *Client) SendMessage(msg *Message) error { func (c *Client) SendMessage(msg *Message) error {
_, err := c.do("POST", "/api/v1/messages", msg) _, err := c.do("POST", "/api/v1/messages", msg)
return err return err
} }
// PollMessages long-polls for new messages. // PollMessages long-polls for new messages. afterID is the queue cursor (last_id).
func (c *Client) PollMessages( func (c *Client) PollMessages(afterID int64, timeout int) (*PollResult, error) {
afterID string, // Use a longer HTTP timeout than the server long-poll timeout.
timeout int, client := &http.Client{Timeout: time.Duration(timeout+5) * time.Second}
) ([]Message, error) {
pollTimeout := time.Duration(
timeout+pollExtraDelay,
) * time.Second
client := &http.Client{Timeout: pollTimeout}
params := url.Values{} params := url.Values{}
if afterID != "" { if afterID > 0 {
params.Set("after", afterID) params.Set("after", fmt.Sprintf("%d", afterID))
} }
params.Set("timeout", fmt.Sprintf("%d", timeout))
params.Set("timeout", strconv.Itoa(timeout)) path := "/api/v1/messages?" + params.Encode()
path := "/api/v1/messages" req, err := http.NewRequest("GET", c.BaseURL+path, nil)
if len(params) > 0 {
path += "?" + params.Encode()
}
req, err := http.NewRequest( //nolint:noctx // CLI tool
http.MethodGet, c.BaseURL+path, nil,
)
if err != nil { if err != nil {
return nil, err return nil, err
} }
req.Header.Set("Authorization", "Bearer "+c.Token) req.Header.Set("Authorization", "Bearer "+c.Token)
resp, err := client.Do(req) //nolint:gosec // URL from user config resp, err := client.Do(req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()
data, err := io.ReadAll(resp.Body) data, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if resp.StatusCode >= httpErrThreshold { if resp.StatusCode >= 400 {
return nil, fmt.Errorf( return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(data))
"%w: %d: %s",
ErrHTTP, resp.StatusCode, string(data),
)
}
return decodeMessages(data)
}
func decodeMessages(data []byte) ([]Message, error) {
var msgs []Message
err := json.Unmarshal(data, &msgs)
if err == nil {
return msgs, nil
} }
var wrapped MessagesResponse var wrapped MessagesResponse
if err := json.Unmarshal(data, &wrapped); err != nil {
err2 := json.Unmarshal(data, &wrapped) return nil, fmt.Errorf("decode messages: %w (raw: %s)", err, string(data))
if err2 != nil {
return nil, fmt.Errorf(
"decode messages: %w (raw: %s)",
err, string(data),
)
} }
return wrapped.Messages, nil return &PollResult{
Messages: wrapped.Messages,
LastID: wrapped.LastID,
}, nil
} }
// JoinChannel joins a channel via the unified command // JoinChannel joins a channel via the unified command endpoint.
// endpoint.
func (c *Client) JoinChannel(channel string) error { func (c *Client) JoinChannel(channel string) error {
return c.SendMessage( return c.SendMessage(&Message{Command: "JOIN", To: channel})
&Message{Command: "JOIN", To: channel},
)
} }
// PartChannel leaves a channel via the unified command // PartChannel leaves a channel via the unified command endpoint.
// endpoint.
func (c *Client) PartChannel(channel string) error { func (c *Client) PartChannel(channel string) error {
return c.SendMessage( return c.SendMessage(&Message{Command: "PART", To: channel})
&Message{Command: "PART", To: channel},
)
} }
// ListChannels returns all channels on the server. // ListChannels returns all channels on the server.
@@ -188,39 +158,29 @@ func (c *Client) ListChannels() ([]Channel, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
var channels []Channel var channels []Channel
if err := json.Unmarshal(data, &channels); err != nil {
err = json.Unmarshal(data, &channels)
if err != nil {
return nil, err return nil, err
} }
return channels, nil return channels, nil
} }
// GetMembers returns members of a channel. // GetMembers returns members of a channel.
func (c *Client) GetMembers( func (c *Client) GetMembers(channel string) ([]string, error) {
channel string, data, err := c.do("GET", "/api/v1/channels/"+url.PathEscape(channel)+"/members", nil)
) ([]string, error) {
path := "/api/v1/channels/" +
url.PathEscape(channel) + "/members"
data, err := c.do("GET", path, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
var members []string var members []string
if err := json.Unmarshal(data, &members); err != nil {
err = json.Unmarshal(data, &members) // Try object format.
if err != nil { var obj map[string]interface{}
return nil, fmt.Errorf( if err2 := json.Unmarshal(data, &obj); err2 != nil {
"%w: members: %s", return nil, err
ErrUnexpectedFormat, string(data), }
) // Extract member names from whatever format.
return nil, fmt.Errorf("unexpected members format: %s", string(data))
} }
return members, nil return members, nil
} }
@@ -230,63 +190,9 @@ func (c *Client) GetServerInfo() (*ServerInfo, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
var info ServerInfo var info ServerInfo
if err := json.Unmarshal(data, &info); err != nil {
err = json.Unmarshal(data, &info)
if err != nil {
return nil, err return nil, err
} }
return &info, nil return &info, nil
} }
func (c *Client) do(
method, path string,
body any,
) ([]byte, error) {
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal: %w", err)
}
bodyReader = bytes.NewReader(data)
}
req, err := http.NewRequest( //nolint:noctx // CLI tool
method, c.BaseURL+path, bodyReader,
)
if err != nil {
return nil, fmt.Errorf("request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
if c.Token != "" {
req.Header.Set("Authorization", "Bearer "+c.Token)
}
resp, err := c.HTTPClient.Do(req) //nolint:gosec // URL from user config
if err != nil {
return nil, fmt.Errorf("http: %w", err)
}
defer func() { _ = resp.Body.Close() }()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)
}
if resp.StatusCode >= httpErrThreshold {
return data, fmt.Errorf(
"%w: %d: %s",
ErrHTTP, resp.StatusCode, string(data),
)
}
return data, nil
}

View File

@@ -74,6 +74,13 @@ type ServerInfo struct {
// MessagesResponse wraps polling results. // MessagesResponse wraps polling results.
type MessagesResponse struct { type MessagesResponse struct {
Messages []Message `json:"messages"` Messages []Message `json:"messages"`
LastID int64 `json:"last_id"`
}
// PollResult wraps the poll response including the cursor.
type PollResult struct {
Messages []Message
LastID int64
} }
// ParseTS parses the message timestamp. // ParseTS parses the message timestamp.

View File

@@ -1,21 +1,13 @@
// Package main implements chat-cli, an IRC-style terminal client.
package main package main
import ( import (
"fmt" "fmt"
"os" "os"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
api "git.eeqj.de/sneak/chat/cmd/chat-cli/api" "git.eeqj.de/sneak/chat/cmd/chat-cli/api"
)
const (
pollTimeoutSec = 15
retryDelay = 2 * time.Second
maxNickLength = 32
) )
// App holds the application state. // App holds the application state.
@@ -27,7 +19,7 @@ type App struct {
nick string nick string
target string // current target (#channel or nick for DM) target string // current target (#channel or nick for DM)
connected bool connected bool
lastMsgID string lastQID int64 // queue cursor for polling
stopPoll chan struct{} stopPoll chan struct{}
} }
@@ -40,18 +32,11 @@ func main() {
app.ui.OnInput(app.handleInput) app.ui.OnInput(app.handleInput)
app.ui.SetStatus(app.nick, "", "disconnected") app.ui.SetStatus(app.nick, "", "disconnected")
app.ui.AddStatus( app.ui.AddStatus("Welcome to chat-cli — an IRC-style client")
"Welcome to chat-cli \u2014 an IRC-style client", app.ui.AddStatus("Type [yellow]/connect <server-url>[white] to begin, or [yellow]/help[white] for commands")
)
app.ui.AddStatus(
"Type [yellow]/connect <server-url>[white] " +
"to begin, or [yellow]/help[white] for commands",
)
err := app.ui.Run()
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", err)
if err := app.ui.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1) os.Exit(1)
} }
} }
@@ -59,34 +44,21 @@ func main() {
func (a *App) handleInput(text string) { func (a *App) handleInput(text string) {
if strings.HasPrefix(text, "/") { if strings.HasPrefix(text, "/") {
a.handleCommand(text) a.handleCommand(text)
return return
} }
a.sendPlainText(text) // Plain text → PRIVMSG to current target.
}
func (a *App) sendPlainText(text string) {
a.mu.Lock() a.mu.Lock()
target := a.target target := a.target
connected := a.connected connected := a.connected
nick := a.nick
a.mu.Unlock() a.mu.Unlock()
if !connected { if !connected {
a.ui.AddStatus( a.ui.AddStatus("[red]Not connected. Use /connect <url>")
"[red]Not connected. Use /connect <url>",
)
return return
} }
if target == "" { if target == "" {
a.ui.AddStatus( a.ui.AddStatus("[red]No target. Use /join #channel or /query nick")
"[red]No target. " +
"Use /join #channel or /query nick",
)
return return
} }
@@ -96,28 +68,21 @@ func (a *App) sendPlainText(text string) {
Body: []string{text}, Body: []string{text},
}) })
if err != nil { if err != nil {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[red]Send error: %v", err))
fmt.Sprintf("[red]Send error: %v", err),
)
return return
} }
// Echo locally.
ts := time.Now().Format("15:04") ts := time.Now().Format("15:04")
a.mu.Lock()
a.ui.AddLine( nick := a.nick
target, a.mu.Unlock()
fmt.Sprintf( a.ui.AddLine(target, fmt.Sprintf("[gray]%s [green]<%s>[white] %s", ts, nick, text))
"[gray]%s [green]<%s>[white] %s",
ts, nick, text,
),
)
} }
func (a *App) handleCommand(text string) { //nolint:cyclop // command dispatch func (a *App) handleCommand(text string) {
parts := strings.SplitN(text, " ", 2) //nolint:mnd // split into cmd+args parts := strings.SplitN(text, " ", 2)
cmd := strings.ToLower(parts[0]) cmd := strings.ToLower(parts[0])
args := "" args := ""
if len(parts) > 1 { if len(parts) > 1 {
args = parts[1] args = parts[1]
@@ -149,41 +114,27 @@ func (a *App) handleCommand(text string) { //nolint:cyclop // command dispatch
case "/help": case "/help":
a.cmdHelp() a.cmdHelp()
default: default:
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[red]Unknown command: %s", cmd))
"[red]Unknown command: " + cmd,
)
} }
} }
func (a *App) cmdConnect(serverURL string) { func (a *App) cmdConnect(serverURL string) {
if serverURL == "" { if serverURL == "" {
a.ui.AddStatus( a.ui.AddStatus("[red]Usage: /connect <server-url>")
"[red]Usage: /connect <server-url>",
)
return return
} }
serverURL = strings.TrimRight(serverURL, "/") serverURL = strings.TrimRight(serverURL, "/")
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("Connecting to %s...", serverURL))
fmt.Sprintf("Connecting to %s...", serverURL),
)
a.mu.Lock() a.mu.Lock()
nick := a.nick nick := a.nick
a.mu.Unlock() a.mu.Unlock()
client := api.NewClient(serverURL) client := api.NewClient(serverURL)
resp, err := client.CreateSession(nick) resp, err := client.CreateSession(nick)
if err != nil { if err != nil {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[red]Connection failed: %v", err))
fmt.Sprintf(
"[red]Connection failed: %v", err,
),
)
return return
} }
@@ -191,29 +142,22 @@ func (a *App) cmdConnect(serverURL string) {
a.client = client a.client = client
a.nick = resp.Nick a.nick = resp.Nick
a.connected = true a.connected = true
a.lastMsgID = "" a.lastQID = 0
a.mu.Unlock() a.mu.Unlock()
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[green]Connected! Nick: %s, Session: %s", resp.Nick, resp.SessionID))
fmt.Sprintf(
"[green]Connected! Nick: %s, Session: %s",
resp.Nick, resp.SessionID,
),
)
a.ui.SetStatus(resp.Nick, "", "connected") a.ui.SetStatus(resp.Nick, "", "connected")
// Start polling.
a.stopPoll = make(chan struct{}) a.stopPoll = make(chan struct{})
go a.pollLoop() go a.pollLoop()
} }
func (a *App) cmdNick(nick string) { func (a *App) cmdNick(nick string) {
if nick == "" { if nick == "" {
a.ui.AddStatus("[red]Usage: /nick <name>") a.ui.AddStatus("[red]Usage: /nick <name>")
return return
} }
a.mu.Lock() a.mu.Lock()
connected := a.connected connected := a.connected
a.mu.Unlock() a.mu.Unlock()
@@ -222,14 +166,7 @@ func (a *App) cmdNick(nick string) {
a.mu.Lock() a.mu.Lock()
a.nick = nick a.nick = nick
a.mu.Unlock() a.mu.Unlock()
a.ui.AddStatus(fmt.Sprintf("Nick set to %s (will be used on connect)", nick))
a.ui.AddStatus(
fmt.Sprintf(
"Nick set to %s (will be used on connect)",
nick,
),
)
return return
} }
@@ -238,12 +175,7 @@ func (a *App) cmdNick(nick string) {
Body: []string{nick}, Body: []string{nick},
}) })
if err != nil { if err != nil {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[red]Nick change failed: %v", err))
fmt.Sprintf(
"[red]Nick change failed: %v", err,
),
)
return return
} }
@@ -251,20 +183,15 @@ func (a *App) cmdNick(nick string) {
a.nick = nick a.nick = nick
target := a.target target := a.target
a.mu.Unlock() a.mu.Unlock()
a.ui.SetStatus(nick, target, "connected") a.ui.SetStatus(nick, target, "connected")
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("Nick changed to %s", nick))
"Nick changed to " + nick,
)
} }
func (a *App) cmdJoin(channel string) { func (a *App) cmdJoin(channel string) {
if channel == "" { if channel == "" {
a.ui.AddStatus("[red]Usage: /join #channel") a.ui.AddStatus("[red]Usage: /join #channel")
return return
} }
if !strings.HasPrefix(channel, "#") { if !strings.HasPrefix(channel, "#") {
channel = "#" + channel channel = "#" + channel
} }
@@ -272,19 +199,14 @@ func (a *App) cmdJoin(channel string) {
a.mu.Lock() a.mu.Lock()
connected := a.connected connected := a.connected
a.mu.Unlock() a.mu.Unlock()
if !connected { if !connected {
a.ui.AddStatus("[red]Not connected") a.ui.AddStatus("[red]Not connected")
return return
} }
err := a.client.JoinChannel(channel) err := a.client.JoinChannel(channel)
if err != nil { if err != nil {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[red]Join failed: %v", err))
fmt.Sprintf("[red]Join failed: %v", err),
)
return return
} }
@@ -294,55 +216,39 @@ func (a *App) cmdJoin(channel string) {
a.mu.Unlock() a.mu.Unlock()
a.ui.SwitchToBuffer(channel) a.ui.SwitchToBuffer(channel)
a.ui.AddLine( a.ui.AddLine(channel, fmt.Sprintf("[yellow]*** Joined %s", channel))
channel,
"[yellow]*** Joined "+channel,
)
a.ui.SetStatus(nick, channel, "connected") a.ui.SetStatus(nick, channel, "connected")
} }
func (a *App) cmdPart(channel string) { func (a *App) cmdPart(channel string) {
a.mu.Lock() a.mu.Lock()
if channel == "" { if channel == "" {
channel = a.target channel = a.target
} }
connected := a.connected connected := a.connected
a.mu.Unlock() a.mu.Unlock()
if channel == "" || !strings.HasPrefix(channel, "#") { if channel == "" || !strings.HasPrefix(channel, "#") {
a.ui.AddStatus("[red]No channel to part") a.ui.AddStatus("[red]No channel to part")
return return
} }
if !connected { if !connected {
a.ui.AddStatus("[red]Not connected") a.ui.AddStatus("[red]Not connected")
return return
} }
err := a.client.PartChannel(channel) err := a.client.PartChannel(channel)
if err != nil { if err != nil {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[red]Part failed: %v", err))
fmt.Sprintf("[red]Part failed: %v", err),
)
return return
} }
a.ui.AddLine( a.ui.AddLine(channel, fmt.Sprintf("[yellow]*** Left %s", channel))
channel,
"[yellow]*** Left "+channel,
)
a.mu.Lock() a.mu.Lock()
if a.target == channel { if a.target == channel {
a.target = "" a.target = ""
} }
nick := a.nick nick := a.nick
a.mu.Unlock() a.mu.Unlock()
@@ -351,23 +257,19 @@ func (a *App) cmdPart(channel string) {
} }
func (a *App) cmdMsg(args string) { func (a *App) cmdMsg(args string) {
parts := strings.SplitN(args, " ", 2) //nolint:mnd // split into target+text parts := strings.SplitN(args, " ", 2)
if len(parts) < 2 { //nolint:mnd // min args if len(parts) < 2 {
a.ui.AddStatus("[red]Usage: /msg <nick> <text>") a.ui.AddStatus("[red]Usage: /msg <nick> <text>")
return return
} }
target, text := parts[0], parts[1] target, text := parts[0], parts[1]
a.mu.Lock() a.mu.Lock()
connected := a.connected connected := a.connected
nick := a.nick nick := a.nick
a.mu.Unlock() a.mu.Unlock()
if !connected { if !connected {
a.ui.AddStatus("[red]Not connected") a.ui.AddStatus("[red]Not connected")
return return
} }
@@ -377,28 +279,17 @@ func (a *App) cmdMsg(args string) {
Body: []string{text}, Body: []string{text},
}) })
if err != nil { if err != nil {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[red]Send failed: %v", err))
fmt.Sprintf("[red]Send failed: %v", err),
)
return return
} }
ts := time.Now().Format("15:04") ts := time.Now().Format("15:04")
a.ui.AddLine(target, fmt.Sprintf("[gray]%s [green]<%s>[white] %s", ts, nick, text))
a.ui.AddLine(
target,
fmt.Sprintf(
"[gray]%s [green]<%s>[white] %s",
ts, nick, text,
),
)
} }
func (a *App) cmdQuery(nick string) { func (a *App) cmdQuery(nick string) {
if nick == "" { if nick == "" {
a.ui.AddStatus("[red]Usage: /query <nick>") a.ui.AddStatus("[red]Usage: /query <nick>")
return return
} }
@@ -419,29 +310,22 @@ func (a *App) cmdTopic(args string) {
if !connected { if !connected {
a.ui.AddStatus("[red]Not connected") a.ui.AddStatus("[red]Not connected")
return return
} }
if !strings.HasPrefix(target, "#") { if !strings.HasPrefix(target, "#") {
a.ui.AddStatus("[red]Not in a channel") a.ui.AddStatus("[red]Not in a channel")
return return
} }
if args == "" { if args == "" {
// Query topic.
err := a.client.SendMessage(&api.Message{ err := a.client.SendMessage(&api.Message{
Command: "TOPIC", Command: "TOPIC",
To: target, To: target,
}) })
if err != nil { if err != nil {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[red]Topic query failed: %v", err))
fmt.Sprintf(
"[red]Topic query failed: %v", err,
),
)
} }
return return
} }
@@ -451,11 +335,7 @@ func (a *App) cmdTopic(args string) {
Body: []string{args}, Body: []string{args},
}) })
if err != nil { if err != nil {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[red]Topic set failed: %v", err))
fmt.Sprintf(
"[red]Topic set failed: %v", err,
),
)
} }
} }
@@ -467,32 +347,20 @@ func (a *App) cmdNames() {
if !connected { if !connected {
a.ui.AddStatus("[red]Not connected") a.ui.AddStatus("[red]Not connected")
return return
} }
if !strings.HasPrefix(target, "#") { if !strings.HasPrefix(target, "#") {
a.ui.AddStatus("[red]Not in a channel") a.ui.AddStatus("[red]Not in a channel")
return return
} }
members, err := a.client.GetMembers(target) members, err := a.client.GetMembers(target)
if err != nil { if err != nil {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[red]Names failed: %v", err))
fmt.Sprintf("[red]Names failed: %v", err),
)
return return
} }
a.ui.AddLine( a.ui.AddLine(target, fmt.Sprintf("[cyan]*** Members of %s: %s", target, strings.Join(members, " ")))
target,
fmt.Sprintf(
"[cyan]*** Members of %s: %s",
target, strings.Join(members, " "),
),
)
} }
func (a *App) cmdList() { func (a *App) cmdList() {
@@ -502,55 +370,46 @@ func (a *App) cmdList() {
if !connected { if !connected {
a.ui.AddStatus("[red]Not connected") a.ui.AddStatus("[red]Not connected")
return return
} }
channels, err := a.client.ListChannels() channels, err := a.client.ListChannels()
if err != nil { if err != nil {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[red]List failed: %v", err))
fmt.Sprintf("[red]List failed: %v", err),
)
return return
} }
a.ui.AddStatus("[cyan]*** Channel list:") a.ui.AddStatus("[cyan]*** Channel list:")
for _, ch := range channels { for _, ch := range channels {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf(" %s (%d members) %s", ch.Name, ch.Members, ch.Topic))
fmt.Sprintf(
" %s (%d members) %s",
ch.Name, ch.Members, ch.Topic,
),
)
} }
a.ui.AddStatus("[cyan]*** End of channel list") a.ui.AddStatus("[cyan]*** End of channel list")
} }
func (a *App) cmdWindow(args string) { func (a *App) cmdWindow(args string) {
if args == "" { if args == "" {
a.ui.AddStatus("[red]Usage: /window <number>") a.ui.AddStatus("[red]Usage: /window <number>")
return return
} }
n := 0
n, _ := strconv.Atoi(args) fmt.Sscanf(args, "%d", &n)
a.ui.SwitchBuffer(n) a.ui.SwitchBuffer(n)
a.mu.Lock() a.mu.Lock()
if n < a.ui.BufferCount() && n >= 0 {
// Update target to the buffer name.
// Needs to be done carefully.
}
nick := a.nick nick := a.nick
a.mu.Unlock() a.mu.Unlock()
if n >= 0 && n < a.ui.BufferCount() { // Update target based on buffer.
if n < a.ui.BufferCount() {
buf := a.ui.buffers[n] buf := a.ui.buffers[n]
if buf.Name != "(status)" { if buf.Name != "(status)" {
a.mu.Lock() a.mu.Lock()
a.target = buf.Name a.target = buf.Name
a.mu.Unlock() a.mu.Unlock()
a.ui.SetStatus(nick, buf.Name, "connected") a.ui.SetStatus(nick, buf.Name, "connected")
} else { } else {
a.ui.SetStatus(nick, "", "connected") a.ui.SetStatus(nick, "", "connected")
@@ -560,17 +419,12 @@ func (a *App) cmdWindow(args string) {
func (a *App) cmdQuit() { func (a *App) cmdQuit() {
a.mu.Lock() a.mu.Lock()
if a.connected && a.client != nil { if a.connected && a.client != nil {
_ = a.client.SendMessage( _ = a.client.SendMessage(&api.Message{Command: "QUIT"})
&api.Message{Command: "QUIT"},
)
} }
if a.stopPoll != nil { if a.stopPoll != nil {
close(a.stopPoll) close(a.stopPoll)
} }
a.mu.Unlock() a.mu.Unlock()
a.ui.Stop() a.ui.Stop()
} }
@@ -578,21 +432,20 @@ func (a *App) cmdQuit() {
func (a *App) cmdHelp() { func (a *App) cmdHelp() {
help := []string{ help := []string{
"[cyan]*** chat-cli commands:", "[cyan]*** chat-cli commands:",
" /connect <url> \u2014 Connect to server", " /connect <url> Connect to server",
" /nick <name> \u2014 Change nickname", " /nick <name> Change nickname",
" /join #channel \u2014 Join channel", " /join #channel Join channel",
" /part [#chan] \u2014 Leave channel", " /part [#chan] Leave channel",
" /msg <nick> <text> \u2014 Send DM", " /msg <nick> <text> Send DM",
" /query <nick> \u2014 Open DM window", " /query <nick> Open DM window",
" /topic [text] \u2014 View/set topic", " /topic [text] View/set topic",
" /names \u2014 List channel members", " /names List channel members",
" /list \u2014 List channels", " /list List channels",
" /window <n> \u2014 Switch buffer (Alt+0-9)", " /window <n> Switch buffer (Alt+0-9)",
" /quit \u2014 Disconnect and exit", " /quit Disconnect and exit",
" /help \u2014 This help", " /help This help",
" Plain text sends to current target.", " Plain text sends to current target.",
} }
for _, line := range help { for _, line := range help {
a.ui.AddStatus(line) a.ui.AddStatus(line)
} }
@@ -609,38 +462,40 @@ func (a *App) pollLoop() {
a.mu.Lock() a.mu.Lock()
client := a.client client := a.client
lastID := a.lastMsgID lastQID := a.lastQID
a.mu.Unlock() a.mu.Unlock()
if client == nil { if client == nil {
return return
} }
msgs, err := client.PollMessages( result, err := client.PollMessages(lastQID, 15)
lastID, pollTimeoutSec,
)
if err != nil { if err != nil {
time.Sleep(retryDelay) // Transient error — retry after delay.
time.Sleep(2 * time.Second)
continue continue
} }
for i := range msgs { if result.LastID > 0 {
a.handleServerMessage(&msgs[i])
if msgs[i].ID != "" {
a.mu.Lock() a.mu.Lock()
a.lastMsgID = msgs[i].ID a.lastQID = result.LastID
a.mu.Unlock() a.mu.Unlock()
} }
for _, msg := range result.Messages {
a.handleServerMessage(&msg)
} }
} }
} }
func (a *App) handleServerMessage( func (a *App) handleServerMessage(msg *api.Message) {
msg *api.Message, ts := ""
) { if msg.TS != "" {
ts := a.parseMessageTS(msg) t := msg.ParseTS()
ts = t.Local().Format("15:04")
} else {
ts = time.Now().Format("15:04")
}
a.mu.Lock() a.mu.Lock()
myNick := a.nick myNick := a.nick
@@ -648,203 +503,79 @@ func (a *App) handleServerMessage(
switch msg.Command { switch msg.Command {
case "PRIVMSG": case "PRIVMSG":
a.handlePrivmsgMsg(msg, ts, myNick)
case "JOIN":
a.handleJoinMsg(msg, ts)
case "PART":
a.handlePartMsg(msg, ts)
case "QUIT":
a.handleQuitMsg(msg, ts)
case "NICK":
a.handleNickMsg(msg, ts, myNick)
case "NOTICE":
a.handleNoticeMsg(msg, ts)
case "TOPIC":
a.handleTopicMsg(msg, ts)
default:
a.handleDefaultMsg(msg, ts)
}
}
func (a *App) parseMessageTS(msg *api.Message) string {
if msg.TS != "" {
t := msg.ParseTS()
return t.In(time.Local).Format("15:04") //nolint:gosmopolitan // CLI uses local time
}
return time.Now().Format("15:04")
}
func (a *App) handlePrivmsgMsg(
msg *api.Message,
ts, myNick string,
) {
lines := msg.BodyLines() lines := msg.BodyLines()
text := strings.Join(lines, " ") text := strings.Join(lines, " ")
if msg.From == myNick { if msg.From == myNick {
// Skip our own echoed messages (already displayed locally).
return return
} }
target := msg.To target := msg.To
if !strings.HasPrefix(target, "#") { if !strings.HasPrefix(target, "#") {
// DM — use sender's nick as buffer name.
target = msg.From target = msg.From
} }
a.ui.AddLine(target, fmt.Sprintf("[gray]%s [green]<%s>[white] %s", ts, msg.From, text))
a.ui.AddLine( case "JOIN":
target,
fmt.Sprintf(
"[gray]%s [green]<%s>[white] %s",
ts, msg.From, text,
),
)
}
func (a *App) handleJoinMsg(
msg *api.Message, ts string,
) {
target := msg.To target := msg.To
if target == "" { if target != "" {
return a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has joined %s", ts, msg.From, target))
} }
a.ui.AddLine( case "PART":
target,
fmt.Sprintf(
"[gray]%s [yellow]*** %s has joined %s",
ts, msg.From, target,
),
)
}
func (a *App) handlePartMsg(
msg *api.Message, ts string,
) {
target := msg.To target := msg.To
if target == "" {
return
}
lines := msg.BodyLines() lines := msg.BodyLines()
reason := strings.Join(lines, " ") reason := strings.Join(lines, " ")
if target != "" {
if reason != "" { if reason != "" {
a.ui.AddLine( a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has left %s (%s)", ts, msg.From, target, reason))
target,
fmt.Sprintf(
"[gray]%s [yellow]*** %s has left %s (%s)",
ts, msg.From, target, reason,
),
)
} else { } else {
a.ui.AddLine( a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has left %s", ts, msg.From, target))
target, }
fmt.Sprintf(
"[gray]%s [yellow]*** %s has left %s",
ts, msg.From, target,
),
)
} }
}
func (a *App) handleQuitMsg( case "QUIT":
msg *api.Message, ts string,
) {
lines := msg.BodyLines() lines := msg.BodyLines()
reason := strings.Join(lines, " ") reason := strings.Join(lines, " ")
if reason != "" { if reason != "" {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s has quit (%s)", ts, msg.From, reason))
fmt.Sprintf(
"[gray]%s [yellow]*** %s has quit (%s)",
ts, msg.From, reason,
),
)
} else { } else {
a.ui.AddStatus( a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s has quit", ts, msg.From))
fmt.Sprintf(
"[gray]%s [yellow]*** %s has quit",
ts, msg.From,
),
)
} }
}
func (a *App) handleNickMsg( case "NICK":
msg *api.Message, ts, myNick string,
) {
lines := msg.BodyLines() lines := msg.BodyLines()
newNick := "" newNick := ""
if len(lines) > 0 { if len(lines) > 0 {
newNick = lines[0] newNick = lines[0]
} }
if msg.From == myNick && newNick != "" { if msg.From == myNick && newNick != "" {
a.mu.Lock() a.mu.Lock()
a.nick = newNick a.nick = newNick
target := a.target target := a.target
a.mu.Unlock() a.mu.Unlock()
a.ui.SetStatus(newNick, target, "connected") a.ui.SetStatus(newNick, target, "connected")
} }
a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s is now known as %s", ts, msg.From, newNick))
a.ui.AddStatus( case "NOTICE":
fmt.Sprintf(
"[gray]%s [yellow]*** %s is now known as %s",
ts, msg.From, newNick,
),
)
}
func (a *App) handleNoticeMsg(
msg *api.Message, ts string,
) {
lines := msg.BodyLines() lines := msg.BodyLines()
text := strings.Join(lines, " ") text := strings.Join(lines, " ")
a.ui.AddStatus(fmt.Sprintf("[gray]%s [magenta]--%s-- %s", ts, msg.From, text))
a.ui.AddStatus( case "TOPIC":
fmt.Sprintf( lines := msg.BodyLines()
"[gray]%s [magenta]--%s-- %s", text := strings.Join(lines, " ")
ts, msg.From, text, if msg.To != "" {
), a.ui.AddLine(msg.To, fmt.Sprintf("[gray]%s [cyan]*** %s set topic: %s", ts, msg.From, text))
)
}
func (a *App) handleTopicMsg(
msg *api.Message, ts string,
) {
if msg.To == "" {
return
} }
default:
// Numeric replies and other messages → status window.
lines := msg.BodyLines() lines := msg.BodyLines()
text := strings.Join(lines, " ") text := strings.Join(lines, " ")
if text != "" {
a.ui.AddLine( a.ui.AddStatus(fmt.Sprintf("[gray]%s [white][%s] %s", ts, msg.Command, text))
msg.To, }
fmt.Sprintf(
"[gray]%s [cyan]*** %s set topic: %s",
ts, msg.From, text,
),
)
}
func (a *App) handleDefaultMsg(
msg *api.Message, ts string,
) {
lines := msg.BodyLines()
text := strings.Join(lines, " ")
if text == "" {
return
} }
a.ui.AddStatus(
fmt.Sprintf(
"[gray]%s [white][%s] %s",
ts, msg.Command, text,
),
)
} }