From ab9dff1afb2dea96c1efbf979dc713f89a27f6da Mon Sep 17 00:00:00 2001 From: Florian Forster Date: Wed, 24 Jan 2018 20:32:36 +0100 Subject: [PATCH] Package gfit: Implement SetActivities(). --- gfit/gfit.go | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 59 insertions(+), 4 deletions(-) diff --git a/gfit/gfit.go b/gfit/gfit.go index 8f3fbac..eca961c 100644 --- a/gfit/gfit.go +++ b/gfit/gfit.go @@ -21,10 +21,11 @@ const ( csrfToken = "@CSRFTOKEN@" userID = "me" - dataTypeNameCalories = "com.google.calories.expended" - dataTypeNameDistance = "com.google.distance.delta" - dataTypeNameSteps = "com.google.step_count.delta" - dataTypeNameHeartrate = "com.google.heart_rate.summary" + dataTypeNameCalories = "com.google.calories.expended" + dataTypeNameDistance = "com.google.distance.delta" + dataTypeNameSteps = "com.google.step_count.delta" + dataTypeNameHeartrate = "com.google.heart_rate.summary" + dataTypeNameActivitySegment = "com.google.activity.segment" ) var oauthConfig = &oauth2.Config{ @@ -218,6 +219,60 @@ func (c *Client) SetCalories(ctx context.Context, totalCalories float64, startOf startOfDay) } +type Activity struct { + Start time.Time + End time.Time + Type int64 +} + +func (c *Client) SetActivities(ctx context.Context, activities []Activity, startOfDay time.Time) error { + dataStreamID := DataStreamID(&fitness.DataSource{ + DataType: &fitness.DataType{ + Name: dataTypeNameActivitySegment, + }, + Type: "raw", + }) + + endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond) + + datasetID := fmt.Sprintf("%d-%d", startOfDay.UnixNano(), endOfDay.UnixNano()) + res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataStreamID, datasetID).Context(ctx).Do() + if err != nil { + log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataStreamID, datasetID, err) + return err + } + + var dataPoints []*fitness.DataPoint +Next: + for _, a := range activities { + startTimeNanos := a.Start.UnixNano() + endTimeNanos := a.End.UnixNano() + + for _, p := range res.Point { + if p.StartTimeNanos == startTimeNanos && + p.EndTimeNanos == endTimeNanos && + p.Value[0].IntVal == a.Type { + continue Next + } + } + + dataPoints = append(dataPoints, &fitness.DataPoint{ + DataTypeName: dataTypeNameActivitySegment, + StartTimeNanos: startTimeNanos, + EndTimeNanos: endTimeNanos, + Value: []*fitness.Value{ + &fitness.Value{IntVal: a.Type}, + }, + }) + } + + if len(dataPoints) == 0 { + return nil + } + + return c.DataSetPatch(ctx, dataStreamID, dataPoints) +} + func (c *Client) updateCumulative(ctx context.Context, dataSource *fitness.DataSource, rawValue *fitness.Value, startOfDay time.Time) error { switch f := dataSource.DataType.Field[0].Format; f { case "integer": -- 2.11.0