2026-03-14 21:17:09 +01:00
|
|
|
package api
|
|
|
|
|
|
|
|
|
|
import (
|
2026-07-24 11:06:59 +02:00
|
|
|
"context"
|
2026-08-01 22:06:14 +02:00
|
|
|
"encoding/json"
|
2026-04-05 21:01:29 +00:00
|
|
|
"errors"
|
2026-03-17 11:05:52 +01:00
|
|
|
"log/slog"
|
2026-03-14 21:17:09 +01:00
|
|
|
"net/http"
|
2026-08-01 22:06:14 +02:00
|
|
|
"net/url"
|
2026-03-14 21:17:09 +01:00
|
|
|
"strconv"
|
2026-03-29 19:39:22 +02:00
|
|
|
"strings"
|
|
|
|
|
"time"
|
2026-03-14 21:17:09 +01:00
|
|
|
|
2026-08-28 06:54:32 +02:00
|
|
|
"github.com/J3vb/OwnCord/Server/auth"
|
|
|
|
|
"github.com/J3vb/OwnCord/Server/db"
|
|
|
|
|
"github.com/J3vb/OwnCord/Server/service"
|
2026-03-14 21:17:09 +01:00
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
defaultMessageLimit = 50
|
|
|
|
|
maxMessageLimit = 100
|
|
|
|
|
)
|
|
|
|
|
|
2026-03-29 19:39:22 +02:00
|
|
|
func isInvalidSearchQueryError(err error) bool {
|
|
|
|
|
if err == nil {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
msg := strings.ToLower(err.Error())
|
|
|
|
|
return strings.Contains(msg, "fts5") ||
|
|
|
|
|
strings.Contains(msg, "unterminated string") ||
|
|
|
|
|
strings.Contains(msg, "malformed") ||
|
|
|
|
|
strings.Contains(msg, "syntax error")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func searchRateLimitMiddleware(limiter *auth.RateLimiter, limit int, window time.Duration, trustedProxies []string) func(http.Handler) http.Handler {
|
2026-07-23 21:07:09 +02:00
|
|
|
proxyNets := parseCIDRList(trustedProxies) // W3-3a: parse once at construction
|
2026-03-29 19:39:22 +02:00
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2026-07-23 21:07:09 +02:00
|
|
|
ip := clientIPWithProxies(r, proxyNets)
|
2026-03-29 19:39:22 +02:00
|
|
|
if !limiter.Allow("search:"+ip, limit, window) {
|
|
|
|
|
w.Header().Set("Retry-After", strconv.Itoa(int(window.Seconds())))
|
|
|
|
|
writeJSON(w, http.StatusTooManyRequests, errorResponse{
|
|
|
|
|
Error: "RATE_LIMITED",
|
|
|
|
|
Message: "too many requests, please slow down",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-01 22:06:14 +02:00
|
|
|
// PurgeBroadcaster is the interface needed to fan a bulk delete out over
|
|
|
|
|
// WebSocket from a REST handler. Satisfied by *ws.Hub.
|
|
|
|
|
type PurgeBroadcaster interface {
|
|
|
|
|
BroadcastChatBulkDeleted(channelID int64, messageIDs []int64)
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-14 21:17:09 +01:00
|
|
|
// MountChannelRoutes registers all channel-related routes onto r.
|
2026-03-29 19:39:22 +02:00
|
|
|
// All routes require authentication. The limiter is used to rate-limit
|
2026-08-01 22:06:14 +02:00
|
|
|
// expensive endpoints like search. broadcaster may be nil, in which case a
|
|
|
|
|
// purge still commits but no chat_bulk_deleted event is emitted.
|
|
|
|
|
func MountChannelRoutes(r chi.Router, database *db.DB, svc *service.Services, limiter *auth.RateLimiter, trustedProxies []string, broadcaster PurgeBroadcaster) {
|
2026-03-14 21:17:09 +01:00
|
|
|
r.Route("/api/v1/channels", func(r chi.Router) {
|
|
|
|
|
r.Use(AuthMiddleware(database))
|
2026-04-05 21:01:29 +00:00
|
|
|
r.Get("/", handleListChannels(svc))
|
|
|
|
|
r.Get("/{id}/messages", handleGetMessages(svc))
|
2026-08-01 22:06:14 +02:00
|
|
|
r.Get("/{id}/messages/around/{messageId}", handleGetMessagesAround(svc))
|
|
|
|
|
r.Post("/{id}/messages/purge", handlePurgeMessages(svc, broadcaster))
|
|
|
|
|
r.Get("/{id}/messages/{messageId}/reactions/{emoji}/users", handleGetReactionUsers(svc))
|
2026-04-05 21:01:29 +00:00
|
|
|
r.Get("/{id}/pins", handleGetPins(svc))
|
|
|
|
|
r.Post("/{id}/pins/{messageId}", handleSetPinned(svc, true))
|
|
|
|
|
r.Delete("/{id}/pins/{messageId}", handleSetPinned(svc, false))
|
2026-03-14 21:17:09 +01:00
|
|
|
})
|
2026-03-29 19:39:22 +02:00
|
|
|
r.With(
|
|
|
|
|
AuthMiddleware(database),
|
2026-04-01 11:37:36 +02:00
|
|
|
searchRateLimitMiddleware(limiter, searchRateLimitPerMinute, time.Minute, trustedProxies),
|
2026-04-05 21:01:29 +00:00
|
|
|
).Get("/api/v1/search", handleSearch(svc))
|
2026-03-19 04:19:03 +01:00
|
|
|
}
|
|
|
|
|
|
2026-03-14 21:17:09 +01:00
|
|
|
// handleListChannels returns all channels the authenticated user can see.
|
2026-04-05 21:01:29 +00:00
|
|
|
func handleListChannels(svc *service.Services) http.HandlerFunc {
|
2026-03-14 21:17:09 +01:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2026-04-05 21:01:29 +00:00
|
|
|
user, _ := r.Context().Value(UserKey).(*db.User)
|
|
|
|
|
if user == nil {
|
|
|
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
|
|
|
Error: "UNAUTHORIZED", Message: "authentication required",
|
2026-03-14 21:17:09 +01:00
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-03-16 16:54:56 +01:00
|
|
|
|
2026-04-07 09:10:14 +02:00
|
|
|
channels, err := svc.Channels.ListVisibleChannels(r.Context(), user.ID)
|
2026-04-05 21:01:29 +00:00
|
|
|
if err != nil {
|
|
|
|
|
slog.Error("handleListChannels", "err", err)
|
|
|
|
|
writeJSON(w, http.StatusInternalServerError, errorResponse{
|
|
|
|
|
Error: "INTERNAL_ERROR", Message: "failed to list channels",
|
|
|
|
|
})
|
|
|
|
|
return
|
2026-03-19 04:19:03 +01:00
|
|
|
}
|
2026-04-05 21:01:29 +00:00
|
|
|
writeJSON(w, http.StatusOK, channels)
|
2026-03-14 21:17:09 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// handleGetMessages returns paginated messages for a channel.
|
2026-04-05 21:01:29 +00:00
|
|
|
func handleGetMessages(svc *service.Services) http.HandlerFunc {
|
2026-03-14 21:17:09 +01:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
channelID, ok := parseIDParam(w, r, "id")
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-05 21:01:29 +00:00
|
|
|
user, _ := r.Context().Value(UserKey).(*db.User)
|
|
|
|
|
if user == nil {
|
|
|
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
|
|
|
Error: "UNAUTHORIZED", Message: "authentication required",
|
2026-03-14 21:17:09 +01:00
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
before := int64(0)
|
|
|
|
|
if raw := r.URL.Query().Get("before"); raw != "" {
|
|
|
|
|
v, parseErr := strconv.ParseInt(raw, 10, 64)
|
|
|
|
|
if parseErr != nil || v < 0 {
|
|
|
|
|
writeJSON(w, http.StatusBadRequest, errorResponse{
|
2026-04-05 21:01:29 +00:00
|
|
|
Error: "BAD_REQUEST", Message: "before must be a non-negative integer",
|
2026-03-14 21:17:09 +01:00
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
before = v
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-01 22:06:14 +02:00
|
|
|
limit, ok := parseLimitParam(w, r)
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
2026-03-14 21:17:09 +01:00
|
|
|
}
|
|
|
|
|
|
2026-07-23 17:03:52 +02:00
|
|
|
msgs, hasMore, err := svc.Messages.GetMessages(r.Context(), user.ID, channelID, before, limit)
|
2026-03-14 21:17:09 +01:00
|
|
|
if err != nil {
|
2026-07-24 11:06:59 +02:00
|
|
|
writeServiceError(r.Context(), w, err)
|
2026-03-14 21:17:09 +01:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type response struct {
|
2026-03-16 16:57:01 +01:00
|
|
|
Messages []db.MessageAPIResponse `json:"messages"`
|
|
|
|
|
HasMore bool `json:"has_more"`
|
2026-03-14 21:17:09 +01:00
|
|
|
}
|
|
|
|
|
writeJSON(w, http.StatusOK, response{Messages: msgs, HasMore: hasMore})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-01 22:06:14 +02:00
|
|
|
// handleGetMessagesAround returns the window of messages centred on a message,
|
|
|
|
|
// oldest-first. Used to jump to a message (search hit, pinned entry, reply
|
|
|
|
|
// reference, permalink) that is not in the client's loaded history.
|
|
|
|
|
func handleGetMessagesAround(svc *service.Services) http.HandlerFunc {
|
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
channelID, ok := parseIDParam(w, r, "id")
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
messageID, ok := parseIDParam(w, r, "messageId")
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
user, _ := r.Context().Value(UserKey).(*db.User)
|
|
|
|
|
if user == nil {
|
|
|
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
|
|
|
Error: "UNAUTHORIZED", Message: "authentication required",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
limit, ok := parseLimitParam(w, r)
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
window, err := svc.Messages.GetMessagesAround(r.Context(), user.ID, channelID, messageID, limit)
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeServiceError(r.Context(), w, err)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
writeJSON(w, http.StatusOK, window)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// handleGetReactionUsers returns the users who reacted to a message with a
|
|
|
|
|
// given emoji, capped server-side at 100. The emoji arrives percent-encoded in
|
|
|
|
|
// the path; chi routes on RawPath when it differs from Path, so the param must
|
|
|
|
|
// be unescaped here rather than taken verbatim.
|
|
|
|
|
func handleGetReactionUsers(svc *service.Services) http.HandlerFunc {
|
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
channelID, ok := parseIDParam(w, r, "id")
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
messageID, ok := parseIDParam(w, r, "messageId")
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
user, _ := r.Context().Value(UserKey).(*db.User)
|
|
|
|
|
if user == nil {
|
|
|
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
|
|
|
Error: "UNAUTHORIZED", Message: "authentication required",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
emoji := chi.URLParam(r, "emoji")
|
|
|
|
|
if decoded, decErr := url.PathUnescape(emoji); decErr == nil {
|
|
|
|
|
emoji = decoded
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
users, err := svc.Messages.GetReactionUsers(r.Context(), user.ID, channelID, messageID, emoji)
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeServiceError(r.Context(), w, err)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type response struct {
|
|
|
|
|
Users []db.ReactionUser `json:"users"`
|
|
|
|
|
}
|
|
|
|
|
writeJSON(w, http.StatusOK, response{Users: users})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// purgeRequest is the JSON body for POST /api/v1/channels/{id}/messages/purge.
|
|
|
|
|
// Before is optional; 0 means "start from the newest message".
|
|
|
|
|
type purgeRequest struct {
|
|
|
|
|
Limit int `json:"limit"`
|
|
|
|
|
Before int64 `json:"before"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// purgeResponse reports what the purge actually deleted, which can be fewer
|
|
|
|
|
// than Limit rows when the channel holds less history.
|
|
|
|
|
type purgeResponse struct {
|
|
|
|
|
ChannelID int64 `json:"channel_id"`
|
|
|
|
|
IDs []int64 `json:"ids"`
|
|
|
|
|
Count int `json:"count"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// handlePurgeMessages bulk soft-deletes the newest messages in a channel and
|
|
|
|
|
// broadcasts a single chat_bulk_deleted event.
|
|
|
|
|
func handlePurgeMessages(svc *service.Services, broadcaster PurgeBroadcaster) http.HandlerFunc {
|
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
channelID, ok := parseIDParam(w, r, "id")
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
user, _ := r.Context().Value(UserKey).(*db.User)
|
|
|
|
|
if user == nil {
|
|
|
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
|
|
|
Error: "UNAUTHORIZED", Message: "authentication required",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var req purgeRequest
|
|
|
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
|
|
|
writeJSON(w, http.StatusBadRequest, errorResponse{
|
|
|
|
|
Error: "BAD_REQUEST", Message: "invalid request body",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
result, err := svc.Messages.PurgeMessages(r.Context(), user.ID, channelID, req.Limit, req.Before)
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeServiceError(r.Context(), w, err)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// A purge that matched nothing is still a success, but there is no
|
|
|
|
|
// state change to announce.
|
|
|
|
|
if broadcaster != nil && len(result.MessageIDs) > 0 {
|
|
|
|
|
broadcaster.BroadcastChatBulkDeleted(result.ChannelID, result.MessageIDs)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
writeJSON(w, http.StatusOK, purgeResponse{
|
|
|
|
|
ChannelID: result.ChannelID,
|
|
|
|
|
IDs: result.MessageIDs,
|
|
|
|
|
Count: len(result.MessageIDs),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-14 21:17:09 +01:00
|
|
|
// handleSearch performs a full-text search across messages.
|
2026-04-05 21:01:29 +00:00
|
|
|
func handleSearch(svc *service.Services) http.HandlerFunc {
|
2026-03-14 21:17:09 +01:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
q := r.URL.Query().Get("q")
|
|
|
|
|
if q == "" {
|
|
|
|
|
writeJSON(w, http.StatusBadRequest, errorResponse{
|
2026-04-05 21:01:29 +00:00
|
|
|
Error: "BAD_REQUEST", Message: "query parameter 'q' is required",
|
|
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
user, _ := r.Context().Value(UserKey).(*db.User)
|
|
|
|
|
if user == nil {
|
|
|
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
|
|
|
Error: "UNAUTHORIZED", Message: "authentication required",
|
2026-03-14 21:17:09 +01:00
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var channelID *int64
|
|
|
|
|
if raw := r.URL.Query().Get("channel_id"); raw != "" {
|
|
|
|
|
v, parseErr := strconv.ParseInt(raw, 10, 64)
|
|
|
|
|
if parseErr != nil || v <= 0 {
|
|
|
|
|
writeJSON(w, http.StatusBadRequest, errorResponse{
|
2026-04-05 21:01:29 +00:00
|
|
|
Error: "BAD_REQUEST", Message: "channel_id must be a positive integer",
|
2026-03-14 21:17:09 +01:00
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
channelID = &v
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-01 22:06:14 +02:00
|
|
|
limit, ok := parseLimitParam(w, r)
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
2026-03-14 21:17:09 +01:00
|
|
|
}
|
|
|
|
|
|
2026-07-23 17:03:52 +02:00
|
|
|
results, err := svc.Messages.SearchMessages(r.Context(), user.ID, q, channelID, limit)
|
2026-04-05 21:01:29 +00:00
|
|
|
if err != nil {
|
|
|
|
|
if isInvalidSearchQueryError(err) {
|
|
|
|
|
writeJSON(w, http.StatusBadRequest, errorResponse{
|
|
|
|
|
Error: "BAD_REQUEST", Message: "invalid search query",
|
2026-03-29 19:39:22 +02:00
|
|
|
})
|
|
|
|
|
return
|
2026-03-19 04:19:03 +01:00
|
|
|
}
|
2026-07-24 11:06:59 +02:00
|
|
|
writeServiceError(r.Context(), w, err)
|
2026-04-05 21:01:29 +00:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if results == nil {
|
|
|
|
|
results = []db.MessageSearchResult{}
|
2026-03-16 16:54:56 +01:00
|
|
|
}
|
|
|
|
|
|
2026-03-14 21:17:09 +01:00
|
|
|
type response struct {
|
|
|
|
|
Results []db.MessageSearchResult `json:"results"`
|
|
|
|
|
}
|
2026-04-01 09:23:17 +02:00
|
|
|
writeJSON(w, http.StatusOK, response{Results: results})
|
2026-03-14 21:17:09 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-21 21:36:10 +01:00
|
|
|
// handleGetPins returns all pinned messages for a channel.
|
2026-04-05 21:01:29 +00:00
|
|
|
func handleGetPins(svc *service.Services) http.HandlerFunc {
|
2026-03-21 21:36:10 +01:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
channelID, ok := parseIDParam(w, r, "id")
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-05 21:01:29 +00:00
|
|
|
user, _ := r.Context().Value(UserKey).(*db.User)
|
|
|
|
|
if user == nil {
|
|
|
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
|
|
|
Error: "UNAUTHORIZED", Message: "authentication required",
|
2026-03-21 21:36:10 +01:00
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-23 17:03:52 +02:00
|
|
|
msgs, err := svc.Messages.GetPinnedMessages(r.Context(), user.ID, channelID)
|
2026-03-21 21:36:10 +01:00
|
|
|
if err != nil {
|
2026-07-24 11:06:59 +02:00
|
|
|
writeServiceError(r.Context(), w, err)
|
2026-03-21 21:36:10 +01:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type response struct {
|
|
|
|
|
Messages []db.MessageAPIResponse `json:"messages"`
|
|
|
|
|
HasMore bool `json:"has_more"`
|
|
|
|
|
}
|
|
|
|
|
writeJSON(w, http.StatusOK, response{Messages: msgs, HasMore: false})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-21 21:42:14 +01:00
|
|
|
// handleSetPinned pins or unpins a message in a channel.
|
2026-04-05 21:01:29 +00:00
|
|
|
func handleSetPinned(svc *service.Services, pinned bool) http.HandlerFunc {
|
2026-03-21 21:36:10 +01:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
channelID, ok := parseIDParam(w, r, "id")
|
|
|
|
|
if !ok {
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-03-21 21:42:14 +01:00
|
|
|
messageID, ok := parseIDParam(w, r, "messageId")
|
|
|
|
|
if !ok {
|
2026-03-21 21:36:10 +01:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-05 21:01:29 +00:00
|
|
|
user, _ := r.Context().Value(UserKey).(*db.User)
|
|
|
|
|
if user == nil {
|
|
|
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
|
|
|
Error: "UNAUTHORIZED", Message: "authentication required",
|
2026-03-28 10:39:23 +01:00
|
|
|
})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-23 17:03:52 +02:00
|
|
|
if err := svc.Messages.SetMessagePinned(r.Context(), user.ID, channelID, messageID, pinned); err != nil {
|
2026-07-24 11:06:59 +02:00
|
|
|
writeServiceError(r.Context(), w, err)
|
2026-03-21 21:36:10 +01:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-05 21:01:29 +00:00
|
|
|
// writeServiceError maps a service-layer error to an HTTP response.
|
2026-07-24 11:06:59 +02:00
|
|
|
func writeServiceError(ctx context.Context, w http.ResponseWriter, err error) {
|
2026-04-05 21:01:29 +00:00
|
|
|
switch {
|
|
|
|
|
case errors.Is(err, service.ErrRateLimited):
|
|
|
|
|
writeJSON(w, http.StatusTooManyRequests, errorResponse{Error: "RATE_LIMITED", Message: err.Error()})
|
|
|
|
|
case errors.Is(err, service.ErrBadRequest):
|
|
|
|
|
writeJSON(w, http.StatusBadRequest, errorResponse{Error: "BAD_REQUEST", Message: err.Error()})
|
|
|
|
|
case errors.Is(err, service.ErrNotFound):
|
|
|
|
|
writeJSON(w, http.StatusNotFound, errorResponse{Error: "NOT_FOUND", Message: err.Error()})
|
|
|
|
|
case errors.Is(err, service.ErrForbidden), errors.Is(err, service.ErrBlocked):
|
|
|
|
|
writeJSON(w, http.StatusForbidden, errorResponse{Error: "FORBIDDEN", Message: err.Error()})
|
|
|
|
|
case errors.Is(err, service.ErrConflict):
|
|
|
|
|
writeJSON(w, http.StatusConflict, errorResponse{Error: "CONFLICT", Message: err.Error()})
|
2026-04-06 22:48:59 +02:00
|
|
|
case errors.Is(err, service.ErrInternal):
|
2026-07-24 11:06:59 +02:00
|
|
|
// ErrorContext so the enriching handler attaches req_id/trace_id,
|
|
|
|
|
// linking this 500 to its request log line and trace.
|
|
|
|
|
slog.ErrorContext(ctx, "service error", "error", err)
|
2026-04-07 07:59:10 +02:00
|
|
|
writeJSON(w, http.StatusInternalServerError, errorResponse{Error: "INTERNAL_ERROR", Message: "an internal error occurred"})
|
2026-04-05 21:01:29 +00:00
|
|
|
default:
|
2026-07-24 11:06:59 +02:00
|
|
|
slog.ErrorContext(ctx, "service error", "error", err)
|
2026-04-05 21:01:29 +00:00
|
|
|
writeJSON(w, http.StatusInternalServerError, errorResponse{Error: "INTERNAL_ERROR", Message: "internal error"})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-01 22:06:14 +02:00
|
|
|
// parseLimitParam reads the shared `limit` query parameter, defaulting to
|
|
|
|
|
// defaultMessageLimit and clamping at maxMessageLimit. Writes a 400 response
|
|
|
|
|
// and returns false when the value is present but not a positive integer.
|
|
|
|
|
func parseLimitParam(w http.ResponseWriter, r *http.Request) (int, bool) {
|
|
|
|
|
raw := r.URL.Query().Get("limit")
|
|
|
|
|
if raw == "" {
|
|
|
|
|
return defaultMessageLimit, true
|
|
|
|
|
}
|
|
|
|
|
v, err := strconv.Atoi(raw)
|
|
|
|
|
if err != nil || v < 1 {
|
|
|
|
|
writeJSON(w, http.StatusBadRequest, errorResponse{
|
|
|
|
|
Error: "BAD_REQUEST", Message: "limit must be a positive integer",
|
|
|
|
|
})
|
|
|
|
|
return 0, false
|
|
|
|
|
}
|
|
|
|
|
return min(v, maxMessageLimit), true
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-14 21:17:09 +01:00
|
|
|
// parseIDParam extracts and validates a chi URL param as int64.
|
|
|
|
|
// Writes a 400 response and returns false on failure.
|
|
|
|
|
func parseIDParam(w http.ResponseWriter, r *http.Request, param string) (int64, bool) {
|
|
|
|
|
raw := chi.URLParam(r, param)
|
|
|
|
|
id, err := strconv.ParseInt(raw, 10, 64)
|
|
|
|
|
if err != nil || id <= 0 {
|
|
|
|
|
writeJSON(w, http.StatusBadRequest, errorResponse{
|
|
|
|
|
Error: "BAD_REQUEST",
|
|
|
|
|
Message: param + " must be a positive integer",
|
|
|
|
|
})
|
|
|
|
|
return 0, false
|
|
|
|
|
}
|
|
|
|
|
return id, true
|
|
|
|
|
}
|