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 } // Destination is where a device moves on an arrive or leave event for place, // given the place it is in now ("" if none yet). Leaving a place only counts // if the device is in it (or nowhere yet), so a late "leave home" after // "arrive gym" doesn't undo the arrival. func Destination(event, place, cur string) string { if event == "arrive" { return place } if cur != "" && cur != place { return cur } return Away }