Major changes: - Consolidated schema into single migration with IRC envelope format - Messages table stores command/from/to/body(JSON)/meta(JSON) per spec - Per-client delivery queues (client_queues table) with fan-out - In-memory broker for long-poll notifications (no busy polling) - GET /messages supports ?after=<queue_id>&timeout=15 long-polling - All commands (JOIN/PART/NICK/TOPIC/QUIT/PING) broadcast events - Channels are ephemeral (deleted when last member leaves) - PRIVMSG to nicks (DMs) fan out to both sender and recipient - SPA rewritten in vanilla JS (no build step needed): - Long-poll via recursive fetch (not setInterval) - IRC envelope parsing with system message display - /nick, /join, /part, /msg, /quit commands - Unread indicators on inactive tabs - DM tabs from user list clicks - Removed unused models package (was for UUID-based schema) - Removed conflicting UUID-based db methods - Increased HTTP write timeout to 60s for long-poll support
503 lines
17 KiB
Go
503 lines
17 KiB
Go
package handlers
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"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
|
|
}
|
|
|
|
// fanOut stores a message and enqueues it to all specified user IDs, then notifies them.
|
|
func (s *Handlers) fanOut(ctx *http.Request, command, from, to string, body json.RawMessage, userIDs []int64) error {
|
|
dbID, _, err := s.params.Database.InsertMessage(ctx.Context(), command, from, to, body, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, uid := range userIDs {
|
|
if err := s.params.Database.EnqueueMessage(ctx.Context(), uid, dbID); err != nil {
|
|
s.log.Error("enqueue failed", "error", err, "user_id", uid)
|
|
}
|
|
s.broker.Notify(uid)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// fanOutRaw stores and fans out, returning the message DB ID.
|
|
func (s *Handlers) fanOutDirect(ctx *http.Request, command, from, to string, body json.RawMessage, userIDs []int64) (int64, string, error) {
|
|
dbID, msgUUID, err := s.params.Database.InsertMessage(ctx.Context(), command, from, to, body, nil)
|
|
if err != nil {
|
|
return 0, "", err
|
|
}
|
|
for _, uid := range userIDs {
|
|
if err := s.params.Database.EnqueueMessage(ctx.Context(), uid, dbID); err != nil {
|
|
s.log.Error("enqueue failed", "error", err, "user_id", uid)
|
|
}
|
|
s.broker.Notify(uid)
|
|
}
|
|
return dbID, msgUUID, nil
|
|
}
|
|
|
|
// getChannelMembers gets all member IDs for a channel by name.
|
|
func (s *Handlers) getChannelMemberIDs(r *http.Request, channelName string) (int64, []int64, error) {
|
|
var chID int64
|
|
err := s.params.Database.GetDB().QueryRowContext(r.Context(),
|
|
"SELECT id FROM channels WHERE name = ?", channelName).Scan(&chID)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
ids, err := s.params.Database.GetChannelMemberIDs(r.Context(), chID)
|
|
return chID, ids, err
|
|
}
|
|
|
|
// 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 {
|
|
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, map[string]any{
|
|
"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 messages via long-polling from the client's queue.
|
|
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)
|
|
timeout, _ := strconv.Atoi(r.URL.Query().Get("timeout"))
|
|
if timeout <= 0 {
|
|
timeout = 0
|
|
}
|
|
if timeout > 30 {
|
|
timeout = 30
|
|
}
|
|
|
|
// First check for existing messages.
|
|
msgs, lastQID, err := s.params.Database.PollMessages(r.Context(), uid, afterID, 100)
|
|
if err != nil {
|
|
s.log.Error("poll messages failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if len(msgs) > 0 || timeout == 0 {
|
|
s.respondJSON(w, r, map[string]any{
|
|
"messages": msgs,
|
|
"last_id": lastQID,
|
|
}, http.StatusOK)
|
|
return
|
|
}
|
|
|
|
// Long-poll: wait for notification or timeout.
|
|
waitCh := s.broker.Wait(uid)
|
|
timer := time.NewTimer(time.Duration(timeout) * time.Second)
|
|
defer timer.Stop()
|
|
|
|
select {
|
|
case <-waitCh:
|
|
case <-timer.C:
|
|
case <-r.Context().Done():
|
|
s.broker.Remove(uid, waitCh)
|
|
return
|
|
}
|
|
s.broker.Remove(uid, waitCh)
|
|
|
|
// Check again after notification.
|
|
msgs, lastQID, err = s.params.Database.PollMessages(r.Context(), uid, afterID, 100)
|
|
if err != nil {
|
|
s.log.Error("poll messages failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
s.respondJSON(w, r, map[string]any{
|
|
"messages": msgs,
|
|
"last_id": lastQID,
|
|
}, http.StatusOK)
|
|
}
|
|
}
|
|
|
|
// HandleSendCommand handles all C2S commands via POST /messages.
|
|
func (s *Handlers) HandleSendCommand() http.HandlerFunc {
|
|
type request struct {
|
|
Command string `json:"command"`
|
|
To string `json:"to"`
|
|
Body json.RawMessage `json:"body,omitempty"`
|
|
Meta json.RawMessage `json:"meta,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)
|
|
|
|
bodyLines := func() []string {
|
|
if req.Body == nil {
|
|
return nil
|
|
}
|
|
var lines []string
|
|
if err := json.Unmarshal(req.Body, &lines); err != nil {
|
|
return nil
|
|
}
|
|
return lines
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
if strings.HasPrefix(req.To, "#") {
|
|
// Channel message — fan out to all channel members.
|
|
_, memberIDs, err := s.getChannelMemberIDs(r, req.To)
|
|
if err != nil {
|
|
s.respondJSON(w, r, map[string]string{"error": "channel not found"}, http.StatusNotFound)
|
|
return
|
|
}
|
|
_, msgUUID, err := s.fanOutDirect(r, req.Command, nick, req.To, req.Body, memberIDs)
|
|
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]string{"id": msgUUID, "status": "sent"}, http.StatusCreated)
|
|
} else {
|
|
// DM — fan out to recipient + sender.
|
|
targetUID, 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
|
|
}
|
|
recipients := []int64{targetUID}
|
|
if targetUID != uid {
|
|
recipients = append(recipients, uid) // echo to sender
|
|
}
|
|
_, msgUUID, err := s.fanOutDirect(r, req.Command, nick, req.To, req.Body, recipients)
|
|
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]string{"id": msgUUID, "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
|
|
}
|
|
// Broadcast JOIN to all channel members (including the joiner).
|
|
memberIDs, _ := s.params.Database.GetChannelMemberIDs(r.Context(), chID)
|
|
_ = s.fanOut(r, "JOIN", nick, channel, nil, memberIDs)
|
|
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
|
|
}
|
|
// Broadcast PART before removing the member.
|
|
memberIDs, _ := s.params.Database.GetChannelMemberIDs(r.Context(), chID)
|
|
_ = s.fanOut(r, "PART", nick, channel, req.Body, memberIDs)
|
|
|
|
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
|
|
}
|
|
// Delete channel if empty (ephemeral).
|
|
_ = s.params.Database.DeleteChannelIfEmpty(r.Context(), chID)
|
|
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
|
|
}
|
|
// Broadcast NICK to all channels the user is in.
|
|
channels, _ := s.params.Database.GetAllChannelMembershipsForUser(r.Context(), uid)
|
|
notified := map[int64]bool{uid: true}
|
|
body, _ := json.Marshal([]string{newNick})
|
|
// Notify self.
|
|
dbID, _, _ := s.params.Database.InsertMessage(r.Context(), "NICK", nick, "", json.RawMessage(body), nil)
|
|
_ = s.params.Database.EnqueueMessage(r.Context(), uid, dbID)
|
|
s.broker.Notify(uid)
|
|
|
|
for _, ch := range channels {
|
|
memberIDs, _ := s.params.Database.GetChannelMemberIDs(r.Context(), ch.ID)
|
|
for _, mid := range memberIDs {
|
|
if !notified[mid] {
|
|
notified[mid] = true
|
|
_ = s.params.Database.EnqueueMessage(r.Context(), mid, dbID)
|
|
s.broker.Notify(mid)
|
|
}
|
|
}
|
|
}
|
|
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, topic); err != nil {
|
|
s.log.Error("set topic failed", "error", err)
|
|
s.respondJSON(w, r, map[string]string{"error": "internal error"}, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
// Broadcast TOPIC to channel members.
|
|
_, memberIDs, _ := s.getChannelMemberIDs(r, channel)
|
|
_ = s.fanOut(r, "TOPIC", nick, channel, req.Body, memberIDs)
|
|
s.respondJSON(w, r, map[string]string{"status": "ok", "topic": topic}, http.StatusOK)
|
|
|
|
case "QUIT":
|
|
// Broadcast QUIT to all channels, then remove user.
|
|
channels, _ := s.params.Database.GetAllChannelMembershipsForUser(r.Context(), uid)
|
|
notified := map[int64]bool{}
|
|
var dbID int64
|
|
if len(channels) > 0 {
|
|
dbID, _, _ = s.params.Database.InsertMessage(r.Context(), "QUIT", nick, "", req.Body, nil)
|
|
}
|
|
for _, ch := range channels {
|
|
memberIDs, _ := s.params.Database.GetChannelMemberIDs(r.Context(), ch.ID)
|
|
for _, mid := range memberIDs {
|
|
if mid != uid && !notified[mid] {
|
|
notified[mid] = true
|
|
_ = s.params.Database.EnqueueMessage(r.Context(), mid, dbID)
|
|
s.broker.Notify(mid)
|
|
}
|
|
}
|
|
_ = s.params.Database.PartChannel(r.Context(), ch.ID, uid)
|
|
_ = s.params.Database.DeleteChannelIfEmpty(r.Context(), ch.ID)
|
|
}
|
|
_ = s.params.Database.DeleteUser(r.Context(), uid)
|
|
s.respondJSON(w, r, map[string]string{"status": "quit"}, http.StatusOK)
|
|
|
|
case "PING":
|
|
s.respondJSON(w, r, map[string]string{"command": "PONG", "from": s.params.Config.ServerName}, http.StatusOK)
|
|
|
|
default:
|
|
s.respondJSON(w, r, map[string]string{"error": "unknown command: " + req.Command}, http.StatusBadRequest)
|
|
}
|
|
}
|
|
}
|
|
|
|
// HandleGetHistory returns message history for a specific target.
|
|
func (s *Handlers) HandleGetHistory() http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
_, _, 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
|
|
}
|
|
msgs, err := s.params.Database.GetHistory(r.Context(), target, 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)
|
|
}
|
|
}
|
|
|
|
// HandleServerInfo returns server metadata.
|
|
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)
|
|
}
|
|
}
|