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 api
|
||||||
package chatapi
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
|
||||||
"time"
|
"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.
|
// Client wraps HTTP calls to the chat server API.
|
||||||
type Client struct {
|
type Client struct {
|
||||||
BaseURL string
|
BaseURL string
|
||||||
@@ -38,27 +22,59 @@ func NewClient(baseURL string) *Client {
|
|||||||
return &Client{
|
return &Client{
|
||||||
BaseURL: baseURL,
|
BaseURL: baseURL,
|
||||||
HTTPClient: &http.Client{
|
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.
|
// CreateSession creates a new session on the server.
|
||||||
func (c *Client) CreateSession(nick string) (*SessionResponse, error) {
|
func (c *Client) CreateSession(nick string) (*SessionResponse, error) {
|
||||||
data, err := c.do("POST", "/api/v1/session", &SessionRequest{Nick: nick})
|
data, err := c.do("POST", "/api/v1/session", &SessionRequest{Nick: nick})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var resp SessionResponse
|
var resp SessionResponse
|
||||||
|
if err := json.Unmarshal(data, &resp); err != nil {
|
||||||
err = json.Unmarshal(data, &resp)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("decode session: %w", err)
|
return nil, fmt.Errorf("decode session: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Token = resp.Token
|
c.Token = resp.Token
|
||||||
|
|
||||||
return &resp, nil
|
return &resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,77 +84,64 @@ func (c *Client) GetState() (*StateResponse, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var resp StateResponse
|
var resp StateResponse
|
||||||
|
if err := json.Unmarshal(data, &resp); err != nil {
|
||||||
err = json.Unmarshal(data, &resp)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("decode state: %w", err)
|
return nil, fmt.Errorf("decode state: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &resp, nil
|
return &resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendMessage sends a message (any IRC command).
|
// SendMessage sends a message (any IRC command).
|
||||||
func (c *Client) SendMessage(msg *Message) error {
|
func (c *Client) SendMessage(msg *Message) error {
|
||||||
_, err := c.do("POST", "/api/v1/messages", msg)
|
_, err := c.do("POST", "/api/v1/messages", msg)
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// PollMessages long-polls for new messages.
|
// PollMessages long-polls for new messages.
|
||||||
func (c *Client) PollMessages(afterID string, timeout int) ([]Message, error) {
|
func (c *Client) PollMessages(afterID string, timeout int) ([]Message, error) {
|
||||||
// Use a longer HTTP timeout than the server long-poll timeout.
|
// 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{}
|
params := url.Values{}
|
||||||
if afterID != "" {
|
if afterID != "" {
|
||||||
params.Set("after", afterID)
|
params.Set("after", afterID)
|
||||||
}
|
}
|
||||||
|
params.Set("timeout", fmt.Sprintf("%d", timeout))
|
||||||
params.Set("timeout", strconv.Itoa(timeout))
|
|
||||||
|
|
||||||
path := "/api/v1/messages"
|
path := "/api/v1/messages"
|
||||||
if len(params) > 0 {
|
if len(params) > 0 {
|
||||||
path += "?" + params.Encode()
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||||
|
|
||||||
resp, err := client.Do(req) //nolint:gosec // URL is constructed from trusted base URL + API path, not user-tainted
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
defer func() { _ = resp.Body.Close() }()
|
|
||||||
|
|
||||||
data, err := io.ReadAll(resp.Body)
|
data, err := io.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode >= httpErrorMinCode {
|
if resp.StatusCode >= 400 {
|
||||||
return nil, fmt.Errorf("%w: %d: %s", ErrHTTPError, resp.StatusCode, string(data))
|
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(data))
|
||||||
}
|
}
|
||||||
|
|
||||||
// The server may return an array directly or wrapped.
|
// The server may return an array directly or wrapped.
|
||||||
var msgs []Message
|
var msgs []Message
|
||||||
|
if err := json.Unmarshal(data, &msgs); err != nil {
|
||||||
err = json.Unmarshal(data, &msgs)
|
|
||||||
if err != nil {
|
|
||||||
// Try wrapped format.
|
// Try wrapped format.
|
||||||
var wrapped MessagesResponse
|
var wrapped MessagesResponse
|
||||||
|
if err2 := json.Unmarshal(data, &wrapped); err2 != nil {
|
||||||
err2 := json.Unmarshal(data, &wrapped)
|
|
||||||
if err2 != nil {
|
|
||||||
return nil, fmt.Errorf("decode messages: %w (raw: %s)", err, string(data))
|
return nil, fmt.Errorf("decode messages: %w (raw: %s)", err, string(data))
|
||||||
}
|
}
|
||||||
|
|
||||||
msgs = wrapped.Messages
|
msgs = wrapped.Messages
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,14 +164,10 @@ func (c *Client) ListChannels() ([]Channel, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var channels []Channel
|
var channels []Channel
|
||||||
|
if err := json.Unmarshal(data, &channels); err != nil {
|
||||||
err = json.Unmarshal(data, &channels)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return channels, nil
|
return channels, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,23 +177,16 @@ func (c *Client) GetMembers(channel string) ([]string, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var members []string
|
var members []string
|
||||||
|
if err := json.Unmarshal(data, &members); err != nil {
|
||||||
err = json.Unmarshal(data, &members)
|
|
||||||
if err != nil {
|
|
||||||
// Try object format.
|
// Try object format.
|
||||||
var obj map[string]any
|
var obj map[string]interface{}
|
||||||
|
if err2 := json.Unmarshal(data, &obj); err2 != nil {
|
||||||
err2 := json.Unmarshal(data, &obj)
|
|
||||||
if err2 != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract member names from whatever format.
|
// 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
|
return members, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,56 +196,9 @@ func (c *Client) GetServerInfo() (*ServerInfo, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var info ServerInfo
|
var info ServerInfo
|
||||||
|
if err := json.Unmarshal(data, &info); err != nil {
|
||||||
err = json.Unmarshal(data, &info)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return &info, nil
|
return &info, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) do(method, path string, body any) ([]byte, error) {
|
|
||||||
var bodyReader io.Reader
|
|
||||||
|
|
||||||
if body != nil {
|
|
||||||
data, err := json.Marshal(body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("marshal: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
bodyReader = bytes.NewReader(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.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"
|
import "time"
|
||||||
|
|
||||||
@@ -9,44 +9,42 @@ type SessionRequest struct {
|
|||||||
|
|
||||||
// SessionResponse is the response from POST /api/v1/session.
|
// SessionResponse is the response from POST /api/v1/session.
|
||||||
type SessionResponse struct {
|
type SessionResponse struct {
|
||||||
SessionID string `json:"sessionId"`
|
SessionID string `json:"session_id"`
|
||||||
ClientID string `json:"clientId"`
|
ClientID string `json:"client_id"`
|
||||||
Nick string `json:"nick"`
|
Nick string `json:"nick"`
|
||||||
Token string `json:"token"`
|
Token string `json:"token"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StateResponse is the response from GET /api/v1/state.
|
// StateResponse is the response from GET /api/v1/state.
|
||||||
type StateResponse struct {
|
type StateResponse struct {
|
||||||
SessionID string `json:"sessionId"`
|
SessionID string `json:"session_id"`
|
||||||
ClientID string `json:"clientId"`
|
ClientID string `json:"client_id"`
|
||||||
Nick string `json:"nick"`
|
Nick string `json:"nick"`
|
||||||
Channels []string `json:"channels"`
|
Channels []string `json:"channels"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Message represents a chat message envelope.
|
// Message represents a chat message envelope.
|
||||||
type Message struct {
|
type Message struct {
|
||||||
Command string `json:"command"`
|
Command string `json:"command"`
|
||||||
From string `json:"from,omitempty"`
|
From string `json:"from,omitempty"`
|
||||||
To string `json:"to,omitempty"`
|
To string `json:"to,omitempty"`
|
||||||
Params []string `json:"params,omitempty"`
|
Params []string `json:"params,omitempty"`
|
||||||
Body any `json:"body,omitempty"`
|
Body interface{} `json:"body,omitempty"`
|
||||||
ID string `json:"id,omitempty"`
|
ID string `json:"id,omitempty"`
|
||||||
TS string `json:"ts,omitempty"`
|
TS string `json:"ts,omitempty"`
|
||||||
Meta any `json:"meta,omitempty"`
|
Meta interface{} `json:"meta,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// BodyLines returns the body as a slice of strings (for text messages).
|
// BodyLines returns the body as a slice of strings (for text messages).
|
||||||
func (m *Message) BodyLines() []string {
|
func (m *Message) BodyLines() []string {
|
||||||
switch v := m.Body.(type) {
|
switch v := m.Body.(type) {
|
||||||
case []any:
|
case []interface{}:
|
||||||
lines := make([]string, 0, len(v))
|
lines := make([]string, 0, len(v))
|
||||||
|
|
||||||
for _, item := range v {
|
for _, item := range v {
|
||||||
if s, ok := item.(string); ok {
|
if s, ok := item.(string); ok {
|
||||||
lines = append(lines, s)
|
lines = append(lines, s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return lines
|
return lines
|
||||||
case []string:
|
case []string:
|
||||||
return v
|
return v
|
||||||
@@ -60,7 +58,7 @@ type Channel struct {
|
|||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Topic string `json:"topic"`
|
Topic string `json:"topic"`
|
||||||
Members int `json:"members"`
|
Members int `json:"members"`
|
||||||
CreatedAt string `json:"createdAt"`
|
CreatedAt string `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServerInfo is the response from GET /api/v1/server.
|
// ServerInfo is the response from GET /api/v1/server.
|
||||||
@@ -81,6 +79,5 @@ func (m *Message) ParseTS() time.Time {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return time.Now()
|
return time.Now()
|
||||||
}
|
}
|
||||||
|
|
||||||
return t
|
return t
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
// Package main provides a terminal-based IRC-style chat client.
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -11,18 +10,10 @@ import (
|
|||||||
"git.eeqj.de/sneak/chat/cmd/chat-cli/api"
|
"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.
|
// App holds the application state.
|
||||||
type App struct {
|
type App struct {
|
||||||
ui *UI
|
ui *UI
|
||||||
client *chatapi.Client
|
client *api.Client
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
nick string
|
nick string
|
||||||
@@ -44,8 +35,7 @@ func main() {
|
|||||||
app.ui.AddStatus("Welcome to chat-cli — an IRC-style client")
|
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")
|
app.ui.AddStatus("Type [yellow]/connect <server-url>[white] to begin, or [yellow]/help[white] for commands")
|
||||||
|
|
||||||
err := app.ui.Run()
|
if err := app.ui.Run(); err != nil {
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
@@ -54,7 +44,6 @@ func main() {
|
|||||||
func (a *App) handleInput(text string) {
|
func (a *App) handleInput(text string) {
|
||||||
if strings.HasPrefix(text, "/") {
|
if strings.HasPrefix(text, "/") {
|
||||||
a.handleCommand(text)
|
a.handleCommand(text)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,95 +55,74 @@ func (a *App) handleInput(text string) {
|
|||||||
|
|
||||||
if !connected {
|
if !connected {
|
||||||
a.ui.AddStatus("[red]Not connected. Use /connect <url>")
|
a.ui.AddStatus("[red]Not connected. Use /connect <url>")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if target == "" {
|
if target == "" {
|
||||||
a.ui.AddStatus("[red]No target. Use /join #channel or /query nick")
|
a.ui.AddStatus("[red]No target. Use /join #channel or /query nick")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err := a.client.SendMessage(&chatapi.Message{
|
err := a.client.SendMessage(&api.Message{
|
||||||
Command: "PRIVMSG",
|
Command: "PRIVMSG",
|
||||||
To: target,
|
To: target,
|
||||||
Body: []string{text},
|
Body: []string{text},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(fmt.Sprintf("[red]Send error: %v", err))
|
a.ui.AddStatus(fmt.Sprintf("[red]Send error: %v", err))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Echo locally.
|
// Echo locally.
|
||||||
ts := time.Now().Format("15:04")
|
ts := time.Now().Format("15:04")
|
||||||
|
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
nick := a.nick
|
nick := a.nick
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
a.ui.AddLine(target, fmt.Sprintf("[gray]%s [green]<%s>[white] %s", ts, nick, text))
|
a.ui.AddLine(target, fmt.Sprintf("[gray]%s [green]<%s>[white] %s", ts, nick, text))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) handleCommand(text string) {
|
func (a *App) handleCommand(text string) {
|
||||||
a.dispatchCommand(text)
|
parts := strings.SplitN(text, " ", 2)
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) dispatchCommand(text string) {
|
|
||||||
parts := strings.SplitN(text, " ", splitNParts)
|
|
||||||
cmd := strings.ToLower(parts[0])
|
cmd := strings.ToLower(parts[0])
|
||||||
|
|
||||||
args := ""
|
args := ""
|
||||||
if len(parts) > 1 {
|
if len(parts) > 1 {
|
||||||
args = parts[1]
|
args = parts[1]
|
||||||
}
|
}
|
||||||
|
|
||||||
a.execCommand(cmd, args)
|
switch cmd {
|
||||||
}
|
case "/connect":
|
||||||
|
a.cmdConnect(args)
|
||||||
func (a *App) execCommand(cmd, args string) {
|
case "/nick":
|
||||||
commands := a.commandMap()
|
a.cmdNick(args)
|
||||||
|
case "/join":
|
||||||
handler, ok := commands[cmd]
|
a.cmdJoin(args)
|
||||||
if !ok {
|
case "/part":
|
||||||
a.ui.AddStatus("[red]Unknown command: " + cmd)
|
a.cmdPart(args)
|
||||||
|
case "/msg":
|
||||||
return
|
a.cmdMsg(args)
|
||||||
}
|
case "/query":
|
||||||
|
a.cmdQuery(args)
|
||||||
handler(args)
|
case "/topic":
|
||||||
}
|
a.cmdTopic(args)
|
||||||
|
case "/names":
|
||||||
func (a *App) commandMap() map[string]func(string) {
|
a.cmdNames()
|
||||||
noArgs := func(fn func()) func(string) {
|
case "/list":
|
||||||
return func(_ string) { fn() }
|
a.cmdList()
|
||||||
}
|
case "/window", "/w":
|
||||||
|
a.cmdWindow(args)
|
||||||
return map[string]func(string){
|
case "/quit":
|
||||||
"/connect": a.cmdConnect,
|
a.cmdQuit()
|
||||||
"/nick": a.cmdNick,
|
case "/help":
|
||||||
"/join": a.cmdJoin,
|
a.cmdHelp()
|
||||||
"/part": a.cmdPart,
|
default:
|
||||||
"/msg": a.cmdMsg,
|
a.ui.AddStatus(fmt.Sprintf("[red]Unknown command: %s", cmd))
|
||||||
"/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),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) cmdConnect(serverURL string) {
|
func (a *App) cmdConnect(serverURL string) {
|
||||||
if serverURL == "" {
|
if serverURL == "" {
|
||||||
a.ui.AddStatus("[red]Usage: /connect <server-url>")
|
a.ui.AddStatus("[red]Usage: /connect <server-url>")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
serverURL = strings.TrimRight(serverURL, "/")
|
serverURL = strings.TrimRight(serverURL, "/")
|
||||||
|
|
||||||
a.ui.AddStatus(fmt.Sprintf("Connecting to %s...", serverURL))
|
a.ui.AddStatus(fmt.Sprintf("Connecting to %s...", serverURL))
|
||||||
@@ -163,12 +131,10 @@ func (a *App) cmdConnect(serverURL string) {
|
|||||||
nick := a.nick
|
nick := a.nick
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
client := chatapi.NewClient(serverURL)
|
client := api.NewClient(serverURL)
|
||||||
|
|
||||||
resp, err := client.CreateSession(nick)
|
resp, err := client.CreateSession(nick)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(fmt.Sprintf("[red]Connection failed: %v", err))
|
a.ui.AddStatus(fmt.Sprintf("[red]Connection failed: %v", err))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,17 +150,14 @@ func (a *App) cmdConnect(serverURL string) {
|
|||||||
|
|
||||||
// Start polling.
|
// Start polling.
|
||||||
a.stopPoll = make(chan struct{})
|
a.stopPoll = make(chan struct{})
|
||||||
|
|
||||||
go a.pollLoop()
|
go a.pollLoop()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) cmdNick(nick string) {
|
func (a *App) cmdNick(nick string) {
|
||||||
if nick == "" {
|
if nick == "" {
|
||||||
a.ui.AddStatus("[red]Usage: /nick <name>")
|
a.ui.AddStatus("[red]Usage: /nick <name>")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
connected := a.connected
|
connected := a.connected
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
@@ -203,19 +166,16 @@ func (a *App) cmdNick(nick string) {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
a.nick = nick
|
a.nick = nick
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
a.ui.AddStatus(fmt.Sprintf("Nick set to %s (will be used on connect)", nick))
|
a.ui.AddStatus(fmt.Sprintf("Nick set to %s (will be used on connect)", nick))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err := a.client.SendMessage(&chatapi.Message{
|
err := a.client.SendMessage(&api.Message{
|
||||||
Command: "NICK",
|
Command: "NICK",
|
||||||
Body: []string{nick},
|
Body: []string{nick},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(fmt.Sprintf("[red]Nick change failed: %v", err))
|
a.ui.AddStatus(fmt.Sprintf("[red]Nick change failed: %v", err))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,18 +183,15 @@ func (a *App) cmdNick(nick string) {
|
|||||||
a.nick = nick
|
a.nick = nick
|
||||||
target := a.target
|
target := a.target
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
a.ui.SetStatus(nick, target, "connected")
|
a.ui.SetStatus(nick, target, "connected")
|
||||||
a.ui.AddStatus("Nick changed to " + nick)
|
a.ui.AddStatus(fmt.Sprintf("Nick changed to %s", nick))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) cmdJoin(channel string) {
|
func (a *App) cmdJoin(channel string) {
|
||||||
if channel == "" {
|
if channel == "" {
|
||||||
a.ui.AddStatus("[red]Usage: /join #channel")
|
a.ui.AddStatus("[red]Usage: /join #channel")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !strings.HasPrefix(channel, "#") {
|
if !strings.HasPrefix(channel, "#") {
|
||||||
channel = "#" + channel
|
channel = "#" + channel
|
||||||
}
|
}
|
||||||
@@ -242,17 +199,14 @@ func (a *App) cmdJoin(channel string) {
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
connected := a.connected
|
connected := a.connected
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
if !connected {
|
if !connected {
|
||||||
a.ui.AddStatus("[red]Not connected")
|
a.ui.AddStatus("[red]Not connected")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err := a.client.JoinChannel(channel)
|
err := a.client.JoinChannel(channel)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(fmt.Sprintf("[red]Join failed: %v", err))
|
a.ui.AddStatus(fmt.Sprintf("[red]Join failed: %v", err))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,47 +216,39 @@ func (a *App) cmdJoin(channel string) {
|
|||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
a.ui.SwitchToBuffer(channel)
|
a.ui.SwitchToBuffer(channel)
|
||||||
a.ui.AddLine(channel, "[yellow]*** Joined "+channel)
|
a.ui.AddLine(channel, fmt.Sprintf("[yellow]*** Joined %s", channel))
|
||||||
a.ui.SetStatus(nick, channel, "connected")
|
a.ui.SetStatus(nick, channel, "connected")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) cmdPart(channel string) {
|
func (a *App) cmdPart(channel string) {
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
|
|
||||||
if channel == "" {
|
if channel == "" {
|
||||||
channel = a.target
|
channel = a.target
|
||||||
}
|
}
|
||||||
|
|
||||||
connected := a.connected
|
connected := a.connected
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
if channel == "" || !strings.HasPrefix(channel, "#") {
|
if channel == "" || !strings.HasPrefix(channel, "#") {
|
||||||
a.ui.AddStatus("[red]No channel to part")
|
a.ui.AddStatus("[red]No channel to part")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !connected {
|
if !connected {
|
||||||
a.ui.AddStatus("[red]Not connected")
|
a.ui.AddStatus("[red]Not connected")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err := a.client.PartChannel(channel)
|
err := a.client.PartChannel(channel)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(fmt.Sprintf("[red]Part failed: %v", err))
|
a.ui.AddStatus(fmt.Sprintf("[red]Part failed: %v", err))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
a.ui.AddLine(channel, "[yellow]*** Left "+channel)
|
a.ui.AddLine(channel, fmt.Sprintf("[yellow]*** Left %s", channel))
|
||||||
|
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
|
|
||||||
if a.target == channel {
|
if a.target == channel {
|
||||||
a.target = ""
|
a.target = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
nick := a.nick
|
nick := a.nick
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
@@ -311,35 +257,29 @@ func (a *App) cmdPart(channel string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) cmdMsg(args string) {
|
func (a *App) cmdMsg(args string) {
|
||||||
parts := strings.SplitN(args, " ", commandSplitArgs)
|
parts := strings.SplitN(args, " ", 2)
|
||||||
|
if len(parts) < 2 {
|
||||||
if len(parts) < commandSplitArgs {
|
|
||||||
a.ui.AddStatus("[red]Usage: /msg <nick> <text>")
|
a.ui.AddStatus("[red]Usage: /msg <nick> <text>")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
target, text := parts[0], parts[1]
|
target, text := parts[0], parts[1]
|
||||||
|
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
connected := a.connected
|
connected := a.connected
|
||||||
nick := a.nick
|
nick := a.nick
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
if !connected {
|
if !connected {
|
||||||
a.ui.AddStatus("[red]Not connected")
|
a.ui.AddStatus("[red]Not connected")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err := a.client.SendMessage(&chatapi.Message{
|
err := a.client.SendMessage(&api.Message{
|
||||||
Command: "PRIVMSG",
|
Command: "PRIVMSG",
|
||||||
To: target,
|
To: target,
|
||||||
Body: []string{text},
|
Body: []string{text},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(fmt.Sprintf("[red]Send failed: %v", err))
|
a.ui.AddStatus(fmt.Sprintf("[red]Send failed: %v", err))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,7 +290,6 @@ func (a *App) cmdMsg(args string) {
|
|||||||
func (a *App) cmdQuery(nick string) {
|
func (a *App) cmdQuery(nick string) {
|
||||||
if nick == "" {
|
if nick == "" {
|
||||||
a.ui.AddStatus("[red]Usage: /query <nick>")
|
a.ui.AddStatus("[red]Usage: /query <nick>")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -371,30 +310,26 @@ func (a *App) cmdTopic(args string) {
|
|||||||
|
|
||||||
if !connected {
|
if !connected {
|
||||||
a.ui.AddStatus("[red]Not connected")
|
a.ui.AddStatus("[red]Not connected")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !strings.HasPrefix(target, "#") {
|
if !strings.HasPrefix(target, "#") {
|
||||||
a.ui.AddStatus("[red]Not in a channel")
|
a.ui.AddStatus("[red]Not in a channel")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if args == "" {
|
if args == "" {
|
||||||
// Query topic.
|
// Query topic.
|
||||||
err := a.client.SendMessage(&chatapi.Message{
|
err := a.client.SendMessage(&api.Message{
|
||||||
Command: "TOPIC",
|
Command: "TOPIC",
|
||||||
To: target,
|
To: target,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(fmt.Sprintf("[red]Topic query failed: %v", err))
|
a.ui.AddStatus(fmt.Sprintf("[red]Topic query failed: %v", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err := a.client.SendMessage(&chatapi.Message{
|
err := a.client.SendMessage(&api.Message{
|
||||||
Command: "TOPIC",
|
Command: "TOPIC",
|
||||||
To: target,
|
To: target,
|
||||||
Body: []string{args},
|
Body: []string{args},
|
||||||
@@ -412,20 +347,16 @@ func (a *App) cmdNames() {
|
|||||||
|
|
||||||
if !connected {
|
if !connected {
|
||||||
a.ui.AddStatus("[red]Not connected")
|
a.ui.AddStatus("[red]Not connected")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !strings.HasPrefix(target, "#") {
|
if !strings.HasPrefix(target, "#") {
|
||||||
a.ui.AddStatus("[red]Not in a channel")
|
a.ui.AddStatus("[red]Not in a channel")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
members, err := a.client.GetMembers(target)
|
members, err := a.client.GetMembers(target)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(fmt.Sprintf("[red]Names failed: %v", err))
|
a.ui.AddStatus(fmt.Sprintf("[red]Names failed: %v", err))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -439,51 +370,46 @@ func (a *App) cmdList() {
|
|||||||
|
|
||||||
if !connected {
|
if !connected {
|
||||||
a.ui.AddStatus("[red]Not connected")
|
a.ui.AddStatus("[red]Not connected")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
channels, err := a.client.ListChannels()
|
channels, err := a.client.ListChannels()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.ui.AddStatus(fmt.Sprintf("[red]List failed: %v", err))
|
a.ui.AddStatus(fmt.Sprintf("[red]List failed: %v", err))
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
a.ui.AddStatus("[cyan]*** Channel list:")
|
a.ui.AddStatus("[cyan]*** Channel list:")
|
||||||
|
|
||||||
for _, ch := range channels {
|
for _, ch := range channels {
|
||||||
a.ui.AddStatus(fmt.Sprintf(" %s (%d members) %s", ch.Name, ch.Members, ch.Topic))
|
a.ui.AddStatus(fmt.Sprintf(" %s (%d members) %s", ch.Name, ch.Members, ch.Topic))
|
||||||
}
|
}
|
||||||
|
|
||||||
a.ui.AddStatus("[cyan]*** End of channel list")
|
a.ui.AddStatus("[cyan]*** End of channel list")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) cmdWindow(args string) {
|
func (a *App) cmdWindow(args string) {
|
||||||
if args == "" {
|
if args == "" {
|
||||||
a.ui.AddStatus("[red]Usage: /window <number>")
|
a.ui.AddStatus("[red]Usage: /window <number>")
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
n := 0
|
n := 0
|
||||||
_, _ = fmt.Sscanf(args, "%d", &n)
|
fmt.Sscanf(args, "%d", &n)
|
||||||
|
|
||||||
a.ui.SwitchBuffer(n)
|
a.ui.SwitchBuffer(n)
|
||||||
|
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
|
if n < a.ui.BufferCount() && n >= 0 {
|
||||||
|
// Update target to the buffer name.
|
||||||
|
// Needs to be done carefully.
|
||||||
|
}
|
||||||
nick := a.nick
|
nick := a.nick
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
// Update target based on buffer.
|
// Update target based on buffer.
|
||||||
if n < a.ui.BufferCount() {
|
if n < a.ui.BufferCount() {
|
||||||
buf := a.ui.buffers[n]
|
buf := a.ui.buffers[n]
|
||||||
|
|
||||||
if buf.Name != "(status)" {
|
if buf.Name != "(status)" {
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
a.target = buf.Name
|
a.target = buf.Name
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
|
|
||||||
a.ui.SetStatus(nick, buf.Name, "connected")
|
a.ui.SetStatus(nick, buf.Name, "connected")
|
||||||
} else {
|
} else {
|
||||||
a.ui.SetStatus(nick, "", "connected")
|
a.ui.SetStatus(nick, "", "connected")
|
||||||
@@ -493,15 +419,12 @@ func (a *App) cmdWindow(args string) {
|
|||||||
|
|
||||||
func (a *App) cmdQuit() {
|
func (a *App) cmdQuit() {
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
|
|
||||||
if a.connected && a.client != nil {
|
if a.connected && a.client != nil {
|
||||||
_ = a.client.SendMessage(&chatapi.Message{Command: "QUIT"})
|
_ = a.client.SendMessage(&api.Message{Command: "QUIT"})
|
||||||
}
|
}
|
||||||
|
|
||||||
if a.stopPoll != nil {
|
if a.stopPoll != nil {
|
||||||
close(a.stopPoll)
|
close(a.stopPoll)
|
||||||
}
|
}
|
||||||
|
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
a.ui.Stop()
|
a.ui.Stop()
|
||||||
}
|
}
|
||||||
@@ -523,7 +446,6 @@ func (a *App) cmdHelp() {
|
|||||||
" /help — This help",
|
" /help — This help",
|
||||||
" Plain text sends to current target.",
|
" Plain text sends to current target.",
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, line := range help {
|
for _, line := range help {
|
||||||
a.ui.AddStatus(line)
|
a.ui.AddStatus(line)
|
||||||
}
|
}
|
||||||
@@ -547,17 +469,15 @@ func (a *App) pollLoop() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
msgs, err := client.PollMessages(lastID, pollTimeoutSec)
|
msgs, err := client.PollMessages(lastID, 15)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Transient error — retry after delay.
|
// Transient error — retry after delay.
|
||||||
time.Sleep(pollRetrySec * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, msg := range msgs {
|
for _, msg := range msgs {
|
||||||
a.handleServerMessage(&msg)
|
a.handleServerMessage(&msg)
|
||||||
|
|
||||||
if msg.ID != "" {
|
if msg.ID != "" {
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
a.lastMsgID = msg.ID
|
a.lastMsgID = msg.ID
|
||||||
@@ -567,8 +487,14 @@ func (a *App) pollLoop() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) handleServerMessage(msg *chatapi.Message) {
|
func (a *App) handleServerMessage(msg *api.Message) {
|
||||||
ts := a.formatMessageTS(msg)
|
ts := ""
|
||||||
|
if msg.TS != "" {
|
||||||
|
t := msg.ParseTS()
|
||||||
|
ts = t.Local().Format("15:04")
|
||||||
|
} else {
|
||||||
|
ts = time.Now().Format("15:04")
|
||||||
|
}
|
||||||
|
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
myNick := a.nick
|
myNick := a.nick
|
||||||
@@ -576,131 +502,79 @@ func (a *App) handleServerMessage(msg *chatapi.Message) {
|
|||||||
|
|
||||||
switch msg.Command {
|
switch msg.Command {
|
||||||
case "PRIVMSG":
|
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":
|
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":
|
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":
|
case "QUIT":
|
||||||
a.handleQuitMsg(msg, ts)
|
lines := msg.BodyLines()
|
||||||
case "NICK":
|
reason := strings.Join(lines, " ")
|
||||||
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 != "" {
|
|
||||||
if reason != "" {
|
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 {
|
} 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()
|
// Message area.
|
||||||
ui.setupInputCapture()
|
ui.messages = tview.NewTextView().
|
||||||
ui.setupLayout()
|
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
|
return ui
|
||||||
}
|
}
|
||||||
@@ -70,13 +121,12 @@ func (ui *UI) AddLine(bufferName string, line string) {
|
|||||||
// Mark unread if not currently viewing this buffer.
|
// Mark unread if not currently viewing this buffer.
|
||||||
if ui.buffers[ui.currentBuffer] != buf {
|
if ui.buffers[ui.currentBuffer] != buf {
|
||||||
buf.Unread++
|
buf.Unread++
|
||||||
|
|
||||||
ui.refreshStatus()
|
ui.refreshStatus()
|
||||||
}
|
}
|
||||||
|
|
||||||
// If viewing this buffer, append to display.
|
// If viewing this buffer, append to display.
|
||||||
if ui.buffers[ui.currentBuffer] == buf {
|
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) {
|
if n < 0 || n >= len(ui.buffers) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ui.currentBuffer = n
|
ui.currentBuffer = n
|
||||||
buf := ui.buffers[n]
|
buf := ui.buffers[n]
|
||||||
|
|
||||||
buf.Unread = 0
|
buf.Unread = 0
|
||||||
|
|
||||||
ui.messages.Clear()
|
ui.messages.Clear()
|
||||||
|
|
||||||
for _, line := range buf.Lines {
|
for _, line := range buf.Lines {
|
||||||
_, _ = fmt.Fprintln(ui.messages, line)
|
fmt.Fprintln(ui.messages, line)
|
||||||
}
|
}
|
||||||
|
|
||||||
ui.messages.ScrollToEnd()
|
ui.messages.ScrollToEnd()
|
||||||
ui.refreshStatus()
|
ui.refreshStatus()
|
||||||
})
|
})
|
||||||
@@ -114,23 +159,17 @@ func (ui *UI) SwitchBuffer(n int) {
|
|||||||
func (ui *UI) SwitchToBuffer(name string) {
|
func (ui *UI) SwitchToBuffer(name string) {
|
||||||
ui.app.QueueUpdateDraw(func() {
|
ui.app.QueueUpdateDraw(func() {
|
||||||
buf := ui.getOrCreateBuffer(name)
|
buf := ui.getOrCreateBuffer(name)
|
||||||
|
|
||||||
for i, b := range ui.buffers {
|
for i, b := range ui.buffers {
|
||||||
if b == buf {
|
if b == buf {
|
||||||
ui.currentBuffer = i
|
ui.currentBuffer = i
|
||||||
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
buf.Unread = 0
|
buf.Unread = 0
|
||||||
|
|
||||||
ui.messages.Clear()
|
ui.messages.Clear()
|
||||||
|
|
||||||
for _, line := range buf.Lines {
|
for _, line := range buf.Lines {
|
||||||
_, _ = fmt.Fprintln(ui.messages, line)
|
fmt.Fprintln(ui.messages, line)
|
||||||
}
|
}
|
||||||
|
|
||||||
ui.messages.ScrollToEnd()
|
ui.messages.ScrollToEnd()
|
||||||
ui.refreshStatus()
|
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.
|
// BufferCount returns the number of buffers.
|
||||||
func (ui *UI) BufferCount() int {
|
func (ui *UI) BufferCount() int {
|
||||||
return len(ui.buffers)
|
return len(ui.buffers)
|
||||||
@@ -155,106 +229,5 @@ func (ui *UI) BufferIndex(name string) int {
|
|||||||
return i
|
return i
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return -1
|
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
|
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.
|
// New creates a new Database instance and registers lifecycle hooks.
|
||||||
func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
||||||
s := new(Database)
|
s := new(Database)
|
||||||
@@ -74,460 +94,6 @@ func New(lc fx.Lifecycle, params Params) (*Database, error) {
|
|||||||
return s, nil
|
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 {
|
func (s *Database) connect(ctx context.Context) error {
|
||||||
dbURL := s.params.Config.DBURL
|
dbURL := s.params.Config.DBURL
|
||||||
if dbURL == "" {
|
if dbURL == "" {
|
||||||
@@ -553,12 +119,6 @@ func (s *Database) connect(ctx context.Context) error {
|
|||||||
s.db = d
|
s.db = d
|
||||||
s.log.Info("database connected")
|
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)
|
return s.runMigrations(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -589,18 +149,13 @@ func (s *Database) runMigrations(ctx context.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Database) bootstrapMigrationsTable(
|
func (s *Database) bootstrapMigrationsTable(ctx context.Context) error {
|
||||||
ctx context.Context,
|
_, err := s.db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
) error {
|
|
||||||
_, err := s.db.ExecContext(ctx,
|
|
||||||
`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
||||||
version INTEGER PRIMARY KEY,
|
version INTEGER PRIMARY KEY,
|
||||||
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
)`)
|
)`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf(
|
return fmt.Errorf("failed to create schema_migrations table: %w", err)
|
||||||
"create schema_migrations table: %w", err,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -609,20 +164,17 @@ func (s *Database) bootstrapMigrationsTable(
|
|||||||
func (s *Database) loadMigrations() ([]migration, error) {
|
func (s *Database) loadMigrations() ([]migration, error) {
|
||||||
entries, err := fs.ReadDir(SchemaFiles, "schema")
|
entries, err := fs.ReadDir(SchemaFiles, "schema")
|
||||||
if err != nil {
|
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
|
var migrations []migration
|
||||||
|
|
||||||
for _, entry := range entries {
|
for _, entry := range entries {
|
||||||
if entry.IsDir() ||
|
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
||||||
!strings.HasSuffix(entry.Name(), ".sql") {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
parts := strings.SplitN(
|
parts := strings.SplitN(entry.Name(), "_", minMigrationParts)
|
||||||
entry.Name(), "_", minMigrationParts,
|
|
||||||
)
|
|
||||||
if len(parts) < minMigrationParts {
|
if len(parts) < minMigrationParts {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -632,13 +184,9 @@ func (s *Database) loadMigrations() ([]migration, error) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
content, err := SchemaFiles.ReadFile(
|
content, err := SchemaFiles.ReadFile("schema/" + entry.Name())
|
||||||
"schema/" + entry.Name(),
|
|
||||||
)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf(
|
return nil, fmt.Errorf("failed to read migration %s: %w", entry.Name(), err)
|
||||||
"read migration %s: %w", entry.Name(), err,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
migrations = append(migrations, migration{
|
migrations = append(migrations, migration{
|
||||||
@@ -655,78 +203,31 @@ func (s *Database) loadMigrations() ([]migration, error) {
|
|||||||
return migrations, nil
|
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 {
|
for _, m := range migrations {
|
||||||
var exists int
|
var exists int
|
||||||
|
|
||||||
err := s.db.QueryRowContext(ctx,
|
err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM schema_migrations WHERE version = ?", m.version).Scan(&exists)
|
||||||
"SELECT COUNT(*) FROM schema_migrations WHERE version = ?",
|
|
||||||
m.version,
|
|
||||||
).Scan(&exists)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf(
|
return fmt.Errorf("failed to check migration %d: %w", m.version, err)
|
||||||
"check migration %d: %w", m.version, err,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if exists > 0 {
|
if exists > 0 {
|
||||||
continue
|
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 {
|
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
|
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 (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"database/sql"
|
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
const tokenBytes = 32
|
|
||||||
|
|
||||||
func generateToken() string {
|
func generateToken() string {
|
||||||
b := make([]byte, tokenBytes)
|
b := make([]byte, 32)
|
||||||
_, _ = rand.Read(b)
|
_, _ = rand.Read(b)
|
||||||
|
|
||||||
return hex.EncodeToString(b)
|
return hex.EncodeToString(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateSimpleUser registers a new user with the given nick and returns the user ID and token.
|
// CreateUser registers a new user with the given nick and returns the user with token.
|
||||||
func (s *Database) CreateSimpleUser(ctx context.Context, nick string) (int64, string, error) {
|
func (s *Database) CreateUser(ctx context.Context, nick string) (int64, string, error) {
|
||||||
token := generateToken()
|
token := generateToken()
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
|
||||||
res, err := s.db.ExecContext(ctx,
|
res, err := s.db.ExecContext(ctx,
|
||||||
"INSERT INTO users (nick, token, created_at, last_seen) VALUES (?, ?, ?, ?)",
|
"INSERT INTO users (nick, token, created_at, last_seen) VALUES (?, ?, ?, ?)",
|
||||||
nick, token, now, now)
|
nick, token, now, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, "", fmt.Errorf("create user: %w", err)
|
return 0, "", fmt.Errorf("create user: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
id, _ := res.LastInsertId()
|
id, _ := res.LastInsertId()
|
||||||
|
|
||||||
return id, token, nil
|
return id, token, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// LookupUserByToken returns user id and nick for a given auth token.
|
// GetUserByToken returns user id and nick for a given auth token.
|
||||||
func (s *Database) LookupUserByToken(ctx context.Context, token string) (int64, string, error) {
|
func (s *Database) GetUserByToken(ctx context.Context, token string) (int64, string, error) {
|
||||||
var id int64
|
var id int64
|
||||||
|
|
||||||
var nick string
|
var nick string
|
||||||
|
|
||||||
err := s.db.QueryRowContext(ctx, "SELECT id, nick FROM users WHERE token = ?", token).Scan(&id, &nick)
|
err := s.db.QueryRowContext(ctx, "SELECT id, nick FROM users WHERE token = ?", token).Scan(&id, &nick)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, "", err
|
return 0, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update last_seen
|
// Update last_seen
|
||||||
_, _ = s.db.ExecContext(ctx, "UPDATE users SET last_seen = ? WHERE id = ?", time.Now(), id)
|
_, _ = s.db.ExecContext(ctx, "UPDATE users SET last_seen = ? WHERE id = ?", time.Now(), id)
|
||||||
|
|
||||||
return id, nick, nil
|
return id, nick, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// LookupUserByNick returns user id for a given nick.
|
// GetUserByNick returns user id for a given nick.
|
||||||
func (s *Database) LookupUserByNick(ctx context.Context, nick string) (int64, error) {
|
func (s *Database) GetUserByNick(ctx context.Context, nick string) (int64, error) {
|
||||||
var id int64
|
var id int64
|
||||||
|
|
||||||
err := s.db.QueryRowContext(ctx, "SELECT id FROM users WHERE nick = ?", nick).Scan(&id)
|
err := s.db.QueryRowContext(ctx, "SELECT id FROM users WHERE nick = ?", nick).Scan(&id)
|
||||||
|
|
||||||
return id, err
|
return id, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetOrCreateChannel returns the channel id, creating it if needed.
|
// GetOrCreateChannel returns the channel id, creating it if needed.
|
||||||
func (s *Database) GetOrCreateChannel(ctx context.Context, name string) (int64, error) {
|
func (s *Database) GetOrCreateChannel(ctx context.Context, name string) (int64, error) {
|
||||||
var id int64
|
var id int64
|
||||||
|
|
||||||
err := s.db.QueryRowContext(ctx, "SELECT id FROM channels WHERE name = ?", name).Scan(&id)
|
err := s.db.QueryRowContext(ctx, "SELECT id FROM channels WHERE name = ?", name).Scan(&id)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return id, nil
|
return id, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
|
||||||
res, err := s.db.ExecContext(ctx,
|
res, err := s.db.ExecContext(ctx,
|
||||||
"INSERT INTO channels (name, created_at, updated_at) VALUES (?, ?, ?)",
|
"INSERT INTO channels (name, created_at, updated_at) VALUES (?, ?, ?)",
|
||||||
name, now, now)
|
name, now, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("create channel: %w", err)
|
return 0, fmt.Errorf("create channel: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
id, _ = res.LastInsertId()
|
id, _ = res.LastInsertId()
|
||||||
|
|
||||||
return id, nil
|
return id, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +71,6 @@ func (s *Database) JoinChannel(ctx context.Context, channelID, userID int64) err
|
|||||||
_, err := s.db.ExecContext(ctx,
|
_, err := s.db.ExecContext(ctx,
|
||||||
"INSERT OR IGNORE INTO channel_members (channel_id, user_id, joined_at) VALUES (?, ?, ?)",
|
"INSERT OR IGNORE INTO channel_members (channel_id, user_id, joined_at) VALUES (?, ?, ?)",
|
||||||
channelID, userID, time.Now())
|
channelID, userID, time.Now())
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,17 +79,9 @@ func (s *Database) PartChannel(ctx context.Context, channelID, userID int64) err
|
|||||||
_, err := s.db.ExecContext(ctx,
|
_, err := s.db.ExecContext(ctx,
|
||||||
"DELETE FROM channel_members WHERE channel_id = ? AND user_id = ?",
|
"DELETE FROM channel_members WHERE channel_id = ? AND user_id = ?",
|
||||||
channelID, userID)
|
channelID, userID)
|
||||||
|
|
||||||
return err
|
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.
|
// ListChannels returns all channels the user has joined.
|
||||||
func (s *Database) ListChannels(ctx context.Context, userID int64) ([]ChannelInfo, error) {
|
func (s *Database) ListChannels(ctx context.Context, userID int64) ([]ChannelInfo, error) {
|
||||||
rows, err := s.db.QueryContext(ctx,
|
rows, err := s.db.QueryContext(ctx,
|
||||||
@@ -118,15 +91,26 @@ func (s *Database) ListChannels(ctx context.Context, userID int64) ([]ChannelInf
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
defer rows.Close()
|
||||||
return scanChannelInfoRows(rows)
|
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.
|
// ChannelInfo is a lightweight channel representation.
|
||||||
type MemberInfo struct {
|
type ChannelInfo struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Nick string `json:"nick"`
|
Name string `json:"name"`
|
||||||
LastSeen time.Time `json:"lastSeen"`
|
Topic string `json:"topic"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ChannelMembers returns all members of a channel.
|
// ChannelMembers returns all members of a channel.
|
||||||
@@ -138,34 +122,28 @@ func (s *Database) ChannelMembers(ctx context.Context, channelID int64) ([]Membe
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
defer rows.Close()
|
||||||
defer func() { _ = rows.Close() }()
|
|
||||||
|
|
||||||
var members []MemberInfo
|
var members []MemberInfo
|
||||||
|
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var m MemberInfo
|
var m MemberInfo
|
||||||
|
if err := rows.Scan(&m.ID, &m.Nick, &m.LastSeen); err != nil {
|
||||||
scanErr := rows.Scan(&m.ID, &m.Nick, &m.LastSeen)
|
return nil, err
|
||||||
if scanErr != nil {
|
|
||||||
return nil, scanErr
|
|
||||||
}
|
}
|
||||||
|
|
||||||
members = append(members, m)
|
members = append(members, m)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = rows.Err()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if members == nil {
|
if members == nil {
|
||||||
members = []MemberInfo{}
|
members = []MemberInfo{}
|
||||||
}
|
}
|
||||||
|
|
||||||
return members, nil
|
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.
|
// MessageInfo represents a chat message.
|
||||||
type MessageInfo struct {
|
type MessageInfo struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
@@ -177,18 +155,11 @@ type MessageInfo struct {
|
|||||||
CreatedAt time.Time `json:"createdAt"`
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultMessageLimit = 50
|
|
||||||
|
|
||||||
const defaultPollLimit = 100
|
|
||||||
|
|
||||||
// GetMessages returns messages for a channel, optionally after a given ID.
|
// GetMessages returns messages for a channel, optionally after a given ID.
|
||||||
func (s *Database) GetMessages(
|
func (s *Database) GetMessages(ctx context.Context, channelID int64, afterID int64, limit int) ([]MessageInfo, error) {
|
||||||
ctx context.Context, channelID int64, afterID int64, limit int,
|
|
||||||
) ([]MessageInfo, error) {
|
|
||||||
if limit <= 0 {
|
if limit <= 0 {
|
||||||
limit = defaultMessageLimit
|
limit = 50
|
||||||
}
|
}
|
||||||
|
|
||||||
rows, err := s.db.QueryContext(ctx,
|
rows, err := s.db.QueryContext(ctx,
|
||||||
`SELECT m.id, c.name, u.nick, m.content, m.created_at
|
`SELECT m.id, c.name, u.nick, m.content, m.created_at
|
||||||
FROM messages m
|
FROM messages m
|
||||||
@@ -199,46 +170,48 @@ func (s *Database) GetMessages(
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
defer rows.Close()
|
||||||
return scanChannelMessages(rows)
|
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.
|
// SendMessage inserts a channel message.
|
||||||
func (s *Database) SendMessage(
|
func (s *Database) SendMessage(ctx context.Context, channelID, userID int64, content string) (int64, error) {
|
||||||
ctx context.Context, channelID, userID int64, content string,
|
|
||||||
) (int64, error) {
|
|
||||||
res, err := s.db.ExecContext(ctx,
|
res, err := s.db.ExecContext(ctx,
|
||||||
"INSERT INTO messages (channel_id, user_id, content, is_dm, created_at) VALUES (?, ?, ?, 0, ?)",
|
"INSERT INTO messages (channel_id, user_id, content, is_dm, created_at) VALUES (?, ?, ?, 0, ?)",
|
||||||
channelID, userID, content, time.Now())
|
channelID, userID, content, time.Now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.LastInsertId()
|
return res.LastInsertId()
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendDM inserts a direct message.
|
// SendDM inserts a direct message.
|
||||||
func (s *Database) SendDM(
|
func (s *Database) SendDM(ctx context.Context, fromID, toID int64, content string) (int64, error) {
|
||||||
ctx context.Context, fromID, toID int64, content string,
|
|
||||||
) (int64, error) {
|
|
||||||
res, err := s.db.ExecContext(ctx,
|
res, err := s.db.ExecContext(ctx,
|
||||||
"INSERT INTO messages (user_id, content, is_dm, dm_target_id, created_at) VALUES (?, ?, 1, ?, ?)",
|
"INSERT INTO messages (user_id, content, is_dm, dm_target_id, created_at) VALUES (?, ?, 1, ?, ?)",
|
||||||
fromID, content, toID, time.Now())
|
fromID, content, toID, time.Now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.LastInsertId()
|
return res.LastInsertId()
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDMs returns direct messages between two users after a given ID.
|
// GetDMs returns direct messages between two users after a given ID.
|
||||||
func (s *Database) GetDMs(
|
func (s *Database) GetDMs(ctx context.Context, userA, userB int64, afterID int64, limit int) ([]MessageInfo, error) {
|
||||||
ctx context.Context, userA, userB int64, afterID int64, limit int,
|
|
||||||
) ([]MessageInfo, error) {
|
|
||||||
if limit <= 0 {
|
if limit <= 0 {
|
||||||
limit = defaultMessageLimit
|
limit = 50
|
||||||
}
|
}
|
||||||
|
|
||||||
rows, err := s.db.QueryContext(ctx,
|
rows, err := s.db.QueryContext(ctx,
|
||||||
`SELECT m.id, u.nick, m.content, t.nick, m.created_at
|
`SELECT m.id, u.nick, m.content, t.nick, m.created_at
|
||||||
FROM messages m
|
FROM messages m
|
||||||
@@ -250,85 +223,152 @@ func (s *Database) GetDMs(
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
defer rows.Close()
|
||||||
return scanDMMessages(rows)
|
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.
|
// PollMessages returns all new messages (channel + DM) for a user after a given ID.
|
||||||
func (s *Database) PollMessages(
|
func (s *Database) PollMessages(ctx context.Context, userID int64, afterID int64, limit int) ([]MessageInfo, error) {
|
||||||
ctx context.Context, userID int64, afterID int64, limit int,
|
|
||||||
) ([]MessageInfo, error) {
|
|
||||||
if limit <= 0 {
|
if limit <= 0 {
|
||||||
limit = defaultPollLimit
|
limit = 100
|
||||||
}
|
}
|
||||||
|
|
||||||
rows, err := s.db.QueryContext(ctx,
|
rows, err := s.db.QueryContext(ctx,
|
||||||
`SELECT m.id, COALESCE(c.name, ''), u.nick, m.content, m.is_dm,
|
`SELECT m.id, COALESCE(c.name, ''), u.nick, m.content, m.is_dm, COALESCE(t.nick, ''), m.created_at
|
||||||
COALESCE(t.nick, ''), m.created_at
|
|
||||||
FROM messages m
|
FROM messages m
|
||||||
INNER JOIN users u ON u.id = m.user_id
|
INNER JOIN users u ON u.id = m.user_id
|
||||||
LEFT JOIN channels c ON c.id = m.channel_id
|
LEFT JOIN channels c ON c.id = m.channel_id
|
||||||
LEFT JOIN users t ON t.id = m.dm_target_id
|
LEFT JOIN users t ON t.id = m.dm_target_id
|
||||||
WHERE m.id > ? AND (
|
WHERE m.id > ? AND (
|
||||||
(m.is_dm = 0 AND m.channel_id IN
|
(m.is_dm = 0 AND m.channel_id IN (SELECT channel_id FROM channel_members WHERE user_id = ?))
|
||||||
(SELECT channel_id FROM channel_members WHERE user_id = ?))
|
|
||||||
OR (m.is_dm = 1 AND (m.user_id = ? OR m.dm_target_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)
|
ORDER BY m.id ASC LIMIT ?`, afterID, userID, userID, userID, limit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
defer rows.Close()
|
||||||
return scanPollMessages(rows)
|
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).
|
// GetMessagesBefore returns channel messages before a given ID (for history scrollback).
|
||||||
func (s *Database) GetMessagesBefore(
|
func (s *Database) GetMessagesBefore(ctx context.Context, channelID int64, beforeID int64, limit int) ([]MessageInfo, error) {
|
||||||
ctx context.Context, channelID int64, beforeID int64, limit int,
|
|
||||||
) ([]MessageInfo, error) {
|
|
||||||
if limit <= 0 {
|
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...)
|
rows, err := s.db.QueryContext(ctx, query, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
defer rows.Close()
|
||||||
msgs, err := scanChannelMessages(rows)
|
var msgs []MessageInfo
|
||||||
if err != nil {
|
for rows.Next() {
|
||||||
return nil, err
|
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
|
return msgs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDMsBefore returns DMs between two users before a given ID (for history scrollback).
|
// GetDMsBefore returns DMs between two users before a given ID (for history scrollback).
|
||||||
func (s *Database) GetDMsBefore(
|
func (s *Database) GetDMsBefore(ctx context.Context, userA, userB int64, beforeID int64, limit int) ([]MessageInfo, error) {
|
||||||
ctx context.Context, userA, userB int64, beforeID int64, limit int,
|
|
||||||
) ([]MessageInfo, error) {
|
|
||||||
if limit <= 0 {
|
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...)
|
rows, err := s.db.QueryContext(ctx, query, args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
defer rows.Close()
|
||||||
msgs, err := scanDMMessages(rows)
|
var msgs []MessageInfo
|
||||||
if err != nil {
|
for rows.Next() {
|
||||||
return nil, err
|
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
|
return msgs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -336,7 +376,6 @@ func (s *Database) GetDMsBefore(
|
|||||||
func (s *Database) ChangeNick(ctx context.Context, userID int64, newNick string) error {
|
func (s *Database) ChangeNick(ctx context.Context, userID int64, newNick string) error {
|
||||||
_, err := s.db.ExecContext(ctx,
|
_, err := s.db.ExecContext(ctx,
|
||||||
"UPDATE users SET nick = ? WHERE id = ?", newNick, userID)
|
"UPDATE users SET nick = ? WHERE id = ?", newNick, userID)
|
||||||
|
|
||||||
return err
|
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 {
|
func (s *Database) SetTopic(ctx context.Context, channelName string, _ int64, topic string) error {
|
||||||
_, err := s.db.ExecContext(ctx,
|
_, err := s.db.ExecContext(ctx,
|
||||||
"UPDATE channels SET topic = ? WHERE name = ?", topic, channelName)
|
"UPDATE channels SET topic = ? WHERE name = ?", topic, channelName)
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -360,174 +398,17 @@ func (s *Database) ListAllChannels(ctx context.Context) ([]ChannelInfo, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
defer rows.Close()
|
||||||
return scanChannelInfoRows(rows)
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Helper functions ---
|
|
||||||
|
|
||||||
func scanChannelInfoRows(rows *sql.Rows) ([]ChannelInfo, error) {
|
|
||||||
defer func() { _ = rows.Close() }()
|
|
||||||
|
|
||||||
var channels []ChannelInfo
|
var channels []ChannelInfo
|
||||||
|
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var ch ChannelInfo
|
var ch ChannelInfo
|
||||||
|
if err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic); err != nil {
|
||||||
scanErr := rows.Scan(&ch.ID, &ch.Name, &ch.Topic)
|
return nil, err
|
||||||
if scanErr != nil {
|
|
||||||
return nil, scanErr
|
|
||||||
}
|
}
|
||||||
|
|
||||||
channels = append(channels, ch)
|
channels = append(channels, ch)
|
||||||
}
|
}
|
||||||
|
|
||||||
err := rows.Err()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if channels == nil {
|
if channels == nil {
|
||||||
channels = []ChannelInfo{}
|
channels = []ChannelInfo{}
|
||||||
}
|
}
|
||||||
|
|
||||||
return channels, nil
|
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.
|
PRAGMA foreign_keys = ON;
|
||||||
-- 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.
|
|
||||||
|
|
||||||
-- Add token column to users table if it doesn't exist.
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
-- SQLite doesn't support IF NOT EXISTS for ALTER TABLE ADD COLUMN,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
-- so we check via pragma first.
|
nick TEXT NOT NULL UNIQUE,
|
||||||
CREATE TABLE IF NOT EXISTS _migration_003_check (done INTEGER);
|
token TEXT NOT NULL UNIQUE,
|
||||||
INSERT OR IGNORE INTO _migration_003_check VALUES (1);
|
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
|
CREATE TABLE IF NOT EXISTS channel_members (
|
||||||
-- didn't already create them with the ORM schema.
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
-- Since 002 creates all needed tables, 003 is effectively a no-op
|
channel_id INTEGER NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
|
||||||
-- when run after 002.
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
DROP TABLE IF EXISTS _migration_003_check;
|
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"
|
"github.com/go-chi/chi"
|
||||||
)
|
)
|
||||||
|
|
||||||
const maxNickLen = 32
|
|
||||||
|
|
||||||
// authUser extracts the user from the Authorization header (Bearer token).
|
// authUser extracts the user from the Authorization header (Bearer token).
|
||||||
func (s *Handlers) authUser(r *http.Request) (int64, string, error) {
|
func (s *Handlers) authUser(r *http.Request) (int64, string, error) {
|
||||||
auth := r.Header.Get("Authorization")
|
auth := r.Header.Get("Authorization")
|
||||||
if !strings.HasPrefix(auth, "Bearer ") {
|
if !strings.HasPrefix(auth, "Bearer ") {
|
||||||
return 0, "", sql.ErrNoRows
|
return 0, "", sql.ErrNoRows
|
||||||
}
|
}
|
||||||
|
|
||||||
token := strings.TrimPrefix(auth, "Bearer ")
|
token := strings.TrimPrefix(auth, "Bearer ")
|
||||||
|
return s.params.Database.GetUserByToken(r.Context(), token)
|
||||||
return s.params.Database.LookupUserByToken(r.Context(), token)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Handlers) requireAuth(w http.ResponseWriter, r *http.Request) (int64, string, bool) {
|
func (s *Handlers) requireAuth(w http.ResponseWriter, r *http.Request) (int64, string, bool) {
|
||||||
uid, nick, err := s.authUser(r)
|
uid, nick, err := s.authUser(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.respondJSON(w, r, map[string]string{"error": "unauthorized"}, http.StatusUnauthorized)
|
s.respondJSON(w, r, map[string]string{"error": "unauthorized"}, http.StatusUnauthorized)
|
||||||
|
|
||||||
return 0, "", false
|
return 0, "", false
|
||||||
}
|
}
|
||||||
|
|
||||||
return uid, nick, true
|
return uid, nick, true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,45 +35,32 @@ func (s *Handlers) HandleCreateSession() http.HandlerFunc {
|
|||||||
type request struct {
|
type request struct {
|
||||||
Nick string `json:"nick"`
|
Nick string `json:"nick"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type response struct {
|
type response struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Nick string `json:"nick"`
|
Nick string `json:"nick"`
|
||||||
Token string `json:"token"`
|
Token string `json:"token"`
|
||||||
}
|
}
|
||||||
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
var req request
|
var req request
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
err := json.NewDecoder(r.Body).Decode(&req)
|
|
||||||
if err != nil {
|
|
||||||
s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest)
|
s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
req.Nick = strings.TrimSpace(req.Nick)
|
req.Nick = strings.TrimSpace(req.Nick)
|
||||||
|
if req.Nick == "" || len(req.Nick) > 32 {
|
||||||
if req.Nick == "" || len(req.Nick) > maxNickLen {
|
|
||||||
s.respondJSON(w, r, map[string]string{"error": "nick must be 1-32 characters"}, http.StatusBadRequest)
|
s.respondJSON(w, r, map[string]string{"error": "nick must be 1-32 characters"}, http.StatusBadRequest)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
id, token, err := s.params.Database.CreateUser(r.Context(), req.Nick)
|
||||||
id, token, err := s.params.Database.CreateSimpleUser(r.Context(), req.Nick)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if strings.Contains(err.Error(), "UNIQUE") {
|
if strings.Contains(err.Error(), "UNIQUE") {
|
||||||
s.respondJSON(w, r, map[string]string{"error": "nick already taken"}, http.StatusConflict)
|
s.respondJSON(w, r, map[string]string{"error": "nick already taken"}, http.StatusConflict)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
s.log.Error("create user failed", "error", err)
|
s.log.Error("create user failed", "error", err)
|
||||||
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
s.respondJSON(w, r, &response{ID: id, Nick: req.Nick, Token: token}, http.StatusCreated)
|
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"`
|
Nick string `json:"nick"`
|
||||||
Channels []db.ChannelInfo `json:"channels"`
|
Channels []db.ChannelInfo `json:"channels"`
|
||||||
}
|
}
|
||||||
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
uid, nick, ok := s.requireAuth(w, r)
|
uid, nick, ok := s.requireAuth(w, r)
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
channels, err := s.params.Database.ListChannels(r.Context(), uid)
|
channels, err := s.params.Database.ListChannels(r.Context(), uid)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.log.Error("list channels failed", "error", err)
|
s.log.Error("list channels failed", "error", err)
|
||||||
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
s.respondJSON(w, r, &response{ID: uid, Nick: nick, Channels: channels}, http.StatusOK)
|
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 {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
channels, err := s.params.Database.ListAllChannels(r.Context())
|
channels, err := s.params.Database.ListAllChannels(r.Context())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.log.Error("list all channels failed", "error", err)
|
s.log.Error("list all channels failed", "error", err)
|
||||||
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
s.respondJSON(w, r, channels, http.StatusOK)
|
s.respondJSON(w, r, channels, http.StatusOK)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -137,24 +111,20 @@ func (s *Handlers) HandleChannelMembers() http.HandlerFunc {
|
|||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
name := "#" + chi.URLParam(r, "channel")
|
name := "#" + chi.URLParam(r, "channel")
|
||||||
|
var chID int64
|
||||||
chID, err := s.lookupChannelID(r, name)
|
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
|
||||||
|
"SELECT id FROM channels WHERE name = ?", name).Scan(&chID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
|
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
members, err := s.params.Database.ChannelMembers(r.Context(), chID)
|
members, err := s.params.Database.ChannelMembers(r.Context(), chID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.log.Error("channel members failed", "error", err)
|
s.log.Error("channel members failed", "error", err)
|
||||||
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
s.respondJSON(w, r, members, http.StatusOK)
|
s.respondJSON(w, r, members, http.StatusOK)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -167,18 +137,14 @@ func (s *Handlers) HandleGetMessages() http.HandlerFunc {
|
|||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
afterID, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
|
afterID, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
|
||||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
|
|
||||||
msgs, err := s.params.Database.PollMessages(r.Context(), uid, afterID, limit)
|
msgs, err := s.params.Database.PollMessages(r.Context(), uid, afterID, limit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.log.Error("get messages failed", "error", err)
|
s.log.Error("get messages failed", "error", err)
|
||||||
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
s.respondJSON(w, r, msgs, http.StatusOK)
|
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.
|
// HandleSendCommand handles all C2S commands via POST /messages.
|
||||||
// The "command" field dispatches to the appropriate logic.
|
// The "command" field dispatches to the appropriate logic.
|
||||||
func (s *Handlers) HandleSendCommand() http.HandlerFunc {
|
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) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
uid, nick, ok := s.requireAuth(w, r)
|
uid, nick, ok := s.requireAuth(w, r)
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
var req request
|
||||||
cmd, err := s.decodeSendCommand(r)
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
if err != nil {
|
|
||||||
s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest)
|
s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
req.Command = strings.ToUpper(strings.TrimSpace(req.Command))
|
||||||
|
req.To = strings.TrimSpace(req.To)
|
||||||
|
|
||||||
switch cmd.Command {
|
// Helper to extract body as string lines.
|
||||||
case "PRIVMSG", "NOTICE":
|
bodyLines := func() []string {
|
||||||
s.handlePrivmsgCommand(w, r, uid, cmd)
|
switch v := req.Body.(type) {
|
||||||
case "JOIN":
|
case []interface{}:
|
||||||
s.handleJoinCommand(w, r, uid, cmd)
|
lines := make([]string, 0, len(v))
|
||||||
case "PART":
|
for _, item := range v {
|
||||||
s.handlePartCommand(w, r, uid, cmd)
|
if s, ok := item.(string); ok {
|
||||||
case "NICK":
|
lines = append(lines, s)
|
||||||
s.handleNickCommand(w, r, uid, cmd)
|
}
|
||||||
case "TOPIC":
|
}
|
||||||
s.handleTopicCommand(w, r, cmd)
|
return lines
|
||||||
case "PING":
|
case []string:
|
||||||
s.respondJSON(w, r, map[string]string{"command": "PONG", "from": s.params.Config.ServerName}, http.StatusOK)
|
return v
|
||||||
default:
|
default:
|
||||||
_ = nick // suppress unused warning
|
return nil
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return lines
|
switch req.Command {
|
||||||
case []string:
|
case "PRIVMSG", "NOTICE":
|
||||||
return v
|
if req.To == "" {
|
||||||
default:
|
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
|
||||||
return nil
|
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(
|
if strings.HasPrefix(req.To, "#") {
|
||||||
w http.ResponseWriter, r *http.Request, uid int64, cmd *sendCommand,
|
// Channel message
|
||||||
) {
|
var chID int64
|
||||||
if cmd.To == "" {
|
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
|
||||||
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
|
"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)
|
case "PART":
|
||||||
if len(lines) == 0 {
|
if req.To == "" {
|
||||||
s.respondJSON(w, r, map[string]string{"error": "body required"}, http.StatusBadRequest)
|
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, "#") {
|
case "PING":
|
||||||
s.sendChannelMessage(w, r, uid, cmd.To, content)
|
s.respondJSON(w, r, map[string]string{"command": "PONG", "from": s.params.Config.ServerName}, http.StatusOK)
|
||||||
} else {
|
|
||||||
s.sendDirectMessage(w, r, uid, cmd.To, content)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Handlers) sendChannelMessage(
|
default:
|
||||||
w http.ResponseWriter, r *http.Request, uid int64, channel, content string,
|
_ = nick // suppress unused warning
|
||||||
) {
|
s.respondJSON(w, r, map[string]string{"error": "unknown command: " + req.Command}, http.StatusBadRequest)
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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).
|
// HandleGetHistory returns message history for a specific target (channel or DM).
|
||||||
@@ -467,93 +340,57 @@ func (s *Handlers) HandleGetHistory() http.HandlerFunc {
|
|||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
target := r.URL.Query().Get("target")
|
target := r.URL.Query().Get("target")
|
||||||
if target == "" {
|
if target == "" {
|
||||||
s.respondJSON(w, r, map[string]string{"error": "target required"}, http.StatusBadRequest)
|
s.respondJSON(w, r, map[string]string{"error": "target required"}, http.StatusBadRequest)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
beforeID, _ := strconv.ParseInt(r.URL.Query().Get("before"), 10, 64)
|
beforeID, _ := strconv.ParseInt(r.URL.Query().Get("before"), 10, 64)
|
||||||
|
|
||||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||||
if limit <= 0 {
|
if limit <= 0 {
|
||||||
limit = defaultHistoryLimit
|
limit = 50
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.HasPrefix(target, "#") {
|
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 {
|
} 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).
|
// HandleServerInfo returns server metadata (MOTD, name).
|
||||||
func (s *Handlers) HandleServerInfo() http.HandlerFunc {
|
func (s *Handlers) HandleServerInfo() http.HandlerFunc {
|
||||||
type response struct {
|
type response struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
MOTD string `json:"motd"`
|
MOTD string `json:"motd"`
|
||||||
}
|
}
|
||||||
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
s.respondJSON(w, r, &response{
|
s.respondJSON(w, r, &response{
|
||||||
Name: s.params.Config.ServerName,
|
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
|
package models
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -9,88 +8,10 @@ import (
|
|||||||
type Channel struct {
|
type Channel struct {
|
||||||
Base
|
Base
|
||||||
|
|
||||||
ID string `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Topic string `json:"topic"`
|
Topic string `json:"topic"`
|
||||||
Modes string `json:"modes"`
|
Modes string `json:"modes"`
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
UpdatedAt time.Time `json:"updatedAt"`
|
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.
|
// 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
|
package models
|
||||||
|
|
||||||
import (
|
import "database/sql"
|
||||||
"context"
|
|
||||||
"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.
|
// This avoids a circular import with the db package.
|
||||||
type DB interface {
|
type DB interface {
|
||||||
GetDB() *sql.DB
|
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.
|
// Base is embedded in all model structs to provide database access.
|
||||||
type Base struct {
|
type Base struct {
|
||||||
db DB
|
db DB
|
||||||
@@ -33,28 +18,3 @@ type Base struct {
|
|||||||
func (b *Base) SetDB(d DB) {
|
func (b *Base) SetDB(d DB) {
|
||||||
b.db = d
|
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() {
|
func (s *Server) SetupRoutes() {
|
||||||
s.router = chi.NewRouter()
|
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.Recoverer)
|
||||||
s.router.Use(middleware.RequestID)
|
s.router.Use(middleware.RequestID)
|
||||||
s.router.Use(s.mw.Logging())
|
s.router.Use(s.mw.Logging())
|
||||||
@@ -44,63 +37,51 @@ func (s *Server) setupMiddleware() {
|
|||||||
})
|
})
|
||||||
s.router.Use(sentryHandler.Handle)
|
s.router.Use(sentryHandler.Handle)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) setupHealthAndMetrics() {
|
// Health check
|
||||||
s.router.Get("/.well-known/healthcheck.json", s.h.HandleHealthCheck())
|
s.router.Get("/.well-known/healthcheck.json", s.h.HandleHealthCheck())
|
||||||
|
|
||||||
|
// Protected metrics endpoint
|
||||||
if viper.GetString("METRICS_USERNAME") != "" {
|
if viper.GetString("METRICS_USERNAME") != "" {
|
||||||
s.router.Group(func(r chi.Router) {
|
s.router.Group(func(r chi.Router) {
|
||||||
r.Use(s.mw.MetricsAuth())
|
r.Use(s.mw.MetricsAuth())
|
||||||
r.Get("/metrics", http.HandlerFunc(promhttp.Handler().ServeHTTP))
|
r.Get("/metrics", http.HandlerFunc(promhttp.Handler().ServeHTTP))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) setupAPIRoutes() {
|
// API v1
|
||||||
s.router.Route("/api/v1", func(r chi.Router) {
|
s.router.Route("/api/v1", func(r chi.Router) {
|
||||||
r.Get("/server", s.h.HandleServerInfo())
|
r.Get("/server", s.h.HandleServerInfo())
|
||||||
r.Post("/session", s.h.HandleCreateSession())
|
r.Post("/session", s.h.HandleCreateSession())
|
||||||
|
|
||||||
|
// Unified state and message endpoints
|
||||||
r.Get("/state", s.h.HandleState())
|
r.Get("/state", s.h.HandleState())
|
||||||
r.Get("/messages", s.h.HandleGetMessages())
|
r.Get("/messages", s.h.HandleGetMessages())
|
||||||
r.Post("/messages", s.h.HandleSendCommand())
|
r.Post("/messages", s.h.HandleSendCommand())
|
||||||
r.Get("/history", s.h.HandleGetHistory())
|
r.Get("/history", s.h.HandleGetHistory())
|
||||||
|
|
||||||
|
// Channels
|
||||||
r.Get("/channels", s.h.HandleListAllChannels())
|
r.Get("/channels", s.h.HandleListAllChannels())
|
||||||
r.Get("/channels/{channel}/members", s.h.HandleChannelMembers())
|
r.Get("/channels/{channel}/members", s.h.HandleChannelMembers())
|
||||||
})
|
})
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) setupSPA() {
|
// Serve embedded SPA
|
||||||
distFS, err := fs.Sub(web.Dist, "dist")
|
distFS, err := fs.Sub(web.Dist, "dist")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.log.Error("failed to get web dist filesystem", "error", err)
|
s.log.Error("failed to get web dist filesystem", "error", err)
|
||||||
|
} else {
|
||||||
return
|
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