10 "github.com/octo/gfitsync/app"
11 "github.com/octo/gfitsync/fitbit"
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"
21 csrfToken = "@CSRFTOKEN@"
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"
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",
37 fitness.FitnessActivityWriteScope,
38 fitness.FitnessBodyWriteScope,
39 fitness.FitnessLocationWriteScope,
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
51 func AuthURL() string {
52 return oauthConfig.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
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)
60 tok, err := oauthConfig.Exchange(ctx, r.FormValue("code"))
65 return u.SetToken(ctx, "Google", tok)
72 func NewClient(ctx context.Context, u *app.User) (*Client, error) {
73 c, err := u.OAuthClient(ctx, "Google", oauthConfig)
78 service, err := fitness.New(c)
88 func DataStreamID(dataSource *fitness.DataSource) string {
91 dataSource.DataType.Name,
92 "@PROJECT_NUMBER@", // FIXME
95 if dev := dataSource.Device; dev != nil {
96 if dev.Manufacturer != "" {
97 fields = append(fields, dev.Manufacturer)
100 fields = append(fields, dev.Model)
103 fields = append(fields, dev.Uid)
107 if dataSource.DataStreamName != "" {
108 fields = append(fields, dataSource.DataStreamName)
111 return strings.Join(fields, ":")
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()
117 if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == http.StatusConflict {
118 if dataSource.DataStreamId != "" {
119 return dataSource.DataStreamId, nil
121 return DataStreamID(dataSource), nil
123 log.Errorf(ctx, "c.Service.Users.DataSources.Create(%q) = (%+v, %v)", dataSource, res, err)
126 return res.DataStreamId, nil
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
135 if endTimeNanos == -1 || endTimeNanos < p.EndTimeNanos {
136 endTimeNanos = p.EndTimeNanos
139 datasetID := fmt.Sprintf("%d-%d", startTimeNanos, endTimeNanos)
141 dataset := &fitness.Dataset{
142 DataSourceId: dataSourceID,
143 MinStartTimeNs: startTimeNanos,
144 MaxEndTimeNs: endTimeNanos,
148 _, err := c.Service.Users.DataSources.Datasets.Patch(userID, dataSourceID, datasetID, dataset).Context(ctx).Do()
150 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Patch() = %v", err)
156 func (c *Client) SetDistance(ctx context.Context, meters float64, startOfDay time.Time) error {
157 return c.updateCumulative(ctx,
159 Application: Application(ctx),
160 DataType: &fitness.DataType{
161 Field: []*fitness.DataTypeField{
162 &fitness.DataTypeField{
164 Format: "floatPoint",
167 Name: dataTypeNameDistance,
169 Name: "Distance covered",
178 func (c *Client) SetSteps(ctx context.Context, totalSteps int, startOfDay time.Time) error {
179 return c.updateCumulative(ctx,
181 Application: Application(ctx),
182 DataType: &fitness.DataType{
183 Field: []*fitness.DataTypeField{
184 &fitness.DataTypeField{
189 Name: dataTypeNameSteps,
195 IntVal: int64(totalSteps),
200 func (c *Client) SetCalories(ctx context.Context, totalCalories float64, startOfDay time.Time) error {
201 return c.updateCumulative(ctx,
203 Application: Application(ctx),
204 DataType: &fitness.DataType{
205 Field: []*fitness.DataTypeField{
206 &fitness.DataTypeField{
208 Format: "floatPoint",
211 Name: dataTypeNameCalories,
213 Name: "Calories expended",
217 FpVal: totalCalories,
222 type Activity struct {
228 func (a Activity) String() string {
229 return fmt.Sprintf("%s-%s %d", a.Start.Format("15:04:05"), a.End.Format("15:04:05"), a.Type)
232 func (c *Client) SetActivities(ctx context.Context, activities []Activity, startOfDay time.Time) error {
233 if len(activities) == 0 {
237 dataStreamID, err := c.DataSourceCreate(ctx, &fitness.DataSource{
238 Application: Application(ctx),
239 DataType: &fitness.DataType{
240 Field: []*fitness.DataTypeField{
241 &fitness.DataTypeField{
246 Name: dataTypeNameActivitySegment,
254 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
256 datasetID := fmt.Sprintf("%d-%d", startOfDay.UnixNano(), endOfDay.UnixNano())
257 res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataStreamID, datasetID).Context(ctx).Do()
259 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataStreamID, datasetID, err)
263 var dataPoints []*fitness.DataPoint
265 for _, a := range activities {
266 startTimeNanos := a.Start.UnixNano()
267 endTimeNanos := a.End.UnixNano()
269 for _, p := range res.Point {
270 if p.StartTimeNanos == startTimeNanos && p.EndTimeNanos == endTimeNanos && p.Value[0].IntVal == a.Type {
271 log.Debugf(ctx, "activity %s already stored in Google Fit", a)
276 log.Debugf(ctx, "activity %s will be added to Google Fit", a)
277 dataPoints = append(dataPoints, &fitness.DataPoint{
278 DataTypeName: dataTypeNameActivitySegment,
279 StartTimeNanos: startTimeNanos,
280 EndTimeNanos: endTimeNanos,
281 Value: []*fitness.Value{
282 &fitness.Value{IntVal: a.Type},
287 if len(dataPoints) == 0 {
291 return c.DataSetPatch(ctx, dataStreamID, dataPoints)
294 func (c *Client) updateCumulative(ctx context.Context, dataSource *fitness.DataSource, rawValue *fitness.Value, startOfDay time.Time) error {
295 switch f := dataSource.DataType.Field[0].Format; f {
297 if rawValue.IntVal == 0 {
301 if rawValue.FpVal == 0 {
305 return fmt.Errorf("unexpected data type field format %q", f)
308 dataSourceID, err := c.DataSourceCreate(ctx, dataSource)
312 dataSource.DataStreamId = dataSourceID
314 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
315 currValue, startTime, err := c.readCumulative(ctx, dataSource, startOfDay, endOfDay)
320 var diffValue fitness.Value
321 if dataSource.DataType.Field[0].Format == "integer" {
322 if rawValue.IntVal == currValue.IntVal {
325 diffValue.IntVal = rawValue.IntVal - currValue.IntVal
326 if diffValue.IntVal < 0 {
327 log.Warningf(ctx, "stored value (%d) is larger than new value (%d); assuming count was reset", currValue.IntVal, rawValue.IntVal)
328 diffValue.IntVal = rawValue.IntVal
330 } else { // if dataSource.DataType.Field[0].Format == "floatPoint"
331 if rawValue.FpVal == currValue.FpVal {
334 diffValue.FpVal = rawValue.FpVal - currValue.FpVal
335 if diffValue.FpVal < 0 {
336 log.Warningf(ctx, "stored value (%g) is larger than new value (%g); assuming count was reset", currValue.FpVal, rawValue.FpVal)
337 diffValue.FpVal = rawValue.FpVal
342 if now := time.Now().In(startOfDay.Location()); now.Before(endOfDay) {
345 log.Debugf(ctx, "adding cumulative data point: %v-%v %+v", startTime, endTime, diffValue)
347 return c.DataSetPatch(ctx, dataSource.DataStreamId, []*fitness.DataPoint{
349 DataTypeName: dataSource.DataType.Name,
350 StartTimeNanos: startTime.UnixNano(),
351 EndTimeNanos: endTime.UnixNano(),
352 Value: []*fitness.Value{&diffValue},
357 func (c *Client) readCumulative(ctx context.Context, dataSource *fitness.DataSource, startTime, endTime time.Time) (*fitness.Value, time.Time, error) {
358 datasetID := fmt.Sprintf("%d-%d", startTime.UnixNano(), endTime.UnixNano())
360 res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataSource.DataStreamId, datasetID).Context(ctx).Do()
362 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataSource.DataStreamId, datasetID, err)
363 return nil, time.Time{}, err
366 if len(res.Point) == 0 {
367 return &fitness.Value{}, startTime, nil
370 var sum fitness.Value
371 maxEndTime := startTime
372 for _, p := range res.Point {
373 switch f := dataSource.DataType.Field[0].Format; f {
375 sum.IntVal += p.Value[0].IntVal
377 sum.FpVal += p.Value[0].FpVal
379 return nil, time.Time{}, fmt.Errorf("unexpected data type field format %q", f)
382 pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
383 if maxEndTime.Before(pointEndTime) {
384 maxEndTime = pointEndTime
388 log.Debugf(ctx, "read cumulative data %s until %v: %+v", dataSource.DataStreamId, maxEndTime, sum)
389 return &sum, maxEndTime, nil
392 type heartRateDuration struct {
395 Duration time.Duration
398 type heartRateDurations []*heartRateDuration
400 func (res heartRateDurations) find(min, max int) (*heartRateDuration, bool) {
401 for _, d := range res {
402 if d.Min != min || d.Max != max {
411 func (c *Client) heartRate(ctx context.Context, dataSource *fitness.DataSource, startTime, endTime time.Time) (heartRateDurations, time.Time, error) {
412 datasetID := fmt.Sprintf("%d-%d", startTime.UnixNano(), endTime.UnixNano())
414 res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataSource.DataStreamId, datasetID).Context(ctx).Do()
416 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataSource.DataStreamId, datasetID, err)
417 return nil, time.Time{}, err
420 if len(res.Point) == 0 {
421 return nil, startTime, nil
424 var results heartRateDurations
425 maxEndTime := startTime
426 for _, p := range res.Point {
427 max := int(p.Value[1].FpVal)
428 min := int(p.Value[2].FpVal)
429 duration := time.Unix(0, p.EndTimeNanos).Sub(time.Unix(0, p.StartTimeNanos))
431 if d, ok := results.find(min, max); ok {
432 d.Duration += duration
434 results = append(results, &heartRateDuration{
441 pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
442 if maxEndTime.Before(pointEndTime) {
443 maxEndTime = pointEndTime
447 return results, maxEndTime, nil
450 func (c *Client) SetHeartRate(ctx context.Context, totalDurations []fitbit.HeartRateZone, restingHeartRate int, startOfDay time.Time) error {
451 dataSource := &fitness.DataSource{
452 Application: Application(ctx),
453 DataType: &fitness.DataType{
454 Field: []*fitness.DataTypeField{
455 &fitness.DataTypeField{
457 Format: "floatPoint",
459 &fitness.DataTypeField{
461 Format: "floatPoint",
463 &fitness.DataTypeField{
465 Format: "floatPoint",
468 Name: dataTypeNameHeartrate,
470 Name: "Heart rate summary",
474 dataSourceID, err := c.DataSourceCreate(ctx, dataSource)
478 dataSource.DataStreamId = dataSourceID
480 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
481 prevDurations, startTime, err := c.heartRate(ctx, dataSource, startOfDay, endOfDay)
483 // calculate the difference between the durations mentioned in
484 // totalDurations and prevDurations and store it in diffDurations.
485 var diffDurations heartRateDurations
486 for _, d := range totalDurations {
487 total := time.Duration(d.Minutes) * time.Minute
489 var prev time.Duration
490 if res, ok := prevDurations.find(d.Min, d.Max); ok {
499 if res, ok := diffDurations.find(d.Min, d.Max); ok {
502 diffDurations = append(diffDurations, &heartRateDuration{
510 // create a fitness.DataPoint for each non-zero duration difference.
511 var dataPoints []*fitness.DataPoint
512 for _, d := range diffDurations {
513 if d.Duration < time.Nanosecond {
517 endTime := startTime.Add(d.Duration)
518 if endTime.After(endOfDay) {
519 log.Warningf(ctx, "heart rate durations exceed one day (current end time: %v)", endTime)
523 average := float64(d.Min+d.Max) / 2.0
524 if d.Min <= restingHeartRate && restingHeartRate <= d.Max {
525 average = float64(restingHeartRate)
528 dataPoints = append(dataPoints, &fitness.DataPoint{
529 DataTypeName: dataSource.DataType.Name,
530 StartTimeNanos: startTime.UnixNano(),
531 EndTimeNanos: endTime.UnixNano(),
532 Value: []*fitness.Value{
537 FpVal: float64(d.Max),
540 FpVal: float64(d.Min),
548 if len(dataPoints) == 0 {
551 return c.DataSetPatch(ctx, dataSource.DataStreamId, dataPoints)