Package gfit: Implement SetActivities().
[kraftakt.git] / gfit / gfit.go
1 package gfit
2
3 import (
4         "context"
5         "fmt"
6         "net/http"
7         "strings"
8         "time"
9
10         "github.com/octo/gfitsync/app"
11         "github.com/octo/gfitsync/fitbit"
12         "golang.org/x/oauth2"
13         oauth2google "golang.org/x/oauth2/google"
14         fitness "google.golang.org/api/fitness/v1"
15         "google.golang.org/api/googleapi"
16         "google.golang.org/appengine"
17         "google.golang.org/appengine/log"
18 )
19
20 const (
21         csrfToken = "@CSRFTOKEN@"
22         userID    = "me"
23
24         dataTypeNameCalories        = "com.google.calories.expended"
25         dataTypeNameDistance        = "com.google.distance.delta"
26         dataTypeNameSteps           = "com.google.step_count.delta"
27         dataTypeNameHeartrate       = "com.google.heart_rate.summary"
28         dataTypeNameActivitySegment = "com.google.activity.segment"
29 )
30
31 var oauthConfig = &oauth2.Config{
32         ClientID:     "@GOOGLE_CLIENT_ID@",
33         ClientSecret: "@GOOGLE_CLIENT_SECRET@",
34         Endpoint:     oauth2google.Endpoint,
35         RedirectURL:  "https://kraftakt.octo.it/google/grant",
36         Scopes: []string{
37                 fitness.FitnessActivityWriteScope,
38                 fitness.FitnessBodyWriteScope,
39                 fitness.FitnessLocationWriteScope,
40         },
41 }
42
43 func Application(ctx context.Context) *fitness.Application {
44         return &fitness.Application{
45                 Name:       "Fitbit to Google Fit sync",
46                 Version:    appengine.VersionID(ctx),
47                 DetailsUrl: "", // optional
48         }
49 }
50
51 func AuthURL() string {
52         return oauthConfig.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
53 }
54
55 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
56         if state := r.FormValue("state"); state != csrfToken {
57                 return fmt.Errorf("invalid state parameter: %q", state)
58         }
59
60         tok, err := oauthConfig.Exchange(ctx, r.FormValue("code"))
61         if err != nil {
62                 return err
63         }
64
65         return u.SetToken(ctx, "Google", tok)
66 }
67
68 type Client struct {
69         *fitness.Service
70 }
71
72 func NewClient(ctx context.Context, u *app.User) (*Client, error) {
73         c, err := u.OAuthClient(ctx, "Google", oauthConfig)
74         if err != nil {
75                 return nil, err
76         }
77
78         service, err := fitness.New(c)
79         if err != nil {
80                 return nil, err
81         }
82
83         return &Client{
84                 Service: service,
85         }, nil
86 }
87
88 func DataStreamID(dataSource *fitness.DataSource) string {
89         fields := []string{
90                 dataSource.Type,
91                 dataSource.DataType.Name,
92                 "@PROJECT_NUMBER@", // FIXME
93         }
94
95         if dev := dataSource.Device; dev != nil {
96                 if dev.Manufacturer != "" {
97                         fields = append(fields, dev.Manufacturer)
98                 }
99                 if dev.Model != "" {
100                         fields = append(fields, dev.Model)
101                 }
102                 if dev.Uid != "" {
103                         fields = append(fields, dev.Uid)
104                 }
105         }
106
107         if dataSource.DataStreamName != "" {
108                 fields = append(fields, dataSource.DataStreamName)
109         }
110
111         return strings.Join(fields, ":")
112 }
113
114 func (c *Client) DataSourceCreate(ctx context.Context, dataSource *fitness.DataSource) (string, error) {
115         res, err := c.Service.Users.DataSources.Create(userID, dataSource).Context(ctx).Do()
116         if err != nil {
117                 if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == http.StatusConflict {
118                         if dataSource.DataStreamId != "" {
119                                 return dataSource.DataStreamId, nil
120                         }
121                         return DataStreamID(dataSource), nil
122                 }
123                 log.Errorf(ctx, "c.Service.Users.DataSources.Create() = (%+v, %v)", res, err)
124                 return "", err
125         }
126         return res.DataStreamId, nil
127 }
128
129 func (c *Client) DataSetPatch(ctx context.Context, dataSourceID string, points []*fitness.DataPoint) error {
130         startTimeNanos, endTimeNanos := int64(-1), int64(-1)
131         for _, p := range points {
132                 if startTimeNanos == -1 || startTimeNanos > p.StartTimeNanos {
133                         startTimeNanos = p.StartTimeNanos
134                 }
135                 if endTimeNanos == -1 || endTimeNanos < p.EndTimeNanos {
136                         endTimeNanos = p.EndTimeNanos
137                 }
138         }
139         datasetID := fmt.Sprintf("%d-%d", startTimeNanos, endTimeNanos)
140
141         dataset := &fitness.Dataset{
142                 DataSourceId:   dataSourceID,
143                 MinStartTimeNs: startTimeNanos,
144                 MaxEndTimeNs:   endTimeNanos,
145                 Point:          points,
146         }
147
148         _, err := c.Service.Users.DataSources.Datasets.Patch(userID, dataSourceID, datasetID, dataset).Context(ctx).Do()
149         if err != nil {
150                 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Patch() = %v", err)
151                 return err
152         }
153         return nil
154 }
155
156 func (c *Client) SetDistance(ctx context.Context, meters float64, startOfDay time.Time) error {
157         return c.updateCumulative(ctx,
158                 &fitness.DataSource{
159                         Application: Application(ctx),
160                         DataType: &fitness.DataType{
161                                 Field: []*fitness.DataTypeField{
162                                         &fitness.DataTypeField{
163                                                 Name:   "distance",
164                                                 Format: "floatPoint",
165                                         },
166                                 },
167                                 Name: dataTypeNameDistance,
168                         },
169                         Name: "Distance covered",
170                         Type: "raw",
171                 },
172                 &fitness.Value{
173                         FpVal: meters,
174                 },
175                 startOfDay)
176 }
177
178 func (c *Client) SetSteps(ctx context.Context, totalSteps int, startOfDay time.Time) error {
179         return c.updateCumulative(ctx,
180                 &fitness.DataSource{
181                         Application: Application(ctx),
182                         DataType: &fitness.DataType{
183                                 Field: []*fitness.DataTypeField{
184                                         &fitness.DataTypeField{
185                                                 Name:   "steps",
186                                                 Format: "integer",
187                                         },
188                                 },
189                                 Name: dataTypeNameSteps,
190                         },
191                         Name: "Step Count",
192                         Type: "raw",
193                 },
194                 &fitness.Value{
195                         IntVal: int64(totalSteps),
196                 },
197                 startOfDay)
198 }
199
200 func (c *Client) SetCalories(ctx context.Context, totalCalories float64, startOfDay time.Time) error {
201         return c.updateCumulative(ctx,
202                 &fitness.DataSource{
203                         Application: Application(ctx),
204                         DataType: &fitness.DataType{
205                                 Field: []*fitness.DataTypeField{
206                                         &fitness.DataTypeField{
207                                                 Name:   "calories",
208                                                 Format: "floatPoint",
209                                         },
210                                 },
211                                 Name: dataTypeNameCalories,
212                         },
213                         Name: "Calories expended",
214                         Type: "raw",
215                 },
216                 &fitness.Value{
217                         FpVal: totalCalories,
218                 },
219                 startOfDay)
220 }
221
222 type Activity struct {
223         Start time.Time
224         End   time.Time
225         Type  int64
226 }
227
228 func (c *Client) SetActivities(ctx context.Context, activities []Activity, startOfDay time.Time) error {
229         dataStreamID := DataStreamID(&fitness.DataSource{
230                 DataType: &fitness.DataType{
231                         Name: dataTypeNameActivitySegment,
232                 },
233                 Type: "raw",
234         })
235
236         endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
237
238         datasetID := fmt.Sprintf("%d-%d", startOfDay.UnixNano(), endOfDay.UnixNano())
239         res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataStreamID, datasetID).Context(ctx).Do()
240         if err != nil {
241                 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataStreamID, datasetID, err)
242                 return err
243         }
244
245         var dataPoints []*fitness.DataPoint
246 Next:
247         for _, a := range activities {
248                 startTimeNanos := a.Start.UnixNano()
249                 endTimeNanos := a.End.UnixNano()
250
251                 for _, p := range res.Point {
252                         if p.StartTimeNanos == startTimeNanos &&
253                                 p.EndTimeNanos == endTimeNanos &&
254                                 p.Value[0].IntVal == a.Type {
255                                 continue Next
256                         }
257                 }
258
259                 dataPoints = append(dataPoints, &fitness.DataPoint{
260                         DataTypeName:   dataTypeNameActivitySegment,
261                         StartTimeNanos: startTimeNanos,
262                         EndTimeNanos:   endTimeNanos,
263                         Value: []*fitness.Value{
264                                 &fitness.Value{IntVal: a.Type},
265                         },
266                 })
267         }
268
269         if len(dataPoints) == 0 {
270                 return nil
271         }
272
273         return c.DataSetPatch(ctx, dataStreamID, dataPoints)
274 }
275
276 func (c *Client) updateCumulative(ctx context.Context, dataSource *fitness.DataSource, rawValue *fitness.Value, startOfDay time.Time) error {
277         switch f := dataSource.DataType.Field[0].Format; f {
278         case "integer":
279                 if rawValue.IntVal == 0 {
280                         return nil
281                 }
282         case "floatPoint":
283                 if rawValue.FpVal == 0 {
284                         return nil
285                 }
286         default:
287                 return fmt.Errorf("unexpected data type field format %q", f)
288         }
289
290         dataSourceID, err := c.DataSourceCreate(ctx, dataSource)
291         if err != nil {
292                 return err
293         }
294         dataSource.DataStreamId = dataSourceID
295
296         endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
297         currValue, startTime, err := c.readCumulative(ctx, dataSource, startOfDay, endOfDay)
298         if err != nil {
299                 return err
300         }
301
302         var diffValue fitness.Value
303         if dataSource.DataType.Field[0].Format == "integer" {
304                 if rawValue.IntVal == currValue.IntVal {
305                         return nil
306                 }
307                 diffValue.IntVal = rawValue.IntVal - currValue.IntVal
308                 if diffValue.IntVal < 0 {
309                         log.Warningf(ctx, "stored value (%d) is larger than new value (%d); assuming count was reset", currValue.IntVal, rawValue.IntVal)
310                         diffValue.IntVal = rawValue.IntVal
311                 }
312         } else { // if dataSource.DataType.Field[0].Format == "floatPoint"
313                 if rawValue.FpVal == currValue.FpVal {
314                         return nil
315                 }
316                 diffValue.FpVal = rawValue.FpVal - currValue.FpVal
317                 if diffValue.FpVal < 0 {
318                         log.Warningf(ctx, "stored value (%g) is larger than new value (%g); assuming count was reset", currValue.FpVal, rawValue.FpVal)
319                         diffValue.FpVal = rawValue.FpVal
320                 }
321         }
322
323         endTime := endOfDay
324         if now := time.Now().In(startOfDay.Location()); now.Before(endOfDay) {
325                 endTime = now
326         }
327         log.Debugf(ctx, "adding cumulative data point: %v-%v %+v", startTime, endTime, diffValue)
328
329         return c.DataSetPatch(ctx, dataSource.DataStreamId, []*fitness.DataPoint{
330                 &fitness.DataPoint{
331                         DataTypeName:   dataSource.DataType.Name,
332                         StartTimeNanos: startTime.UnixNano(),
333                         EndTimeNanos:   endTime.UnixNano(),
334                         Value:          []*fitness.Value{&diffValue},
335                 },
336         })
337 }
338
339 func (c *Client) readCumulative(ctx context.Context, dataSource *fitness.DataSource, startTime, endTime time.Time) (*fitness.Value, time.Time, error) {
340         datasetID := fmt.Sprintf("%d-%d", startTime.UnixNano(), endTime.UnixNano())
341
342         res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataSource.DataStreamId, datasetID).Context(ctx).Do()
343         if err != nil {
344                 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataSource.DataStreamId, datasetID, err)
345                 return nil, time.Time{}, err
346         }
347
348         if len(res.Point) == 0 {
349                 return &fitness.Value{}, startTime, nil
350         }
351
352         var sum fitness.Value
353         maxEndTime := startTime
354         for _, p := range res.Point {
355                 switch f := dataSource.DataType.Field[0].Format; f {
356                 case "integer":
357                         sum.IntVal += p.Value[0].IntVal
358                 case "floatPoint":
359                         sum.FpVal += p.Value[0].FpVal
360                 default:
361                         return nil, time.Time{}, fmt.Errorf("unexpected data type field format %q", f)
362                 }
363
364                 pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
365                 if maxEndTime.Before(pointEndTime) {
366                         maxEndTime = pointEndTime
367                 }
368         }
369
370         log.Debugf(ctx, "read cumulative data %s until %v: %+v", dataSource.DataStreamId, maxEndTime, sum)
371         return &sum, maxEndTime, nil
372 }
373
374 type heartRateDuration struct {
375         Min      int
376         Max      int
377         Duration time.Duration
378 }
379
380 type heartRateDurations []*heartRateDuration
381
382 func (res heartRateDurations) find(min, max int) (*heartRateDuration, bool) {
383         for _, d := range res {
384                 if d.Min != min || d.Max != max {
385                         continue
386                 }
387                 return d, true
388         }
389
390         return nil, false
391 }
392
393 func (c *Client) heartRate(ctx context.Context, dataSource *fitness.DataSource, startTime, endTime time.Time) (heartRateDurations, time.Time, error) {
394         datasetID := fmt.Sprintf("%d-%d", startTime.UnixNano(), endTime.UnixNano())
395
396         res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataSource.DataStreamId, datasetID).Context(ctx).Do()
397         if err != nil {
398                 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataSource.DataStreamId, datasetID, err)
399                 return nil, time.Time{}, err
400         }
401
402         if len(res.Point) == 0 {
403                 return nil, startTime, nil
404         }
405
406         var results heartRateDurations
407         maxEndTime := startTime
408         for _, p := range res.Point {
409                 max := int(p.Value[1].FpVal)
410                 min := int(p.Value[2].FpVal)
411                 duration := time.Unix(0, p.EndTimeNanos).Sub(time.Unix(0, p.StartTimeNanos))
412
413                 if d, ok := results.find(min, max); ok {
414                         d.Duration += duration
415                 } else {
416                         results = append(results, &heartRateDuration{
417                                 Min:      min,
418                                 Max:      max,
419                                 Duration: duration,
420                         })
421                 }
422
423                 pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
424                 if maxEndTime.Before(pointEndTime) {
425                         maxEndTime = pointEndTime
426                 }
427         }
428
429         return results, maxEndTime, nil
430 }
431
432 func (c *Client) SetHeartRate(ctx context.Context, totalDurations []fitbit.HeartRateZone, restingHeartRate int, startOfDay time.Time) error {
433         dataSource := &fitness.DataSource{
434                 Application: Application(ctx),
435                 DataType: &fitness.DataType{
436                         Field: []*fitness.DataTypeField{
437                                 &fitness.DataTypeField{
438                                         Name:   "average",
439                                         Format: "floatPoint",
440                                 },
441                                 &fitness.DataTypeField{
442                                         Name:   "max",
443                                         Format: "floatPoint",
444                                 },
445                                 &fitness.DataTypeField{
446                                         Name:   "min",
447                                         Format: "floatPoint",
448                                 },
449                         },
450                         Name: dataTypeNameHeartrate,
451                 },
452                 Name: "Heart rate summary",
453                 Type: "raw",
454         }
455
456         dataSourceID, err := c.DataSourceCreate(ctx, dataSource)
457         if err != nil {
458                 return err
459         }
460         dataSource.DataStreamId = dataSourceID
461
462         endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
463         prevDurations, startTime, err := c.heartRate(ctx, dataSource, startOfDay, endOfDay)
464
465         // calculate the difference between the durations mentioned in
466         // totalDurations and prevDurations and store it in diffDurations.
467         var diffDurations heartRateDurations
468         for _, d := range totalDurations {
469                 total := time.Duration(d.Minutes) * time.Minute
470
471                 var prev time.Duration
472                 if res, ok := prevDurations.find(d.Min, d.Max); ok {
473                         prev = res.Duration
474                 }
475
476                 diff := total - prev
477                 if diff < 0 {
478                         diff = total
479                 }
480
481                 if res, ok := diffDurations.find(d.Min, d.Max); ok {
482                         res.Duration += diff
483                 } else {
484                         diffDurations = append(diffDurations, &heartRateDuration{
485                                 Min:      d.Min,
486                                 Max:      d.Max,
487                                 Duration: diff,
488                         })
489                 }
490         }
491
492         // create a fitness.DataPoint for each non-zero duration difference.
493         var dataPoints []*fitness.DataPoint
494         for _, d := range diffDurations {
495                 if d.Duration < time.Nanosecond {
496                         continue
497                 }
498
499                 endTime := startTime.Add(d.Duration)
500                 if endTime.After(endOfDay) {
501                         log.Warningf(ctx, "heart rate durations exceed one day (current end time: %v)", endTime)
502                         break
503                 }
504
505                 average := float64(d.Min+d.Max) / 2.0
506                 if d.Min <= restingHeartRate && restingHeartRate <= d.Max {
507                         average = float64(restingHeartRate)
508                 }
509
510                 dataPoints = append(dataPoints, &fitness.DataPoint{
511                         DataTypeName:   dataSource.DataType.Name,
512                         StartTimeNanos: startTime.UnixNano(),
513                         EndTimeNanos:   endTime.UnixNano(),
514                         Value: []*fitness.Value{
515                                 &fitness.Value{
516                                         FpVal: average,
517                                 },
518                                 &fitness.Value{
519                                         FpVal: float64(d.Max),
520                                 },
521                                 &fitness.Value{
522                                         FpVal: float64(d.Min),
523                                 },
524                         },
525                 })
526
527                 startTime = endTime
528         }
529
530         if len(dataPoints) == 0 {
531                 return nil
532         }
533         return c.DataSetPatch(ctx, dataSource.DataStreamId, dataPoints)
534 }