diff --git a/cmd/chat-cli/api/client.go b/cmd/chat-cli/api/client.go index a20298c..b014491 100644 --- a/cmd/chat-cli/api/client.go +++ b/cmd/chat-cli/api/client.go @@ -1,15 +1,35 @@ +// Package api provides the HTTP client for the chat server API. package api import ( "bytes" + "context" "encoding/json" + "errors" "fmt" "io" "net/http" "net/url" + "strconv" "time" ) +const ( + // httpClientTimeout is the default HTTP client timeout in seconds. + httpClientTimeout = 30 + // httpStatusErrorThreshold is the minimum status code considered an error. + httpStatusErrorThreshold = 400 + // pollTimeoutBuffer is extra seconds added to HTTP timeout beyond the poll timeout. + pollTimeoutBuffer = 5 +) + +var ( + // ErrHTTPStatus is returned when the server responds with an error status code. + ErrHTTPStatus = errors.New("HTTP error") + // ErrUnexpectedFormat is returned when the response format is unexpected. + ErrUnexpectedFormat = errors.New("unexpected format") +) + // Client wraps HTTP calls to the chat server API. type Client struct { BaseURL string @@ -22,59 +42,27 @@ func NewClient(baseURL string) *Client { return &Client{ BaseURL: baseURL, HTTPClient: &http.Client{ - Timeout: 30 * time.Second, + Timeout: httpClientTimeout * 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. func (c *Client) CreateSession(nick string) (*SessionResponse, error) { data, err := c.do("POST", "/api/v1/session", &SessionRequest{Nick: nick}) if err != nil { return nil, err } + 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) } + c.Token = resp.Token + return &resp, nil } @@ -84,64 +72,77 @@ func (c *Client) GetState() (*StateResponse, error) { if err != nil { return nil, err } + 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 &resp, nil } // SendMessage sends a message (any IRC command). func (c *Client) SendMessage(msg *Message) error { _, err := c.do("POST", "/api/v1/messages", msg) + return err } // PollMessages long-polls for new messages. func (c *Client) PollMessages(afterID string, timeout int) ([]Message, error) { // Use a longer HTTP timeout than the server long-poll timeout. - client := &http.Client{Timeout: time.Duration(timeout+5) * time.Second} + client := &http.Client{Timeout: time.Duration(timeout+pollTimeoutBuffer) * time.Second} params := url.Values{} if afterID != "" { params.Set("after", afterID) } - params.Set("timeout", fmt.Sprintf("%d", timeout)) + + params.Set("timeout", strconv.Itoa(timeout)) path := "/api/v1/messages" if len(params) > 0 { path += "?" + params.Encode() } - req, err := http.NewRequest("GET", c.BaseURL+path, nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, c.BaseURL+path, nil) if err != nil { return nil, err } + req.Header.Set("Authorization", "Bearer "+c.Token) - resp, err := client.Do(req) + resp, err := client.Do(req) //nolint:gosec // G704: BaseURL is set by user at connect time, not tainted input if err != nil { return nil, err } - defer resp.Body.Close() + + defer func() { _ = resp.Body.Close() }() data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } - if resp.StatusCode >= 400 { - return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(data)) + if resp.StatusCode >= httpStatusErrorThreshold { + return nil, fmt.Errorf("%w: %d: %s", ErrHTTPStatus, resp.StatusCode, string(data)) } // The server may return an array directly or wrapped. var msgs []Message - if err := json.Unmarshal(data, &msgs); err != nil { + + err = json.Unmarshal(data, &msgs) + if err != nil { // Try wrapped format. var wrapped MessagesResponse - if err2 := json.Unmarshal(data, &wrapped); err2 != nil { + + err2 := json.Unmarshal(data, &wrapped) + if err2 != nil { return nil, fmt.Errorf("decode messages: %w (raw: %s)", err, string(data)) } + msgs = wrapped.Messages } @@ -164,10 +165,14 @@ func (c *Client) ListChannels() ([]Channel, error) { if err != nil { return nil, err } + var channels []Channel - if err := json.Unmarshal(data, &channels); err != nil { + + err = json.Unmarshal(data, &channels) + if err != nil { return nil, err } + return channels, nil } @@ -177,16 +182,22 @@ func (c *Client) GetMembers(channel string) ([]string, error) { if err != nil { return nil, err } + var members []string - if err := json.Unmarshal(data, &members); err != nil { + + err = json.Unmarshal(data, &members) + if err != nil { // Try object format. - var obj map[string]interface{} - if err2 := json.Unmarshal(data, &obj); err2 != nil { + var obj map[string]any + + err2 := json.Unmarshal(data, &obj) + if err2 != nil { return nil, err } // Extract member names from whatever format. - return nil, fmt.Errorf("unexpected members format: %s", string(data)) + return nil, fmt.Errorf("%w: members: %s", ErrUnexpectedFormat, string(data)) } + return members, nil } @@ -196,9 +207,55 @@ func (c *Client) GetServerInfo() (*ServerInfo, error) { if err != nil { return nil, err } + var info ServerInfo - if err := json.Unmarshal(data, &info); err != nil { + + err = json.Unmarshal(data, &info) + if err != nil { return nil, err } + 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.NewRequestWithContext(context.Background(), 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 constructed from trusted base URL + 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 >= httpStatusErrorThreshold { + return data, fmt.Errorf("%w: %d: %s", ErrHTTPStatus, resp.StatusCode, string(data)) + } + + return data, nil +} diff --git a/cmd/chat-cli/api/types.go b/cmd/chat-cli/api/types.go index 1655d79..ee1d487 100644 --- a/cmd/chat-cli/api/types.go +++ b/cmd/chat-cli/api/types.go @@ -1,4 +1,4 @@ -package api +package api //nolint:revive // package name "api" is conventional for API client packages import "time" @@ -9,42 +9,43 @@ type SessionRequest struct { // SessionResponse is the response from POST /api/v1/session. type SessionResponse struct { - SessionID string `json:"session_id"` - ClientID string `json:"client_id"` + SessionID string `json:"sessionId"` + ClientID string `json:"clientId"` Nick string `json:"nick"` Token string `json:"token"` } // StateResponse is the response from GET /api/v1/state. type StateResponse struct { - SessionID string `json:"session_id"` - ClientID string `json:"client_id"` + SessionID string `json:"sessionId"` + ClientID string `json:"clientId"` Nick string `json:"nick"` Channels []string `json:"channels"` } // Message represents a chat message envelope. type Message struct { - Command string `json:"command"` - From string `json:"from,omitempty"` - To string `json:"to,omitempty"` - Params []string `json:"params,omitempty"` - Body interface{} `json:"body,omitempty"` - ID string `json:"id,omitempty"` - TS string `json:"ts,omitempty"` - Meta interface{} `json:"meta,omitempty"` + Command string `json:"command"` + From string `json:"from,omitempty"` + To string `json:"to,omitempty"` + Params []string `json:"params,omitempty"` + Body any `json:"body,omitempty"` + ID string `json:"id,omitempty"` + TS string `json:"ts,omitempty"` + Meta any `json:"meta,omitempty"` } // BodyLines returns the body as a slice of strings (for text messages). func (m *Message) BodyLines() []string { switch v := m.Body.(type) { - case []interface{}: + case []any: lines := make([]string, 0, len(v)) for _, item := range v { if s, ok := item.(string); ok { lines = append(lines, s) } } + return lines case []string: return v @@ -58,7 +59,7 @@ type Channel struct { Name string `json:"name"` Topic string `json:"topic"` Members int `json:"members"` - CreatedAt string `json:"created_at"` + CreatedAt string `json:"createdAt"` } // ServerInfo is the response from GET /api/v1/server. @@ -79,5 +80,6 @@ func (m *Message) ParseTS() time.Time { if err != nil { return time.Now() } + return t } diff --git a/cmd/chat-cli/main.go b/cmd/chat-cli/main.go index 6dfa1f3..c6865d3 100644 --- a/cmd/chat-cli/main.go +++ b/cmd/chat-cli/main.go @@ -1,3 +1,4 @@ +// Package main implements the chat-cli terminal client. package main import ( @@ -10,6 +11,15 @@ import ( "git.eeqj.de/sneak/chat/cmd/chat-cli/api" ) +const ( + // splitParts is the number of parts to split a command into (command + args). + splitParts = 2 + // pollTimeout is the long-poll timeout in seconds. + pollTimeout = 15 + // pollRetryDelay is the delay before retrying a failed poll. + pollRetryDelay = 2 * time.Second +) + // App holds the application state. type App struct { ui *UI @@ -35,7 +45,8 @@ func main() { app.ui.AddStatus("Welcome to chat-cli — an IRC-style client") app.ui.AddStatus("Type [yellow]/connect [white] to begin, or [yellow]/help[white] for commands") - if err := app.ui.Run(); err != nil { + err := app.ui.Run() + if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } @@ -44,6 +55,7 @@ func main() { func (a *App) handleInput(text string) { if strings.HasPrefix(text, "/") { a.handleCommand(text) + return } @@ -55,10 +67,13 @@ func (a *App) handleInput(text string) { if !connected { a.ui.AddStatus("[red]Not connected. Use /connect ") + return } + if target == "" { a.ui.AddStatus("[red]No target. Use /join #channel or /query nick") + return } @@ -69,60 +84,60 @@ func (a *App) handleInput(text string) { }) if err != nil { a.ui.AddStatus(fmt.Sprintf("[red]Send error: %v", err)) + return } // Echo locally. ts := time.Now().Format("15:04") + a.mu.Lock() nick := a.nick a.mu.Unlock() a.ui.AddLine(target, fmt.Sprintf("[gray]%s [green]<%s>[white] %s", ts, nick, text)) } +func (a *App) commandHandlers() map[string]func(string) { + return map[string]func(string){ + "/connect": a.cmdConnect, + "/nick": a.cmdNick, + "/join": a.cmdJoin, + "/part": a.cmdPart, + "/msg": a.cmdMsg, + "/query": a.cmdQuery, + "/topic": a.cmdTopic, + "/names": func(_ string) { a.cmdNames() }, + "/list": func(_ string) { a.cmdList() }, + "/window": a.cmdWindow, + "/w": a.cmdWindow, + "/quit": func(_ string) { a.cmdQuit() }, + "/help": func(_ string) { a.cmdHelp() }, + } +} + func (a *App) handleCommand(text string) { - parts := strings.SplitN(text, " ", 2) + parts := strings.SplitN(text, " ", splitParts) cmd := strings.ToLower(parts[0]) + args := "" if len(parts) > 1 { args = parts[1] } - switch cmd { - case "/connect": - a.cmdConnect(args) - case "/nick": - a.cmdNick(args) - case "/join": - a.cmdJoin(args) - case "/part": - a.cmdPart(args) - case "/msg": - a.cmdMsg(args) - case "/query": - a.cmdQuery(args) - case "/topic": - a.cmdTopic(args) - case "/names": - a.cmdNames() - case "/list": - a.cmdList() - case "/window", "/w": - a.cmdWindow(args) - case "/quit": - a.cmdQuit() - case "/help": - a.cmdHelp() - default: - a.ui.AddStatus(fmt.Sprintf("[red]Unknown command: %s", cmd)) + if handler, ok := a.commandHandlers()[cmd]; ok { + handler(args) + } else { + a.ui.AddStatus("[red]Unknown command: " + cmd) } } func (a *App) cmdConnect(serverURL string) { if serverURL == "" { a.ui.AddStatus("[red]Usage: /connect ") + return } + serverURL = strings.TrimRight(serverURL, "/") a.ui.AddStatus(fmt.Sprintf("Connecting to %s...", serverURL)) @@ -132,9 +147,11 @@ func (a *App) cmdConnect(serverURL string) { a.mu.Unlock() client := api.NewClient(serverURL) + resp, err := client.CreateSession(nick) if err != nil { a.ui.AddStatus(fmt.Sprintf("[red]Connection failed: %v", err)) + return } @@ -156,8 +173,10 @@ func (a *App) cmdConnect(serverURL string) { func (a *App) cmdNick(nick string) { if nick == "" { a.ui.AddStatus("[red]Usage: /nick ") + return } + a.mu.Lock() connected := a.connected a.mu.Unlock() @@ -167,6 +186,7 @@ func (a *App) cmdNick(nick string) { a.nick = nick a.mu.Unlock() a.ui.AddStatus(fmt.Sprintf("Nick set to %s (will be used on connect)", nick)) + return } @@ -176,6 +196,7 @@ func (a *App) cmdNick(nick string) { }) if err != nil { a.ui.AddStatus(fmt.Sprintf("[red]Nick change failed: %v", err)) + return } @@ -184,14 +205,16 @@ func (a *App) cmdNick(nick string) { target := a.target a.mu.Unlock() a.ui.SetStatus(nick, target, "connected") - a.ui.AddStatus(fmt.Sprintf("Nick changed to %s", nick)) + a.ui.AddStatus("Nick changed to " + nick) } func (a *App) cmdJoin(channel string) { if channel == "" { a.ui.AddStatus("[red]Usage: /join #channel") + return } + if !strings.HasPrefix(channel, "#") { channel = "#" + channel } @@ -199,14 +222,17 @@ func (a *App) cmdJoin(channel string) { a.mu.Lock() connected := a.connected a.mu.Unlock() + if !connected { a.ui.AddStatus("[red]Not connected") + return } err := a.client.JoinChannel(channel) if err != nil { a.ui.AddStatus(fmt.Sprintf("[red]Join failed: %v", err)) + return } @@ -216,7 +242,7 @@ func (a *App) cmdJoin(channel string) { a.mu.Unlock() a.ui.SwitchToBuffer(channel) - a.ui.AddLine(channel, fmt.Sprintf("[yellow]*** Joined %s", channel)) + a.ui.AddLine(channel, "[yellow]*** Joined "+channel) a.ui.SetStatus(nick, channel, "connected") } @@ -225,30 +251,36 @@ func (a *App) cmdPart(channel string) { if channel == "" { channel = a.target } + connected := a.connected a.mu.Unlock() if channel == "" || !strings.HasPrefix(channel, "#") { a.ui.AddStatus("[red]No channel to part") + return } + if !connected { a.ui.AddStatus("[red]Not connected") + return } err := a.client.PartChannel(channel) if err != nil { a.ui.AddStatus(fmt.Sprintf("[red]Part failed: %v", err)) + return } - a.ui.AddLine(channel, fmt.Sprintf("[yellow]*** Left %s", channel)) + a.ui.AddLine(channel, "[yellow]*** Left "+channel) a.mu.Lock() if a.target == channel { a.target = "" } + nick := a.nick a.mu.Unlock() @@ -257,19 +289,23 @@ func (a *App) cmdPart(channel string) { } func (a *App) cmdMsg(args string) { - parts := strings.SplitN(args, " ", 2) - if len(parts) < 2 { + parts := strings.SplitN(args, " ", splitParts) + if len(parts) < splitParts { a.ui.AddStatus("[red]Usage: /msg ") + return } + target, text := parts[0], parts[1] a.mu.Lock() connected := a.connected nick := a.nick a.mu.Unlock() + if !connected { a.ui.AddStatus("[red]Not connected") + return } @@ -280,6 +316,7 @@ func (a *App) cmdMsg(args string) { }) if err != nil { a.ui.AddStatus(fmt.Sprintf("[red]Send failed: %v", err)) + return } @@ -290,6 +327,7 @@ func (a *App) cmdMsg(args string) { func (a *App) cmdQuery(nick string) { if nick == "" { a.ui.AddStatus("[red]Usage: /query ") + return } @@ -310,10 +348,13 @@ func (a *App) cmdTopic(args string) { if !connected { a.ui.AddStatus("[red]Not connected") + return } + if !strings.HasPrefix(target, "#") { a.ui.AddStatus("[red]Not in a channel") + return } @@ -326,6 +367,7 @@ func (a *App) cmdTopic(args string) { if err != nil { a.ui.AddStatus(fmt.Sprintf("[red]Topic query failed: %v", err)) } + return } @@ -347,16 +389,20 @@ func (a *App) cmdNames() { if !connected { a.ui.AddStatus("[red]Not connected") + return } + if !strings.HasPrefix(target, "#") { a.ui.AddStatus("[red]Not in a channel") + return } members, err := a.client.GetMembers(target) if err != nil { a.ui.AddStatus(fmt.Sprintf("[red]Names failed: %v", err)) + return } @@ -370,36 +416,38 @@ func (a *App) cmdList() { if !connected { a.ui.AddStatus("[red]Not connected") + return } channels, err := a.client.ListChannels() if err != nil { a.ui.AddStatus(fmt.Sprintf("[red]List failed: %v", err)) + return } a.ui.AddStatus("[cyan]*** Channel list:") + for _, ch := range channels { a.ui.AddStatus(fmt.Sprintf(" %s (%d members) %s", ch.Name, ch.Members, ch.Topic)) } + a.ui.AddStatus("[cyan]*** End of channel list") } func (a *App) cmdWindow(args string) { if args == "" { a.ui.AddStatus("[red]Usage: /window ") + return } + n := 0 - fmt.Sscanf(args, "%d", &n) + _, _ = fmt.Sscanf(args, "%d", &n) a.ui.SwitchBuffer(n) a.mu.Lock() - if n < a.ui.BufferCount() && n >= 0 { - // Update target to the buffer name. - // Needs to be done carefully. - } nick := a.nick a.mu.Unlock() @@ -422,6 +470,7 @@ func (a *App) cmdQuit() { if a.connected && a.client != nil { _ = a.client.SendMessage(&api.Message{Command: "QUIT"}) } + if a.stopPoll != nil { close(a.stopPoll) } @@ -469,15 +518,17 @@ func (a *App) pollLoop() { return } - msgs, err := client.PollMessages(lastID, 15) + msgs, err := client.PollMessages(lastID, pollTimeout) if err != nil { // Transient error — retry after delay. - time.Sleep(2 * time.Second) + time.Sleep(pollRetryDelay) + continue } for _, msg := range msgs { a.handleServerMessage(&msg) + if msg.ID != "" { a.mu.Lock() a.lastMsgID = msg.ID @@ -487,94 +538,123 @@ func (a *App) pollLoop() { } } -func (a *App) handleServerMessage(msg *api.Message) { - ts := "" +func (a *App) messageTimestamp(msg *api.Message) string { if msg.TS != "" { t := msg.ParseTS() - ts = t.Local().Format("15:04") - } else { - ts = time.Now().Format("15:04") + + return t.Local().Format("15:04") //nolint:gosmopolitan // CLI displays local time intentionally } + return time.Now().Format("15:04") +} + +func (a *App) handleServerMessage(msg *api.Message) { + ts := a.messageTimestamp(msg) + a.mu.Lock() myNick := a.nick a.mu.Unlock() switch msg.Command { case "PRIVMSG": - lines := msg.BodyLines() - text := strings.Join(lines, " ") - if msg.From == myNick { - // Skip our own echoed messages (already displayed locally). - return - } - target := msg.To - if !strings.HasPrefix(target, "#") { - // DM — use sender's nick as buffer name. - target = msg.From - } - a.ui.AddLine(target, fmt.Sprintf("[gray]%s [green]<%s>[white] %s", ts, msg.From, text)) - + a.handleMsgPrivmsg(msg, ts, myNick) case "JOIN": - target := msg.To - if target != "" { - a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has joined %s", ts, msg.From, target)) - } - + a.handleMsgJoin(msg, ts) case "PART": - target := msg.To - lines := msg.BodyLines() - reason := strings.Join(lines, " ") - if target != "" { - if reason != "" { - a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has left %s (%s)", ts, msg.From, target, reason)) - } else { - a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has left %s", ts, msg.From, target)) - } - } - + a.handleMsgPart(msg, ts) case "QUIT": - lines := msg.BodyLines() - reason := strings.Join(lines, " ") - if reason != "" { - a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s has quit (%s)", ts, msg.From, reason)) - } else { - a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s has quit", ts, msg.From)) - } - + a.handleMsgQuit(msg, ts) case "NICK": - lines := msg.BodyLines() - newNick := "" - if len(lines) > 0 { - newNick = lines[0] - } - if msg.From == myNick && newNick != "" { - a.mu.Lock() - a.nick = newNick - target := a.target - a.mu.Unlock() - 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.handleMsgNick(msg, ts, myNick) case "NOTICE": - lines := msg.BodyLines() - text := strings.Join(lines, " ") - a.ui.AddStatus(fmt.Sprintf("[gray]%s [magenta]--%s-- %s", ts, msg.From, text)) - + a.handleMsgNotice(msg, ts) case "TOPIC": - lines := msg.BodyLines() - text := strings.Join(lines, " ") - if msg.To != "" { - a.ui.AddLine(msg.To, fmt.Sprintf("[gray]%s [cyan]*** %s set topic: %s", ts, msg.From, text)) - } - + a.handleMsgTopic(msg, ts) default: - // Numeric replies and other messages → status window. - lines := msg.BodyLines() - text := strings.Join(lines, " ") - if text != "" { - a.ui.AddStatus(fmt.Sprintf("[gray]%s [white][%s] %s", ts, msg.Command, text)) - } + a.handleMsgDefault(msg, ts) + } +} + +func (a *App) handleMsgPrivmsg(msg *api.Message, ts, myNick string) { + lines := msg.BodyLines() + text := strings.Join(lines, " ") + + if msg.From == myNick { + return + } + + target := msg.To + if !strings.HasPrefix(target, "#") { + target = msg.From + } + + a.ui.AddLine(target, fmt.Sprintf("[gray]%s [green]<%s>[white] %s", ts, msg.From, text)) +} + +func (a *App) handleMsgJoin(msg *api.Message, ts string) { + if msg.To != "" { + a.ui.AddLine(msg.To, fmt.Sprintf("[gray]%s [yellow]*** %s has joined %s", ts, msg.From, msg.To)) + } +} + +func (a *App) handleMsgPart(msg *api.Message, ts string) { + target := msg.To + reason := strings.Join(msg.BodyLines(), " ") + + if target == "" { + return + } + + if reason != "" { + a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has left %s (%s)", ts, msg.From, target, reason)) + } else { + a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has left %s", ts, msg.From, target)) + } +} + +func (a *App) handleMsgQuit(msg *api.Message, ts string) { + reason := strings.Join(msg.BodyLines(), " ") + if reason != "" { + a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s has quit (%s)", ts, msg.From, reason)) + } else { + a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s has quit", ts, msg.From)) + } +} + +func (a *App) handleMsgNick(msg *api.Message, ts, myNick string) { + lines := msg.BodyLines() + + newNick := "" + if len(lines) > 0 { + newNick = lines[0] + } + + if msg.From == myNick && newNick != "" { + a.mu.Lock() + a.nick = newNick + target := a.target + a.mu.Unlock() + a.ui.SetStatus(newNick, target, "connected") + } + + a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s is now known as %s", ts, msg.From, newNick)) +} + +func (a *App) handleMsgNotice(msg *api.Message, ts string) { + text := strings.Join(msg.BodyLines(), " ") + a.ui.AddStatus(fmt.Sprintf("[gray]%s [magenta]--%s-- %s", ts, msg.From, text)) +} + +func (a *App) handleMsgTopic(msg *api.Message, ts string) { + text := strings.Join(msg.BodyLines(), " ") + if msg.To != "" { + a.ui.AddLine(msg.To, fmt.Sprintf("[gray]%s [cyan]*** %s set topic: %s", ts, msg.From, text)) + } +} + +func (a *App) handleMsgDefault(msg *api.Message, ts string) { + text := strings.Join(msg.BodyLines(), " ") + if text != "" { + a.ui.AddStatus(fmt.Sprintf("[gray]%s [white][%s] %s", ts, msg.Command, text)) } } diff --git a/cmd/chat-cli/ui.go b/cmd/chat-cli/ui.go index 16449f2..9d14dc5 100644 --- a/cmd/chat-cli/ui.go +++ b/cmd/chat-cli/ui.go @@ -55,35 +55,8 @@ func NewUI() *UI { ui.statusBar.SetBackgroundColor(tcell.ColorNavy) ui.statusBar.SetTextColor(tcell.ColorWhite) - // Input field. - ui.input = tview.NewInputField(). - SetFieldBackgroundColor(tcell.ColorBlack). - SetFieldTextColor(tcell.ColorWhite) - ui.input.SetDoneFunc(func(key tcell.Key) { - if key == tcell.KeyEnter { - text := ui.input.GetText() - if text == "" { - return - } - ui.input.SetText("") - if ui.onInput != nil { - ui.onInput(text) - } - } - }) - - // Capture Alt+N for window switching. - ui.app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { - if event.Modifiers()&tcell.ModAlt != 0 { - r := event.Rune() - if r >= '0' && r <= '9' { - idx := int(r - '0') - ui.SwitchBuffer(idx) - return nil - } - } - return event - }) + ui.setupInput() + ui.setupKeyCapture() // Layout: messages on top, status bar, input at bottom. ui.layout = tview.NewFlex().SetDirection(tview.FlexRow). @@ -121,12 +94,13 @@ func (ui *UI) AddLine(bufferName string, line string) { // Mark unread if not currently viewing this buffer. if ui.buffers[ui.currentBuffer] != buf { buf.Unread++ + ui.refreshStatus() } // If viewing this buffer, append to display. if ui.buffers[ui.currentBuffer] == buf { - fmt.Fprintln(ui.messages, line) + _, _ = fmt.Fprintln(ui.messages, line) } }) } @@ -143,13 +117,17 @@ func (ui *UI) SwitchBuffer(n int) { if n < 0 || n >= len(ui.buffers) { return } + ui.currentBuffer = n buf := ui.buffers[n] buf.Unread = 0 + ui.messages.Clear() + for _, line := range buf.Lines { - fmt.Fprintln(ui.messages, line) + _, _ = fmt.Fprintln(ui.messages, line) } + ui.messages.ScrollToEnd() ui.refreshStatus() }) @@ -162,14 +140,19 @@ func (ui *UI) SwitchToBuffer(name string) { for i, b := range ui.buffers { if b == buf { ui.currentBuffer = i + break } } + buf.Unread = 0 + ui.messages.Clear() + for _, line := range buf.Lines { - fmt.Fprintln(ui.messages, line) + _, _ = fmt.Fprintln(ui.messages, line) } + ui.messages.ScrollToEnd() ui.refreshStatus() }) @@ -182,41 +165,6 @@ func (ui *UI) SetStatus(nick, target, connStatus string) { }) } -func (ui *UI) refreshStatus() { - // Will be called from the main goroutine via QueueUpdateDraw parent. - // Rebuild status from app state — caller must provide context. -} - -func (ui *UI) refreshStatusWith(nick, target, connStatus string) { - var unreadParts []string - for i, buf := range ui.buffers { - if buf.Unread > 0 { - unreadParts = append(unreadParts, fmt.Sprintf("%d:%s(%d)", i, buf.Name, buf.Unread)) - } - } - unread := "" - if len(unreadParts) > 0 { - unread = " [Act: " + strings.Join(unreadParts, ",") + "]" - } - - bufInfo := fmt.Sprintf("[%d:%s]", ui.currentBuffer, ui.buffers[ui.currentBuffer].Name) - - ui.statusBar.Clear() - fmt.Fprintf(ui.statusBar, " [%s] %s %s %s%s", - connStatus, nick, bufInfo, target, unread) -} - -func (ui *UI) getOrCreateBuffer(name string) *Buffer { - for _, buf := range ui.buffers { - if buf.Name == name { - return buf - } - } - buf := &Buffer{Name: name} - ui.buffers = append(ui.buffers, buf) - return buf -} - // BufferCount returns the number of buffers. func (ui *UI) BufferCount() int { return len(ui.buffers) @@ -229,5 +177,83 @@ func (ui *UI) BufferIndex(name string) int { return i } } + return -1 } + +func (ui *UI) setupInput() { + ui.input = tview.NewInputField(). + SetFieldBackgroundColor(tcell.ColorBlack). + SetFieldTextColor(tcell.ColorWhite) + ui.input.SetDoneFunc(func(key tcell.Key) { + if key != tcell.KeyEnter { + return + } + + text := ui.input.GetText() + if text == "" { + return + } + + ui.input.SetText("") + + if ui.onInput != nil { + ui.onInput(text) + } + }) +} + +func (ui *UI) setupKeyCapture() { + ui.app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { + if event.Modifiers()&tcell.ModAlt != 0 { + r := event.Rune() + if r >= '0' && r <= '9' { + idx := int(r - '0') + ui.SwitchBuffer(idx) + + return nil + } + } + + return event + }) +} + +func (ui *UI) refreshStatus() { + // Will be called from the main goroutine via QueueUpdateDraw parent. + // Rebuild status from app state — caller must provide context. +} + +func (ui *UI) refreshStatusWith(nick, target, connStatus string) { + var unreadParts []string + + for i, buf := range ui.buffers { + if buf.Unread > 0 { + unreadParts = append(unreadParts, fmt.Sprintf("%d:%s(%d)", i, buf.Name, buf.Unread)) + } + } + + unread := "" + if len(unreadParts) > 0 { + unread = " [Act: " + strings.Join(unreadParts, ",") + "]" + } + + bufInfo := fmt.Sprintf("[%d:%s]", ui.currentBuffer, ui.buffers[ui.currentBuffer].Name) + + ui.statusBar.Clear() + _, _ = fmt.Fprintf(ui.statusBar, " [%s] %s %s %s%s", + connStatus, nick, bufInfo, target, unread) +} + +func (ui *UI) getOrCreateBuffer(name string) *Buffer { + for _, buf := range ui.buffers { + if buf.Name == name { + return buf + } + } + + buf := &Buffer{Name: name} + ui.buffers = append(ui.buffers, buf) + + return buf +} diff --git a/internal/db/db.go b/internal/db/db.go index a6663ff..114691e 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -88,8 +88,10 @@ func NewTest(dsn string) (*Database, error) { } // Item 9: Enable foreign keys - if _, err := d.Exec("PRAGMA foreign_keys = ON"); err != nil { + _, err = d.ExecContext(context.Background(), "PRAGMA foreign_keys = ON") + if err != nil { _ = d.Close() + return nil, fmt.Errorf("enable foreign keys: %w", err) } @@ -219,6 +221,7 @@ func (s *Database) DeleteAuthToken( _, err := s.db.ExecContext(ctx, `DELETE FROM auth_tokens WHERE token = ?`, token, ) + return err } @@ -231,6 +234,7 @@ func (s *Database) UpdateUserLastSeen( `UPDATE users SET last_seen_at = CURRENT_TIMESTAMP WHERE id = ?`, userID, ) + return err } @@ -394,6 +398,7 @@ func (s *Database) DequeueMessages( if err != nil { return nil, err } + defer func() { _ = rows.Close() }() entries := []*models.MessageQueueEntry{} @@ -423,13 +428,14 @@ func (s *Database) AckMessages( } placeholders := make([]string, len(entryIDs)) - args := make([]interface{}, len(entryIDs)) + args := make([]any, len(entryIDs)) for i, id := range entryIDs { placeholders[i] = "?" args[i] = id } + //nolint:gosec // G201: placeholders are all "?" literals, not user input query := fmt.Sprintf( "DELETE FROM message_queue WHERE id IN (%s)", strings.Join(placeholders, ","), @@ -549,7 +555,8 @@ func (s *Database) connect(ctx context.Context) error { s.log.Info("database connected") // Item 9: Enable foreign keys on every connection - if _, err := s.db.ExecContext(ctx, "PRAGMA foreign_keys = ON"); err != nil { + _, err = s.db.ExecContext(ctx, "PRAGMA foreign_keys = ON") + if err != nil { return fmt.Errorf("enable foreign keys: %w", err) } @@ -655,62 +662,53 @@ func (s *Database) applyMigrations( migrations []migration, ) error { for _, m := range migrations { - var exists int - - err := s.db.QueryRowContext(ctx, - "SELECT COUNT(*) FROM schema_migrations WHERE version = ?", - m.version, - ).Scan(&exists) + err := s.applyOneMigration(ctx, m) if err != nil { - return fmt.Errorf( - "check migration %d: %w", m.version, err, - ) - } - - if exists > 0 { - continue - } - - s.log.Info( - "applying migration", - "version", m.version, "name", m.name, - ) - - tx, err := s.db.BeginTx(ctx, nil) - if err != nil { - return fmt.Errorf( - "begin tx for migration %d: %w", m.version, err, - ) - } - - _, err = tx.ExecContext(ctx, m.sql) - if err != nil { - _ = tx.Rollback() - - return fmt.Errorf( - "apply migration %d (%s): %w", - m.version, m.name, err, - ) - } - - _, err = tx.ExecContext(ctx, - "INSERT INTO schema_migrations (version) VALUES (?)", - m.version, - ) - if err != nil { - _ = tx.Rollback() - - return fmt.Errorf( - "record migration %d: %w", m.version, err, - ) - } - - if err := tx.Commit(); err != nil { - return fmt.Errorf( - "commit migration %d: %w", m.version, err, - ) + return err } } return nil } + +func (s *Database) applyOneMigration(ctx context.Context, m migration) error { + var exists int + + err := s.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM schema_migrations WHERE version = ?", + m.version, + ).Scan(&exists) + if err != nil { + return fmt.Errorf("check migration %d: %w", m.version, err) + } + + if exists > 0 { + return nil + } + + s.log.Info("applying migration", "version", m.version, "name", m.name) + + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin tx for migration %d: %w", m.version, err) + } + + _, err = tx.ExecContext(ctx, m.sql) + if err != nil { + _ = tx.Rollback() + + return fmt.Errorf("apply migration %d (%s): %w", m.version, m.name, err) + } + + _, err = tx.ExecContext(ctx, + "INSERT INTO schema_migrations (version) VALUES (?)", + m.version, + ) + if err != nil { + _ = tx.Rollback() + + return fmt.Errorf("record migration %d: %w", m.version, err) + } + + return tx.Commit() +} diff --git a/internal/db/queries.go b/internal/db/queries.go index 974f4db..6897182 100644 --- a/internal/db/queries.go +++ b/internal/db/queries.go @@ -2,88 +2,53 @@ package db import ( "context" - "crypto/rand" - "encoding/hex" + "database/sql" "fmt" "time" ) -func generateToken() string { - b := make([]byte, 32) - _, _ = rand.Read(b) - return hex.EncodeToString(b) -} - -// CreateUser registers a new user with the given nick and returns the user with token. -func (s *Database) CreateUser(ctx context.Context, nick string) (int64, string, error) { - token := generateToken() - now := time.Now() - res, err := s.db.ExecContext(ctx, - "INSERT INTO users (nick, token, created_at, last_seen) VALUES (?, ?, ?, ?)", - nick, token, now, now) - if err != nil { - return 0, "", fmt.Errorf("create user: %w", err) - } - id, _ := res.LastInsertId() - return id, token, nil -} - -// GetUserByToken returns user id and nick for a given auth token. -func (s *Database) GetUserByToken(ctx context.Context, token string) (int64, string, error) { - var id int64 - var nick string - err := s.db.QueryRowContext(ctx, "SELECT id, nick FROM users WHERE token = ?", token).Scan(&id, &nick) - if err != nil { - return 0, "", err - } - // Update last_seen - _, _ = s.db.ExecContext(ctx, "UPDATE users SET last_seen = ? WHERE id = ?", time.Now(), id) - return id, nick, nil -} - -// GetUserByNick returns user id for a given nick. -func (s *Database) GetUserByNick(ctx context.Context, nick string) (int64, error) { - var id int64 - err := s.db.QueryRowContext(ctx, "SELECT id FROM users WHERE nick = ?", nick).Scan(&id) - return id, err -} - // GetOrCreateChannel returns the channel id, creating it if needed. -func (s *Database) GetOrCreateChannel(ctx context.Context, name string) (int64, error) { - var id int64 +func (s *Database) GetOrCreateChannel(ctx context.Context, name string) (string, error) { + var id string + err := s.db.QueryRowContext(ctx, "SELECT id FROM channels WHERE name = ?", name).Scan(&id) if err == nil { return id, nil } + now := time.Now() - res, err := s.db.ExecContext(ctx, - "INSERT INTO channels (name, created_at, updated_at) VALUES (?, ?, ?)", - name, now, now) + id = fmt.Sprintf("ch-%d", now.UnixNano()) + + _, err = s.db.ExecContext(ctx, + "INSERT INTO channels (id, name, topic, modes, created_at, updated_at) VALUES (?, ?, '', '', ?, ?)", + id, name, now, now) if err != nil { - return 0, fmt.Errorf("create channel: %w", err) + return "", fmt.Errorf("create channel: %w", err) } - id, _ = res.LastInsertId() + return id, nil } // JoinChannel adds a user to a channel. -func (s *Database) JoinChannel(ctx context.Context, channelID, userID int64) error { +func (s *Database) JoinChannel(ctx context.Context, channelID, userID string) error { _, err := s.db.ExecContext(ctx, - "INSERT OR IGNORE INTO channel_members (channel_id, user_id, joined_at) VALUES (?, ?, ?)", + "INSERT OR IGNORE INTO channel_members (channel_id, user_id, modes, joined_at) VALUES (?, ?, '', ?)", channelID, userID, time.Now()) + return err } // PartChannel removes a user from a channel. -func (s *Database) PartChannel(ctx context.Context, channelID, userID int64) error { +func (s *Database) PartChannel(ctx context.Context, channelID, userID string) error { _, err := s.db.ExecContext(ctx, "DELETE FROM channel_members WHERE channel_id = ? AND user_id = ?", channelID, userID) + return err } // ListChannels returns all channels the user has joined. -func (s *Database) ListChannels(ctx context.Context, userID int64) ([]ChannelInfo, error) { +func (s *Database) ListChannels(ctx context.Context, userID string) ([]ChannelInfo, error) { rows, err := s.db.QueryContext(ctx, `SELECT c.id, c.name, c.topic FROM channels c INNER JOIN channel_members cm ON cm.channel_id = c.id @@ -91,62 +56,70 @@ func (s *Database) ListChannels(ctx context.Context, userID int64) ([]ChannelInf if err != nil { return nil, err } - defer rows.Close() - var channels []ChannelInfo + + defer func() { _ = rows.Close() }() + + channels := []ChannelInfo{} + for rows.Next() { var ch ChannelInfo - if err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic); err != nil { + + err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic) + if err != nil { return nil, err } + channels = append(channels, ch) } - if channels == nil { - channels = []ChannelInfo{} - } - return channels, nil + + return channels, rows.Err() } // ChannelInfo is a lightweight channel representation. type ChannelInfo struct { - ID int64 `json:"id"` + ID string `json:"id"` Name string `json:"name"` Topic string `json:"topic"` } // ChannelMembers returns all members of a channel. -func (s *Database) ChannelMembers(ctx context.Context, channelID int64) ([]MemberInfo, error) { +func (s *Database) ChannelMembers(ctx context.Context, channelID string) ([]MemberInfo, error) { rows, err := s.db.QueryContext(ctx, - `SELECT u.id, u.nick, u.last_seen FROM users u + `SELECT u.id, u.nick, u.last_seen_at FROM users u INNER JOIN channel_members cm ON cm.user_id = u.id WHERE cm.channel_id = ? ORDER BY u.nick`, channelID) if err != nil { return nil, err } - defer rows.Close() - var members []MemberInfo + + defer func() { _ = rows.Close() }() + + members := []MemberInfo{} + for rows.Next() { var m MemberInfo - if err := rows.Scan(&m.ID, &m.Nick, &m.LastSeen); err != nil { + + err := rows.Scan(&m.ID, &m.Nick, &m.LastSeen) + if err != nil { return nil, err } + members = append(members, m) } - if members == nil { - members = []MemberInfo{} - } - return members, nil + + return members, rows.Err() } // MemberInfo represents a channel member. type MemberInfo struct { - ID int64 `json:"id"` - Nick string `json:"nick"` - LastSeen time.Time `json:"lastSeen"` + ID string `json:"id"` + Nick string `json:"nick"` + LastSeen *time.Time `json:"lastSeen"` } // MessageInfo represents a chat message. type MessageInfo struct { - ID int64 `json:"id"` + ID string `json:"id"` Channel string `json:"channel,omitempty"` Nick string `json:"nick"` Content string `json:"content"` @@ -155,234 +128,202 @@ type MessageInfo struct { CreatedAt time.Time `json:"createdAt"` } -// GetMessages returns messages for a channel, optionally after a given ID. -func (s *Database) GetMessages(ctx context.Context, channelID int64, afterID int64, limit int) ([]MessageInfo, error) { - if limit <= 0 { - limit = 50 - } - rows, err := s.db.QueryContext(ctx, - `SELECT m.id, c.name, u.nick, m.content, m.created_at - FROM messages m - INNER JOIN users u ON u.id = m.user_id - INNER JOIN channels c ON c.id = m.channel_id - WHERE m.channel_id = ? AND m.is_dm = 0 AND m.id > ? - ORDER BY m.id ASC LIMIT ?`, channelID, afterID, limit) - if err != nil { - return nil, err - } - defer rows.Close() - var msgs []MessageInfo - for rows.Next() { - var m MessageInfo - if err := rows.Scan(&m.ID, &m.Channel, &m.Nick, &m.Content, &m.CreatedAt); err != nil { - return nil, err - } - msgs = append(msgs, m) - } - if msgs == nil { - msgs = []MessageInfo{} - } - return msgs, nil -} - // SendMessage inserts a channel message. -func (s *Database) SendMessage(ctx context.Context, channelID, userID int64, content string) (int64, error) { - res, err := s.db.ExecContext(ctx, - "INSERT INTO messages (channel_id, user_id, content, is_dm, created_at) VALUES (?, ?, ?, 0, ?)", - channelID, userID, content, time.Now()) +func (s *Database) SendMessage(ctx context.Context, channelID, userID, nick, content string) (string, error) { + now := time.Now() + id := fmt.Sprintf("msg-%d", now.UnixNano()) + + _, err := s.db.ExecContext(ctx, + `INSERT INTO messages (id, ts, from_user_id, from_nick, target, type, body, meta, created_at) + VALUES (?, ?, ?, ?, ?, 'message', ?, '{}', ?)`, + id, now, userID, nick, channelID, content, now) if err != nil { - return 0, err + return "", err } - return res.LastInsertId() + + return id, nil } // SendDM inserts a direct message. -func (s *Database) SendDM(ctx context.Context, fromID, toID int64, content string) (int64, error) { - res, err := s.db.ExecContext(ctx, - "INSERT INTO messages (user_id, content, is_dm, dm_target_id, created_at) VALUES (?, ?, 1, ?, ?)", - fromID, content, toID, time.Now()) +func (s *Database) SendDM(ctx context.Context, fromID, fromNick, toID, content string) (string, error) { + now := time.Now() + id := fmt.Sprintf("msg-%d", now.UnixNano()) + + _, err := s.db.ExecContext(ctx, + `INSERT INTO messages (id, ts, from_user_id, from_nick, target, type, body, meta, created_at) + VALUES (?, ?, ?, ?, ?, 'message', ?, '{}', ?)`, + id, now, fromID, fromNick, toID, content, now) if err != nil { - return 0, err + return "", err } - return res.LastInsertId() + + return id, nil } -// GetDMs returns direct messages between two users after a given ID. -func (s *Database) GetDMs(ctx context.Context, userA, userB int64, afterID int64, limit int) ([]MessageInfo, error) { - if limit <= 0 { - limit = 50 - } - rows, err := s.db.QueryContext(ctx, - `SELECT m.id, u.nick, m.content, t.nick, m.created_at - FROM messages m - INNER JOIN users u ON u.id = m.user_id - INNER JOIN users t ON t.id = m.dm_target_id - WHERE m.is_dm = 1 AND m.id > ? - AND ((m.user_id = ? AND m.dm_target_id = ?) OR (m.user_id = ? AND m.dm_target_id = ?)) - ORDER BY m.id ASC LIMIT ?`, afterID, userA, userB, userB, userA, limit) - if err != nil { - return nil, err - } - defer rows.Close() - var msgs []MessageInfo - for rows.Next() { - var m MessageInfo - if err := rows.Scan(&m.ID, &m.Nick, &m.Content, &m.DMTarget, &m.CreatedAt); err != nil { - return nil, err - } - m.IsDM = true - msgs = append(msgs, m) - } - if msgs == nil { - msgs = []MessageInfo{} - } - return msgs, nil -} - -// PollMessages returns all new messages (channel + DM) for a user after a given ID. -func (s *Database) PollMessages(ctx context.Context, userID int64, afterID int64, limit int) ([]MessageInfo, error) { +// PollMessages returns all new messages for a user's joined channels, ordered by timestamp. +func (s *Database) PollMessages(ctx context.Context, userID string, afterTS string, limit int) ([]MessageInfo, error) { if limit <= 0 { limit = 100 } + rows, err := s.db.QueryContext(ctx, - `SELECT m.id, COALESCE(c.name, ''), u.nick, m.content, m.is_dm, COALESCE(t.nick, ''), m.created_at + `SELECT m.id, m.target, m.from_nick, m.body, m.created_at FROM messages m - INNER JOIN users u ON u.id = m.user_id - LEFT JOIN channels c ON c.id = m.channel_id - LEFT JOIN users t ON t.id = m.dm_target_id - WHERE m.id > ? AND ( - (m.is_dm = 0 AND m.channel_id IN (SELECT channel_id FROM channel_members WHERE user_id = ?)) - OR (m.is_dm = 1 AND (m.user_id = ? OR m.dm_target_id = ?)) + WHERE m.created_at > COALESCE(NULLIF(?, ''), '1970-01-01') + AND ( + m.target IN (SELECT cm.channel_id FROM channel_members cm WHERE cm.user_id = ?) + OR m.target = ? + OR m.from_user_id = ? ) - ORDER BY m.id ASC LIMIT ?`, afterID, userID, userID, userID, limit) + ORDER BY m.created_at ASC LIMIT ?`, + afterTS, userID, userID, userID, limit) if err != nil { return nil, err } - defer rows.Close() - var msgs []MessageInfo + + defer func() { _ = rows.Close() }() + + msgs := []MessageInfo{} + for rows.Next() { var m MessageInfo - var isDM int - if err := rows.Scan(&m.ID, &m.Channel, &m.Nick, &m.Content, &isDM, &m.DMTarget, &m.CreatedAt); err != nil { + + err := rows.Scan(&m.ID, &m.Channel, &m.Nick, &m.Content, &m.CreatedAt) + if err != nil { return nil, err } - m.IsDM = isDM == 1 + msgs = append(msgs, m) } - if msgs == nil { - msgs = []MessageInfo{} - } - return msgs, nil + + return msgs, rows.Err() } -// GetMessagesBefore returns channel messages before a given ID (for history scrollback). -func (s *Database) GetMessagesBefore(ctx context.Context, channelID int64, beforeID int64, limit int) ([]MessageInfo, error) { +// GetMessagesBefore returns channel messages before a given timestamp (for history scrollback). +func (s *Database) GetMessagesBefore( + ctx context.Context, target string, beforeTS string, limit int, +) ([]MessageInfo, error) { if limit <= 0 { limit = 50 } - var query string - var args []any - if beforeID > 0 { - query = `SELECT m.id, c.name, u.nick, m.content, m.created_at - FROM messages m - INNER JOIN users u ON u.id = m.user_id - INNER JOIN channels c ON c.id = m.channel_id - WHERE m.channel_id = ? AND m.is_dm = 0 AND m.id < ? - ORDER BY m.id DESC LIMIT ?` - args = []any{channelID, beforeID, limit} + + var rows *sql.Rows + + var err error + + if beforeTS != "" { + rows, err = s.db.QueryContext(ctx, + `SELECT m.id, m.target, m.from_nick, m.body, m.created_at + FROM messages m + WHERE m.target = ? AND m.created_at < ? + ORDER BY m.created_at DESC LIMIT ?`, + target, beforeTS, limit) } else { - query = `SELECT m.id, c.name, u.nick, m.content, m.created_at - FROM messages m - INNER JOIN users u ON u.id = m.user_id - INNER JOIN channels c ON c.id = m.channel_id - WHERE m.channel_id = ? AND m.is_dm = 0 - ORDER BY m.id DESC LIMIT ?` - args = []any{channelID, limit} + rows, err = s.db.QueryContext(ctx, + `SELECT m.id, m.target, m.from_nick, m.body, m.created_at + FROM messages m + WHERE m.target = ? + ORDER BY m.created_at DESC LIMIT ?`, + target, limit) } - rows, err := s.db.QueryContext(ctx, query, args...) + if err != nil { return nil, err } - defer rows.Close() - var msgs []MessageInfo + + defer func() { _ = rows.Close() }() + + msgs := []MessageInfo{} + for rows.Next() { var m MessageInfo - if err := rows.Scan(&m.ID, &m.Channel, &m.Nick, &m.Content, &m.CreatedAt); err != nil { + + err := rows.Scan(&m.ID, &m.Channel, &m.Nick, &m.Content, &m.CreatedAt) + if err != nil { return nil, err } + msgs = append(msgs, m) } - if msgs == nil { - msgs = []MessageInfo{} - } - // Reverse to ascending order + + // Reverse to ascending order. for i, j := 0, len(msgs)-1; i < j; i, j = i+1, j-1 { msgs[i], msgs[j] = msgs[j], msgs[i] } - return msgs, nil + + return msgs, rows.Err() } -// GetDMsBefore returns DMs between two users before a given ID (for history scrollback). -func (s *Database) GetDMsBefore(ctx context.Context, userA, userB int64, beforeID int64, limit int) ([]MessageInfo, error) { +// GetDMsBefore returns DMs between two users before a given timestamp. +func (s *Database) GetDMsBefore( + ctx context.Context, userA, userB string, beforeTS string, limit int, +) ([]MessageInfo, error) { if limit <= 0 { limit = 50 } - var query string - var args []any - if beforeID > 0 { - query = `SELECT m.id, u.nick, m.content, t.nick, m.created_at - FROM messages m - INNER JOIN users u ON u.id = m.user_id - INNER JOIN users t ON t.id = m.dm_target_id - WHERE m.is_dm = 1 AND m.id < ? - AND ((m.user_id = ? AND m.dm_target_id = ?) OR (m.user_id = ? AND m.dm_target_id = ?)) - ORDER BY m.id DESC LIMIT ?` - args = []any{beforeID, userA, userB, userB, userA, limit} + + var rows *sql.Rows + + var err error + + if beforeTS != "" { + rows, err = s.db.QueryContext(ctx, + `SELECT m.id, m.from_nick, m.body, m.target, m.created_at + FROM messages m + WHERE m.created_at < ? + AND ((m.from_user_id = ? AND m.target = ?) OR (m.from_user_id = ? AND m.target = ?)) + ORDER BY m.created_at DESC LIMIT ?`, + beforeTS, userA, userB, userB, userA, limit) } else { - query = `SELECT m.id, u.nick, m.content, t.nick, m.created_at - FROM messages m - INNER JOIN users u ON u.id = m.user_id - INNER JOIN users t ON t.id = m.dm_target_id - WHERE m.is_dm = 1 - AND ((m.user_id = ? AND m.dm_target_id = ?) OR (m.user_id = ? AND m.dm_target_id = ?)) - ORDER BY m.id DESC LIMIT ?` - args = []any{userA, userB, userB, userA, limit} + rows, err = s.db.QueryContext(ctx, + `SELECT m.id, m.from_nick, m.body, m.target, m.created_at + FROM messages m + WHERE (m.from_user_id = ? AND m.target = ?) OR (m.from_user_id = ? AND m.target = ?) + ORDER BY m.created_at DESC LIMIT ?`, + userA, userB, userB, userA, limit) } - rows, err := s.db.QueryContext(ctx, query, args...) + if err != nil { return nil, err } - defer rows.Close() - var msgs []MessageInfo + + defer func() { _ = rows.Close() }() + + msgs := []MessageInfo{} + for rows.Next() { var m MessageInfo - if err := rows.Scan(&m.ID, &m.Nick, &m.Content, &m.DMTarget, &m.CreatedAt); err != nil { + + err := rows.Scan(&m.ID, &m.Nick, &m.Content, &m.DMTarget, &m.CreatedAt) + if err != nil { return nil, err } + m.IsDM = true msgs = append(msgs, m) } - if msgs == nil { - msgs = []MessageInfo{} - } - // Reverse to ascending order + + // Reverse to ascending order. for i, j := 0, len(msgs)-1; i < j; i, j = i+1, j-1 { msgs[i], msgs[j] = msgs[j], msgs[i] } - return msgs, nil + + return msgs, rows.Err() } // ChangeNick updates a user's nickname. -func (s *Database) ChangeNick(ctx context.Context, userID int64, newNick string) error { +func (s *Database) ChangeNick(ctx context.Context, userID string, newNick string) error { _, err := s.db.ExecContext(ctx, "UPDATE users SET nick = ? WHERE id = ?", newNick, userID) + return err } // SetTopic sets the topic for a channel. -func (s *Database) SetTopic(ctx context.Context, channelName string, _ int64, topic string) error { +func (s *Database) SetTopic(ctx context.Context, channelName string, _ string, topic string) error { _, err := s.db.ExecContext(ctx, "UPDATE channels SET topic = ? WHERE name = ?", topic, channelName) + return err } @@ -398,17 +339,21 @@ func (s *Database) ListAllChannels(ctx context.Context) ([]ChannelInfo, error) { if err != nil { return nil, err } - defer rows.Close() - var channels []ChannelInfo + + defer func() { _ = rows.Close() }() + + channels := []ChannelInfo{} + for rows.Next() { var ch ChannelInfo - if err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic); err != nil { + + err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic) + if err != nil { return nil, err } + channels = append(channels, ch) } - if channels == nil { - channels = []ChannelInfo{} - } - return channels, nil + + return channels, rows.Err() } diff --git a/internal/db/schema/003_users.sql b/internal/db/schema/003_users.sql index f305aa0..c5a9069 100644 --- a/internal/db/schema/003_users.sql +++ b/internal/db/schema/003_users.sql @@ -1,31 +1,4 @@ -PRAGMA foreign_keys = ON; - -CREATE TABLE IF NOT EXISTS users ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - nick TEXT NOT NULL UNIQUE, - token TEXT NOT NULL UNIQUE, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - last_seen DATETIME DEFAULT CURRENT_TIMESTAMP -); - -CREATE TABLE IF NOT EXISTS channel_members ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - channel_id INTEGER NOT NULL REFERENCES channels(id) ON DELETE CASCADE, - user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, - joined_at DATETIME DEFAULT CURRENT_TIMESTAMP, - UNIQUE(channel_id, user_id) -); - -CREATE TABLE IF NOT EXISTS messages ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - channel_id INTEGER REFERENCES channels(id) ON DELETE CASCADE, - user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, - content TEXT NOT NULL, - is_dm INTEGER NOT NULL DEFAULT 0, - dm_target_id INTEGER REFERENCES users(id) ON DELETE CASCADE, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP -); - -CREATE INDEX IF NOT EXISTS idx_messages_channel ON messages(channel_id, created_at); -CREATE INDEX IF NOT EXISTS idx_messages_dm ON messages(user_id, dm_target_id, created_at); -CREATE INDEX IF NOT EXISTS idx_users_token ON users(token); +-- Migration 003: no-op (schema already created by 002_schema.sql) +-- This migration previously conflicted with 002 by attempting to recreate +-- tables with incompatible column types (INTEGER vs TEXT IDs). +SELECT 1; diff --git a/internal/handlers/api.go b/internal/handlers/api.go index 975b7a1..10d8fe9 100644 --- a/internal/handlers/api.go +++ b/internal/handlers/api.go @@ -1,7 +1,9 @@ package handlers import ( + "crypto/rand" "database/sql" + "encoding/hex" "encoding/json" "net/http" "strconv" @@ -12,77 +14,123 @@ import ( ) // authUser extracts the user from the Authorization header (Bearer token). -func (s *Handlers) authUser(r *http.Request) (int64, string, error) { +func (s *Handlers) authUser(r *http.Request) (string, string, error) { auth := r.Header.Get("Authorization") if !strings.HasPrefix(auth, "Bearer ") { - return 0, "", sql.ErrNoRows + return "", "", sql.ErrNoRows } + token := strings.TrimPrefix(auth, "Bearer ") - return s.params.Database.GetUserByToken(r.Context(), token) + + u, err := s.params.Database.GetUserByToken(r.Context(), token) + if err != nil { + return "", "", err + } + + return u.ID, u.Nick, nil } -func (s *Handlers) requireAuth(w http.ResponseWriter, r *http.Request) (int64, string, bool) { +func (s *Handlers) requireAuth(w http.ResponseWriter, r *http.Request) (string, string, bool) { uid, nick, err := s.authUser(r) if err != nil { s.respondJSON(w, r, map[string]string{"error": "unauthorized"}, http.StatusUnauthorized) - return 0, "", false + + return "", "", false } + return uid, nick, true } +const idBytes = 16 + +func generateID() string { + b := make([]byte, idBytes) + _, _ = rand.Read(b) + + return hex.EncodeToString(b) +} + // HandleCreateSession creates a new user session and returns the auth token. func (s *Handlers) HandleCreateSession() http.HandlerFunc { type request struct { Nick string `json:"nick"` } + type response struct { - ID int64 `json:"id"` + ID string `json:"id"` Nick string `json:"nick"` Token string `json:"token"` } + return func(w http.ResponseWriter, r *http.Request) { var req request - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + + err := json.NewDecoder(r.Body).Decode(&req) + if err != nil { s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest) + return } + req.Nick = strings.TrimSpace(req.Nick) if req.Nick == "" || len(req.Nick) > 32 { s.respondJSON(w, r, map[string]string{"error": "nick must be 1-32 characters"}, http.StatusBadRequest) + return } - id, token, err := s.params.Database.CreateUser(r.Context(), req.Nick) + + id := generateID() + + u, err := s.params.Database.CreateUser(r.Context(), id, req.Nick, "") if err != nil { if strings.Contains(err.Error(), "UNIQUE") { s.respondJSON(w, r, map[string]string{"error": "nick already taken"}, http.StatusConflict) + return } + s.log.Error("create user failed", "error", err) s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + return } - s.respondJSON(w, r, &response{ID: id, Nick: req.Nick, Token: token}, http.StatusCreated) + + tokenStr := generateID() + + _, err = s.params.Database.CreateAuthToken(r.Context(), tokenStr, u.ID) + if err != nil { + s.log.Error("create auth token failed", "error", err) + s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + + return + } + + s.respondJSON(w, r, &response{ID: u.ID, Nick: req.Nick, Token: tokenStr}, http.StatusCreated) } } // HandleState returns the current user's info and joined channels. func (s *Handlers) HandleState() http.HandlerFunc { type response struct { - ID int64 `json:"id"` + ID string `json:"id"` Nick string `json:"nick"` Channels []db.ChannelInfo `json:"channels"` } + return func(w http.ResponseWriter, r *http.Request) { uid, nick, ok := s.requireAuth(w, r) if !ok { return } + channels, err := s.params.Database.ListChannels(r.Context(), uid) if err != nil { s.log.Error("list channels failed", "error", err) s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + return } + s.respondJSON(w, r, &response{ID: uid, Nick: nick, Channels: channels}, http.StatusOK) } } @@ -94,12 +142,15 @@ func (s *Handlers) HandleListAllChannels() http.HandlerFunc { if !ok { return } + channels, err := s.params.Database.ListAllChannels(r.Context()) if err != nil { s.log.Error("list all channels failed", "error", err) s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + return } + s.respondJSON(w, r, channels, http.StatusOK) } } @@ -111,20 +162,28 @@ func (s *Handlers) HandleChannelMembers() http.HandlerFunc { if !ok { return } + name := "#" + chi.URLParam(r, "channel") - var chID int64 + + var chID string + + //nolint:gosec // G701: parameterized query with ? placeholder, not injection err := s.params.Database.GetDB().QueryRowContext(r.Context(), "SELECT id FROM channels WHERE name = ?", name).Scan(&chID) if err != nil { s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound) + return } + members, err := s.params.Database.ChannelMembers(r.Context(), chID) if err != nil { s.log.Error("channel members failed", "error", err) s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + return } + s.respondJSON(w, r, members, http.StatusOK) } } @@ -137,14 +196,18 @@ func (s *Handlers) HandleGetMessages() http.HandlerFunc { if !ok { return } - afterID, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64) + + afterTS := r.URL.Query().Get("after") limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) - msgs, err := s.params.Database.PollMessages(r.Context(), uid, afterID, limit) + + msgs, err := s.params.Database.PollMessages(r.Context(), uid, afterTS, limit) if err != nil { s.log.Error("get messages failed", "error", err) s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + return } + s.respondJSON(w, r, msgs, http.StatusOK) } } @@ -153,186 +216,279 @@ func (s *Handlers) HandleGetMessages() http.HandlerFunc { // The "command" field dispatches to the appropriate logic. func (s *Handlers) HandleSendCommand() http.HandlerFunc { type request struct { - Command string `json:"command"` - To string `json:"to"` - Params []string `json:"params,omitempty"` - Body interface{} `json:"body,omitempty"` + Command string `json:"command"` + To string `json:"to"` + Params []string `json:"params,omitempty"` + Body any `json:"body,omitempty"` } + return func(w http.ResponseWriter, r *http.Request) { uid, nick, ok := s.requireAuth(w, r) if !ok { return } + var req request - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + + err := json.NewDecoder(r.Body).Decode(&req) + if err != nil { s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest) + return } + req.Command = strings.ToUpper(strings.TrimSpace(req.Command)) req.To = strings.TrimSpace(req.To) + lines := extractBodyLines(req.Body) - // Helper to extract body as string lines. - bodyLines := func() []string { - switch v := req.Body.(type) { - case []interface{}: - lines := make([]string, 0, len(v)) - for _, item := range v { - if s, ok := item.(string); ok { - lines = append(lines, s) - } - } - return lines - case []string: - return v - default: - return nil - } - } - - switch req.Command { - case "PRIVMSG", "NOTICE": - if req.To == "" { - s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) - return - } - lines := bodyLines() - if len(lines) == 0 { - s.respondJSON(w, r, map[string]string{"error": "body required"}, http.StatusBadRequest) - return - } - content := strings.Join(lines, "\n") - - if strings.HasPrefix(req.To, "#") { - // Channel message - var chID int64 - err := s.params.Database.GetDB().QueryRowContext(r.Context(), - "SELECT id FROM channels WHERE name = ?", req.To).Scan(&chID) - if err != nil { - s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound) - return - } - msgID, err := s.params.Database.SendMessage(r.Context(), chID, uid, content) - if err != nil { - s.log.Error("send message failed", "error", err) - s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) - return - } - s.respondJSON(w, r, map[string]any{"id": msgID, "status": "sent"}, http.StatusCreated) - } else { - // DM - targetID, err := s.params.Database.GetUserByNick(r.Context(), req.To) - if err != nil { - s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound) - return - } - msgID, err := s.params.Database.SendDM(r.Context(), uid, targetID, content) - if err != nil { - s.log.Error("send dm failed", "error", err) - s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) - return - } - s.respondJSON(w, r, map[string]any{"id": msgID, "status": "sent"}, http.StatusCreated) - } - - case "JOIN": - if req.To == "" { - s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) - return - } - channel := req.To - if !strings.HasPrefix(channel, "#") { - channel = "#" + channel - } - chID, err := s.params.Database.GetOrCreateChannel(r.Context(), channel) - if err != nil { - s.log.Error("get/create channel failed", "error", err) - s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) - return - } - if err := s.params.Database.JoinChannel(r.Context(), chID, uid); err != nil { - s.log.Error("join channel failed", "error", err) - s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) - return - } - s.respondJSON(w, r, map[string]string{"status": "joined", "channel": channel}, http.StatusOK) - - case "PART": - if req.To == "" { - s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) - return - } - channel := req.To - if !strings.HasPrefix(channel, "#") { - channel = "#" + channel - } - var chID int64 - err := s.params.Database.GetDB().QueryRowContext(r.Context(), - "SELECT id FROM channels WHERE name = ?", channel).Scan(&chID) - if err != nil { - s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound) - return - } - if err := s.params.Database.PartChannel(r.Context(), chID, uid); err != nil { - s.log.Error("part channel failed", "error", err) - s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) - return - } - s.respondJSON(w, r, map[string]string{"status": "parted", "channel": channel}, http.StatusOK) - - case "NICK": - lines := bodyLines() - if len(lines) == 0 { - s.respondJSON(w, r, map[string]string{"error": "body required (new nick)"}, http.StatusBadRequest) - return - } - newNick := strings.TrimSpace(lines[0]) - if newNick == "" || len(newNick) > 32 { - s.respondJSON(w, r, map[string]string{"error": "nick must be 1-32 characters"}, http.StatusBadRequest) - return - } - if err := s.params.Database.ChangeNick(r.Context(), uid, newNick); err != nil { - if strings.Contains(err.Error(), "UNIQUE") { - s.respondJSON(w, r, map[string]string{"error": "nick already in use"}, http.StatusConflict) - return - } - s.log.Error("change nick failed", "error", err) - s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) - return - } - s.respondJSON(w, r, map[string]string{"status": "ok", "nick": newNick}, http.StatusOK) - - case "TOPIC": - if req.To == "" { - s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) - return - } - lines := bodyLines() - if len(lines) == 0 { - s.respondJSON(w, r, map[string]string{"error": "body required (topic text)"}, http.StatusBadRequest) - return - } - topic := strings.Join(lines, " ") - channel := req.To - if !strings.HasPrefix(channel, "#") { - channel = "#" + channel - } - if err := s.params.Database.SetTopic(r.Context(), channel, uid, topic); err != nil { - s.log.Error("set topic failed", "error", err) - s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) - return - } - s.respondJSON(w, r, map[string]string{"status": "ok", "topic": topic}, http.StatusOK) - - case "PING": - s.respondJSON(w, r, map[string]string{"command": "PONG", "from": s.params.Config.ServerName}, http.StatusOK) - - default: - _ = nick // suppress unused warning - s.respondJSON(w, r, map[string]string{"error": "unknown command: " + req.Command}, http.StatusBadRequest) - } + s.dispatchCommand(w, r, uid, nick, req.Command, req.To, lines) } } +// extractBodyLines converts the request body to string lines. +func extractBodyLines(body any) []string { + switch v := body.(type) { + case []any: + lines := make([]string, 0, len(v)) + + for _, item := range v { + if str, ok := item.(string); ok { + lines = append(lines, str) + } + } + + return lines + case []string: + return v + default: + return nil + } +} + +func (s *Handlers) dispatchCommand( + w http.ResponseWriter, r *http.Request, + uid, nick, command, to string, lines []string, +) { + switch command { + case "PRIVMSG", "NOTICE": + s.handlePrivmsg(w, r, uid, nick, to, lines) + case "JOIN": + s.handleJoin(w, r, uid, to) + case "PART": + s.handlePart(w, r, uid, to) + case "NICK": + s.handleNick(w, r, uid, lines) + case "TOPIC": + s.handleTopic(w, r, uid, to, lines) + case "PING": + s.respondJSON(w, r, map[string]string{"command": "PONG", "from": s.params.Config.ServerName}, http.StatusOK) + default: + _ = nick + + s.respondJSON(w, r, map[string]string{"error": "unknown command: " + command}, http.StatusBadRequest) + } +} + +func (s *Handlers) handlePrivmsg(w http.ResponseWriter, r *http.Request, uid, nick, to string, lines []string) { + if to == "" { + s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) + + return + } + + if len(lines) == 0 { + s.respondJSON(w, r, map[string]string{"error": "body required"}, http.StatusBadRequest) + + return + } + + content := strings.Join(lines, "\n") + + if strings.HasPrefix(to, "#") { + s.sendChannelMessage(w, r, uid, nick, to, content) + + return + } + + // DM. + s.sendDirectMessage(w, r, uid, nick, to, content) +} + +func (s *Handlers) sendChannelMessage( + w http.ResponseWriter, r *http.Request, + uid, nick, channel, content string, +) { + var chID string + + //nolint:gosec // G701: parameterized query, not injection + err := s.params.Database.GetDB().QueryRowContext(r.Context(), + "SELECT id FROM channels WHERE name = ?", channel).Scan(&chID) + if err != nil { + s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound) + + return + } + + msgID, err := s.params.Database.SendMessage(r.Context(), chID, uid, nick, content) + if err != nil { + s.log.Error("send message failed", "error", err) + s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + + return + } + + s.respondJSON(w, r, map[string]any{"id": msgID, "status": "sent"}, http.StatusCreated) +} + +func (s *Handlers) sendDirectMessage( + w http.ResponseWriter, r *http.Request, + uid, nick, to, content string, +) { + targetUser, err := s.params.Database.GetUserByNick(r.Context(), to) + if err != nil { + s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound) + + return + } + + msgID, err := s.params.Database.SendDM(r.Context(), uid, nick, targetUser.ID, content) + if err != nil { + s.log.Error("send dm failed", "error", err) + s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + + return + } + + s.respondJSON(w, r, map[string]any{"id": msgID, "status": "sent"}, http.StatusCreated) +} + +func (s *Handlers) handleJoin(w http.ResponseWriter, r *http.Request, uid, to string) { + if to == "" { + s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) + + return + } + + channel := to + if !strings.HasPrefix(channel, "#") { + channel = "#" + channel + } + + chID, err := s.params.Database.GetOrCreateChannel(r.Context(), channel) + if err != nil { + s.log.Error("get/create channel failed", "error", err) + s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + + return + } + + err = s.params.Database.JoinChannel(r.Context(), chID, uid) + if err != nil { + s.log.Error("join channel failed", "error", err) + s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + + return + } + + s.respondJSON(w, r, map[string]string{"status": "joined", "channel": channel}, http.StatusOK) +} + +func (s *Handlers) handlePart(w http.ResponseWriter, r *http.Request, uid, to string) { + if to == "" { + s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) + + return + } + + channel := to + if !strings.HasPrefix(channel, "#") { + channel = "#" + channel + } + + var chID string + + //nolint:gosec // G701: parameterized query, not injection + err := s.params.Database.GetDB().QueryRowContext(r.Context(), + "SELECT id FROM channels WHERE name = ?", channel).Scan(&chID) + if err != nil { + s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound) + + return + } + + err = s.params.Database.PartChannel(r.Context(), chID, uid) + if err != nil { + s.log.Error("part channel failed", "error", err) + s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + + return + } + + s.respondJSON(w, r, map[string]string{"status": "parted", "channel": channel}, http.StatusOK) +} + +func (s *Handlers) handleNick(w http.ResponseWriter, r *http.Request, uid string, lines []string) { + if len(lines) == 0 { + s.respondJSON(w, r, map[string]string{"error": "body required (new nick)"}, http.StatusBadRequest) + + return + } + + newNick := strings.TrimSpace(lines[0]) + if newNick == "" || len(newNick) > 32 { + s.respondJSON(w, r, map[string]string{"error": "nick must be 1-32 characters"}, http.StatusBadRequest) + + return + } + + err := s.params.Database.ChangeNick(r.Context(), uid, newNick) + if err != nil { + if strings.Contains(err.Error(), "UNIQUE") { + s.respondJSON(w, r, map[string]string{"error": "nick already in use"}, http.StatusConflict) + + return + } + + s.log.Error("change nick failed", "error", err) + s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + + return + } + + s.respondJSON(w, r, map[string]string{"status": "ok", "nick": newNick}, http.StatusOK) +} + +func (s *Handlers) handleTopic(w http.ResponseWriter, r *http.Request, uid, to string, lines []string) { + if to == "" { + s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest) + + return + } + + if len(lines) == 0 { + s.respondJSON(w, r, map[string]string{"error": "body required (topic text)"}, http.StatusBadRequest) + + return + } + + topic := strings.Join(lines, " ") + + channel := to + if !strings.HasPrefix(channel, "#") { + channel = "#" + channel + } + + err := s.params.Database.SetTopic(r.Context(), channel, uid, topic) + if err != nil { + s.log.Error("set topic failed", "error", err) + s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + + return + } + + s.respondJSON(w, r, map[string]string{"status": "ok", "topic": topic}, http.StatusOK) +} + // HandleGetHistory returns message history for a specific target (channel or DM). func (s *Handlers) HandleGetHistory() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { @@ -340,57 +496,86 @@ func (s *Handlers) HandleGetHistory() http.HandlerFunc { if !ok { return } + target := r.URL.Query().Get("target") if target == "" { s.respondJSON(w, r, map[string]string{"error": "target required"}, http.StatusBadRequest) + return } - beforeID, _ := strconv.ParseInt(r.URL.Query().Get("before"), 10, 64) + + beforeTS := r.URL.Query().Get("before") limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) + if limit <= 0 { limit = 50 } if strings.HasPrefix(target, "#") { - // Channel history - var chID int64 - err := s.params.Database.GetDB().QueryRowContext(r.Context(), - "SELECT id FROM channels WHERE name = ?", target).Scan(&chID) - if err != nil { - s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound) - return - } - msgs, err := s.params.Database.GetMessagesBefore(r.Context(), chID, beforeID, limit) - if err != nil { - s.log.Error("get history failed", "error", err) - s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) - return - } - s.respondJSON(w, r, msgs, http.StatusOK) - } else { - // DM history - targetID, err := s.params.Database.GetUserByNick(r.Context(), target) - if err != nil { - s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound) - return - } - msgs, err := s.params.Database.GetDMsBefore(r.Context(), uid, targetID, beforeID, limit) - if err != nil { - s.log.Error("get dm history failed", "error", err) - s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) - return - } - s.respondJSON(w, r, msgs, http.StatusOK) + s.getChannelHistory(w, r, target, beforeTS, limit) + + return } + + s.getDMHistory(w, r, uid, target, beforeTS, limit) } } +func (s *Handlers) getChannelHistory( + w http.ResponseWriter, r *http.Request, + channel, beforeTS string, limit int, +) { + var chID string + + //nolint:gosec // G701: parameterized query, not injection + err := s.params.Database.GetDB().QueryRowContext(r.Context(), + "SELECT id FROM channels WHERE name = ?", channel).Scan(&chID) + if err != nil { + s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound) + + return + } + + msgs, err := s.params.Database.GetMessagesBefore(r.Context(), chID, beforeTS, limit) + if err != nil { + s.log.Error("get history failed", "error", err) + s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + + return + } + + s.respondJSON(w, r, msgs, http.StatusOK) +} + +func (s *Handlers) getDMHistory( + w http.ResponseWriter, r *http.Request, + uid, target, beforeTS string, limit int, +) { + targetUser, err := s.params.Database.GetUserByNick(r.Context(), target) + if err != nil { + s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound) + + return + } + + msgs, err := s.params.Database.GetDMsBefore(r.Context(), uid, targetUser.ID, beforeTS, limit) + if err != nil { + s.log.Error("get dm history failed", "error", err) + s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError) + + return + } + + s.respondJSON(w, r, msgs, http.StatusOK) +} + // HandleServerInfo returns server metadata (MOTD, name). func (s *Handlers) HandleServerInfo() http.HandlerFunc { type response struct { Name string `json:"name"` MOTD string `json:"motd"` } + return func(w http.ResponseWriter, r *http.Request) { s.respondJSON(w, r, &response{ Name: s.params.Config.ServerName, diff --git a/internal/models/auth_token.go b/internal/models/auth_token.go index f1646e2..c2c3fd1 100644 --- a/internal/models/auth_token.go +++ b/internal/models/auth_token.go @@ -2,7 +2,6 @@ package models import ( "context" - "fmt" "time" ) @@ -23,5 +22,5 @@ func (t *AuthToken) User(ctx context.Context) (*User, error) { return ul.GetUserByID(ctx, t.UserID) } - return nil, fmt.Errorf("user lookup not available") + return nil, ErrUserLookupNotAvailable } diff --git a/internal/models/channel_member.go b/internal/models/channel_member.go index f93ed9d..59586c7 100644 --- a/internal/models/channel_member.go +++ b/internal/models/channel_member.go @@ -2,7 +2,6 @@ package models import ( "context" - "fmt" "time" ) @@ -23,7 +22,7 @@ func (cm *ChannelMember) User(ctx context.Context) (*User, error) { return ul.GetUserByID(ctx, cm.UserID) } - return nil, fmt.Errorf("user lookup not available") + return nil, ErrUserLookupNotAvailable } // Channel returns the full Channel for this membership. @@ -32,5 +31,5 @@ func (cm *ChannelMember) Channel(ctx context.Context) (*Channel, error) { return cl.GetChannelByID(ctx, cm.ChannelID) } - return nil, fmt.Errorf("channel lookup not available") + return nil, ErrChannelLookupNotAvailable } diff --git a/internal/models/model.go b/internal/models/model.go index b65c6e8..103934b 100644 --- a/internal/models/model.go +++ b/internal/models/model.go @@ -6,6 +6,14 @@ package models import ( "context" "database/sql" + "errors" +) + +var ( + // ErrUserLookupNotAvailable is returned when the user lookup interface is not set. + ErrUserLookupNotAvailable = errors.New("user lookup not available") + // ErrChannelLookupNotAvailable is returned when the channel lookup interface is not set. + ErrChannelLookupNotAvailable = errors.New("channel lookup not available") ) // DB is the interface that models use to query the database. @@ -40,7 +48,7 @@ func (b *Base) GetDB() *sql.DB { } // GetUserLookup returns the DB as a UserLookup if it implements the interface. -func (b *Base) GetUserLookup() UserLookup { +func (b *Base) GetUserLookup() UserLookup { //nolint:ireturn // intentional interface return for dependency inversion if ul, ok := b.db.(UserLookup); ok { return ul } @@ -48,7 +56,10 @@ func (b *Base) GetUserLookup() UserLookup { return nil } -// GetChannelLookup returns the DB as a ChannelLookup if it implements the interface. +// GetChannelLookup returns the DB as a ChannelLookup +// if it implements the interface. +// +//nolint:ireturn // intentional interface return for dependency inversion func (b *Base) GetChannelLookup() ChannelLookup { if cl, ok := b.db.(ChannelLookup); ok { return cl diff --git a/internal/models/session.go b/internal/models/session.go index 42231d9..295def2 100644 --- a/internal/models/session.go +++ b/internal/models/session.go @@ -2,7 +2,6 @@ package models import ( "context" - "fmt" "time" ) @@ -23,5 +22,5 @@ func (s *Session) User(ctx context.Context) (*User, error) { return ul.GetUserByID(ctx, s.UserID) } - return nil, fmt.Errorf("user lookup not available") + return nil, ErrUserLookupNotAvailable } diff --git a/internal/server/routes.go b/internal/server/routes.go index e211492..5a4363e 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -65,23 +65,38 @@ func (s *Server) SetupRoutes() { r.Get("/channels/{channel}/members", s.h.HandleChannelMembers()) }) - // Serve embedded SPA + s.setupSPA() +} + +func (s *Server) setupSPA() { distFS, err := fs.Sub(web.Dist, "dist") if err != nil { s.log.Error("failed to get web dist filesystem", "error", err) - } else { - fileServer := http.FileServer(http.FS(distFS)) - s.router.Get("/*", func(w http.ResponseWriter, r *http.Request) { - // Try to serve the file; if not found, serve index.html for SPA routing - f, err := distFS.(fs.ReadFileFS).ReadFile(r.URL.Path[1:]) - if err != nil || len(f) == 0 { - indexHTML, _ := distFS.(fs.ReadFileFS).ReadFile("index.html") - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.WriteHeader(http.StatusOK) - _, _ = w.Write(indexHTML) - return - } - fileServer.ServeHTTP(w, r) - }) + + return } + + fileServer := http.FileServer(http.FS(distFS)) + + s.router.Get("/*", func(w http.ResponseWriter, r *http.Request) { + readFS, ok := distFS.(fs.ReadFileFS) + if !ok { + http.Error(w, "internal error", http.StatusInternalServerError) + + return + } + + f, err := readFS.ReadFile(r.URL.Path[1:]) + if err != nil || len(f) == 0 { + indexHTML, _ := readFS.ReadFile("index.html") + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(indexHTML) + + return + } + + fileServer.ServeHTTP(w, r) + }) }