Files

183 lines
5.2 KiB
Go
Raw Permalink Normal View History

package main
import (
2026-10-19 07:48:07 +00:00
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"strconv"
2026-10-19 07:48:07 +00:00
"strings"
"time"
)
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
s.writeWebData(w, r, requestUserID(r))
}
func (s *Server) writeWebData(w http.ResponseWriter, r *http.Request, userID int64) {
lists, err := s.db.queryLists(r.Context(), userID, false, nil)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
return
}
fields, err := s.db.queryFields(r.Context(), userID, false, nil, "")
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
return
}
items, err := s.db.queryItems(r.Context(), userID, false, nil, "")
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
return
}
values, err := s.db.queryValues(r.Context(), userID, nil, "")
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
return
}
itemToList := make(map[string]string, len(items))
for _, item := range items {
itemToList[item.ID] = item.ListID
}
fieldMax := make(map[string]int64)
for _, field := range fields {
if int64(field.UpdatedAt) > fieldMax[field.ListID] {
fieldMax[field.ListID] = int64(field.UpdatedAt)
}
}
itemMax := make(map[string]int64)
for _, item := range items {
if int64(item.UpdatedAt) > itemMax[item.ListID] {
itemMax[item.ListID] = int64(item.UpdatedAt)
}
}
valueMax := make(map[string]int64)
for _, value := range values {
listID := itemToList[value.ItemID]
if listID != "" && int64(value.UpdatedAt) > valueMax[listID] {
valueMax[listID] = int64(value.UpdatedAt)
}
}
type webList struct {
List
EffectiveUpdatedAt int64 `json:"effectiveUpdatedAt"`
}
webLists := make([]webList, 0, len(lists))
for _, list := range lists {
effective := int64(list.UpdatedAt)
if fieldMax[list.ID] > effective {
effective = fieldMax[list.ID]
}
if itemMax[list.ID] > effective {
effective = itemMax[list.ID]
}
if valueMax[list.ID] > effective {
effective = valueMax[list.ID]
}
webLists = append(webLists, webList{List: list, EffectiveUpdatedAt: effective})
}
2026-10-19 07:48:07 +00:00
payload := map[string]any{
"lists": webLists,
"fields": fields,
"items": items,
"values": values,
"stats": map[string]int{
"lists": len(lists),
"fields": len(fields),
"items": len(items),
"values": len(values),
},
2026-10-19 07:48:07 +00:00
}
// The ETag covers the data only; the timestamp is added after hashing because
// it changes on every request.
body, err := json.Marshal(payload)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
return
}
digest := sha256.Sum256(body)
etag := `W/"` + hex.EncodeToString(digest[:]) + `"`
// Browsers may keep this per-user response, but revalidate it on every poll,
// so an unchanged dashboard gets a 304 instead of the full body.
w.Header().Set("Cache-Control", "private, no-cache")
w.Header().Set("ETag", etag)
if etagMatches(r.Header.Get("If-None-Match"), etag) {
w.WriteHeader(http.StatusNotModified)
return
}
payload["timestamp"] = time.Now().UnixMilli()
writeJSON(w, http.StatusOK, payload)
}
// etagMatches reports whether an If-None-Match header matches etag under the
// weak comparison of RFC 9110, which ignores the W/ prefix.
func etagMatches(ifNoneMatch, etag string) bool {
if strings.TrimSpace(ifNoneMatch) == "*" {
return true
}
want := strings.TrimPrefix(etag, "W/")
for _, candidate := range strings.Split(ifNoneMatch, ",") {
if strings.TrimPrefix(strings.TrimSpace(candidate), "W/") == want {
return true
}
}
return false
}
func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request) {
since, err := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
if err != nil || since < 0 {
since = 0
}
deviceID := requestDeviceID(r, "")
query := `
SELECT id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat
FROM notifications
WHERE createdat > $1
AND EXISTS (
SELECT 1 FROM list_memberships m
WHERE m.listid = notifications.listid AND m.user_id = $2
)
`
args := []any{since, requestUserID(r)}
if deviceID != "" {
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $3)`
args = append(args, deviceID)
}
query += ` ORDER BY createdat ASC LIMIT 500`
rows, err := s.db.pool.Query(r.Context(), query, args...)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to poll notifications")
return
}
defer rows.Close()
events := make([]NotificationEvent, 0)
for rows.Next() {
var event NotificationEvent
var origin, entityID, listID *string
if err := rows.Scan(&event.ID, &origin, &event.EventType, &event.EntityType, &entityID, &listID, &event.CreatedAt); err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to poll notifications")
return
}
if origin != nil {
event.DeviceIDOrigin = *origin
}
if entityID != nil {
event.EntityID = *entityID
}
if listID != nil {
event.ListID = *listID
}
events = append(events, event)
}
if err := rows.Err(); err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to poll notifications")
return
}
writeJSON(w, http.StatusOK, PollResponse{Notifications: events, ServerTimestamp: time.Now().UnixMilli()})
}