10 "github.com/octo/kraftakt/app"
11 "github.com/octo/kraftakt/fitbit"
12 "github.com/octo/retry"
14 oauth2google "golang.org/x/oauth2/google"
15 fitness "google.golang.org/api/fitness/v1"
16 "google.golang.org/api/googleapi"
17 "google.golang.org/appengine"
18 "google.golang.org/appengine/log"
22 csrfToken = "@CSRFTOKEN@"
25 dataTypeNameCalories = "com.google.calories.expended"
26 dataTypeNameDistance = "com.google.distance.delta"
27 dataTypeNameSteps = "com.google.step_count.delta"
28 dataTypeNameHeartrate = "com.google.heart_rate.summary"
29 dataTypeNameActivitySegment = "com.google.activity.segment"
32 func oauthConfig() *oauth2.Config {
33 return &oauth2.Config{
34 ClientID: app.Config.GoogleClientID,
35 ClientSecret: app.Config.GoogleClientSecret,
36 Endpoint: oauth2google.Endpoint,
37 RedirectURL: "https://kraftakt.octo.it/google/grant",
39 fitness.FitnessActivityWriteScope,
40 fitness.FitnessBodyWriteScope,
41 fitness.FitnessLocationWriteScope,
46 func Application(ctx context.Context) *fitness.Application {
47 return &fitness.Application{
49 Version: appengine.VersionID(ctx),
50 DetailsUrl: "", // optional
54 func AuthURL() string {
55 return oauthConfig().AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
58 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
59 if state := r.FormValue("state"); state != csrfToken {
60 return fmt.Errorf("invalid state parameter: %q", state)
63 tok, err := oauthConfig().Exchange(ctx, r.FormValue("code"))
68 return u.SetToken(ctx, "Google", tok)
76 func NewClient(ctx context.Context, u *app.User) (*Client, error) {
77 c, err := u.OAuthClient(ctx, "Google", oauthConfig())
82 service, err := fitness.New(c)
93 func (c *Client) DeleteToken(ctx context.Context) error {
94 return c.appUser.DeleteToken(ctx, "Google")
97 func DataStreamID(dataSource *fitness.DataSource) string {
100 dataSource.DataType.Name,
101 app.Config.ProjectNumber,
104 if dev := dataSource.Device; dev != nil {
105 if dev.Manufacturer != "" {
106 fields = append(fields, dev.Manufacturer)
109 fields = append(fields, dev.Model)
112 fields = append(fields, dev.Uid)
116 if dataSource.DataStreamName != "" {
117 fields = append(fields, dataSource.DataStreamName)
120 return strings.Join(fields, ":")
123 func wrapGoogleError(err error) error {
128 if gerr, ok := err.(*googleapi.Error); ok && gerr.Code >= 400 && gerr.Code < 500 {
129 return retry.Abort(err)
135 func (c *Client) DataSourceCreate(ctx context.Context, dataSource *fitness.DataSource) (string, error) {
136 var dataStreamID string
137 err := retry.Do(ctx, func(ctx context.Context) error {
138 res, err := c.Service.Users.DataSources.Create(userID, dataSource).Context(ctx).Do()
140 return wrapGoogleError(err)
142 dataStreamID = res.DataStreamId
146 if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == http.StatusConflict {
147 if dataSource.DataStreamId != "" {
148 return dataSource.DataStreamId, nil
150 return DataStreamID(dataSource), nil
152 log.Errorf(ctx, "c.Service.Users.DataSources.Create(%q) = %v", DataStreamID(dataSource), err)
155 return dataStreamID, nil
158 func (c *Client) DatasetGet(ctx context.Context, dataStreamID string, startTime, endTime time.Time) (*fitness.Dataset, error) {
159 datasetID := fmt.Sprintf("%d-%d", startTime.UnixNano(), endTime.UnixNano())
161 var dataset *fitness.Dataset
162 err := retry.Do(ctx, func(ctx context.Context) error {
163 res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataStreamID, datasetID).Context(ctx).Do()
165 return wrapGoogleError(err)
171 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataStreamID, datasetID, err)
177 func (c *Client) DatasetPatch(ctx context.Context, dataSourceID string, points []*fitness.DataPoint) error {
178 startTimeNanos, endTimeNanos := int64(-1), int64(-1)
179 for _, p := range points {
180 if startTimeNanos == -1 || startTimeNanos > p.StartTimeNanos {
181 startTimeNanos = p.StartTimeNanos
183 if endTimeNanos == -1 || endTimeNanos < p.EndTimeNanos {
184 endTimeNanos = p.EndTimeNanos
187 datasetID := fmt.Sprintf("%d-%d", startTimeNanos, endTimeNanos)
189 dataset := &fitness.Dataset{
190 DataSourceId: dataSourceID,
191 MinStartTimeNs: startTimeNanos,
192 MaxEndTimeNs: endTimeNanos,
196 err := retry.Do(ctx, func(ctx context.Context) error {
197 _, err := c.Service.Users.DataSources.Datasets.Patch(userID, dataSourceID, datasetID, dataset).Context(ctx).Do()
198 return wrapGoogleError(err)
201 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Patch() = %v", err)
207 func (c *Client) SetDistance(ctx context.Context, meters float64, startOfDay time.Time) error {
208 return c.updateCumulative(ctx,
210 Application: Application(ctx),
211 DataType: &fitness.DataType{
212 Field: []*fitness.DataTypeField{
213 &fitness.DataTypeField{
215 Format: "floatPoint",
218 Name: dataTypeNameDistance,
220 Name: "Distance covered",
229 func (c *Client) SetSteps(ctx context.Context, totalSteps int, startOfDay time.Time) error {
230 return c.updateCumulative(ctx,
232 Application: Application(ctx),
233 DataType: &fitness.DataType{
234 Field: []*fitness.DataTypeField{
235 &fitness.DataTypeField{
240 Name: dataTypeNameSteps,
246 IntVal: int64(totalSteps),
251 func (c *Client) SetCalories(ctx context.Context, totalCalories float64, startOfDay time.Time) error {
252 return c.updateCumulative(ctx,
254 Application: Application(ctx),
255 DataType: &fitness.DataType{
256 Field: []*fitness.DataTypeField{
257 &fitness.DataTypeField{
259 Format: "floatPoint",
262 Name: dataTypeNameCalories,
264 Name: "Calories expended",
268 FpVal: totalCalories,
273 type Activity struct {
279 func (a Activity) String() string {
280 return fmt.Sprintf("%s-%s %d", a.Start.Format("15:04:05"), a.End.Format("15:04:05"), a.Type)
283 func (c *Client) SetActivities(ctx context.Context, activities []Activity, startOfDay time.Time) error {
284 if len(activities) == 0 {
288 dataStreamID, err := c.DataSourceCreate(ctx, &fitness.DataSource{
289 Application: Application(ctx),
290 DataType: &fitness.DataType{
291 Field: []*fitness.DataTypeField{
292 &fitness.DataTypeField{
297 Name: dataTypeNameActivitySegment,
305 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
307 dataset, err := c.DatasetGet(ctx, dataStreamID, startOfDay, endOfDay)
312 var dataPoints []*fitness.DataPoint
314 for _, a := range activities {
315 startTimeNanos := a.Start.UnixNano()
316 endTimeNanos := a.End.UnixNano()
318 for _, p := range dataset.Point {
319 if p.StartTimeNanos == startTimeNanos && p.EndTimeNanos == endTimeNanos && p.Value[0].IntVal == a.Type {
320 log.Debugf(ctx, "activity %s already stored in Google Fit", a)
325 log.Debugf(ctx, "activity %s will be added to Google Fit", a)
326 dataPoints = append(dataPoints, &fitness.DataPoint{
327 DataTypeName: dataTypeNameActivitySegment,
328 StartTimeNanos: startTimeNanos,
329 EndTimeNanos: endTimeNanos,
330 Value: []*fitness.Value{
331 &fitness.Value{IntVal: a.Type},
336 if len(dataPoints) == 0 {
340 return c.DatasetPatch(ctx, dataStreamID, dataPoints)
343 func (c *Client) updateCumulative(ctx context.Context, dataSource *fitness.DataSource, rawValue *fitness.Value, startOfDay time.Time) error {
344 switch f := dataSource.DataType.Field[0].Format; f {
346 if rawValue.IntVal == 0 {
350 if rawValue.FpVal == 0 {
354 return fmt.Errorf("unexpected data type field format %q", f)
357 dataSourceID, err := c.DataSourceCreate(ctx, dataSource)
361 dataSource.DataStreamId = dataSourceID
363 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
364 currValue, startTime, err := c.readCumulative(ctx, dataSource, startOfDay, endOfDay)
369 var diffValue fitness.Value
370 if dataSource.DataType.Field[0].Format == "integer" {
371 if rawValue.IntVal == currValue.IntVal {
374 diffValue.IntVal = rawValue.IntVal - currValue.IntVal
375 if diffValue.IntVal < 0 {
376 log.Warningf(ctx, "stored value (%d) is larger than new value (%d); assuming count was reset", currValue.IntVal, rawValue.IntVal)
377 diffValue.IntVal = rawValue.IntVal
379 } else { // if dataSource.DataType.Field[0].Format == "floatPoint"
380 if rawValue.FpVal == currValue.FpVal {
383 diffValue.FpVal = rawValue.FpVal - currValue.FpVal
384 if diffValue.FpVal < 0 {
385 log.Warningf(ctx, "stored value (%g) is larger than new value (%g); assuming count was reset", currValue.FpVal, rawValue.FpVal)
386 diffValue.FpVal = rawValue.FpVal
391 if now := time.Now().In(startOfDay.Location()); now.Before(endOfDay) {
394 log.Debugf(ctx, "add cumulative data %s until %v: %+v", dataSource.DataStreamId, endTime, diffValue)
396 return c.DatasetPatch(ctx, dataSource.DataStreamId, []*fitness.DataPoint{
398 DataTypeName: dataSource.DataType.Name,
399 StartTimeNanos: startTime.UnixNano(),
400 EndTimeNanos: endTime.UnixNano(),
401 Value: []*fitness.Value{&diffValue},
406 func (c *Client) readCumulative(ctx context.Context, dataSource *fitness.DataSource, startTime, endTime time.Time) (*fitness.Value, time.Time, error) {
407 dataset, err := c.DatasetGet(ctx, dataSource.DataStreamId, startTime, endTime)
409 return nil, time.Time{}, err
412 if len(dataset.Point) == 0 {
413 log.Debugf(ctx, "read cumulative data %s until %v: []", dataSource.DataStreamId, endTime)
414 return &fitness.Value{}, startTime, nil
417 var sum fitness.Value
418 maxEndTime := startTime
419 for _, p := range dataset.Point {
420 switch f := dataSource.DataType.Field[0].Format; f {
422 sum.IntVal += p.Value[0].IntVal
424 sum.FpVal += p.Value[0].FpVal
426 return nil, time.Time{}, fmt.Errorf("unexpected data type field format %q", f)
429 pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
430 if maxEndTime.Before(pointEndTime) {
431 maxEndTime = pointEndTime
435 log.Debugf(ctx, "read cumulative data %s until %v: %+v", dataSource.DataStreamId, maxEndTime, sum)
436 return &sum, maxEndTime, nil
439 type heartRateDuration struct {
442 Duration time.Duration
445 type heartRateDurations []*heartRateDuration
447 func (res heartRateDurations) find(min, max int) (*heartRateDuration, bool) {
448 for _, d := range res {
449 if d.Min != min || d.Max != max {
458 func (c *Client) heartRate(ctx context.Context, dataSource *fitness.DataSource, startTime, endTime time.Time) (heartRateDurations, time.Time, error) {
459 dataset, err := c.DatasetGet(ctx, dataSource.DataStreamId, startTime, endTime)
461 return nil, time.Time{}, err
464 if len(dataset.Point) == 0 {
465 return nil, startTime, nil
468 var results heartRateDurations
469 maxEndTime := startTime
470 for _, p := range dataset.Point {
471 max := int(p.Value[1].FpVal)
472 min := int(p.Value[2].FpVal)
473 duration := time.Unix(0, p.EndTimeNanos).Sub(time.Unix(0, p.StartTimeNanos))
475 if d, ok := results.find(min, max); ok {
476 d.Duration += duration
478 results = append(results, &heartRateDuration{
485 pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
486 if maxEndTime.Before(pointEndTime) {
487 maxEndTime = pointEndTime
491 return results, maxEndTime, nil
494 func (c *Client) SetHeartRate(ctx context.Context, totalDurations []fitbit.HeartRateZone, restingHeartRate int, startOfDay time.Time) error {
495 dataSource := &fitness.DataSource{
496 Application: Application(ctx),
497 DataType: &fitness.DataType{
498 Field: []*fitness.DataTypeField{
499 &fitness.DataTypeField{
501 Format: "floatPoint",
503 &fitness.DataTypeField{
505 Format: "floatPoint",
507 &fitness.DataTypeField{
509 Format: "floatPoint",
512 Name: dataTypeNameHeartrate,
514 Name: "Heart rate summary",
518 dataSourceID, err := c.DataSourceCreate(ctx, dataSource)
522 dataSource.DataStreamId = dataSourceID
524 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
525 prevDurations, startTime, err := c.heartRate(ctx, dataSource, startOfDay, endOfDay)
527 // calculate the difference between the durations mentioned in
528 // totalDurations and prevDurations and store it in diffDurations.
529 var diffDurations heartRateDurations
530 for _, d := range totalDurations {
531 total := time.Duration(d.Minutes) * time.Minute
533 var prev time.Duration
534 if res, ok := prevDurations.find(d.Min, d.Max); ok {
543 if res, ok := diffDurations.find(d.Min, d.Max); ok {
546 diffDurations = append(diffDurations, &heartRateDuration{
554 // create a fitness.DataPoint for each non-zero duration difference.
555 var dataPoints []*fitness.DataPoint
556 for _, d := range diffDurations {
557 if d.Duration < time.Nanosecond {
561 endTime := startTime.Add(d.Duration)
562 if endTime.After(endOfDay) {
563 log.Warningf(ctx, "heart rate durations exceed one day (current end time: %v)", endTime)
567 average := float64(d.Min+d.Max) / 2.0
568 if d.Min <= restingHeartRate && restingHeartRate <= d.Max {
569 average = float64(restingHeartRate)
572 dataPoints = append(dataPoints, &fitness.DataPoint{
573 DataTypeName: dataSource.DataType.Name,
574 StartTimeNanos: startTime.UnixNano(),
575 EndTimeNanos: endTime.UnixNano(),
576 Value: []*fitness.Value{
581 FpVal: float64(d.Max),
584 FpVal: float64(d.Min),
592 if len(dataPoints) == 0 {
595 return c.DatasetPatch(ctx, dataSource.DataStreamId, dataPoints)