Read runtime configuration from datastore.
[kraftakt.git] / gfit / gfit.go
index fcd88f1..1599799 100644 (file)
@@ -3,13 +3,12 @@ package gfit
 import (
        "context"
        "fmt"
-       "math"
        "net/http"
        "strings"
        "time"
 
-       "github.com/octo/gfitsync/app"
-       "github.com/octo/gfitsync/fitbit"
+       "github.com/octo/kraftakt/app"
+       "github.com/octo/kraftakt/fitbit"
        "golang.org/x/oauth2"
        oauth2google "golang.org/x/oauth2/google"
        fitness "google.golang.org/api/fitness/v1"
@@ -22,25 +21,28 @@ const (
        csrfToken = "@CSRFTOKEN@"
        userID    = "me"
 
-       dataTypeNameCalories  = "com.google.calories.expended"
-       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{
-       ClientID:     "@GOOGLE_CLIENT_ID@",
-       ClientSecret: "@GOOGLE_CLIENT_SECRET@",
+       ClientID:     app.Config.GoogleClientID,
+       ClientSecret: app.Config.GoogleClientSecret,
        Endpoint:     oauth2google.Endpoint,
        RedirectURL:  "https://kraftakt.octo.it/google/grant",
        Scopes: []string{
                fitness.FitnessActivityWriteScope,
                fitness.FitnessBodyWriteScope,
+               fitness.FitnessLocationWriteScope,
        },
 }
 
 func Application(ctx context.Context) *fitness.Application {
        return &fitness.Application{
-               Name:       "Fitbit to Google Fit sync",
+               Name:       "Kraftakt",
                Version:    appengine.VersionID(ctx),
                DetailsUrl: "", // optional
        }
@@ -87,7 +89,7 @@ func DataStreamID(dataSource *fitness.DataSource) string {
        fields := []string{
                dataSource.Type,
                dataSource.DataType.Name,
-               "@PROJECT_NUMBER@", // FIXME
+               app.Config.ProjectNumber,
        }
 
        if dev := dataSource.Device; dev != nil {
@@ -102,6 +104,10 @@ func DataStreamID(dataSource *fitness.DataSource) string {
                }
        }
 
+       if dataSource.DataStreamName != "" {
+               fields = append(fields, dataSource.DataStreamName)
+       }
+
        return strings.Join(fields, ":")
 }
 
@@ -114,7 +120,7 @@ func (c *Client) DataSourceCreate(ctx context.Context, dataSource *fitness.DataS
                        }
                        return DataStreamID(dataSource), nil
                }
-               log.Errorf(ctx, "c.Service.Users.DataSources.Create() = (%+v, %v)", res, err)
+               log.Errorf(ctx, "c.Service.Users.DataSources.Create(%q) = (%+v, %v)", dataSource, res, err)
                return "", err
        }
        return res.DataStreamId, nil
@@ -147,6 +153,28 @@ func (c *Client) DataSetPatch(ctx context.Context, dataSourceID string, points [
        return nil
 }
 
+func (c *Client) SetDistance(ctx context.Context, meters float64, startOfDay time.Time) error {
+       return c.updateCumulative(ctx,
+               &fitness.DataSource{
+                       Application: Application(ctx),
+                       DataType: &fitness.DataType{
+                               Field: []*fitness.DataTypeField{
+                                       &fitness.DataTypeField{
+                                               Name:   "distance",
+                                               Format: "floatPoint",
+                                       },
+                               },
+                               Name: dataTypeNameDistance,
+                       },
+                       Name: "Distance covered",
+                       Type: "raw",
+               },
+               &fitness.Value{
+                       FpVal: meters,
+               },
+               startOfDay)
+}
+
 func (c *Client) SetSteps(ctx context.Context, totalSteps int, startOfDay time.Time) error {
        return c.updateCumulative(ctx,
                &fitness.DataSource{
@@ -191,6 +219,78 @@ func (c *Client) SetCalories(ctx context.Context, totalCalories float64, startOf
                startOfDay)
 }
 
+type Activity struct {
+       Start time.Time
+       End   time.Time
+       Type  int64
+}
+
+func (a Activity) String() string {
+       return fmt.Sprintf("%s-%s %d", a.Start.Format("15:04:05"), a.End.Format("15:04:05"), a.Type)
+}
+
+func (c *Client) SetActivities(ctx context.Context, activities []Activity, startOfDay time.Time) error {
+       if len(activities) == 0 {
+               return nil
+       }
+
+       dataStreamID, err := c.DataSourceCreate(ctx, &fitness.DataSource{
+               Application: Application(ctx),
+               DataType: &fitness.DataType{
+                       Field: []*fitness.DataTypeField{
+                               &fitness.DataTypeField{
+                                       Name:   "activity",
+                                       Format: "integer",
+                               },
+                       },
+                       Name: dataTypeNameActivitySegment,
+               },
+               Type: "raw",
+       })
+       if err != nil {
+               return err
+       }
+
+       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 {
+                               log.Debugf(ctx, "activity %s already stored in Google Fit", a)
+                               continue Next
+                       }
+               }
+
+               log.Debugf(ctx, "activity %s will be added to Google Fit", a)
+               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":
@@ -213,6 +313,9 @@ func (c *Client) updateCumulative(ctx context.Context, dataSource *fitness.DataS
 
        endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
        currValue, startTime, err := c.readCumulative(ctx, dataSource, startOfDay, endOfDay)
+       if err != nil {
+               return err
+       }
 
        var diffValue fitness.Value
        if dataSource.DataType.Field[0].Format == "integer" {
@@ -239,7 +342,7 @@ func (c *Client) updateCumulative(ctx context.Context, dataSource *fitness.DataS
        if now := time.Now().In(startOfDay.Location()); now.Before(endOfDay) {
                endTime = now
        }
-       log.Debugf(ctx, "adding cumulative data point: %v-%v %+v", startTime, endTime, diffValue)
+       log.Debugf(ctx, "add  cumulative data %s until %v: %+v", dataSource.DataStreamId, endTime, diffValue)
 
        return c.DataSetPatch(ctx, dataSource.DataStreamId, []*fitness.DataPoint{
                &fitness.DataPoint{
@@ -261,6 +364,7 @@ func (c *Client) readCumulative(ctx context.Context, dataSource *fitness.DataSou
        }
 
        if len(res.Point) == 0 {
+               log.Debugf(ctx, "read cumulative data %s until %v: []", dataSource.DataStreamId, endTime)
                return &fitness.Value{}, startTime, nil
        }
 
@@ -344,7 +448,7 @@ func (c *Client) heartRate(ctx context.Context, dataSource *fitness.DataSource,
        return results, maxEndTime, nil
 }
 
-func (c *Client) SetHeartRate(ctx context.Context, totalDurations []fitbit.HeartRateZone, startOfDay time.Time) error {
+func (c *Client) SetHeartRate(ctx context.Context, totalDurations []fitbit.HeartRateZone, restingHeartRate int, startOfDay time.Time) error {
        dataSource := &fitness.DataSource{
                Application: Application(ctx),
                DataType: &fitness.DataType{
@@ -417,13 +521,18 @@ func (c *Client) SetHeartRate(ctx context.Context, totalDurations []fitbit.Heart
                        break
                }
 
+               average := float64(d.Min+d.Max) / 2.0
+               if d.Min <= restingHeartRate && restingHeartRate <= d.Max {
+                       average = float64(restingHeartRate)
+               }
+
                dataPoints = append(dataPoints, &fitness.DataPoint{
                        DataTypeName:   dataSource.DataType.Name,
                        StartTimeNanos: startTime.UnixNano(),
                        EndTimeNanos:   endTime.UnixNano(),
                        Value: []*fitness.Value{
                                &fitness.Value{
-                                       FpVal: math.NaN(),
+                                       FpVal: average,
                                },
                                &fitness.Value{
                                        FpVal: float64(d.Max),