Something went wrong. Try again.
forked from scottlanoue.com/atmosphere-mail
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118// SPDX-License-Identifier: AGPL-3.0-or-later
package server
import ( "encoding/base64" "encoding/json" "log" "net/http" "strconv"
"comail/internal/store")
type queryLabelsResponse struct { Cursor string `json:"cursor,omitempty"` Labels []labelResponse `json:"labels"`}
type labelResponse struct { Src string `json:"src"` URI string `json:"uri"` Val string `json:"val"` Cts string `json:"cts"` Neg *bool `json:"neg,omitempty"` Sig *bytesJSON `json:"sig,omitempty"` Ver int64 `json:"ver"`}
// bytesJSON encodes bytes as {"$bytes": "<base64>"} per atproto data model.type bytesJSON struct { Bytes string `json:"$bytes"`}
func newBytesJSON(b []byte) *bytesJSON { if len(b) == 0 { return nil } return &bytesJSON{Bytes: base64.StdEncoding.EncodeToString(b)}}
func labelToResponse(l store.Label) labelResponse { lr := labelResponse{ Src: l.Src, URI: l.URI, Val: l.Val, Cts: l.Cts, Sig: newBytesJSON(l.Sig), Ver: store.LabelVersion, } if l.Neg { neg := true lr.Neg = &neg } return lr}
func (s *Server) handleQueryLabels(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return }
q := r.URL.Query() uriPatterns := q["uriPatterns"] sources := q["sources"] cursor := q.Get("cursor") limitStr := q.Get("limit")
limit := 50 if limitStr != "" { n, err := strconv.Atoi(limitStr) if err != nil || n < 1 { http.Error(w, "invalid limit", http.StatusBadRequest) return } if n > 250 { n = 250 } limit = n }
if len(uriPatterns) == 0 { http.Error(w, "uriPatterns required", http.StatusBadRequest) return }
ctx := r.Context()
// Build source filter set for O(1) lookup sourceSet := map[string]bool{} for _, src := range sources { sourceSet[src] = true }
// Single query across all patterns with correct global pagination labels, nextCursor, err := s.store.GetLabelsByURIPatterns(ctx, uriPatterns, cursor, limit) if err != nil { log.Printf("queryLabels: %v", err) http.Error(w, "internal error", http.StatusInternalServerError) return }
allLabels := make([]labelResponse, 0, len(labels)) for _, l := range labels { if len(sourceSet) > 0 && !sourceSet[l.Src] { continue } allLabels = append(allLabels, labelToResponse(l)) }
w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(queryLabelsResponse{ Cursor: nextCursor, Labels: allLabels, })}