Files
dumpsterChat/internal/message/handlers.go
T

397 lines
12 KiB
Go

package message
import (
"context"
"database/sql"
"encoding/json"
"errors"
"log/slog"
"net/http"
"strconv"
"git.dustin.coffee/hobokenchicken/dumpsterChat/internal/gateway"
"git.dustin.coffee/hobokenchicken/dumpsterChat/internal/middleware"
"git.dustin.coffee/hobokenchicken/dumpsterChat/internal/push"
"github.com/go-chi/chi/v5"
)
type Handler struct {
db *sql.DB
hub *gateway.Hub
mentions *MentionHandler
pushHandler *push.Handler
logger *slog.Logger
}
type Handler_old struct {
db *sql.DB
hub *gateway.Hub
mentions *MentionHandler
}
func NewHandler(db *sql.DB, hub *gateway.Hub, pushHandler *push.Handler, logger *slog.Logger) *Handler {
return &Handler{
db: db,
hub: hub,
mentions: NewMentionHandler(db, pushHandler, logger),
}
}
func (h *Handler) RegisterRoutes(r chi.Router) {
r.Get("/", h.List)
r.Post("/", h.Create)
r.Patch("/{messageID}", h.Update)
r.Delete("/{messageID}", h.Delete)
}
type messageResponse struct {
ID string `json:"id"`
ChannelID string `json:"channel_id"`
AuthorID string `json:"author_id"`
AuthorName string `json:"author_username"`
DisplayName *string `json:"author_display_name"`
Content string `json:"content"`
EditedAt *string `json:"edited_at"`
CreatedAt string `json:"created_at"`
}
// isMember checks whether the given user is a member of the given server.
func (h *Handler) isMember(ctx context.Context, userID, serverID string) (bool, error) {
var exists bool
err := h.db.QueryRowContext(ctx, `
SELECT EXISTS(SELECT 1 FROM members WHERE user_id = $1 AND server_id = $2)
`, userID, serverID).Scan(&exists)
return exists, err
}
type createMessageRequest struct {
Content string `json:"content"`
ReplyTo *string `json:"reply_to,omitempty"`
}
// @Summary Create a message
// @Description Send a message to a channel
// @Tags messages
// @Accept json
// @Produce json
// @Security SessionAuth
// @Param channelID path string true "Channel ID"
// @Param body body createMessageRequest true "Message data"
// @Success 201 {object} messageResponse
// @Failure 400 {object} map[string]string
// @Failure 401 {object} map[string]string
// @Failure 403 {object} map[string]string
// @Router /channels/{channelID}/messages [post]
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
channelID := chi.URLParam(r, "channelID")
userID, serverID, ok := h.requireChannelAccess(w, r, channelID)
if !ok {
return
}
var req createMessageRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, `{"error":"invalid request"}`, http.StatusBadRequest)
return
}
if req.Content == "" {
http.Error(w, `{"error":"content is required"}`, http.StatusBadRequest)
return
}
if len(req.Content) > 4000 {
http.Error(w, `{"error":"message too long (max 4000 chars)"}`, http.StatusBadRequest)
return
}
var msg messageResponse
var editedAt sql.NullString
var createdAt sql.NullString
var replyTo sql.NullString
if req.ReplyTo != nil {
replyTo = sql.NullString{String: *req.ReplyTo, Valid: true}
}
err := h.db.QueryRowContext(r.Context(), `
INSERT INTO messages (channel_id, author_id, content, reply_to)
VALUES ($1, $2, $3, $4)
RETURNING id, channel_id, author_id, content, edited_at::text, created_at::text
`, channelID, userID, req.Content, replyTo).Scan(
&msg.ID, &msg.ChannelID, &msg.AuthorID, &msg.Content, &editedAt, &createdAt,
)
if err != nil {
http.Error(w, `{"error":"failed to create message"}`, http.StatusInternalServerError)
return
}
// Fetch author info
err = h.db.QueryRowContext(r.Context(), `
SELECT username, display_name FROM users WHERE id = $1
`, userID).Scan(&msg.AuthorName, &msg.DisplayName)
if err != nil {
http.Error(w, `{"error":"server error"}`, http.StatusInternalServerError)
return
}
if editedAt.Valid {
msg.EditedAt = &editedAt.String
}
msg.CreatedAt = createdAt.String
// Broadcast MESSAGE_CREATE event via WebSocket (scoped to server)
h.hub.BroadcastToServer(serverID, gateway.Event{
Type: gateway.EventMessageCreate,
Data: msg,
})
// Dispatch push notifications for @mentions
go h.mentions.ParseAndNotify(r.Context(), channelID, userID, req.Content)
// Dispatch push notifications to channel members
go func() {
var channelName string
_ = h.db.QueryRowContext(context.Background(), `SELECT name FROM channels WHERE id = $1`, channelID).Scan(&channelName)
if channelName == "" {
channelName = channelID
}
h.pushHandler.SendChannelNotification(context.Background(), channelID, userID, channelName, req.Content)
}()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(msg)
}
type updateMessageRequest struct {
Content string `json:"content"`
}
// @Summary Update a message
// @Description Edit a message (author only)
// @Tags messages
// @Accept json
// @Produce json
// @Security SessionAuth
// @Param channelID path string true "Channel ID"
// @Param messageID path string true "Message ID"
// @Param body body updateMessageRequest true "Message update data"
// @Success 200 {object} messageResponse
// @Failure 400 {object} map[string]string
// @Failure 401 {object} map[string]string
// @Failure 404 {object} map[string]string
// @Router /channels/{channelID}/messages/{messageID} [patch]
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
messageID := chi.URLParam(r, "messageID")
userID, ok := middleware.UserIDFromContext(r.Context())
if !ok {
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
return
}
var req updateMessageRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, `{"error":"invalid request"}`, http.StatusBadRequest)
return
}
if req.Content == "" {
http.Error(w, `{"error":"content is required"}`, http.StatusBadRequest)
return
}
if len(req.Content) > 4000 {
http.Error(w, `{"error":"message too long (max 4000 chars)"}`, http.StatusBadRequest)
return
}
var msg messageResponse
var editedAt sql.NullString
var createdAt sql.NullString
err := h.db.QueryRowContext(r.Context(), `
UPDATE messages SET content = $1, edited_at = NOW()
WHERE id = $2 AND author_id = $3
RETURNING id, channel_id, author_id, content, edited_at::text, created_at::text
`, req.Content, messageID, userID).Scan(
&msg.ID, &msg.ChannelID, &msg.AuthorID, &msg.Content, &editedAt, &createdAt,
)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
http.Error(w, `{"error":"message not found or not authorized"}`, http.StatusNotFound)
return
}
http.Error(w, `{"error":"failed to update message"}`, http.StatusInternalServerError)
return
}
err = h.db.QueryRowContext(r.Context(), `
SELECT username, display_name FROM users WHERE id = $1
`, userID).Scan(&msg.AuthorName, &msg.DisplayName)
if err != nil {
http.Error(w, `{"error":"server error"}`, http.StatusInternalServerError)
return
}
if editedAt.Valid {
msg.EditedAt = &editedAt.String
}
msg.CreatedAt = createdAt.String
// Look up serverID for scoped broadcast
serverID, _ := h.hub.ServerIDForChannel(r.Context(), msg.ChannelID)
if serverID != "" {
h.hub.BroadcastToServer(serverID, gateway.Event{
Type: gateway.EventMessageUpdate,
Data: msg,
})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(msg)
}
// @Summary Delete a message
// @Description Delete a message (author only)
// @Tags messages
// @Security SessionAuth
// @Param channelID path string true "Channel ID"
// @Param messageID path string true "Message ID"
// @Success 204
// @Failure 401 {object} map[string]string
// @Failure 404 {object} map[string]string
// @Router /channels/{channelID}/messages/{messageID} [delete]
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
messageID := chi.URLParam(r, "messageID")
userID, ok := middleware.UserIDFromContext(r.Context())
if !ok {
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
return
}
var channelID string
err := h.db.QueryRowContext(r.Context(), `
DELETE FROM messages WHERE id = $1 AND author_id = $2
RETURNING channel_id
`, messageID, userID).Scan(&channelID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
http.Error(w, `{"error":"message not found or not authorized"}`, http.StatusNotFound)
return
}
http.Error(w, `{"error":"failed to delete message"}`, http.StatusInternalServerError)
return
}
// Look up serverID for scoped broadcast
serverID, _ := h.hub.ServerIDForChannel(r.Context(), channelID)
if serverID != "" {
h.hub.BroadcastToServer(serverID, gateway.Event{
Type: gateway.EventMessageDelete,
Data: map[string]string{
"id": messageID,
"channel_id": channelID,
},
})
}
w.WriteHeader(http.StatusNoContent)
}
// @Summary List messages
// @Description List messages in a channel with pagination
// @Tags messages
// @Produce json
// @Security SessionAuth
// @Param channelID path string true "Channel ID"
// @Param limit query int false "Max messages to return (1-100, default 50)"
// @Param before query string false "Message ID to fetch messages before"
// @Success 200 {array} messageResponse
// @Failure 401 {object} map[string]string
// @Failure 403 {object} map[string]string
// @Router /channels/{channelID}/messages [get]
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
channelID := chi.URLParam(r, "channelID")
userID, _, ok := h.requireChannelAccess(w, r, channelID)
if !ok {
return
}
limitStr := r.URL.Query().Get("limit")
limit := 50
if limitStr != "" {
if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 100 {
limit = l
}
}
before := r.URL.Query().Get("before")
var rows *sql.Rows
var err error
if before != "" {
rows, err = h.db.QueryContext(r.Context(), `
SELECT m.id, m.channel_id, m.author_id, u.username, u.display_name, m.content, m.edited_at::text, m.created_at::text
FROM messages m
JOIN users u ON m.author_id = u.id
WHERE m.channel_id = $1 AND m.created_at < (SELECT created_at FROM messages WHERE id = $2)
ORDER BY m.created_at ASC
LIMIT $3
`, channelID, before, limit)
} else {
rows, err = h.db.QueryContext(r.Context(), `
SELECT m.id, m.channel_id, m.author_id, u.username, u.display_name, m.content, m.edited_at::text, m.created_at::text
FROM messages m
JOIN users u ON m.author_id = u.id
WHERE m.channel_id = $1
ORDER BY m.created_at ASC
LIMIT $2
`, channelID, limit)
}
if err != nil {
http.Error(w, `{"error":"failed to list messages"}`, http.StatusInternalServerError)
return
}
defer rows.Close()
messages := make([]messageResponse, 0)
for rows.Next() {
var msg messageResponse
var editedAt sql.NullString
var createdAt sql.NullString
err := rows.Scan(&msg.ID, &msg.ChannelID, &msg.AuthorID, &msg.AuthorName, &msg.DisplayName, &msg.Content, &editedAt, &createdAt)
if err != nil {
continue
}
if editedAt.Valid {
msg.EditedAt = &editedAt.String
}
msg.CreatedAt = createdAt.String
messages = append(messages, msg)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(messages)
_ = userID
}
// requireChannelAccess checks if user is authenticated and is a member of the channel's server.
// Returns (userID, serverID, ok).
func (h *Handler) requireChannelAccess(w http.ResponseWriter, r *http.Request, channelID string) (string, string, bool) {
userID, ok := middleware.UserIDFromContext(r.Context())
if !ok {
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
return "", "", false
}
var serverID string
err := h.db.QueryRowContext(r.Context(), `SELECT server_id FROM channels WHERE id = $1`, channelID).Scan(&serverID)
if err != nil {
http.Error(w, `{"error":"channel not found"}`, http.StatusNotFound)
return "", "", false
}
isMember, err := h.isMember(r.Context(), userID, serverID)
if err != nil || !isMember {
http.Error(w, `{"error":"not a member"}`, http.StatusForbidden)
return "", "", false
}
return userID, serverID, true
}