Expand tracker analytics and dashboard UX
This commit is contained in:
+378
-2
@@ -3,10 +3,13 @@ package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -53,13 +56,27 @@ func New(s *store.Store, admin auth.Checker, loc *time.Location, log *slog.Logge
|
||||
api.Handle("POST /browser/events", srv.device(srv.ingestEvents(ingest.Browser)))
|
||||
api.Handle("POST /presence/events", srv.device(srv.ingestEvents(ingest.Presence)))
|
||||
api.Handle("POST /manual/events", srv.device(srv.ingestEvents(ingest.Manual)))
|
||||
api.Handle("POST /samples", srv.device(http.HandlerFunc(srv.ingestSamples)))
|
||||
api.Handle("POST /samples/events", srv.device(http.HandlerFunc(srv.ingestSamples)))
|
||||
api.Handle("GET /samples", srv.deviceOrAdmin(http.HandlerFunc(srv.samples)))
|
||||
api.Handle("POST /location/{event}", srv.device(http.HandlerFunc(srv.ingestLocation)))
|
||||
api.Handle("POST /location/{event}/{place}", srv.device(http.HandlerFunc(srv.ingestLocation)))
|
||||
api.Handle("GET /activities", srv.deviceOrAdmin(http.HandlerFunc(srv.activities)))
|
||||
api.Handle("GET /activities/export", srv.adminAPI(http.HandlerFunc(srv.exportActivities)))
|
||||
api.Handle("GET /summary/daily", srv.deviceOrAdmin(http.HandlerFunc(srv.dailySummary)))
|
||||
api.Handle("GET /summary/range", srv.deviceOrAdmin(http.HandlerFunc(srv.rangeSummary)))
|
||||
api.Handle("GET /goals", srv.adminAPI(http.HandlerFunc(srv.listGoals)))
|
||||
api.Handle("POST /goals", srv.adminAPI(http.HandlerFunc(srv.createGoal)))
|
||||
api.Handle("PUT /goals/{id}", srv.adminAPI(http.HandlerFunc(srv.updateGoal)))
|
||||
api.Handle("DELETE /goals/{id}", srv.adminAPI(http.HandlerFunc(srv.deleteGoal)))
|
||||
api.Handle("GET /devices", srv.adminAPI(http.HandlerFunc(srv.listDevices)))
|
||||
api.Handle("POST /devices", srv.adminAPI(http.HandlerFunc(srv.createDevice)))
|
||||
api.Handle("DELETE /devices/{name}", srv.adminAPI(http.HandlerFunc(srv.revokeDevice)))
|
||||
api.Handle("GET /reports", srv.adminAPI(http.HandlerFunc(srv.listReports)))
|
||||
api.Handle("POST /reports", srv.adminAPI(http.HandlerFunc(srv.createReport)))
|
||||
api.Handle("GET /notifications/status", srv.adminAPI(http.HandlerFunc(srv.notificationStatus)))
|
||||
api.Handle("PUT /notifications/config", srv.adminAPI(http.HandlerFunc(srv.updateNotificationConfig)))
|
||||
api.Handle("POST /privacy/purge", srv.adminAPI(http.HandlerFunc(srv.purgePrivacyData)))
|
||||
mux.Handle("/api/v1/", http.StripPrefix("/api/v1", api))
|
||||
|
||||
return srv.logRequests(mux)
|
||||
@@ -193,6 +210,93 @@ func (s *Server) ingestEvents(spec ingest.Spec) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
type sampleRequest struct {
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"`
|
||||
Metric string `json:"metric"`
|
||||
TS time.Time `json:"ts"`
|
||||
Value float64 `json:"value"`
|
||||
Unit string `json:"unit"`
|
||||
}
|
||||
|
||||
func (s *Server) ingestSamples(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Samples []sampleRequest `json:"samples"`
|
||||
}
|
||||
if !s.decode(w, r, maxEventBody, &req) {
|
||||
return
|
||||
}
|
||||
if len(req.Samples) == 0 || len(req.Samples) > ingest.MaxBatch {
|
||||
writeError(w, http.StatusBadRequest, "samples must contain 1-1000 items")
|
||||
return
|
||||
}
|
||||
samples := make([]store.Sample, 0, len(req.Samples))
|
||||
for i, in := range req.Samples {
|
||||
in.ID, in.Source, in.Metric, in.Unit = strings.TrimSpace(in.ID), strings.TrimSpace(in.Source), strings.TrimSpace(in.Metric), strings.TrimSpace(in.Unit)
|
||||
if in.ID == "" || in.Source == "" || in.Metric == "" || in.TS.IsZero() || !isFinite(in.Value) {
|
||||
writeError(w, http.StatusUnprocessableEntity, "sample "+strconv.Itoa(i)+" has invalid id, source, metric, ts, or value")
|
||||
return
|
||||
}
|
||||
if in.TS.After(s.now().Add(5 * time.Minute)) {
|
||||
writeError(w, http.StatusUnprocessableEntity, "sample timestamp is in the future")
|
||||
return
|
||||
}
|
||||
samples = append(samples, store.Sample{ExternalID: in.ID, Source: in.Source, Metric: in.Metric, TS: in.TS.UTC(), Value: in.Value, Unit: in.Unit})
|
||||
}
|
||||
n, err := s.store.InsertSamples(r.Context(), deviceFrom(r.Context()).ID, samples)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"received": len(samples), "inserted": n})
|
||||
}
|
||||
|
||||
func isFinite(v float64) bool { return !math.IsNaN(v) && !math.IsInf(v, 0) }
|
||||
|
||||
func (s *Server) samples(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
now := s.now()
|
||||
f := store.SampleFilter{From: now.Add(-24 * time.Hour), To: now, Source: q.Get("source"), Metric: q.Get("metric"), Limit: 1000}
|
||||
var err error
|
||||
if v := q.Get("from"); v != "" {
|
||||
if f.From, err = time.Parse(time.RFC3339, v); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "from must be RFC3339")
|
||||
return
|
||||
}
|
||||
}
|
||||
if v := q.Get("to"); v != "" {
|
||||
if f.To, err = time.Parse(time.RFC3339, v); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "to must be RFC3339")
|
||||
return
|
||||
}
|
||||
}
|
||||
if v := q.Get("limit"); v != "" {
|
||||
if f.Limit, err = strconv.Atoi(v); err != nil || f.Limit < 1 || f.Limit > 10000 {
|
||||
writeError(w, http.StatusBadRequest, "limit must be 1-10000")
|
||||
return
|
||||
}
|
||||
}
|
||||
if v := q.Get("cursor"); v != "" {
|
||||
var c activityCursor
|
||||
b, decodeErr := base64.RawURLEncoding.DecodeString(v)
|
||||
if decodeErr != nil || json.Unmarshal(b, &c) != nil || c.ID < 1 || c.StartedAt.IsZero() {
|
||||
writeError(w, http.StatusBadRequest, "cursor is invalid")
|
||||
return
|
||||
}
|
||||
f.After = &store.SampleCursor{TS: c.StartedAt, ID: c.ID}
|
||||
}
|
||||
items, next, err := s.store.SamplesPage(r.Context(), f)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
out := map[string]any{"samples": items}
|
||||
if next != nil {
|
||||
out["next_cursor"] = encodeActivityCursor(activityCursor{StartedAt: next.TS, ID: next.ID})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// ingestLocation takes an arrive or leave from a phone geofence automation.
|
||||
// The place comes from the path (/arrive/gym), ?place=, the body's "place",
|
||||
// or defaults to home. ingest.Destination decides where the device ends up.
|
||||
@@ -259,13 +363,84 @@ func (s *Server) activities(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
var cursor *store.ActivityCursor
|
||||
if v := q.Get("cursor"); v != "" {
|
||||
var payload activityCursor
|
||||
decoded, decodeErr := base64.RawURLEncoding.DecodeString(v)
|
||||
if decodeErr != nil || json.Unmarshal(decoded, &payload) != nil || payload.ID < 1 || payload.StartedAt.IsZero() {
|
||||
writeError(w, http.StatusBadRequest, "cursor is invalid")
|
||||
return
|
||||
}
|
||||
cursor = &store.ActivityCursor{StartedAt: payload.StartedAt, ID: payload.ID}
|
||||
f.After = cursor
|
||||
}
|
||||
|
||||
acts, err := s.store.Activities(r.Context(), f)
|
||||
acts, next, err := s.store.ActivitiesPage(r.Context(), f)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"activities": acts})
|
||||
out := map[string]any{"activities": acts}
|
||||
if next != nil {
|
||||
out["next_cursor"] = encodeActivityCursor(activityCursor{StartedAt: next.StartedAt, ID: next.ID})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
type activityCursor struct {
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
|
||||
func encodeActivityCursor(c activityCursor) string {
|
||||
b, _ := json.Marshal(c)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func (s *Server) exportActivities(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
now := s.now()
|
||||
f := store.ActivityFilter{From: now.Add(-24 * time.Hour), To: now, Source: q.Get("source"), Kind: q.Get("kind"), Limit: 10000}
|
||||
var err error
|
||||
if v := q.Get("from"); v != "" {
|
||||
if f.From, err = time.Parse(time.RFC3339, v); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "from must be RFC3339")
|
||||
return
|
||||
}
|
||||
}
|
||||
if v := q.Get("to"); v != "" {
|
||||
if f.To, err = time.Parse(time.RFC3339, v); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "to must be RFC3339")
|
||||
return
|
||||
}
|
||||
}
|
||||
var acts []store.StoredActivity
|
||||
for {
|
||||
page, next, pageErr := s.store.ActivitiesPage(r.Context(), f)
|
||||
if pageErr != nil {
|
||||
s.internalError(w, r, pageErr)
|
||||
return
|
||||
}
|
||||
acts = append(acts, page...)
|
||||
if next == nil {
|
||||
break
|
||||
}
|
||||
f.After = next
|
||||
}
|
||||
if q.Get("format") == "json" {
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=activities.json")
|
||||
writeJSON(w, http.StatusOK, map[string]any{"activities": acts})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=activities.csv")
|
||||
cw := csv.NewWriter(w)
|
||||
_ = cw.Write([]string{"id", "device", "source", "kind", "label", "started_at", "ended_at", "duration_s", "attrs"})
|
||||
for _, a := range acts {
|
||||
attrs, _ := json.Marshal(a.Attrs)
|
||||
_ = cw.Write([]string{strconv.FormatInt(a.ID, 10), a.Device, a.Source, a.Kind, a.Label, a.StartedAt.Format(time.RFC3339Nano), a.EndedAt.Format(time.RFC3339Nano), strconv.Itoa(a.DurationS), string(attrs)})
|
||||
}
|
||||
cw.Flush()
|
||||
}
|
||||
|
||||
func (s *Server) dailySummary(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -292,6 +467,207 @@ func (s *Server) dailySummary(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, summary.Build(from.Format(time.DateOnly), from, to, totals, goals))
|
||||
}
|
||||
|
||||
func (s *Server) rangeSummary(w http.ResponseWriter, r *http.Request) {
|
||||
from, to, ok := s.parseRange(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
totals, err := s.store.Totals(r.Context(), from, to)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
samples, err := s.store.SampleSummary(r.Context(), from, to)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"from": from, "to": to, "totals": totals, "samples": samples})
|
||||
}
|
||||
|
||||
func (s *Server) parseRange(w http.ResponseWriter, r *http.Request) (time.Time, time.Time, bool) {
|
||||
now := s.now()
|
||||
from, to := now.Add(-24*time.Hour), now
|
||||
var err error
|
||||
if v := r.URL.Query().Get("from"); v != "" {
|
||||
from, err = time.Parse(time.RFC3339, v)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "from must be RFC3339")
|
||||
return time.Time{}, time.Time{}, false
|
||||
}
|
||||
}
|
||||
if v := r.URL.Query().Get("to"); v != "" {
|
||||
to, err = time.Parse(time.RFC3339, v)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "to must be RFC3339")
|
||||
return time.Time{}, time.Time{}, false
|
||||
}
|
||||
}
|
||||
if !from.Before(to) {
|
||||
writeError(w, http.StatusBadRequest, "from must be before to")
|
||||
return time.Time{}, time.Time{}, false
|
||||
}
|
||||
return from, to, true
|
||||
}
|
||||
|
||||
func (s *Server) listReports(w http.ResponseWriter, r *http.Request) {
|
||||
reports, err := s.store.Reports(r.Context())
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"reports": reports})
|
||||
}
|
||||
|
||||
func (s *Server) createReport(w http.ResponseWriter, r *http.Request) {
|
||||
var report store.Report
|
||||
if !s.decode(w, r, 1<<20, &report) {
|
||||
return
|
||||
}
|
||||
if report.PeriodStart.IsZero() || report.PeriodEnd.IsZero() || !report.PeriodStart.Before(report.PeriodEnd) || strings.TrimSpace(report.Model) == "" || report.Body == "" {
|
||||
writeError(w, http.StatusBadRequest, "period_start, period_end, model, and body are required")
|
||||
return
|
||||
}
|
||||
report.Model, report.PromptHash = strings.TrimSpace(report.Model), strings.TrimSpace(report.PromptHash)
|
||||
created, err := s.store.CreateReport(r.Context(), report)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, created)
|
||||
}
|
||||
|
||||
func (s *Server) notificationStatus(w http.ResponseWriter, r *http.Request) {
|
||||
settings, err := s.store.NotificationSettings(r.Context())
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"configured": settings.Enabled && settings.NtfyTopic != "", "settings": settings})
|
||||
}
|
||||
|
||||
func (s *Server) updateNotificationConfig(w http.ResponseWriter, r *http.Request) {
|
||||
var settings store.NotificationSettings
|
||||
if !s.decode(w, r, 16<<10, &settings) {
|
||||
return
|
||||
}
|
||||
settings.NtfyServer, settings.NtfyTopic = strings.TrimRight(strings.TrimSpace(settings.NtfyServer), "/"), strings.TrimSpace(settings.NtfyTopic)
|
||||
if settings.NtfyServer == "" {
|
||||
settings.NtfyServer = "https://ntfy.sh"
|
||||
}
|
||||
if settings.RetentionDays < 0 || (settings.Enabled && settings.NtfyTopic == "") {
|
||||
writeError(w, http.StatusBadRequest, "retention_days must be non-negative and enabled requires ntfy_topic")
|
||||
return
|
||||
}
|
||||
updated, err := s.store.UpdateNotificationSettings(r.Context(), settings)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
func (s *Server) purgePrivacyData(w http.ResponseWriter, r *http.Request) {
|
||||
cutoff := r.URL.Query().Get("before")
|
||||
if cutoff == "" {
|
||||
writeError(w, http.StatusBadRequest, "before must be RFC3339")
|
||||
return
|
||||
}
|
||||
before, err := time.Parse(time.RFC3339, cutoff)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "before must be RFC3339")
|
||||
return
|
||||
}
|
||||
n, err := s.store.PurgeBefore(r.Context(), before)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"deleted": n, "before": before})
|
||||
}
|
||||
|
||||
func (s *Server) listGoals(w http.ResponseWriter, r *http.Request) {
|
||||
goals, err := s.store.Goals(r.Context())
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"goals": goals})
|
||||
}
|
||||
|
||||
type goalRequest struct {
|
||||
Kind string `json:"kind"`
|
||||
Label string `json:"label"`
|
||||
Op string `json:"op"`
|
||||
TargetS int64 `json:"target_s"`
|
||||
Period string `json:"period"`
|
||||
}
|
||||
|
||||
func (s *Server) decodeGoal(w http.ResponseWriter, r *http.Request) (store.Goal, bool) {
|
||||
var req goalRequest
|
||||
if !s.decode(w, r, 4<<10, &req) {
|
||||
return store.Goal{}, false
|
||||
}
|
||||
req.Kind, req.Label, req.Op, req.Period = strings.TrimSpace(req.Kind), strings.TrimSpace(req.Label), strings.TrimSpace(req.Op), strings.TrimSpace(req.Period)
|
||||
if req.Kind == "" || (req.Op != ">=" && req.Op != "<=") || req.TargetS < 0 || (req.Period != "" && req.Period != "day") {
|
||||
writeError(w, http.StatusBadRequest, "kind, op (>= or <=), target_s >= 0, and period=day are required")
|
||||
return store.Goal{}, false
|
||||
}
|
||||
return store.Goal{Kind: req.Kind, Label: req.Label, Op: req.Op, TargetS: req.TargetS}, true
|
||||
}
|
||||
|
||||
func (s *Server) createGoal(w http.ResponseWriter, r *http.Request) {
|
||||
goal, ok := s.decodeGoal(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
goal, err := s.store.CreateGoal(r.Context(), goal)
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, goal)
|
||||
}
|
||||
|
||||
func (s *Server) updateGoal(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
writeError(w, http.StatusBadRequest, "id must be a positive integer")
|
||||
return
|
||||
}
|
||||
goal, ok := s.decodeGoal(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
goal.ID = id
|
||||
goal, err = s.store.UpdateGoal(r.Context(), goal)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "goal not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, goal)
|
||||
}
|
||||
|
||||
func (s *Server) deleteGoal(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
writeError(w, http.StatusBadRequest, "id must be a positive integer")
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteGoal(r.Context(), id); errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "goal not found")
|
||||
return
|
||||
} else if err != nil {
|
||||
s.internalError(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||||
}
|
||||
|
||||
func (s *Server) listDevices(w http.ResponseWriter, r *http.Request) {
|
||||
devs, err := s.store.ListDevices(r.Context())
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user