Compare commits
22 Commits
15caf5c8d2
...
feature/we
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e60c83f191 | ||
|
|
f4a9ec13bd | ||
|
|
a2c47f5618 | ||
|
|
1a6e929f56 | ||
|
|
af3a26fcdf | ||
|
|
d06bb5334a | ||
|
|
0ee3fd78d2 | ||
|
|
f7776f8d3f | ||
|
|
4b074aafd7 | ||
|
|
ab70f889a6 | ||
|
|
dfb1636be5 | ||
|
|
c8d88de8c5 | ||
|
|
02acf1c919 | ||
|
|
909da3cc99 | ||
|
|
4645be5f20 | ||
|
|
065b243def | ||
|
|
6483670dc7 | ||
|
|
16e08c2839 | ||
|
|
aabf8e902c | ||
|
|
74437b8372 | ||
|
|
7361e8bd9b | ||
|
|
ac933d07d2 |
@@ -1,31 +1,15 @@
|
||||
// Package chatapi provides a client for the chat server's HTTP API.
|
||||
package chatapi
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
httpClientTimeout = 30
|
||||
httpErrorMinCode = 400
|
||||
pollExtraTimeout = 5
|
||||
)
|
||||
|
||||
// ErrHTTPError is returned when the server responds with an error status.
|
||||
var ErrHTTPError = errors.New("HTTP error")
|
||||
|
||||
// ErrUnexpectedFormat is returned when a response has an unexpected structure.
|
||||
var ErrUnexpectedFormat = errors.New("unexpected format")
|
||||
|
||||
// Client wraps HTTP calls to the chat server API.
|
||||
type Client struct {
|
||||
BaseURL string
|
||||
@@ -38,27 +22,59 @@ func NewClient(baseURL string) *Client {
|
||||
return &Client{
|
||||
BaseURL: baseURL,
|
||||
HTTPClient: &http.Client{
|
||||
Timeout: httpClientTimeout * time.Second,
|
||||
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.
|
||||
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
|
||||
|
||||
err = json.Unmarshal(data, &resp)
|
||||
if err != nil {
|
||||
if err := json.Unmarshal(data, &resp); err != nil {
|
||||
return nil, fmt.Errorf("decode session: %w", err)
|
||||
}
|
||||
|
||||
c.Token = resp.Token
|
||||
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
@@ -68,77 +84,64 @@ func (c *Client) GetState() (*StateResponse, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp StateResponse
|
||||
|
||||
err = json.Unmarshal(data, &resp)
|
||||
if err != nil {
|
||||
if err := json.Unmarshal(data, &resp); 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+pollExtraTimeout) * time.Second}
|
||||
client := &http.Client{Timeout: time.Duration(timeout+5) * time.Second}
|
||||
|
||||
params := url.Values{}
|
||||
if afterID != "" {
|
||||
params.Set("after", afterID)
|
||||
}
|
||||
|
||||
params.Set("timeout", strconv.Itoa(timeout))
|
||||
params.Set("timeout", fmt.Sprintf("%d", timeout))
|
||||
|
||||
path := "/api/v1/messages"
|
||||
if len(params) > 0 {
|
||||
path += "?" + params.Encode()
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, c.BaseURL+path, nil)
|
||||
req, err := http.NewRequest("GET", c.BaseURL+path, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||
|
||||
resp, err := client.Do(req) //nolint:gosec // URL is constructed from trusted base URL + API path, not user-tainted
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
defer resp.Body.Close()
|
||||
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode >= httpErrorMinCode {
|
||||
return nil, fmt.Errorf("%w: %d: %s", ErrHTTPError, resp.StatusCode, string(data))
|
||||
if resp.StatusCode >= 400 {
|
||||
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(data))
|
||||
}
|
||||
|
||||
// The server may return an array directly or wrapped.
|
||||
var msgs []Message
|
||||
|
||||
err = json.Unmarshal(data, &msgs)
|
||||
if err != nil {
|
||||
if err := json.Unmarshal(data, &msgs); err != nil {
|
||||
// Try wrapped format.
|
||||
var wrapped MessagesResponse
|
||||
|
||||
err2 := json.Unmarshal(data, &wrapped)
|
||||
if err2 != nil {
|
||||
if err2 := json.Unmarshal(data, &wrapped); err2 != nil {
|
||||
return nil, fmt.Errorf("decode messages: %w (raw: %s)", err, string(data))
|
||||
}
|
||||
|
||||
msgs = wrapped.Messages
|
||||
}
|
||||
|
||||
@@ -161,14 +164,10 @@ func (c *Client) ListChannels() ([]Channel, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var channels []Channel
|
||||
|
||||
err = json.Unmarshal(data, &channels)
|
||||
if err != nil {
|
||||
if err := json.Unmarshal(data, &channels); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return channels, nil
|
||||
}
|
||||
|
||||
@@ -178,23 +177,16 @@ func (c *Client) GetMembers(channel string) ([]string, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var members []string
|
||||
|
||||
err = json.Unmarshal(data, &members)
|
||||
if err != nil {
|
||||
if err := json.Unmarshal(data, &members); err != nil {
|
||||
// Try object format.
|
||||
var obj map[string]any
|
||||
|
||||
err2 := json.Unmarshal(data, &obj)
|
||||
if err2 != nil {
|
||||
var obj map[string]interface{}
|
||||
if err2 := json.Unmarshal(data, &obj); err2 != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Extract member names from whatever format.
|
||||
return nil, fmt.Errorf("%w: members: %s", ErrUnexpectedFormat, string(data))
|
||||
return nil, fmt.Errorf("unexpected members format: %s", string(data))
|
||||
}
|
||||
|
||||
return members, nil
|
||||
}
|
||||
|
||||
@@ -204,56 +196,9 @@ func (c *Client) GetServerInfo() (*ServerInfo, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var info ServerInfo
|
||||
|
||||
err = json.Unmarshal(data, &info)
|
||||
if err != nil {
|
||||
if err := json.Unmarshal(data, &info); 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)
|
||||
}
|
||||
|
||||
//nolint:gosec // URL built from trusted base + API path
|
||||
resp, err := c.HTTPClient.Do(req)
|
||||
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 >= httpErrorMinCode {
|
||||
return data, fmt.Errorf("%w: %d: %s", ErrHTTPError, resp.StatusCode, string(data))
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package chatapi
|
||||
package api
|
||||
|
||||
import "time"
|
||||
|
||||
@@ -9,44 +9,42 @@ type SessionRequest struct {
|
||||
|
||||
// SessionResponse is the response from POST /api/v1/session.
|
||||
type SessionResponse struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
ClientID string `json:"clientId"`
|
||||
SessionID string `json:"session_id"`
|
||||
ClientID string `json:"client_id"`
|
||||
Nick string `json:"nick"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// StateResponse is the response from GET /api/v1/state.
|
||||
type StateResponse struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
ClientID string `json:"clientId"`
|
||||
SessionID string `json:"session_id"`
|
||||
ClientID string `json:"client_id"`
|
||||
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 any `json:"body,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
TS string `json:"ts,omitempty"`
|
||||
Meta any `json:"meta,omitempty"`
|
||||
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"`
|
||||
}
|
||||
|
||||
// BodyLines returns the body as a slice of strings (for text messages).
|
||||
func (m *Message) BodyLines() []string {
|
||||
switch v := m.Body.(type) {
|
||||
case []any:
|
||||
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
|
||||
@@ -60,7 +58,7 @@ type Channel struct {
|
||||
Name string `json:"name"`
|
||||
Topic string `json:"topic"`
|
||||
Members int `json:"members"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
// ServerInfo is the response from GET /api/v1/server.
|
||||
@@ -81,6 +79,5 @@ func (m *Message) ParseTS() time.Time {
|
||||
if err != nil {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
return t
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// Package main provides a terminal-based IRC-style chat client.
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -11,18 +10,10 @@ import (
|
||||
"git.eeqj.de/sneak/chat/cmd/chat-cli/api"
|
||||
)
|
||||
|
||||
const (
|
||||
maxNickLen = 32
|
||||
pollTimeoutSec = 15
|
||||
pollRetrySec = 2
|
||||
splitNParts = 2
|
||||
commandSplitArgs = 2
|
||||
)
|
||||
|
||||
// App holds the application state.
|
||||
type App struct {
|
||||
ui *UI
|
||||
client *chatapi.Client
|
||||
client *api.Client
|
||||
|
||||
mu sync.Mutex
|
||||
nick string
|
||||
@@ -44,8 +35,7 @@ func main() {
|
||||
app.ui.AddStatus("Welcome to chat-cli — an IRC-style client")
|
||||
app.ui.AddStatus("Type [yellow]/connect <server-url>[white] to begin, or [yellow]/help[white] for commands")
|
||||
|
||||
err := app.ui.Run()
|
||||
if err != nil {
|
||||
if err := app.ui.Run(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -54,7 +44,6 @@ func main() {
|
||||
func (a *App) handleInput(text string) {
|
||||
if strings.HasPrefix(text, "/") {
|
||||
a.handleCommand(text)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -66,95 +55,74 @@ func (a *App) handleInput(text string) {
|
||||
|
||||
if !connected {
|
||||
a.ui.AddStatus("[red]Not connected. Use /connect <url>")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if target == "" {
|
||||
a.ui.AddStatus("[red]No target. Use /join #channel or /query nick")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err := a.client.SendMessage(&chatapi.Message{
|
||||
err := a.client.SendMessage(&api.Message{
|
||||
Command: "PRIVMSG",
|
||||
To: target,
|
||||
Body: []string{text},
|
||||
})
|
||||
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) handleCommand(text string) {
|
||||
a.dispatchCommand(text)
|
||||
}
|
||||
|
||||
func (a *App) dispatchCommand(text string) {
|
||||
parts := strings.SplitN(text, " ", splitNParts)
|
||||
parts := strings.SplitN(text, " ", 2)
|
||||
cmd := strings.ToLower(parts[0])
|
||||
|
||||
args := ""
|
||||
if len(parts) > 1 {
|
||||
args = parts[1]
|
||||
}
|
||||
|
||||
a.execCommand(cmd, args)
|
||||
}
|
||||
|
||||
func (a *App) execCommand(cmd, args string) {
|
||||
commands := a.commandMap()
|
||||
|
||||
handler, ok := commands[cmd]
|
||||
if !ok {
|
||||
a.ui.AddStatus("[red]Unknown command: " + cmd)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
handler(args)
|
||||
}
|
||||
|
||||
func (a *App) commandMap() map[string]func(string) {
|
||||
noArgs := func(fn func()) func(string) {
|
||||
return func(_ string) { fn() }
|
||||
}
|
||||
|
||||
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": noArgs(a.cmdNames),
|
||||
"/list": noArgs(a.cmdList),
|
||||
"/window": a.cmdWindow,
|
||||
"/w": a.cmdWindow,
|
||||
"/quit": noArgs(a.cmdQuit),
|
||||
"/help": noArgs(a.cmdHelp),
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) cmdConnect(serverURL string) {
|
||||
if serverURL == "" {
|
||||
a.ui.AddStatus("[red]Usage: /connect <server-url>")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
serverURL = strings.TrimRight(serverURL, "/")
|
||||
|
||||
a.ui.AddStatus(fmt.Sprintf("Connecting to %s...", serverURL))
|
||||
@@ -163,12 +131,10 @@ func (a *App) cmdConnect(serverURL string) {
|
||||
nick := a.nick
|
||||
a.mu.Unlock()
|
||||
|
||||
client := chatapi.NewClient(serverURL)
|
||||
|
||||
client := api.NewClient(serverURL)
|
||||
resp, err := client.CreateSession(nick)
|
||||
if err != nil {
|
||||
a.ui.AddStatus(fmt.Sprintf("[red]Connection failed: %v", err))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -184,17 +150,14 @@ func (a *App) cmdConnect(serverURL string) {
|
||||
|
||||
// Start polling.
|
||||
a.stopPoll = make(chan struct{})
|
||||
|
||||
go a.pollLoop()
|
||||
}
|
||||
|
||||
func (a *App) cmdNick(nick string) {
|
||||
if nick == "" {
|
||||
a.ui.AddStatus("[red]Usage: /nick <name>")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
connected := a.connected
|
||||
a.mu.Unlock()
|
||||
@@ -203,19 +166,16 @@ func (a *App) cmdNick(nick string) {
|
||||
a.mu.Lock()
|
||||
a.nick = nick
|
||||
a.mu.Unlock()
|
||||
|
||||
a.ui.AddStatus(fmt.Sprintf("Nick set to %s (will be used on connect)", nick))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err := a.client.SendMessage(&chatapi.Message{
|
||||
err := a.client.SendMessage(&api.Message{
|
||||
Command: "NICK",
|
||||
Body: []string{nick},
|
||||
})
|
||||
if err != nil {
|
||||
a.ui.AddStatus(fmt.Sprintf("[red]Nick change failed: %v", err))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -223,18 +183,15 @@ func (a *App) cmdNick(nick string) {
|
||||
a.nick = nick
|
||||
target := a.target
|
||||
a.mu.Unlock()
|
||||
|
||||
a.ui.SetStatus(nick, target, "connected")
|
||||
a.ui.AddStatus("Nick changed to " + nick)
|
||||
a.ui.AddStatus(fmt.Sprintf("Nick changed to %s", nick))
|
||||
}
|
||||
|
||||
func (a *App) cmdJoin(channel string) {
|
||||
if channel == "" {
|
||||
a.ui.AddStatus("[red]Usage: /join #channel")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(channel, "#") {
|
||||
channel = "#" + channel
|
||||
}
|
||||
@@ -242,17 +199,14 @@ 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
|
||||
}
|
||||
|
||||
@@ -262,47 +216,39 @@ func (a *App) cmdJoin(channel string) {
|
||||
a.mu.Unlock()
|
||||
|
||||
a.ui.SwitchToBuffer(channel)
|
||||
a.ui.AddLine(channel, "[yellow]*** Joined "+channel)
|
||||
a.ui.AddLine(channel, fmt.Sprintf("[yellow]*** Joined %s", channel))
|
||||
a.ui.SetStatus(nick, channel, "connected")
|
||||
}
|
||||
|
||||
func (a *App) cmdPart(channel string) {
|
||||
a.mu.Lock()
|
||||
|
||||
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, "[yellow]*** Left "+channel)
|
||||
a.ui.AddLine(channel, fmt.Sprintf("[yellow]*** Left %s", channel))
|
||||
|
||||
a.mu.Lock()
|
||||
|
||||
if a.target == channel {
|
||||
a.target = ""
|
||||
}
|
||||
|
||||
nick := a.nick
|
||||
a.mu.Unlock()
|
||||
|
||||
@@ -311,35 +257,29 @@ func (a *App) cmdPart(channel string) {
|
||||
}
|
||||
|
||||
func (a *App) cmdMsg(args string) {
|
||||
parts := strings.SplitN(args, " ", commandSplitArgs)
|
||||
|
||||
if len(parts) < commandSplitArgs {
|
||||
parts := strings.SplitN(args, " ", 2)
|
||||
if len(parts) < 2 {
|
||||
a.ui.AddStatus("[red]Usage: /msg <nick> <text>")
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
err := a.client.SendMessage(&chatapi.Message{
|
||||
err := a.client.SendMessage(&api.Message{
|
||||
Command: "PRIVMSG",
|
||||
To: target,
|
||||
Body: []string{text},
|
||||
})
|
||||
if err != nil {
|
||||
a.ui.AddStatus(fmt.Sprintf("[red]Send failed: %v", err))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -350,7 +290,6 @@ func (a *App) cmdMsg(args string) {
|
||||
func (a *App) cmdQuery(nick string) {
|
||||
if nick == "" {
|
||||
a.ui.AddStatus("[red]Usage: /query <nick>")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -371,30 +310,26 @@ 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
|
||||
}
|
||||
|
||||
if args == "" {
|
||||
// Query topic.
|
||||
err := a.client.SendMessage(&chatapi.Message{
|
||||
err := a.client.SendMessage(&api.Message{
|
||||
Command: "TOPIC",
|
||||
To: target,
|
||||
})
|
||||
if err != nil {
|
||||
a.ui.AddStatus(fmt.Sprintf("[red]Topic query failed: %v", err))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err := a.client.SendMessage(&chatapi.Message{
|
||||
err := a.client.SendMessage(&api.Message{
|
||||
Command: "TOPIC",
|
||||
To: target,
|
||||
Body: []string{args},
|
||||
@@ -412,20 +347,16 @@ 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
|
||||
}
|
||||
|
||||
@@ -439,51 +370,46 @@ 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 <number>")
|
||||
|
||||
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()
|
||||
|
||||
// Update target based on buffer.
|
||||
if n < a.ui.BufferCount() {
|
||||
buf := a.ui.buffers[n]
|
||||
|
||||
if buf.Name != "(status)" {
|
||||
a.mu.Lock()
|
||||
a.target = buf.Name
|
||||
a.mu.Unlock()
|
||||
|
||||
a.ui.SetStatus(nick, buf.Name, "connected")
|
||||
} else {
|
||||
a.ui.SetStatus(nick, "", "connected")
|
||||
@@ -493,15 +419,12 @@ func (a *App) cmdWindow(args string) {
|
||||
|
||||
func (a *App) cmdQuit() {
|
||||
a.mu.Lock()
|
||||
|
||||
if a.connected && a.client != nil {
|
||||
_ = a.client.SendMessage(&chatapi.Message{Command: "QUIT"})
|
||||
_ = a.client.SendMessage(&api.Message{Command: "QUIT"})
|
||||
}
|
||||
|
||||
if a.stopPoll != nil {
|
||||
close(a.stopPoll)
|
||||
}
|
||||
|
||||
a.mu.Unlock()
|
||||
a.ui.Stop()
|
||||
}
|
||||
@@ -523,7 +446,6 @@ func (a *App) cmdHelp() {
|
||||
" /help — This help",
|
||||
" Plain text sends to current target.",
|
||||
}
|
||||
|
||||
for _, line := range help {
|
||||
a.ui.AddStatus(line)
|
||||
}
|
||||
@@ -547,17 +469,15 @@ func (a *App) pollLoop() {
|
||||
return
|
||||
}
|
||||
|
||||
msgs, err := client.PollMessages(lastID, pollTimeoutSec)
|
||||
msgs, err := client.PollMessages(lastID, 15)
|
||||
if err != nil {
|
||||
// Transient error — retry after delay.
|
||||
time.Sleep(pollRetrySec * time.Second)
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
for _, msg := range msgs {
|
||||
a.handleServerMessage(&msg)
|
||||
|
||||
if msg.ID != "" {
|
||||
a.mu.Lock()
|
||||
a.lastMsgID = msg.ID
|
||||
@@ -567,8 +487,14 @@ func (a *App) pollLoop() {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) handleServerMessage(msg *chatapi.Message) {
|
||||
ts := a.formatMessageTS(msg)
|
||||
func (a *App) handleServerMessage(msg *api.Message) {
|
||||
ts := ""
|
||||
if msg.TS != "" {
|
||||
t := msg.ParseTS()
|
||||
ts = t.Local().Format("15:04")
|
||||
} else {
|
||||
ts = time.Now().Format("15:04")
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
myNick := a.nick
|
||||
@@ -576,131 +502,79 @@ func (a *App) handleServerMessage(msg *chatapi.Message) {
|
||||
|
||||
switch msg.Command {
|
||||
case "PRIVMSG":
|
||||
a.handlePrivmsg(msg, ts, myNick)
|
||||
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))
|
||||
|
||||
case "JOIN":
|
||||
a.handleJoinMsg(msg, ts)
|
||||
target := msg.To
|
||||
if target != "" {
|
||||
a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has joined %s", ts, msg.From, target))
|
||||
}
|
||||
|
||||
case "PART":
|
||||
a.handlePartMsg(msg, ts)
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
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) formatMessageTS(msg *chatapi.Message) string {
|
||||
if msg.TS != "" {
|
||||
t := msg.ParseTS()
|
||||
|
||||
return t.Local().Format("15:04") //nolint:gosmopolitan // Local time display is intentional for UI
|
||||
}
|
||||
|
||||
return time.Now().Format("15:04")
|
||||
}
|
||||
|
||||
func (a *App) handlePrivmsg(msg *chatapi.Message, ts, myNick string) {
|
||||
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))
|
||||
}
|
||||
|
||||
func (a *App) handleJoinMsg(msg *chatapi.Message, ts string) {
|
||||
target := msg.To
|
||||
if target != "" {
|
||||
a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has joined %s", ts, msg.From, target))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) handlePartMsg(msg *chatapi.Message, ts string) {
|
||||
target := msg.To
|
||||
lines := msg.BodyLines()
|
||||
|
||||
reason := strings.Join(lines, " ")
|
||||
|
||||
if target != "" {
|
||||
lines := msg.BodyLines()
|
||||
reason := strings.Join(lines, " ")
|
||||
if reason != "" {
|
||||
a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has left %s (%s)", ts, msg.From, target, reason))
|
||||
a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s has quit (%s)", ts, msg.From, reason))
|
||||
} else {
|
||||
a.ui.AddLine(target, fmt.Sprintf("[gray]%s [yellow]*** %s has left %s", ts, msg.From, target))
|
||||
a.ui.AddStatus(fmt.Sprintf("[gray]%s [yellow]*** %s has quit", ts, msg.From))
|
||||
}
|
||||
|
||||
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))
|
||||
|
||||
case "NOTICE":
|
||||
lines := msg.BodyLines()
|
||||
text := strings.Join(lines, " ")
|
||||
a.ui.AddStatus(fmt.Sprintf("[gray]%s [magenta]--%s-- %s", ts, msg.From, text))
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) handleQuitMsg(msg *chatapi.Message, ts string) {
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) handleNickMsg(msg *chatapi.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) handleNoticeMsg(msg *chatapi.Message, ts string) {
|
||||
lines := msg.BodyLines()
|
||||
|
||||
text := strings.Join(lines, " ")
|
||||
|
||||
a.ui.AddStatus(fmt.Sprintf("[gray]%s [magenta]--%s-- %s", ts, msg.From, text))
|
||||
}
|
||||
|
||||
func (a *App) handleTopicMsg(msg *chatapi.Message, ts string) {
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) handleDefaultMsg(msg *chatapi.Message, ts string) {
|
||||
lines := msg.BodyLines()
|
||||
|
||||
text := strings.Join(lines, " ")
|
||||
|
||||
if text != "" {
|
||||
a.ui.AddStatus(fmt.Sprintf("[gray]%s [white][%s] %s", ts, msg.Command, text))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,9 +39,60 @@ func NewUI() *UI {
|
||||
},
|
||||
}
|
||||
|
||||
ui.setupWidgets()
|
||||
ui.setupInputCapture()
|
||||
ui.setupLayout()
|
||||
// Message area.
|
||||
ui.messages = tview.NewTextView().
|
||||
SetDynamicColors(true).
|
||||
SetScrollable(true).
|
||||
SetWordWrap(true).
|
||||
SetChangedFunc(func() {
|
||||
ui.app.Draw()
|
||||
})
|
||||
ui.messages.SetBorder(false)
|
||||
|
||||
// Status bar.
|
||||
ui.statusBar = tview.NewTextView().
|
||||
SetDynamicColors(true)
|
||||
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
|
||||
})
|
||||
|
||||
// Layout: messages on top, status bar, input at bottom.
|
||||
ui.layout = tview.NewFlex().SetDirection(tview.FlexRow).
|
||||
AddItem(ui.messages, 0, 1, false).
|
||||
AddItem(ui.statusBar, 1, 0, false).
|
||||
AddItem(ui.input, 1, 0, true)
|
||||
|
||||
ui.app.SetRoot(ui.layout, true)
|
||||
ui.app.SetFocus(ui.input)
|
||||
|
||||
return ui
|
||||
}
|
||||
@@ -70,13 +121,12 @@ 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -93,18 +143,13 @@ 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()
|
||||
})
|
||||
@@ -114,23 +159,17 @@ func (ui *UI) SwitchBuffer(n int) {
|
||||
func (ui *UI) SwitchToBuffer(name string) {
|
||||
ui.app.QueueUpdateDraw(func() {
|
||||
buf := ui.getOrCreateBuffer(name)
|
||||
|
||||
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()
|
||||
})
|
||||
@@ -143,6 +182,41 @@ 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)
|
||||
@@ -155,106 +229,5 @@ func (ui *UI) BufferIndex(name string) int {
|
||||
return i
|
||||
}
|
||||
}
|
||||
|
||||
return -1
|
||||
}
|
||||
|
||||
func (ui *UI) setupWidgets() {
|
||||
ui.messages = tview.NewTextView().
|
||||
SetDynamicColors(true).
|
||||
SetScrollable(true).
|
||||
SetWordWrap(true).
|
||||
SetChangedFunc(func() {
|
||||
ui.app.Draw()
|
||||
})
|
||||
ui.messages.SetBorder(false)
|
||||
|
||||
ui.statusBar = tview.NewTextView().
|
||||
SetDynamicColors(true)
|
||||
ui.statusBar.SetBackgroundColor(tcell.ColorNavy)
|
||||
ui.statusBar.SetTextColor(tcell.ColorWhite)
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (ui *UI) setupInputCapture() {
|
||||
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) setupLayout() {
|
||||
ui.layout = tview.NewFlex().SetDirection(tview.FlexRow).
|
||||
AddItem(ui.messages, 0, 1, false).
|
||||
AddItem(ui.statusBar, 1, 0, false).
|
||||
AddItem(ui.input, 1, 0, true)
|
||||
|
||||
ui.app.SetRoot(ui.layout, true)
|
||||
ui.app.SetFocus(ui.input)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@@ -46,6 +46,26 @@ type Database struct {
|
||||
params *Params
|
||||
}
|
||||
|
||||
// GetDB returns the underlying sql.DB connection.
|
||||
func (s *Database) GetDB() *sql.DB {
|
||||
return s.db
|
||||
}
|
||||
|
||||
// NewChannel creates a Channel model instance with the db reference injected.
|
||||
func (s *Database) NewChannel(id int64, name, topic, modes string, createdAt, updatedAt time.Time) *models.Channel {
|
||||
c := &models.Channel{
|
||||
ID: id,
|
||||
Name: name,
|
||||
Topic: topic,
|
||||
Modes: modes,
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: updatedAt,
|
||||
}
|
||||
c.SetDB(s)
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
// New creates a new Database instance and registers lifecycle hooks.
|
||||
func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
||||
s := new(Database)
|
||||
@@ -74,460 +94,6 @@ func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// NewTest creates a Database for testing, bypassing fx lifecycle.
|
||||
// It connects to the given DSN and runs all migrations.
|
||||
func NewTest(dsn string) (*Database, error) {
|
||||
d, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s := &Database{
|
||||
db: d,
|
||||
log: slog.Default(),
|
||||
}
|
||||
|
||||
// Item 9: Enable foreign keys
|
||||
_, err = d.ExecContext(context.Background(), "PRAGMA foreign_keys = ON")
|
||||
if err != nil {
|
||||
_ = d.Close()
|
||||
|
||||
return nil, fmt.Errorf("enable foreign keys: %w", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
err = s.runMigrations(ctx)
|
||||
if err != nil {
|
||||
_ = d.Close()
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// GetDB returns the underlying sql.DB connection.
|
||||
func (s *Database) GetDB() *sql.DB {
|
||||
return s.db
|
||||
}
|
||||
|
||||
// Hydrate injects the database reference into any model that
|
||||
// embeds Base.
|
||||
func (s *Database) Hydrate(m interface{ SetDB(d models.DB) }) {
|
||||
m.SetDB(s)
|
||||
}
|
||||
|
||||
// GetUserByID looks up a user by their ID.
|
||||
func (s *Database) GetUserByID(
|
||||
ctx context.Context,
|
||||
id string,
|
||||
) (*models.User, error) {
|
||||
u := &models.User{}
|
||||
s.Hydrate(u)
|
||||
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, nick, password_hash, created_at, updated_at, last_seen_at
|
||||
FROM users WHERE id = ?`,
|
||||
id,
|
||||
).Scan(
|
||||
&u.ID, &u.Nick, &u.PasswordHash,
|
||||
&u.CreatedAt, &u.UpdatedAt, &u.LastSeenAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// GetChannelByID looks up a channel by its ID.
|
||||
func (s *Database) GetChannelByID(
|
||||
ctx context.Context,
|
||||
id string,
|
||||
) (*models.Channel, error) {
|
||||
c := &models.Channel{}
|
||||
s.Hydrate(c)
|
||||
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, name, topic, modes, created_at, updated_at
|
||||
FROM channels WHERE id = ?`,
|
||||
id,
|
||||
).Scan(
|
||||
&c.ID, &c.Name, &c.Topic, &c.Modes,
|
||||
&c.CreatedAt, &c.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// GetUserByNick looks up a user by their nick.
|
||||
func (s *Database) GetUserByNick(
|
||||
ctx context.Context,
|
||||
nick string,
|
||||
) (*models.User, error) {
|
||||
u := &models.User{}
|
||||
s.Hydrate(u)
|
||||
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, nick, password_hash, created_at, updated_at, last_seen_at
|
||||
FROM users WHERE nick = ?`,
|
||||
nick,
|
||||
).Scan(
|
||||
&u.ID, &u.Nick, &u.PasswordHash,
|
||||
&u.CreatedAt, &u.UpdatedAt, &u.LastSeenAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// GetUserByToken looks up a user by their auth token.
|
||||
func (s *Database) GetUserByToken(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (*models.User, error) {
|
||||
u := &models.User{}
|
||||
s.Hydrate(u)
|
||||
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT u.id, u.nick, u.password_hash,
|
||||
u.created_at, u.updated_at, u.last_seen_at
|
||||
FROM users u
|
||||
JOIN auth_tokens t ON t.user_id = u.id
|
||||
WHERE t.token = ?`,
|
||||
token,
|
||||
).Scan(
|
||||
&u.ID, &u.Nick, &u.PasswordHash,
|
||||
&u.CreatedAt, &u.UpdatedAt, &u.LastSeenAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// DeleteAuthToken removes an auth token from the database.
|
||||
func (s *Database) DeleteAuthToken(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`DELETE FROM auth_tokens WHERE token = ?`, token,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// UpdateUserLastSeen updates the last_seen_at timestamp for a user.
|
||||
func (s *Database) UpdateUserLastSeen(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`UPDATE users SET last_seen_at = CURRENT_TIMESTAMP WHERE id = ?`,
|
||||
userID,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// CreateUser inserts a new user into the database.
|
||||
func (s *Database) CreateUser(
|
||||
ctx context.Context,
|
||||
id, nick, passwordHash string,
|
||||
) (*models.User, error) {
|
||||
now := time.Now()
|
||||
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO users (id, nick, password_hash)
|
||||
VALUES (?, ?, ?)`,
|
||||
id, nick, passwordHash,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
u := &models.User{
|
||||
ID: id, Nick: nick, PasswordHash: passwordHash,
|
||||
CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
s.Hydrate(u)
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// CreateChannel inserts a new channel into the database.
|
||||
func (s *Database) CreateChannel(
|
||||
ctx context.Context,
|
||||
id, name, topic, modes string,
|
||||
) (*models.Channel, error) {
|
||||
now := time.Now()
|
||||
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO channels (id, name, topic, modes)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
id, name, topic, modes,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c := &models.Channel{
|
||||
ID: id, Name: name, Topic: topic, Modes: modes,
|
||||
CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
s.Hydrate(c)
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// AddChannelMember adds a user to a channel with the given modes.
|
||||
func (s *Database) AddChannelMember(
|
||||
ctx context.Context,
|
||||
channelID, userID, modes string,
|
||||
) (*models.ChannelMember, error) {
|
||||
now := time.Now()
|
||||
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO channel_members
|
||||
(channel_id, user_id, modes)
|
||||
VALUES (?, ?, ?)`,
|
||||
channelID, userID, modes,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cm := &models.ChannelMember{
|
||||
ChannelID: channelID,
|
||||
UserID: userID,
|
||||
Modes: modes,
|
||||
JoinedAt: now,
|
||||
}
|
||||
s.Hydrate(cm)
|
||||
|
||||
return cm, nil
|
||||
}
|
||||
|
||||
// CreateMessage inserts a new message into the database.
|
||||
func (s *Database) CreateMessage(
|
||||
ctx context.Context,
|
||||
id, fromUserID, fromNick, target, msgType, body string,
|
||||
) (*models.Message, error) {
|
||||
now := time.Now()
|
||||
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO messages
|
||||
(id, from_user_id, from_nick, target, type, body)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
id, fromUserID, fromNick, target, msgType, body,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
m := &models.Message{
|
||||
ID: id,
|
||||
FromUserID: fromUserID,
|
||||
FromNick: fromNick,
|
||||
Target: target,
|
||||
Type: msgType,
|
||||
Body: body,
|
||||
Timestamp: now,
|
||||
CreatedAt: now,
|
||||
}
|
||||
s.Hydrate(m)
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// QueueMessage adds a message to a user's delivery queue.
|
||||
func (s *Database) QueueMessage(
|
||||
ctx context.Context,
|
||||
userID, messageID string,
|
||||
) (*models.MessageQueueEntry, error) {
|
||||
now := time.Now()
|
||||
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO message_queue (user_id, message_id)
|
||||
VALUES (?, ?)`,
|
||||
userID, messageID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entryID, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get last insert id: %w", err)
|
||||
}
|
||||
|
||||
mq := &models.MessageQueueEntry{
|
||||
ID: entryID,
|
||||
UserID: userID,
|
||||
MessageID: messageID,
|
||||
QueuedAt: now,
|
||||
}
|
||||
s.Hydrate(mq)
|
||||
|
||||
return mq, nil
|
||||
}
|
||||
|
||||
// DequeueMessages returns up to limit pending messages for a user,
|
||||
// ordered by queue time (oldest first).
|
||||
func (s *Database) DequeueMessages(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
limit int,
|
||||
) ([]*models.MessageQueueEntry, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, user_id, message_id, queued_at
|
||||
FROM message_queue
|
||||
WHERE user_id = ?
|
||||
ORDER BY queued_at ASC
|
||||
LIMIT ?`,
|
||||
userID, limit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
entries := []*models.MessageQueueEntry{}
|
||||
|
||||
for rows.Next() {
|
||||
e := &models.MessageQueueEntry{}
|
||||
s.Hydrate(e)
|
||||
|
||||
err = rows.Scan(&e.ID, &e.UserID, &e.MessageID, &e.QueuedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entries = append(entries, e)
|
||||
}
|
||||
|
||||
return entries, rows.Err()
|
||||
}
|
||||
|
||||
// AckMessages removes the given queue entry IDs, marking them as delivered.
|
||||
func (s *Database) AckMessages(
|
||||
ctx context.Context,
|
||||
entryIDs []int64,
|
||||
) error {
|
||||
if len(entryIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
placeholders := make([]string, len(entryIDs))
|
||||
args := make([]any, len(entryIDs))
|
||||
|
||||
for i, id := range entryIDs {
|
||||
placeholders[i] = "?"
|
||||
args[i] = id
|
||||
}
|
||||
|
||||
query := fmt.Sprintf( //nolint:gosec // G201: placeholders are literal "?" strings, not user input
|
||||
"DELETE FROM message_queue WHERE id IN (%s)",
|
||||
strings.Join(placeholders, ","),
|
||||
)
|
||||
|
||||
_, err := s.db.ExecContext(ctx, query, args...)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// CreateAuthToken inserts a new auth token for a user.
|
||||
func (s *Database) CreateAuthToken(
|
||||
ctx context.Context,
|
||||
token, userID string,
|
||||
) (*models.AuthToken, error) {
|
||||
now := time.Now()
|
||||
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO auth_tokens (token, user_id)
|
||||
VALUES (?, ?)`,
|
||||
token, userID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
at := &models.AuthToken{Token: token, UserID: userID, CreatedAt: now}
|
||||
s.Hydrate(at)
|
||||
|
||||
return at, nil
|
||||
}
|
||||
|
||||
// CreateSession inserts a new session for a user.
|
||||
func (s *Database) CreateSession(
|
||||
ctx context.Context,
|
||||
id, userID string,
|
||||
) (*models.Session, error) {
|
||||
now := time.Now()
|
||||
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO sessions (id, user_id)
|
||||
VALUES (?, ?)`,
|
||||
id, userID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sess := &models.Session{
|
||||
ID: id, UserID: userID,
|
||||
CreatedAt: now, LastActiveAt: now,
|
||||
}
|
||||
s.Hydrate(sess)
|
||||
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// CreateServerLink inserts a new server link.
|
||||
func (s *Database) CreateServerLink(
|
||||
ctx context.Context,
|
||||
id, name, url, sharedKeyHash string,
|
||||
isActive bool,
|
||||
) (*models.ServerLink, error) {
|
||||
now := time.Now()
|
||||
active := 0
|
||||
|
||||
if isActive {
|
||||
active = 1
|
||||
}
|
||||
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO server_links
|
||||
(id, name, url, shared_key_hash, is_active)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
id, name, url, sharedKeyHash, active,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sl := &models.ServerLink{
|
||||
ID: id,
|
||||
Name: name,
|
||||
URL: url,
|
||||
SharedKeyHash: sharedKeyHash,
|
||||
IsActive: isActive,
|
||||
CreatedAt: now,
|
||||
}
|
||||
s.Hydrate(sl)
|
||||
|
||||
return sl, nil
|
||||
}
|
||||
|
||||
func (s *Database) connect(ctx context.Context) error {
|
||||
dbURL := s.params.Config.DBURL
|
||||
if dbURL == "" {
|
||||
@@ -553,12 +119,6 @@ func (s *Database) connect(ctx context.Context) error {
|
||||
s.db = d
|
||||
s.log.Info("database connected")
|
||||
|
||||
// Item 9: Enable foreign keys on every connection
|
||||
_, err = s.db.ExecContext(ctx, "PRAGMA foreign_keys = ON")
|
||||
if err != nil {
|
||||
return fmt.Errorf("enable foreign keys: %w", err)
|
||||
}
|
||||
|
||||
return s.runMigrations(ctx)
|
||||
}
|
||||
|
||||
@@ -589,18 +149,13 @@ func (s *Database) runMigrations(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Database) bootstrapMigrationsTable(
|
||||
ctx context.Context,
|
||||
) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
func (s *Database) bootstrapMigrationsTable(ctx context.Context) error {
|
||||
_, err := s.db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INTEGER PRIMARY KEY,
|
||||
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`)
|
||||
if err != nil {
|
||||
return fmt.Errorf(
|
||||
"create schema_migrations table: %w", err,
|
||||
)
|
||||
return fmt.Errorf("failed to create schema_migrations table: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -609,20 +164,17 @@ func (s *Database) bootstrapMigrationsTable(
|
||||
func (s *Database) loadMigrations() ([]migration, error) {
|
||||
entries, err := fs.ReadDir(SchemaFiles, "schema")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read schema dir: %w", err)
|
||||
return nil, fmt.Errorf("failed to read schema dir: %w", err)
|
||||
}
|
||||
|
||||
var migrations []migration
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() ||
|
||||
!strings.HasSuffix(entry.Name(), ".sql") {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
||||
continue
|
||||
}
|
||||
|
||||
parts := strings.SplitN(
|
||||
entry.Name(), "_", minMigrationParts,
|
||||
)
|
||||
parts := strings.SplitN(entry.Name(), "_", minMigrationParts)
|
||||
if len(parts) < minMigrationParts {
|
||||
continue
|
||||
}
|
||||
@@ -632,13 +184,9 @@ func (s *Database) loadMigrations() ([]migration, error) {
|
||||
continue
|
||||
}
|
||||
|
||||
content, err := SchemaFiles.ReadFile(
|
||||
"schema/" + entry.Name(),
|
||||
)
|
||||
content, err := SchemaFiles.ReadFile("schema/" + entry.Name())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"read migration %s: %w", entry.Name(), err,
|
||||
)
|
||||
return nil, fmt.Errorf("failed to read migration %s: %w", entry.Name(), err)
|
||||
}
|
||||
|
||||
migrations = append(migrations, migration{
|
||||
@@ -655,78 +203,31 @@ func (s *Database) loadMigrations() ([]migration, error) {
|
||||
return migrations, nil
|
||||
}
|
||||
|
||||
// Item 4: Wrap each migration in a transaction
|
||||
func (s *Database) applyMigrations(
|
||||
ctx context.Context,
|
||||
migrations []migration,
|
||||
) error {
|
||||
func (s *Database) applyMigrations(ctx context.Context, 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.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,
|
||||
)
|
||||
return fmt.Errorf("failed to check migration %d: %w", m.version, err)
|
||||
}
|
||||
|
||||
if exists > 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
err = s.applySingleMigration(ctx, m)
|
||||
s.log.Info("applying migration", "version", m.version, "name", m.name)
|
||||
|
||||
_, err = s.db.ExecContext(ctx, m.sql)
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("failed to apply migration %d (%s): %w", m.version, m.name, err)
|
||||
}
|
||||
|
||||
_, err = s.db.ExecContext(ctx, "INSERT INTO schema_migrations (version) VALUES (?)", m.version)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to record migration %d: %w", m.version, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Database) applySingleMigration(ctx context.Context, m migration) error {
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
if err != nil {
|
||||
return fmt.Errorf(
|
||||
"commit migration %d: %w", m.version, err,
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,494 +0,0 @@
|
||||
package db_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.eeqj.de/sneak/chat/internal/db"
|
||||
)
|
||||
|
||||
const (
|
||||
nickAlice = "alice"
|
||||
nickBob = "bob"
|
||||
nickCharlie = "charlie"
|
||||
)
|
||||
|
||||
// setupTestDB creates a fresh database in a temp directory with
|
||||
// all migrations applied.
|
||||
func setupTestDB(t *testing.T) *db.Database {
|
||||
t.Helper()
|
||||
|
||||
dir := t.TempDir()
|
||||
dsn := fmt.Sprintf(
|
||||
"file:%s?_journal_mode=WAL",
|
||||
filepath.Join(dir, "test.db"),
|
||||
)
|
||||
|
||||
d, err := db.NewTest(dsn)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create test database: %v", err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() { _ = d.GetDB().Close() })
|
||||
|
||||
return d
|
||||
}
|
||||
|
||||
func TestCreateUser(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
u, err := d.CreateUser(ctx, "u1", nickAlice, "hash1")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser: %v", err)
|
||||
}
|
||||
|
||||
if u.ID != "u1" || u.Nick != nickAlice {
|
||||
t.Errorf("got user %+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAuthToken(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser: %v", err)
|
||||
}
|
||||
|
||||
tok, err := d.CreateAuthToken(ctx, "tok1", "u1")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateAuthToken: %v", err)
|
||||
}
|
||||
|
||||
if tok.Token != "tok1" || tok.UserID != "u1" {
|
||||
t.Errorf("unexpected token: %+v", tok)
|
||||
}
|
||||
|
||||
u, err := tok.User(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("AuthToken.User: %v", err)
|
||||
}
|
||||
|
||||
if u.ID != "u1" || u.Nick != nickAlice {
|
||||
t.Errorf("AuthToken.User got %+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChannel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
ch, err := d.CreateChannel(
|
||||
ctx, "c1", "#general", "welcome", "+n",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateChannel: %v", err)
|
||||
}
|
||||
|
||||
if ch.ID != "c1" || ch.Name != "#general" {
|
||||
t.Errorf("unexpected channel: %+v", ch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddChannelMember(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
_, _ = d.CreateChannel(ctx, "c1", "#general", "", "")
|
||||
|
||||
cm, err := d.AddChannelMember(ctx, "c1", "u1", "+o")
|
||||
if err != nil {
|
||||
t.Fatalf("AddChannelMember: %v", err)
|
||||
}
|
||||
|
||||
if cm.ChannelID != "c1" || cm.Modes != "+o" {
|
||||
t.Errorf("unexpected member: %+v", cm)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateMessage(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
|
||||
msg, err := d.CreateMessage(
|
||||
ctx, "m1", "u1", nickAlice,
|
||||
"#general", "message", "hello",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateMessage: %v", err)
|
||||
}
|
||||
|
||||
if msg.ID != "m1" || msg.Body != "hello" {
|
||||
t.Errorf("unexpected message: %+v", msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueueMessage(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
_, _ = d.CreateUser(ctx, "u2", nickBob, "h")
|
||||
_, _ = d.CreateMessage(
|
||||
ctx, "m1", "u1", nickAlice, "u2", "message", "hi",
|
||||
)
|
||||
|
||||
mq, err := d.QueueMessage(ctx, "u2", "m1")
|
||||
if err != nil {
|
||||
t.Fatalf("QueueMessage: %v", err)
|
||||
}
|
||||
|
||||
if mq.UserID != "u2" || mq.MessageID != "m1" {
|
||||
t.Errorf("unexpected queue entry: %+v", mq)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSession(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
|
||||
sess, err := d.CreateSession(ctx, "s1", "u1")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession: %v", err)
|
||||
}
|
||||
|
||||
if sess.ID != "s1" || sess.UserID != "u1" {
|
||||
t.Errorf("unexpected session: %+v", sess)
|
||||
}
|
||||
|
||||
u, err := sess.User(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Session.User: %v", err)
|
||||
}
|
||||
|
||||
if u.ID != "u1" {
|
||||
t.Errorf("Session.User got %v, want u1", u.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateServerLink(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
sl, err := d.CreateServerLink(
|
||||
ctx, "sl1", "peer1",
|
||||
"https://peer.example.com", "keyhash", true,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateServerLink: %v", err)
|
||||
}
|
||||
|
||||
if sl.ID != "sl1" || !sl.IsActive {
|
||||
t.Errorf("unexpected server link: %+v", sl)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserChannels(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
u, _ := d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
_, _ = d.CreateChannel(ctx, "c1", "#alpha", "", "")
|
||||
_, _ = d.CreateChannel(ctx, "c2", "#beta", "", "")
|
||||
_, _ = d.AddChannelMember(ctx, "c1", "u1", "")
|
||||
_, _ = d.AddChannelMember(ctx, "c2", "u1", "")
|
||||
|
||||
channels, err := u.Channels(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("User.Channels: %v", err)
|
||||
}
|
||||
|
||||
if len(channels) != 2 {
|
||||
t.Fatalf("expected 2 channels, got %d", len(channels))
|
||||
}
|
||||
|
||||
if channels[0].Name != "#alpha" {
|
||||
t.Errorf("first channel: got %s", channels[0].Name)
|
||||
}
|
||||
|
||||
if channels[1].Name != "#beta" {
|
||||
t.Errorf("second channel: got %s", channels[1].Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserChannelsEmpty(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
u, _ := d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
|
||||
channels, err := u.Channels(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("User.Channels: %v", err)
|
||||
}
|
||||
|
||||
if len(channels) != 0 {
|
||||
t.Errorf("expected 0 channels, got %d", len(channels))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserQueuedMessages(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
u, _ := d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
_, _ = d.CreateUser(ctx, "u2", nickBob, "h")
|
||||
|
||||
for i := range 3 {
|
||||
id := fmt.Sprintf("m%d", i)
|
||||
|
||||
_, _ = d.CreateMessage(
|
||||
ctx, id, "u2", nickBob, "u1",
|
||||
"message", fmt.Sprintf("msg%d", i),
|
||||
)
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
_, _ = d.QueueMessage(ctx, "u1", id)
|
||||
}
|
||||
|
||||
msgs, err := u.QueuedMessages(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("User.QueuedMessages: %v", err)
|
||||
}
|
||||
|
||||
if len(msgs) != 3 {
|
||||
t.Fatalf("expected 3 messages, got %d", len(msgs))
|
||||
}
|
||||
|
||||
for i, msg := range msgs {
|
||||
want := fmt.Sprintf("msg%d", i)
|
||||
if msg.Body != want {
|
||||
t.Errorf("msg %d: got %q, want %q", i, msg.Body, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserQueuedMessagesEmpty(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
u, _ := d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
|
||||
msgs, err := u.QueuedMessages(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("User.QueuedMessages: %v", err)
|
||||
}
|
||||
|
||||
if len(msgs) != 0 {
|
||||
t.Errorf("expected 0 messages, got %d", len(msgs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelMembers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
ch, _ := d.CreateChannel(ctx, "c1", "#general", "", "")
|
||||
_, _ = d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
_, _ = d.CreateUser(ctx, "u2", nickBob, "h")
|
||||
_, _ = d.CreateUser(ctx, "u3", nickCharlie, "h")
|
||||
_, _ = d.AddChannelMember(ctx, "c1", "u1", "+o")
|
||||
_, _ = d.AddChannelMember(ctx, "c1", "u2", "+v")
|
||||
_, _ = d.AddChannelMember(ctx, "c1", "u3", "")
|
||||
|
||||
members, err := ch.Members(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Channel.Members: %v", err)
|
||||
}
|
||||
|
||||
if len(members) != 3 {
|
||||
t.Fatalf("expected 3 members, got %d", len(members))
|
||||
}
|
||||
|
||||
nicks := map[string]bool{}
|
||||
for _, m := range members {
|
||||
nicks[m.Nick] = true
|
||||
}
|
||||
|
||||
for _, want := range []string{
|
||||
nickAlice, nickBob, nickCharlie,
|
||||
} {
|
||||
if !nicks[want] {
|
||||
t.Errorf("missing nick %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelMembersEmpty(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
ch, _ := d.CreateChannel(ctx, "c1", "#empty", "", "")
|
||||
|
||||
members, err := ch.Members(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Channel.Members: %v", err)
|
||||
}
|
||||
|
||||
if len(members) != 0 {
|
||||
t.Errorf("expected 0, got %d", len(members))
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelRecentMessages(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
ch, _ := d.CreateChannel(ctx, "c1", "#general", "", "")
|
||||
_, _ = d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
|
||||
for i := range 5 {
|
||||
id := fmt.Sprintf("m%d", i)
|
||||
|
||||
_, _ = d.CreateMessage(
|
||||
ctx, id, "u1", nickAlice, "#general",
|
||||
"message", fmt.Sprintf("msg%d", i),
|
||||
)
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
|
||||
msgs, err := ch.RecentMessages(ctx, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("RecentMessages: %v", err)
|
||||
}
|
||||
|
||||
if len(msgs) != 3 {
|
||||
t.Fatalf("expected 3, got %d", len(msgs))
|
||||
}
|
||||
|
||||
if msgs[0].Body != "msg4" {
|
||||
t.Errorf("first: got %q, want msg4", msgs[0].Body)
|
||||
}
|
||||
|
||||
if msgs[2].Body != "msg2" {
|
||||
t.Errorf("last: got %q, want msg2", msgs[2].Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelRecentMessagesLargeLimit(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
ch, _ := d.CreateChannel(ctx, "c1", "#general", "", "")
|
||||
_, _ = d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
_, _ = d.CreateMessage(
|
||||
ctx, "m1", "u1", nickAlice,
|
||||
"#general", "message", "only",
|
||||
)
|
||||
|
||||
msgs, err := ch.RecentMessages(ctx, 100)
|
||||
if err != nil {
|
||||
t.Fatalf("RecentMessages: %v", err)
|
||||
}
|
||||
|
||||
if len(msgs) != 1 {
|
||||
t.Errorf("expected 1, got %d", len(msgs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelMemberUser(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
_, _ = d.CreateChannel(ctx, "c1", "#general", "", "")
|
||||
|
||||
cm, _ := d.AddChannelMember(ctx, "c1", "u1", "+o")
|
||||
|
||||
u, err := cm.User(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ChannelMember.User: %v", err)
|
||||
}
|
||||
|
||||
if u.ID != "u1" || u.Nick != nickAlice {
|
||||
t.Errorf("got %+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelMemberChannel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
_, _ = d.CreateChannel(ctx, "c1", "#general", "topic", "+n")
|
||||
|
||||
cm, _ := d.AddChannelMember(ctx, "c1", "u1", "")
|
||||
|
||||
ch, err := cm.Channel(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ChannelMember.Channel: %v", err)
|
||||
}
|
||||
|
||||
if ch.ID != "c1" || ch.Topic != "topic" {
|
||||
t.Errorf("got %+v", ch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDMMessage(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := setupTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
_, _ = d.CreateUser(ctx, "u1", nickAlice, "h")
|
||||
_, _ = d.CreateUser(ctx, "u2", nickBob, "h")
|
||||
|
||||
msg, err := d.CreateMessage(
|
||||
ctx, "m1", "u1", nickAlice, "u2", "message", "hey",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateMessage DM: %v", err)
|
||||
}
|
||||
|
||||
if msg.Target != "u2" {
|
||||
t.Errorf("target: got %q, want u2", msg.Target)
|
||||
}
|
||||
}
|
||||
@@ -3,84 +3,66 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
const tokenBytes = 32
|
||||
|
||||
func generateToken() string {
|
||||
b := make([]byte, tokenBytes)
|
||||
b := make([]byte, 32)
|
||||
_, _ = rand.Read(b)
|
||||
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// CreateSimpleUser registers a new user with the given nick and returns the user ID and token.
|
||||
func (s *Database) CreateSimpleUser(ctx context.Context, nick string) (int64, string, error) {
|
||||
// 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
|
||||
}
|
||||
|
||||
// LookupUserByToken returns user id and nick for a given auth token.
|
||||
func (s *Database) LookupUserByToken(ctx context.Context, token string) (int64, string, error) {
|
||||
// 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
|
||||
}
|
||||
|
||||
// LookupUserByNick returns user id for a given nick.
|
||||
func (s *Database) LookupUserByNick(ctx context.Context, nick string) (int64, error) {
|
||||
// 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
|
||||
|
||||
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)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("create channel: %w", err)
|
||||
}
|
||||
|
||||
id, _ = res.LastInsertId()
|
||||
|
||||
return id, nil
|
||||
}
|
||||
|
||||
@@ -89,7 +71,6 @@ func (s *Database) JoinChannel(ctx context.Context, channelID, userID int64) err
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"INSERT OR IGNORE INTO channel_members (channel_id, user_id, joined_at) VALUES (?, ?, ?)",
|
||||
channelID, userID, time.Now())
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -98,17 +79,9 @@ func (s *Database) PartChannel(ctx context.Context, channelID, userID int64) err
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"DELETE FROM channel_members WHERE channel_id = ? AND user_id = ?",
|
||||
channelID, userID)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ChannelInfo is a lightweight channel representation.
|
||||
type ChannelInfo struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Topic string `json:"topic"`
|
||||
}
|
||||
|
||||
// ListChannels returns all channels the user has joined.
|
||||
func (s *Database) ListChannels(ctx context.Context, userID int64) ([]ChannelInfo, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
@@ -118,15 +91,26 @@ func (s *Database) ListChannels(ctx context.Context, userID int64) ([]ChannelInf
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return scanChannelInfoRows(rows)
|
||||
defer rows.Close()
|
||||
var channels []ChannelInfo
|
||||
for rows.Next() {
|
||||
var ch ChannelInfo
|
||||
if err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channels = append(channels, ch)
|
||||
}
|
||||
if channels == nil {
|
||||
channels = []ChannelInfo{}
|
||||
}
|
||||
return channels, nil
|
||||
}
|
||||
|
||||
// MemberInfo represents a channel member.
|
||||
type MemberInfo struct {
|
||||
ID int64 `json:"id"`
|
||||
Nick string `json:"nick"`
|
||||
LastSeen time.Time `json:"lastSeen"`
|
||||
// ChannelInfo is a lightweight channel representation.
|
||||
type ChannelInfo struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Topic string `json:"topic"`
|
||||
}
|
||||
|
||||
// ChannelMembers returns all members of a channel.
|
||||
@@ -138,34 +122,28 @@ func (s *Database) ChannelMembers(ctx context.Context, channelID int64) ([]Membe
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
defer rows.Close()
|
||||
var members []MemberInfo
|
||||
|
||||
for rows.Next() {
|
||||
var m MemberInfo
|
||||
|
||||
scanErr := rows.Scan(&m.ID, &m.Nick, &m.LastSeen)
|
||||
if scanErr != nil {
|
||||
return nil, scanErr
|
||||
if err := rows.Scan(&m.ID, &m.Nick, &m.LastSeen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
members = append(members, m)
|
||||
}
|
||||
|
||||
err = rows.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if members == nil {
|
||||
members = []MemberInfo{}
|
||||
}
|
||||
|
||||
return members, nil
|
||||
}
|
||||
|
||||
// MemberInfo represents a channel member.
|
||||
type MemberInfo struct {
|
||||
ID int64 `json:"id"`
|
||||
Nick string `json:"nick"`
|
||||
LastSeen time.Time `json:"lastSeen"`
|
||||
}
|
||||
|
||||
// MessageInfo represents a chat message.
|
||||
type MessageInfo struct {
|
||||
ID int64 `json:"id"`
|
||||
@@ -177,18 +155,11 @@ type MessageInfo struct {
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
const defaultMessageLimit = 50
|
||||
|
||||
const defaultPollLimit = 100
|
||||
|
||||
// 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) {
|
||||
func (s *Database) GetMessages(ctx context.Context, channelID int64, afterID int64, limit int) ([]MessageInfo, error) {
|
||||
if limit <= 0 {
|
||||
limit = defaultMessageLimit
|
||||
limit = 50
|
||||
}
|
||||
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT m.id, c.name, u.nick, m.content, m.created_at
|
||||
FROM messages m
|
||||
@@ -199,46 +170,48 @@ func (s *Database) GetMessages(
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return scanChannelMessages(rows)
|
||||
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) {
|
||||
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())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return res.LastInsertId()
|
||||
}
|
||||
|
||||
// SendDM inserts a direct message.
|
||||
func (s *Database) SendDM(
|
||||
ctx context.Context, fromID, toID int64, content string,
|
||||
) (int64, error) {
|
||||
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())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return res.LastInsertId()
|
||||
}
|
||||
|
||||
// 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) {
|
||||
func (s *Database) GetDMs(ctx context.Context, userA, userB int64, afterID int64, limit int) ([]MessageInfo, error) {
|
||||
if limit <= 0 {
|
||||
limit = defaultMessageLimit
|
||||
limit = 50
|
||||
}
|
||||
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT m.id, u.nick, m.content, t.nick, m.created_at
|
||||
FROM messages m
|
||||
@@ -250,85 +223,152 @@ func (s *Database) GetDMs(
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return scanDMMessages(rows)
|
||||
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) {
|
||||
func (s *Database) PollMessages(ctx context.Context, userID int64, afterID int64, limit int) ([]MessageInfo, error) {
|
||||
if limit <= 0 {
|
||||
limit = defaultPollLimit
|
||||
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, COALESCE(c.name, ''), u.nick, m.content, m.is_dm, COALESCE(t.nick, ''), 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 = ?))
|
||||
(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 = ?))
|
||||
)
|
||||
ORDER BY m.id ASC LIMIT ?`, afterID, userID, userID, userID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return scanPollMessages(rows)
|
||||
defer rows.Close()
|
||||
var 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 {
|
||||
return nil, err
|
||||
}
|
||||
m.IsDM = isDM == 1
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
if msgs == nil {
|
||||
msgs = []MessageInfo{}
|
||||
}
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
// 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) {
|
||||
func (s *Database) GetMessagesBefore(ctx context.Context, channelID int64, beforeID int64, limit int) ([]MessageInfo, error) {
|
||||
if limit <= 0 {
|
||||
limit = defaultMessageLimit
|
||||
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}
|
||||
} 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}
|
||||
}
|
||||
|
||||
query, args := buildChannelHistoryQuery(channelID, beforeID, limit)
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgs, err := scanChannelMessages(rows)
|
||||
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{}
|
||||
}
|
||||
// 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]
|
||||
}
|
||||
|
||||
reverseMessages(msgs)
|
||||
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
// 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) {
|
||||
func (s *Database) GetDMsBefore(ctx context.Context, userA, userB int64, beforeID int64, limit int) ([]MessageInfo, error) {
|
||||
if limit <= 0 {
|
||||
limit = defaultMessageLimit
|
||||
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}
|
||||
} 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}
|
||||
}
|
||||
|
||||
query, args := buildDMHistoryQuery(userA, userB, beforeID, limit)
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgs, err := scanDMMessages(rows)
|
||||
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{}
|
||||
}
|
||||
// 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]
|
||||
}
|
||||
|
||||
reverseMessages(msgs)
|
||||
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
@@ -336,7 +376,6 @@ func (s *Database) GetDMsBefore(
|
||||
func (s *Database) ChangeNick(ctx context.Context, userID int64, newNick string) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"UPDATE users SET nick = ? WHERE id = ?", newNick, userID)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -344,7 +383,6 @@ func (s *Database) ChangeNick(ctx context.Context, userID int64, newNick string)
|
||||
func (s *Database) SetTopic(ctx context.Context, channelName string, _ int64, topic string) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
"UPDATE channels SET topic = ? WHERE name = ?", topic, channelName)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -360,174 +398,17 @@ func (s *Database) ListAllChannels(ctx context.Context) ([]ChannelInfo, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return scanChannelInfoRows(rows)
|
||||
}
|
||||
|
||||
// --- Helper functions ---
|
||||
|
||||
func scanChannelInfoRows(rows *sql.Rows) ([]ChannelInfo, error) {
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
defer rows.Close()
|
||||
var channels []ChannelInfo
|
||||
|
||||
for rows.Next() {
|
||||
var ch ChannelInfo
|
||||
|
||||
scanErr := rows.Scan(&ch.ID, &ch.Name, &ch.Topic)
|
||||
if scanErr != nil {
|
||||
return nil, scanErr
|
||||
if err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
channels = append(channels, ch)
|
||||
}
|
||||
|
||||
err := rows.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if channels == nil {
|
||||
channels = []ChannelInfo{}
|
||||
}
|
||||
|
||||
return channels, nil
|
||||
}
|
||||
|
||||
func scanChannelMessages(rows *sql.Rows) ([]MessageInfo, error) {
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var msgs []MessageInfo
|
||||
|
||||
for rows.Next() {
|
||||
var m MessageInfo
|
||||
|
||||
scanErr := rows.Scan(&m.ID, &m.Channel, &m.Nick, &m.Content, &m.CreatedAt)
|
||||
if scanErr != nil {
|
||||
return nil, scanErr
|
||||
}
|
||||
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
|
||||
err := rows.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if msgs == nil {
|
||||
msgs = []MessageInfo{}
|
||||
}
|
||||
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
func scanDMMessages(rows *sql.Rows) ([]MessageInfo, error) {
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var msgs []MessageInfo
|
||||
|
||||
for rows.Next() {
|
||||
var m MessageInfo
|
||||
|
||||
scanErr := rows.Scan(&m.ID, &m.Nick, &m.Content, &m.DMTarget, &m.CreatedAt)
|
||||
if scanErr != nil {
|
||||
return nil, scanErr
|
||||
}
|
||||
|
||||
m.IsDM = true
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
|
||||
err := rows.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if msgs == nil {
|
||||
msgs = []MessageInfo{}
|
||||
}
|
||||
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
func scanPollMessages(rows *sql.Rows) ([]MessageInfo, error) {
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var msgs []MessageInfo
|
||||
|
||||
for rows.Next() {
|
||||
var m MessageInfo
|
||||
|
||||
var isDM int
|
||||
|
||||
scanErr := rows.Scan(
|
||||
&m.ID, &m.Channel, &m.Nick, &m.Content, &isDM, &m.DMTarget, &m.CreatedAt,
|
||||
)
|
||||
if scanErr != nil {
|
||||
return nil, scanErr
|
||||
}
|
||||
|
||||
m.IsDM = isDM == 1
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
|
||||
err := rows.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if msgs == nil {
|
||||
msgs = []MessageInfo{}
|
||||
}
|
||||
|
||||
return msgs, nil
|
||||
}
|
||||
|
||||
func buildChannelHistoryQuery(channelID, beforeID int64, limit int) (string, []any) {
|
||||
if beforeID > 0 {
|
||||
return `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 ?`, []any{channelID, beforeID, limit}
|
||||
}
|
||||
|
||||
return `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 ?`, []any{channelID, limit}
|
||||
}
|
||||
|
||||
func buildDMHistoryQuery(userA, userB, beforeID int64, limit int) (string, []any) {
|
||||
if beforeID > 0 {
|
||||
return `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 ?`,
|
||||
[]any{beforeID, userA, userB, userB, userA, limit}
|
||||
}
|
||||
|
||||
return `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 ?`,
|
||||
[]any{userA, userB, userB, userA, limit}
|
||||
}
|
||||
|
||||
func reverseMessages(msgs []MessageInfo) {
|
||||
for i, j := 0, len(msgs)-1; i < j; i, j = i+1, j-1 {
|
||||
msgs[i], msgs[j] = msgs[j], msgs[i]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
-- All schema changes go into this file until 1.0.0 is tagged.
|
||||
-- There will not be migrations during the early development phase.
|
||||
-- After 1.0.0, new changes get their own numbered migration files.
|
||||
|
||||
-- Users: accounts and authentication
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
nick TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_seen_at DATETIME
|
||||
);
|
||||
|
||||
-- Auth tokens: one user can have multiple active tokens (multiple devices)
|
||||
CREATE TABLE IF NOT EXISTS auth_tokens (
|
||||
token TEXT PRIMARY KEY, -- random token string
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at DATETIME, -- NULL = no expiry
|
||||
last_used_at DATETIME
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_auth_tokens_user_id ON auth_tokens(user_id);
|
||||
|
||||
-- Channels: chat rooms
|
||||
CREATE TABLE IF NOT EXISTS channels (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
name TEXT NOT NULL UNIQUE, -- #general, etc.
|
||||
topic TEXT NOT NULL DEFAULT '',
|
||||
modes TEXT NOT NULL DEFAULT '', -- +i, +m, +s, +t, +n
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Channel members: who is in which channel, with per-user modes
|
||||
CREATE TABLE IF NOT EXISTS channel_members (
|
||||
channel_id TEXT NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
modes TEXT NOT NULL DEFAULT '', -- +o (operator), +v (voice)
|
||||
joined_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (channel_id, user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_channel_members_user_id ON channel_members(user_id);
|
||||
|
||||
-- Messages: channel and DM history (rotated per MAX_HISTORY)
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
ts DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
from_user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
from_nick TEXT NOT NULL, -- denormalized for history
|
||||
target TEXT NOT NULL, -- #channel name or user UUID for DMs
|
||||
type TEXT NOT NULL DEFAULT 'message', -- message, action, notice, join, part, quit, topic, mode, nick, system
|
||||
body TEXT NOT NULL DEFAULT '',
|
||||
meta TEXT NOT NULL DEFAULT '{}', -- JSON extensible metadata
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_target_ts ON messages(target, ts);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_from_user ON messages(from_user_id);
|
||||
|
||||
-- Message queue: per-user pending delivery (unread messages)
|
||||
CREATE TABLE IF NOT EXISTS message_queue (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
message_id TEXT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
queued_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(user_id, message_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_message_queue_user_id ON message_queue(user_id, queued_at);
|
||||
|
||||
-- Sessions: server-held session state
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_active_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at DATETIME -- idle timeout
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
|
||||
|
||||
-- Server links: federation peer configuration
|
||||
CREATE TABLE IF NOT EXISTS server_links (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
name TEXT NOT NULL UNIQUE, -- human-readable peer name
|
||||
url TEXT NOT NULL, -- base URL of peer server
|
||||
shared_key_hash TEXT NOT NULL, -- hashed shared secret
|
||||
is_active INTEGER NOT NULL DEFAULT 1,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_seen_at DATETIME
|
||||
);
|
||||
8
internal/db/schema/002_tables.sql
Normal file
8
internal/db/schema/002_tables.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE IF NOT EXISTS channels (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
topic TEXT NOT NULL DEFAULT '',
|
||||
modes TEXT NOT NULL DEFAULT '',
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
@@ -1,16 +1,31 @@
|
||||
-- Migration 003: Add simple user auth columns.
|
||||
-- This migration adds token-based auth support for the web client.
|
||||
-- Tables created by 002 (with TEXT ids) take precedence via IF NOT EXISTS.
|
||||
-- We only add columns/indexes that don't already exist.
|
||||
PRAGMA foreign_keys = ON;
|
||||
|
||||
-- Add token column to users table if it doesn't exist.
|
||||
-- SQLite doesn't support IF NOT EXISTS for ALTER TABLE ADD COLUMN,
|
||||
-- so we check via pragma first.
|
||||
CREATE TABLE IF NOT EXISTS _migration_003_check (done INTEGER);
|
||||
INSERT OR IGNORE INTO _migration_003_check VALUES (1);
|
||||
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
|
||||
);
|
||||
|
||||
-- The web chat client's simple tables are only created if migration 002
|
||||
-- didn't already create them with the ORM schema.
|
||||
-- Since 002 creates all needed tables, 003 is effectively a no-op
|
||||
-- when run after 002.
|
||||
DROP TABLE IF EXISTS _migration_003_check;
|
||||
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);
|
||||
|
||||
@@ -11,28 +11,22 @@ import (
|
||||
"github.com/go-chi/chi"
|
||||
)
|
||||
|
||||
const maxNickLen = 32
|
||||
|
||||
// authUser extracts the user from the Authorization header (Bearer token).
|
||||
func (s *Handlers) authUser(r *http.Request) (int64, string, error) {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(auth, "Bearer ") {
|
||||
return 0, "", sql.ErrNoRows
|
||||
}
|
||||
|
||||
token := strings.TrimPrefix(auth, "Bearer ")
|
||||
|
||||
return s.params.Database.LookupUserByToken(r.Context(), token)
|
||||
return s.params.Database.GetUserByToken(r.Context(), token)
|
||||
}
|
||||
|
||||
func (s *Handlers) requireAuth(w http.ResponseWriter, r *http.Request) (int64, 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 uid, nick, true
|
||||
}
|
||||
|
||||
@@ -41,45 +35,32 @@ func (s *Handlers) HandleCreateSession() http.HandlerFunc {
|
||||
type request struct {
|
||||
Nick string `json:"nick"`
|
||||
}
|
||||
|
||||
type response struct {
|
||||
ID int64 `json:"id"`
|
||||
Nick string `json:"nick"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req request
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); 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) > maxNickLen {
|
||||
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.CreateSimpleUser(r.Context(), req.Nick)
|
||||
id, token, err := s.params.Database.CreateUser(r.Context(), 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)
|
||||
}
|
||||
}
|
||||
@@ -91,21 +72,17 @@ func (s *Handlers) HandleState() http.HandlerFunc {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -117,15 +94,12 @@ 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)
|
||||
}
|
||||
}
|
||||
@@ -137,24 +111,20 @@ func (s *Handlers) HandleChannelMembers() http.HandlerFunc {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
name := "#" + chi.URLParam(r, "channel")
|
||||
|
||||
chID, err := s.lookupChannelID(r, name)
|
||||
var chID int64
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -167,18 +137,14 @@ func (s *Handlers) HandleGetMessages() http.HandlerFunc {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
afterID, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
|
||||
msgs, err := s.params.Database.PollMessages(r.Context(), uid, afterID, 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)
|
||||
}
|
||||
}
|
||||
@@ -186,278 +152,185 @@ func (s *Handlers) HandleGetMessages() http.HandlerFunc {
|
||||
// HandleSendCommand handles all C2S commands via POST /messages.
|
||||
// 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"`
|
||||
}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, nick, ok := s.requireAuth(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
cmd, err := s.decodeSendCommand(r)
|
||||
if err != nil {
|
||||
var req request
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); 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)
|
||||
|
||||
switch cmd.Command {
|
||||
case "PRIVMSG", "NOTICE":
|
||||
s.handlePrivmsgCommand(w, r, uid, cmd)
|
||||
case "JOIN":
|
||||
s.handleJoinCommand(w, r, uid, cmd)
|
||||
case "PART":
|
||||
s.handlePartCommand(w, r, uid, cmd)
|
||||
case "NICK":
|
||||
s.handleNickCommand(w, r, uid, cmd)
|
||||
case "TOPIC":
|
||||
s.handleTopicCommand(w, r, cmd)
|
||||
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: " + cmd.Command}, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type sendCommand struct {
|
||||
Command string `json:"command"`
|
||||
To string `json:"to"`
|
||||
Params []string `json:"params,omitempty"`
|
||||
Body any `json:"body,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Handlers) decodeSendCommand(r *http.Request) (*sendCommand, error) {
|
||||
var cmd sendCommand
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&cmd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cmd.Command = strings.ToUpper(strings.TrimSpace(cmd.Command))
|
||||
cmd.To = strings.TrimSpace(cmd.To)
|
||||
|
||||
return &cmd, nil
|
||||
}
|
||||
|
||||
func bodyLines(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)
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
|
||||
func (s *Handlers) handlePrivmsgCommand(
|
||||
w http.ResponseWriter, r *http.Request, uid int64, cmd *sendCommand,
|
||||
) {
|
||||
if cmd.To == "" {
|
||||
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
|
||||
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)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
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)
|
||||
|
||||
lines := bodyLines(cmd.Body)
|
||||
if len(lines) == 0 {
|
||||
s.respondJSON(w, r, map[string]string{"error": "body required"}, http.StatusBadRequest)
|
||||
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)
|
||||
|
||||
return
|
||||
}
|
||||
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)
|
||||
|
||||
content := strings.Join(lines, "\n")
|
||||
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)
|
||||
|
||||
if strings.HasPrefix(cmd.To, "#") {
|
||||
s.sendChannelMessage(w, r, uid, cmd.To, content)
|
||||
} else {
|
||||
s.sendDirectMessage(w, r, uid, cmd.To, content)
|
||||
}
|
||||
}
|
||||
case "PING":
|
||||
s.respondJSON(w, r, map[string]string{"command": "PONG", "from": s.params.Config.ServerName}, http.StatusOK)
|
||||
|
||||
func (s *Handlers) sendChannelMessage(
|
||||
w http.ResponseWriter, r *http.Request, uid int64, channel, content string,
|
||||
) {
|
||||
chID, err := s.lookupChannelID(r, channel)
|
||||
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)
|
||||
}
|
||||
|
||||
func (s *Handlers) sendDirectMessage(
|
||||
w http.ResponseWriter, r *http.Request, uid int64, toNick, content string,
|
||||
) {
|
||||
targetID, err := s.params.Database.LookupUserByNick(r.Context(), toNick)
|
||||
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)
|
||||
}
|
||||
|
||||
func (s *Handlers) handleJoinCommand(
|
||||
w http.ResponseWriter, r *http.Request, uid int64, cmd *sendCommand,
|
||||
) {
|
||||
if cmd.To == "" {
|
||||
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
channel := cmd.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) handlePartCommand(
|
||||
w http.ResponseWriter, r *http.Request, uid int64, cmd *sendCommand,
|
||||
) {
|
||||
if cmd.To == "" {
|
||||
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
channel := cmd.To
|
||||
if !strings.HasPrefix(channel, "#") {
|
||||
channel = "#" + channel
|
||||
}
|
||||
|
||||
chID, err := s.lookupChannelID(r, channel)
|
||||
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) handleNickCommand(
|
||||
w http.ResponseWriter, r *http.Request, uid int64, cmd *sendCommand,
|
||||
) {
|
||||
lines := bodyLines(cmd.Body)
|
||||
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) > maxNickLen {
|
||||
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
|
||||
default:
|
||||
_ = nick // suppress unused warning
|
||||
s.respondJSON(w, r, map[string]string{"error": "unknown command: " + req.Command}, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
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) handleTopicCommand(
|
||||
w http.ResponseWriter, r *http.Request, cmd *sendCommand,
|
||||
) {
|
||||
if cmd.To == "" {
|
||||
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
lines := bodyLines(cmd.Body)
|
||||
if len(lines) == 0 {
|
||||
s.respondJSON(w, r, map[string]string{"error": "body required (topic text)"}, http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
topic := strings.Join(lines, " ")
|
||||
|
||||
channel := cmd.To
|
||||
if !strings.HasPrefix(channel, "#") {
|
||||
channel = "#" + channel
|
||||
}
|
||||
|
||||
err := s.params.Database.SetTopic(r.Context(), channel, 0, 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).
|
||||
@@ -467,93 +340,57 @@ 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)
|
||||
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
if limit <= 0 {
|
||||
limit = defaultHistoryLimit
|
||||
limit = 50
|
||||
}
|
||||
|
||||
if strings.HasPrefix(target, "#") {
|
||||
s.handleChannelHistory(w, r, target, beforeID, limit)
|
||||
// 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 {
|
||||
s.handleDMHistory(w, r, uid, target, beforeID, limit)
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const defaultHistoryLimit = 50
|
||||
|
||||
func (s *Handlers) handleChannelHistory(
|
||||
w http.ResponseWriter, r *http.Request,
|
||||
target string, beforeID int64, limit int,
|
||||
) {
|
||||
chID, err := s.lookupChannelID(r, target)
|
||||
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)
|
||||
}
|
||||
|
||||
func (s *Handlers) handleDMHistory(
|
||||
w http.ResponseWriter, r *http.Request,
|
||||
uid int64, target string, beforeID int64, limit int,
|
||||
) {
|
||||
targetID, err := s.params.Database.LookupUserByNick(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)
|
||||
}
|
||||
|
||||
// lookupChannelID queries the channel ID by name using a parameterized query.
|
||||
func (s *Handlers) lookupChannelID(r *http.Request, name string) (int64, error) {
|
||||
var chID int64
|
||||
|
||||
//nolint:gosec // query uses parameterized placeholder (?), not string interpolation
|
||||
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
|
||||
"SELECT id FROM channels WHERE name = ?", name).Scan(&chID)
|
||||
|
||||
return chID, err
|
||||
}
|
||||
|
||||
// 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,
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrUserLookupNotAvailable is returned when user lookup is not configured.
|
||||
var ErrUserLookupNotAvailable = errors.New("user lookup not available")
|
||||
|
||||
// AuthToken represents an authentication token for a user session.
|
||||
type AuthToken struct {
|
||||
Base
|
||||
|
||||
Token string `json:"-"`
|
||||
UserID string `json:"userId"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
|
||||
LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
|
||||
}
|
||||
|
||||
// User returns the user who owns this token.
|
||||
func (t *AuthToken) User(ctx context.Context) (*User, error) {
|
||||
return t.LookupUser(ctx, t.UserID)
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -9,88 +8,10 @@ import (
|
||||
type Channel struct {
|
||||
Base
|
||||
|
||||
ID string `json:"id"`
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Topic string `json:"topic"`
|
||||
Modes string `json:"modes"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// Members returns all users who are members of this channel.
|
||||
func (c *Channel) Members(ctx context.Context) ([]*ChannelMember, error) {
|
||||
rows, err := c.GetDB().QueryContext(ctx, `
|
||||
SELECT cm.channel_id, cm.user_id, cm.modes, cm.joined_at,
|
||||
u.nick
|
||||
FROM channel_members cm
|
||||
JOIN users u ON u.id = cm.user_id
|
||||
WHERE cm.channel_id = ?
|
||||
ORDER BY cm.joined_at`,
|
||||
c.ID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
members := []*ChannelMember{}
|
||||
|
||||
for rows.Next() {
|
||||
m := &ChannelMember{}
|
||||
m.SetDB(c.db)
|
||||
|
||||
err = rows.Scan(
|
||||
&m.ChannelID, &m.UserID, &m.Modes,
|
||||
&m.JoinedAt, &m.Nick,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
members = append(members, m)
|
||||
}
|
||||
|
||||
return members, rows.Err()
|
||||
}
|
||||
|
||||
// RecentMessages returns the most recent messages in this channel.
|
||||
func (c *Channel) RecentMessages(
|
||||
ctx context.Context,
|
||||
limit int,
|
||||
) ([]*Message, error) {
|
||||
rows, err := c.GetDB().QueryContext(ctx, `
|
||||
SELECT id, ts, from_user_id, from_nick,
|
||||
target, type, body, meta, created_at
|
||||
FROM messages
|
||||
WHERE target = ?
|
||||
ORDER BY ts DESC
|
||||
LIMIT ?`,
|
||||
c.Name, limit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
messages := []*Message{}
|
||||
|
||||
for rows.Next() {
|
||||
msg := &Message{}
|
||||
msg.SetDB(c.db)
|
||||
|
||||
err = rows.Scan(
|
||||
&msg.ID, &msg.Timestamp, &msg.FromUserID,
|
||||
&msg.FromNick, &msg.Target, &msg.Type,
|
||||
&msg.Body, &msg.Meta, &msg.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
messages = append(messages, msg)
|
||||
}
|
||||
|
||||
return messages, rows.Err()
|
||||
}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrChannelLookupNotAvailable is returned when channel lookup is not configured.
|
||||
var ErrChannelLookupNotAvailable = errors.New("channel lookup not available")
|
||||
|
||||
// ChannelMember represents a user's membership in a channel.
|
||||
type ChannelMember struct {
|
||||
Base
|
||||
|
||||
ChannelID string `json:"channelId"`
|
||||
UserID string `json:"userId"`
|
||||
Modes string `json:"modes"`
|
||||
JoinedAt time.Time `json:"joinedAt"`
|
||||
Nick string `json:"nick"` // denormalized from users table
|
||||
}
|
||||
|
||||
// User returns the full User for this membership.
|
||||
func (cm *ChannelMember) User(ctx context.Context) (*User, error) {
|
||||
return cm.LookupUser(ctx, cm.UserID)
|
||||
}
|
||||
|
||||
// Channel returns the full Channel for this membership.
|
||||
func (cm *ChannelMember) Channel(ctx context.Context) (*Channel, error) {
|
||||
return cm.LookupChannel(ctx, cm.ChannelID)
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Message represents a chat message (channel or DM).
|
||||
type Message struct {
|
||||
Base
|
||||
|
||||
ID string `json:"id"`
|
||||
Timestamp time.Time `json:"ts"`
|
||||
FromUserID string `json:"fromUserId"`
|
||||
FromNick string `json:"from"`
|
||||
Target string `json:"to"`
|
||||
Type string `json:"type"`
|
||||
Body string `json:"body"`
|
||||
Meta string `json:"meta"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// MessageQueueEntry represents a pending message delivery for a user.
|
||||
type MessageQueueEntry struct {
|
||||
Base
|
||||
|
||||
ID int64 `json:"id"`
|
||||
UserID string `json:"userId"`
|
||||
MessageID string `json:"messageId"`
|
||||
QueuedAt time.Time `json:"queuedAt"`
|
||||
}
|
||||
@@ -1,29 +1,14 @@
|
||||
// Package models defines the data models used by the chat application.
|
||||
// All model structs embed Base, which provides database access for
|
||||
// relation-fetching methods directly on model instances.
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
import "database/sql"
|
||||
|
||||
// DB is the interface that models use to query the database.
|
||||
// DB is the interface that models use to query relations.
|
||||
// This avoids a circular import with the db package.
|
||||
type DB interface {
|
||||
GetDB() *sql.DB
|
||||
}
|
||||
|
||||
// UserLookup provides user lookup by ID without circular imports.
|
||||
type UserLookup interface {
|
||||
GetUserByID(ctx context.Context, id string) (*User, error)
|
||||
}
|
||||
|
||||
// ChannelLookup provides channel lookup by ID without circular imports.
|
||||
type ChannelLookup interface {
|
||||
GetChannelByID(ctx context.Context, id string) (*Channel, error)
|
||||
}
|
||||
|
||||
// Base is embedded in all model structs to provide database access.
|
||||
type Base struct {
|
||||
db DB
|
||||
@@ -33,28 +18,3 @@ type Base struct {
|
||||
func (b *Base) SetDB(d DB) {
|
||||
b.db = d
|
||||
}
|
||||
|
||||
// GetDB returns the database interface for use in model methods.
|
||||
func (b *Base) GetDB() *sql.DB {
|
||||
return b.db.GetDB()
|
||||
}
|
||||
|
||||
// LookupUser looks up a user by ID if the database supports it.
|
||||
func (b *Base) LookupUser(ctx context.Context, id string) (*User, error) {
|
||||
ul, ok := b.db.(UserLookup)
|
||||
if !ok {
|
||||
return nil, ErrUserLookupNotAvailable
|
||||
}
|
||||
|
||||
return ul.GetUserByID(ctx, id)
|
||||
}
|
||||
|
||||
// LookupChannel looks up a channel by ID if the database supports it.
|
||||
func (b *Base) LookupChannel(ctx context.Context, id string) (*Channel, error) {
|
||||
cl, ok := b.db.(ChannelLookup)
|
||||
if !ok {
|
||||
return nil, ErrChannelLookupNotAvailable
|
||||
}
|
||||
|
||||
return cl.GetChannelByID(ctx, id)
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// ServerLink represents a federation peer server configuration.
|
||||
type ServerLink struct {
|
||||
Base
|
||||
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
SharedKeyHash string `json:"-"`
|
||||
IsActive bool `json:"isActive"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
LastSeenAt *time.Time `json:"lastSeenAt,omitempty"`
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Session represents a server-held user session.
|
||||
type Session struct {
|
||||
Base
|
||||
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"userId"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
LastActiveAt time.Time `json:"lastActiveAt"`
|
||||
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
|
||||
}
|
||||
|
||||
// User returns the user who owns this session.
|
||||
func (s *Session) User(ctx context.Context) (*User, error) {
|
||||
return s.LookupUser(ctx, s.UserID)
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// User represents a registered user account.
|
||||
type User struct {
|
||||
Base
|
||||
|
||||
ID string `json:"id"`
|
||||
Nick string `json:"nick"`
|
||||
PasswordHash string `json:"-"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
LastSeenAt *time.Time `json:"lastSeenAt,omitempty"`
|
||||
}
|
||||
|
||||
// Channels returns all channels the user is a member of.
|
||||
func (u *User) Channels(ctx context.Context) ([]*Channel, error) {
|
||||
rows, err := u.GetDB().QueryContext(ctx, `
|
||||
SELECT c.id, c.name, c.topic, c.modes, c.created_at, c.updated_at
|
||||
FROM channels c
|
||||
JOIN channel_members cm ON cm.channel_id = c.id
|
||||
WHERE cm.user_id = ?
|
||||
ORDER BY c.name`,
|
||||
u.ID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
channels := []*Channel{}
|
||||
|
||||
for rows.Next() {
|
||||
c := &Channel{}
|
||||
c.SetDB(u.db)
|
||||
|
||||
err = rows.Scan(
|
||||
&c.ID, &c.Name, &c.Topic, &c.Modes,
|
||||
&c.CreatedAt, &c.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
channels = append(channels, c)
|
||||
}
|
||||
|
||||
return channels, rows.Err()
|
||||
}
|
||||
|
||||
// QueuedMessages returns undelivered messages for this user.
|
||||
func (u *User) QueuedMessages(ctx context.Context) ([]*Message, error) {
|
||||
rows, err := u.GetDB().QueryContext(ctx, `
|
||||
SELECT m.id, m.ts, m.from_user_id, m.from_nick,
|
||||
m.target, m.type, m.body, m.meta, m.created_at
|
||||
FROM messages m
|
||||
JOIN message_queue mq ON mq.message_id = m.id
|
||||
WHERE mq.user_id = ?
|
||||
ORDER BY mq.queued_at ASC`,
|
||||
u.ID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
messages := []*Message{}
|
||||
|
||||
for rows.Next() {
|
||||
msg := &Message{}
|
||||
msg.SetDB(u.db)
|
||||
|
||||
err = rows.Scan(
|
||||
&msg.ID, &msg.Timestamp, &msg.FromUserID,
|
||||
&msg.FromNick, &msg.Target, &msg.Type,
|
||||
&msg.Body, &msg.Meta, &msg.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
messages = append(messages, msg)
|
||||
}
|
||||
|
||||
return messages, rows.Err()
|
||||
}
|
||||
@@ -20,13 +20,6 @@ const routeTimeout = 60 * time.Second
|
||||
func (s *Server) SetupRoutes() {
|
||||
s.router = chi.NewRouter()
|
||||
|
||||
s.setupMiddleware()
|
||||
s.setupHealthAndMetrics()
|
||||
s.setupAPIRoutes()
|
||||
s.setupSPA()
|
||||
}
|
||||
|
||||
func (s *Server) setupMiddleware() {
|
||||
s.router.Use(middleware.Recoverer)
|
||||
s.router.Use(middleware.RequestID)
|
||||
s.router.Use(s.mw.Logging())
|
||||
@@ -44,63 +37,51 @@ func (s *Server) setupMiddleware() {
|
||||
})
|
||||
s.router.Use(sentryHandler.Handle)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) setupHealthAndMetrics() {
|
||||
// Health check
|
||||
s.router.Get("/.well-known/healthcheck.json", s.h.HandleHealthCheck())
|
||||
|
||||
// Protected metrics endpoint
|
||||
if viper.GetString("METRICS_USERNAME") != "" {
|
||||
s.router.Group(func(r chi.Router) {
|
||||
r.Use(s.mw.MetricsAuth())
|
||||
r.Get("/metrics", http.HandlerFunc(promhttp.Handler().ServeHTTP))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) setupAPIRoutes() {
|
||||
// API v1
|
||||
s.router.Route("/api/v1", func(r chi.Router) {
|
||||
r.Get("/server", s.h.HandleServerInfo())
|
||||
r.Post("/session", s.h.HandleCreateSession())
|
||||
|
||||
// Unified state and message endpoints
|
||||
r.Get("/state", s.h.HandleState())
|
||||
r.Get("/messages", s.h.HandleGetMessages())
|
||||
r.Post("/messages", s.h.HandleSendCommand())
|
||||
r.Get("/history", s.h.HandleGetHistory())
|
||||
|
||||
// Channels
|
||||
r.Get("/channels", s.h.HandleListAllChannels())
|
||||
r.Get("/channels/{channel}/members", s.h.HandleChannelMembers())
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) setupSPA() {
|
||||
// Serve embedded SPA
|
||||
distFS, err := fs.Sub(web.Dist, "dist")
|
||||
if err != nil {
|
||||
s.log.Error("failed to get web dist filesystem", "error", err)
|
||||
|
||||
return
|
||||
} 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)
|
||||
})
|
||||
}
|
||||
|
||||
fileServer := http.FileServer(http.FS(distFS))
|
||||
|
||||
s.router.Get("/*", func(w http.ResponseWriter, r *http.Request) {
|
||||
readFS, ok := distFS.(fs.ReadFileFS)
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
f, readErr := readFS.ReadFile(r.URL.Path[1:])
|
||||
if readErr != 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)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user