Files
chat/internal/handlers/api.go
clawbot 0ee3fd78d2 refactor: unify all C2S commands through POST /messages
All client-to-server commands now go through POST /api/v1/messages
with a 'command' field. The server dispatches by command type:

- PRIVMSG/NOTICE: send message to channel or user
- JOIN: join channel (creates if needed)
- PART: leave channel
- NICK: change nickname
- TOPIC: set channel topic
- PING: keepalive (returns PONG)

Removed separate routes:
- POST /channels/join
- DELETE /channels/{channel}
- POST /register (renamed to POST /session)
- GET /channels/all (moved to GET /channels)

Added DB methods: ChangeNick, SetTopic
2026-02-10 17:53:08 -08:00

401 lines
14 KiB
Go

package handlers
import (
"database/sql"
"encoding/json"
"net/http"
"strconv"
"strings"
"git.eeqj.de/sneak/chat/internal/db"
"github.com/go-chi/chi"
)
// authUser extracts the user from the Authorization header (Bearer token).
func (s *Handlers) authUser(r *http.Request) (int64, string, error) {
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
return 0, "", sql.ErrNoRows
}
token := strings.TrimPrefix(auth, "Bearer ")
return s.params.Database.GetUserByToken(r.Context(), token)
}
func (s *Handlers) requireAuth(w http.ResponseWriter, r *http.Request) (int64, string, bool) {
uid, nick, err := s.authUser(r)
if err != nil {
s.respondJSON(w, r, map[string]string{"error": "unauthorized"}, http.StatusUnauthorized)
return 0, "", false
}
return uid, nick, true
}
// HandleCreateSession creates a new user session and returns the auth token.
func (s *Handlers) HandleCreateSession() http.HandlerFunc {
type request struct {
Nick string `json:"nick"`
}
type response struct {
ID int64 `json:"id"`
Nick string `json:"nick"`
Token string `json:"token"`
}
return func(w http.ResponseWriter, r *http.Request) {
var req request
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest)
return
}
req.Nick = strings.TrimSpace(req.Nick)
if req.Nick == "" || len(req.Nick) > 32 {
s.respondJSON(w, r, map[string]string{"error": "nick must be 1-32 characters"}, http.StatusBadRequest)
return
}
id, token, err := s.params.Database.CreateUser(r.Context(), req.Nick)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE") {
s.respondJSON(w, r, map[string]string{"error": "nick already taken"}, http.StatusConflict)
return
}
s.log.Error("create user failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, &response{ID: id, Nick: req.Nick, Token: token}, http.StatusCreated)
}
}
// HandleState returns the current user's info and joined channels.
func (s *Handlers) HandleState() http.HandlerFunc {
type response struct {
ID int64 `json:"id"`
Nick string `json:"nick"`
Channels []db.ChannelInfo `json:"channels"`
}
return func(w http.ResponseWriter, r *http.Request) {
uid, nick, ok := s.requireAuth(w, r)
if !ok {
return
}
channels, err := s.params.Database.ListChannels(r.Context(), uid)
if err != nil {
s.log.Error("list channels failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, &response{ID: uid, Nick: nick, Channels: channels}, http.StatusOK)
}
}
// HandleListAllChannels returns all channels on the server.
func (s *Handlers) HandleListAllChannels() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, _, ok := s.requireAuth(w, r)
if !ok {
return
}
channels, err := s.params.Database.ListAllChannels(r.Context())
if err != nil {
s.log.Error("list all channels failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, channels, http.StatusOK)
}
}
// HandleChannelMembers returns members of a channel.
func (s *Handlers) HandleChannelMembers() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, _, ok := s.requireAuth(w, r)
if !ok {
return
}
name := "#" + chi.URLParam(r, "channel")
var chID int64
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
"SELECT id FROM channels WHERE name = ?", name).Scan(&chID)
if err != nil {
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
return
}
members, err := s.params.Database.ChannelMembers(r.Context(), chID)
if err != nil {
s.log.Error("channel members failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, members, http.StatusOK)
}
}
// HandleGetMessages returns all new messages (channel + DM) for the user via long-polling.
// This is the single unified message stream — replaces separate channel/DM/poll endpoints.
func (s *Handlers) HandleGetMessages() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
uid, _, ok := s.requireAuth(w, r)
if !ok {
return
}
afterID, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
msgs, err := s.params.Database.PollMessages(r.Context(), uid, afterID, limit)
if err != nil {
s.log.Error("get messages failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, msgs, http.StatusOK)
}
}
// HandleSendCommand handles all C2S commands via POST /messages.
// The "command" field dispatches to the appropriate logic.
func (s *Handlers) HandleSendCommand() http.HandlerFunc {
type request struct {
Command string `json:"command"`
To string `json:"to"`
Params []string `json:"params,omitempty"`
Body interface{} `json:"body,omitempty"`
}
return func(w http.ResponseWriter, r *http.Request) {
uid, nick, ok := s.requireAuth(w, r)
if !ok {
return
}
var req request
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
s.respondJSON(w, r, map[string]string{"error": "invalid request"}, http.StatusBadRequest)
return
}
req.Command = strings.ToUpper(strings.TrimSpace(req.Command))
req.To = strings.TrimSpace(req.To)
// Helper to extract body as string lines.
bodyLines := func() []string {
switch v := req.Body.(type) {
case []interface{}:
lines := make([]string, 0, len(v))
for _, item := range v {
if s, ok := item.(string); ok {
lines = append(lines, s)
}
}
return lines
case []string:
return v
default:
return nil
}
}
switch req.Command {
case "PRIVMSG", "NOTICE":
if req.To == "" {
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
return
}
lines := bodyLines()
if len(lines) == 0 {
s.respondJSON(w, r, map[string]string{"error": "body required"}, http.StatusBadRequest)
return
}
content := strings.Join(lines, "\n")
if strings.HasPrefix(req.To, "#") {
// Channel message
var chID int64
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
"SELECT id FROM channels WHERE name = ?", req.To).Scan(&chID)
if err != nil {
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
return
}
msgID, err := s.params.Database.SendMessage(r.Context(), chID, uid, content)
if err != nil {
s.log.Error("send message failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, map[string]any{"id": msgID, "status": "sent"}, http.StatusCreated)
} else {
// DM
targetID, err := s.params.Database.GetUserByNick(r.Context(), req.To)
if err != nil {
s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound)
return
}
msgID, err := s.params.Database.SendDM(r.Context(), uid, targetID, content)
if err != nil {
s.log.Error("send dm failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, map[string]any{"id": msgID, "status": "sent"}, http.StatusCreated)
}
case "JOIN":
if req.To == "" {
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
return
}
channel := req.To
if !strings.HasPrefix(channel, "#") {
channel = "#" + channel
}
chID, err := s.params.Database.GetOrCreateChannel(r.Context(), channel)
if err != nil {
s.log.Error("get/create channel failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
if err := s.params.Database.JoinChannel(r.Context(), chID, uid); err != nil {
s.log.Error("join channel failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, map[string]string{"status": "joined", "channel": channel}, http.StatusOK)
case "PART":
if req.To == "" {
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
return
}
channel := req.To
if !strings.HasPrefix(channel, "#") {
channel = "#" + channel
}
var chID int64
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
"SELECT id FROM channels WHERE name = ?", channel).Scan(&chID)
if err != nil {
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
return
}
if err := s.params.Database.PartChannel(r.Context(), chID, uid); err != nil {
s.log.Error("part channel failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, map[string]string{"status": "parted", "channel": channel}, http.StatusOK)
case "NICK":
lines := bodyLines()
if len(lines) == 0 {
s.respondJSON(w, r, map[string]string{"error": "body required (new nick)"}, http.StatusBadRequest)
return
}
newNick := strings.TrimSpace(lines[0])
if newNick == "" || len(newNick) > 32 {
s.respondJSON(w, r, map[string]string{"error": "nick must be 1-32 characters"}, http.StatusBadRequest)
return
}
if err := s.params.Database.ChangeNick(r.Context(), uid, newNick); err != nil {
if strings.Contains(err.Error(), "UNIQUE") {
s.respondJSON(w, r, map[string]string{"error": "nick already in use"}, http.StatusConflict)
return
}
s.log.Error("change nick failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, map[string]string{"status": "ok", "nick": newNick}, http.StatusOK)
case "TOPIC":
if req.To == "" {
s.respondJSON(w, r, map[string]string{"error": "to field required"}, http.StatusBadRequest)
return
}
lines := bodyLines()
if len(lines) == 0 {
s.respondJSON(w, r, map[string]string{"error": "body required (topic text)"}, http.StatusBadRequest)
return
}
topic := strings.Join(lines, " ")
channel := req.To
if !strings.HasPrefix(channel, "#") {
channel = "#" + channel
}
if err := s.params.Database.SetTopic(r.Context(), channel, uid, topic); err != nil {
s.log.Error("set topic failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, map[string]string{"status": "ok", "topic": topic}, http.StatusOK)
case "PING":
s.respondJSON(w, r, map[string]string{"command": "PONG", "from": s.params.Config.ServerName}, http.StatusOK)
default:
_ = nick // suppress unused warning
s.respondJSON(w, r, map[string]string{"error": "unknown command: " + req.Command}, http.StatusBadRequest)
}
}
}
// HandleGetHistory returns message history for a specific target (channel or DM).
func (s *Handlers) HandleGetHistory() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
uid, _, ok := s.requireAuth(w, r)
if !ok {
return
}
target := r.URL.Query().Get("target")
if target == "" {
s.respondJSON(w, r, map[string]string{"error": "target required"}, http.StatusBadRequest)
return
}
beforeID, _ := strconv.ParseInt(r.URL.Query().Get("before"), 10, 64)
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
if limit <= 0 {
limit = 50
}
if strings.HasPrefix(target, "#") {
// Channel history
var chID int64
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
"SELECT id FROM channels WHERE name = ?", target).Scan(&chID)
if err != nil {
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
return
}
msgs, err := s.params.Database.GetMessagesBefore(r.Context(), chID, beforeID, limit)
if err != nil {
s.log.Error("get history failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, msgs, http.StatusOK)
} else {
// DM history
targetID, err := s.params.Database.GetUserByNick(r.Context(), target)
if err != nil {
s.respondJSON(w, r, map[string]string{"error": "user not found"}, http.StatusNotFound)
return
}
msgs, err := s.params.Database.GetDMsBefore(r.Context(), uid, targetID, beforeID, limit)
if err != nil {
s.log.Error("get dm history failed", "error", err)
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
return
}
s.respondJSON(w, r, msgs, http.StatusOK)
}
}
}
// HandleServerInfo returns server metadata (MOTD, name).
func (s *Handlers) HandleServerInfo() http.HandlerFunc {
type response struct {
Name string `json:"name"`
MOTD string `json:"motd"`
}
return func(w http.ResponseWriter, r *http.Request) {
s.respondJSON(w, r, &response{
Name: s.params.Config.ServerName,
MOTD: s.params.Config.MOTD,
}, http.StatusOK)
}
}