package server import ( "database/sql" "encoding/json" "errors" "net/http" "strconv" "strings" "time" ) func (s *Server) handleNotificationsAPI(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "private, no-store") domain := s.domainUUIDForRequest(r) principal, err := s.store.PrincipalForSession(domain, s.authTokenFromRequest(r)) if err != nil { writeEventJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"}) return } action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/api/v1/notifications"), "/") switch action { case "push": s.handleNotificationPush(w, r, domain, principal.UUID) return case "": if r.Method != http.MethodGet { break } limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) startedMS := time.Now().UnixMilli() items, next, err := s.store.ListNotifications(r.Context(), domain, principal.UUID, r.URL.Query().Get("unread") == "1", r.URL.Query().Get("before"), limit) if err != nil { writeEventJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()}) return } for i := range items { s.decorateTaskNotification(r, &items[i]) if items[i].Href == "/v/notification" || items[i].Href == "" { items[i].Href = "/v/notification?uuid=" + items[i].UUID } } writeEventJSON(w, http.StatusOK, map[string]any{"notifications": items, "next_cursor": next, "server_time_ms": startedMS}) return case "read": if r.Method != http.MethodPost && r.Method != http.MethodPatch { break } r.Body = http.MaxBytesReader(w, r.Body, 32<<10) var input struct { UUID string `json:"uuid"` } if err := json.NewDecoder(r.Body).Decode(&input); err != nil || strings.TrimSpace(input.UUID) == "" { writeEventJSON(w, http.StatusBadRequest, map[string]string{"error": "notification uuid is required"}) return } if err := s.store.MarkNotificationRead(domain, principal.UUID, input.UUID); err != nil { code := http.StatusInternalServerError if errors.Is(err, sql.ErrNoRows) { code = http.StatusNotFound } writeEventJSON(w, code, map[string]string{"error": err.Error()}) return } writeEventJSON(w, http.StatusOK, map[string]bool{"read": true}) return } w.Header().Set("Allow", "GET, POST, PATCH") writeEventJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "unsupported notification operation"}) }