Replace Apple Health ingest with iPhone location geofences
POST /api/v1/location/{arrive,leave} records place intervals (home or a
named place, and away in between) from Shortcuts automations. A stale
"leave" for a place the device has already left is ignored. The Health
Auto Export endpoint and its normalizer are removed.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -1,156 +0,0 @@
|
||||
package ingest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Health Auto Export (iOS) REST automation payload (JSON export format).
|
||||
// Only the fields we use are declared.
|
||||
type HAEPayload struct {
|
||||
Data struct {
|
||||
Metrics []HAEMetric `json:"metrics"`
|
||||
Workouts []HAEWorkout `json:"workouts"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type HAEMetric struct {
|
||||
Name string `json:"name"`
|
||||
Units string `json:"units"`
|
||||
Data []map[string]any `json:"data"`
|
||||
}
|
||||
|
||||
type HAEWorkout struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Location string `json:"location"`
|
||||
Distance map[string]any `json:"distance"`
|
||||
Energy map[string]any `json:"activeEnergyBurned"`
|
||||
}
|
||||
|
||||
const (
|
||||
haeSource = "health"
|
||||
haeTimeLayout = "2006-01-02 15:04:05 -0700"
|
||||
)
|
||||
|
||||
// NormalizeHAE converts workouts and sleep into activities, and every other
|
||||
// quantity metric into samples. Entries that can't be parsed are skipped
|
||||
// rather than failing the whole export.
|
||||
func NormalizeHAE(p HAEPayload) ([]Activity, []Sample, error) {
|
||||
var acts []Activity
|
||||
var samples []Sample
|
||||
|
||||
for _, w := range p.Data.Workouts {
|
||||
start, err1 := parseHAETime(w.Start)
|
||||
end, err2 := parseHAETime(w.End)
|
||||
if err1 != nil || err2 != nil || end.Before(start) {
|
||||
continue
|
||||
}
|
||||
id := w.ID
|
||||
if id == "" {
|
||||
id = fmt.Sprintf("workout|%s|%s", w.Name, w.Start)
|
||||
}
|
||||
attrs := map[string]any{"name": w.Name}
|
||||
if w.Location != "" {
|
||||
attrs["location"] = w.Location
|
||||
}
|
||||
if w.Distance != nil {
|
||||
attrs["distance"] = w.Distance
|
||||
}
|
||||
if w.Energy != nil {
|
||||
attrs["active_energy"] = w.Energy
|
||||
}
|
||||
acts = append(acts, Activity{
|
||||
Source: haeSource,
|
||||
Kind: workoutKind(w.Name),
|
||||
Label: w.Name,
|
||||
StartedAt: start,
|
||||
EndedAt: end,
|
||||
Attrs: attrs,
|
||||
ExternalID: id,
|
||||
})
|
||||
}
|
||||
|
||||
for _, m := range p.Data.Metrics {
|
||||
if m.Name == "sleep_analysis" {
|
||||
acts = append(acts, sleepActivities(m)...)
|
||||
continue
|
||||
}
|
||||
for _, d := range m.Data {
|
||||
date, _ := d["date"].(string)
|
||||
qty, ok := d["qty"].(float64)
|
||||
ts, err := parseHAETime(date)
|
||||
if !ok || err != nil {
|
||||
continue
|
||||
}
|
||||
src, _ := d["source"].(string)
|
||||
samples = append(samples, Sample{
|
||||
Source: haeSource,
|
||||
Metric: m.Name,
|
||||
TS: ts,
|
||||
Value: qty,
|
||||
Unit: m.Units,
|
||||
ExternalID: fmt.Sprintf("%s|%s|%s", m.Name, date, src),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(acts) == 0 && len(samples) == 0 {
|
||||
return nil, nil, fmt.Errorf("payload contains no usable workouts or metrics")
|
||||
}
|
||||
return acts, samples, nil
|
||||
}
|
||||
|
||||
// sleepActivities handles the aggregated sleep_analysis format, which has
|
||||
// sleepStart/sleepEnd instead of a qty.
|
||||
func sleepActivities(m HAEMetric) []Activity {
|
||||
var out []Activity
|
||||
for _, d := range m.Data {
|
||||
s, _ := d["sleepStart"].(string)
|
||||
e, _ := d["sleepEnd"].(string)
|
||||
start, err1 := parseHAETime(s)
|
||||
end, err2 := parseHAETime(e)
|
||||
if err1 != nil || err2 != nil || end.Before(start) {
|
||||
continue
|
||||
}
|
||||
attrs := map[string]any{}
|
||||
for _, k := range []string{"asleep", "inBed", "core", "deep", "rem", "awake"} {
|
||||
if v, ok := d[k]; ok {
|
||||
attrs[k] = v
|
||||
}
|
||||
}
|
||||
out = append(out, Activity{
|
||||
Source: haeSource,
|
||||
Kind: "sleep",
|
||||
Label: "sleep",
|
||||
StartedAt: start,
|
||||
EndedAt: end,
|
||||
Attrs: attrs,
|
||||
ExternalID: "sleep|" + s,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func workoutKind(name string) string {
|
||||
n := strings.ToLower(name)
|
||||
switch {
|
||||
case strings.Contains(n, "walk"), strings.Contains(n, "hik"):
|
||||
return "walk"
|
||||
case strings.Contains(n, "run"):
|
||||
return "run"
|
||||
default:
|
||||
return "workout"
|
||||
}
|
||||
}
|
||||
|
||||
func parseHAETime(s string) (time.Time, error) {
|
||||
t, err := time.Parse(haeTimeLayout, s)
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
return t.UTC(), nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package ingest defines the wire format collectors upload and normalises it
|
||||
// into activities and samples ready for storage.
|
||||
// into activities ready for storage.
|
||||
package ingest
|
||||
|
||||
import (
|
||||
@@ -42,16 +42,6 @@ type Activity struct {
|
||||
ExternalID string
|
||||
}
|
||||
|
||||
// Sample is a normalised point-in-time metric ready to be stored.
|
||||
type Sample struct {
|
||||
Source string
|
||||
Metric string
|
||||
TS time.Time
|
||||
Value float64
|
||||
Unit string
|
||||
ExternalID string
|
||||
}
|
||||
|
||||
// Spec describes which kinds an endpoint accepts and the source its
|
||||
// activities are stored under.
|
||||
type Spec struct {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package ingest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -41,32 +40,24 @@ func TestNormalizeValidation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeHAE(t *testing.T) {
|
||||
raw := `{"data":{
|
||||
"workouts":[{"id":"W1","name":"Outdoor Walk","start":"2026-10-14 07:00:00 -0700","end":"2026-10-14 07:45:00 -0700","location":"Outdoor"}],
|
||||
"metrics":[
|
||||
{"name":"step_count","units":"count","data":[{"date":"2026-10-14 07:00:00 -0700","qty":812,"source":"iPhone"},{"date":"bad"}]},
|
||||
{"name":"sleep_analysis","units":"hr","data":[{"sleepStart":"2026-10-13 23:10:00 -0700","sleepEnd":"2026-10-14 06:40:00 -0700","asleep":7.1}]}
|
||||
]}}`
|
||||
var p HAEPayload
|
||||
if err := json.Unmarshal([]byte(raw), &p); err != nil {
|
||||
t.Fatal(err)
|
||||
func TestNormalizeLocation(t *testing.T) {
|
||||
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
e, err := NormalizeLocation(LocationEvent{}, now)
|
||||
if err != nil || e.Place != "home" || !e.At.Equal(now) {
|
||||
t.Fatalf("defaults: got %+v, %v", e, err)
|
||||
}
|
||||
acts, samples, err := NormalizeHAE(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
e, err = NormalizeLocation(LocationEvent{Place: " Gym "}, now)
|
||||
if err != nil || e.Place != "gym" {
|
||||
t.Fatalf("got %+v, %v", e, err)
|
||||
}
|
||||
if len(acts) != 2 || len(samples) != 1 {
|
||||
t.Fatalf("got %d activities, %d samples", len(acts), len(samples))
|
||||
}
|
||||
walk := acts[0]
|
||||
if walk.Kind != "walk" || walk.ExternalID != "W1" || walk.EndedAt.Sub(walk.StartedAt) != 45*time.Minute {
|
||||
t.Errorf("walk: %+v", walk)
|
||||
}
|
||||
if walk.StartedAt.Hour() != 14 { // 07:00 -0700 is 14:00 UTC
|
||||
t.Errorf("start not converted to UTC: %v", walk.StartedAt)
|
||||
}
|
||||
if acts[1].Kind != "sleep" || samples[0].Value != 812 {
|
||||
t.Errorf("sleep %+v, sample %+v", acts[1], samples[0])
|
||||
for _, bad := range []LocationEvent{
|
||||
{Place: "Away"},
|
||||
{At: now.Add(time.Hour)},
|
||||
{At: now.Add(-8 * 24 * time.Hour)},
|
||||
} {
|
||||
if _, err := NormalizeLocation(bad, now); err == nil {
|
||||
t.Errorf("%+v: want error", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package ingest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Location transitions come from phone geofence automations (e.g. iOS
|
||||
// Shortcuts "Arrive"/"Leave"), which can only report the moment of crossing.
|
||||
// The store turns them into back-to-back intervals with kind "place",
|
||||
// labelled by the place, or Away between places.
|
||||
const (
|
||||
LocationSource = "location"
|
||||
PlaceKind = "place"
|
||||
Away = "away"
|
||||
DefaultPlace = "home"
|
||||
)
|
||||
|
||||
// LocationEvent is the optional body of POST /location/{arrive,leave}. An
|
||||
// empty body means "home, now".
|
||||
type LocationEvent struct {
|
||||
Place string `json:"place"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
// NormalizeLocation fills defaults and validates a transition.
|
||||
func NormalizeLocation(e LocationEvent, now time.Time) (LocationEvent, error) {
|
||||
e.Place = strings.ToLower(strings.TrimSpace(e.Place))
|
||||
if e.Place == "" {
|
||||
e.Place = DefaultPlace
|
||||
}
|
||||
if e.At.IsZero() {
|
||||
e.At = now
|
||||
}
|
||||
e.At = e.At.UTC()
|
||||
switch {
|
||||
case e.Place == Away:
|
||||
return e, fmt.Errorf("%q is reserved for time between places", Away)
|
||||
case len(e.Place) > maxLabelLength:
|
||||
return e, fmt.Errorf("place longer than %d characters", maxLabelLength)
|
||||
case e.At.After(now.Add(maxFutureSkew)):
|
||||
return e, fmt.Errorf("at is in the future")
|
||||
case e.At.Before(now.Add(-maxDuration)):
|
||||
return e, fmt.Errorf("at is more than %s ago", maxDuration)
|
||||
}
|
||||
return e, nil
|
||||
}
|
||||
Reference in New Issue
Block a user