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() = (%+v, %v)", 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 (c *Client) SetActivities(ctx context.Context, activities []Activity, startOfDay time.Time) error {
229 dataStreamID := DataStreamID(&fitness.DataSource{
230 DataType: &fitness.DataType{
231 Name: dataTypeNameActivitySegment,
236 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
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()
241 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataStreamID, datasetID, err)
245 var dataPoints []*fitness.DataPoint
247 for _, a := range activities {
248 startTimeNanos := a.Start.UnixNano()
249 endTimeNanos := a.End.UnixNano()
251 for _, p := range res.Point {
252 if p.StartTimeNanos == startTimeNanos &&
253 p.EndTimeNanos == endTimeNanos &&
254 p.Value[0].IntVal == a.Type {
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},
269 if len(dataPoints) == 0 {
273 return c.DataSetPatch(ctx, dataStreamID, dataPoints)
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 {
279 if rawValue.IntVal == 0 {
283 if rawValue.FpVal == 0 {
287 return fmt.Errorf("unexpected data type field format %q", f)
290 dataSourceID, err := c.DataSourceCreate(ctx, dataSource)
294 dataSource.DataStreamId = dataSourceID
296 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
297 currValue, startTime, err := c.readCumulative(ctx, dataSource, startOfDay, endOfDay)
302 var diffValue fitness.Value
303 if dataSource.DataType.Field[0].Format == "integer" {
304 if rawValue.IntVal == currValue.IntVal {
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
312 } else { // if dataSource.DataType.Field[0].Format == "floatPoint"
313 if rawValue.FpVal == currValue.FpVal {
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
324 if now := time.Now().In(startOfDay.Location()); now.Before(endOfDay) {
327 log.Debugf(ctx, "adding cumulative data point: %v-%v %+v", startTime, endTime, diffValue)
329 return c.DataSetPatch(ctx, dataSource.DataStreamId, []*fitness.DataPoint{
331 DataTypeName: dataSource.DataType.Name,
332 StartTimeNanos: startTime.UnixNano(),
333 EndTimeNanos: endTime.UnixNano(),
334 Value: []*fitness.Value{&diffValue},
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())
342 res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataSource.DataStreamId, datasetID).Context(ctx).Do()
344 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataSource.DataStreamId, datasetID, err)
345 return nil, time.Time{}, err
348 if len(res.Point) == 0 {
349 return &fitness.Value{}, startTime, nil
352 var sum fitness.Value
353 maxEndTime := startTime
354 for _, p := range res.Point {
355 switch f := dataSource.DataType.Field[0].Format; f {
357 sum.IntVal += p.Value[0].IntVal
359 sum.FpVal += p.Value[0].FpVal
361 return nil, time.Time{}, fmt.Errorf("unexpected data type field format %q", f)
364 pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
365 if maxEndTime.Before(pointEndTime) {
366 maxEndTime = pointEndTime
370 log.Debugf(ctx, "read cumulative data %s until %v: %+v", dataSource.DataStreamId, maxEndTime, sum)
371 return &sum, maxEndTime, nil
374 type heartRateDuration struct {
377 Duration time.Duration
380 type heartRateDurations []*heartRateDuration
382 func (res heartRateDurations) find(min, max int) (*heartRateDuration, bool) {
383 for _, d := range res {
384 if d.Min != min || d.Max != max {
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())
396 res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataSource.DataStreamId, datasetID).Context(ctx).Do()
398 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataSource.DataStreamId, datasetID, err)
399 return nil, time.Time{}, err
402 if len(res.Point) == 0 {
403 return nil, startTime, nil
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))
413 if d, ok := results.find(min, max); ok {
414 d.Duration += duration
416 results = append(results, &heartRateDuration{
423 pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
424 if maxEndTime.Before(pointEndTime) {
425 maxEndTime = pointEndTime
429 return results, maxEndTime, nil
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{
439 Format: "floatPoint",
441 &fitness.DataTypeField{
443 Format: "floatPoint",
445 &fitness.DataTypeField{
447 Format: "floatPoint",
450 Name: dataTypeNameHeartrate,
452 Name: "Heart rate summary",
456 dataSourceID, err := c.DataSourceCreate(ctx, dataSource)
460 dataSource.DataStreamId = dataSourceID
462 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
463 prevDurations, startTime, err := c.heartRate(ctx, dataSource, startOfDay, endOfDay)
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
471 var prev time.Duration
472 if res, ok := prevDurations.find(d.Min, d.Max); ok {
481 if res, ok := diffDurations.find(d.Min, d.Max); ok {
484 diffDurations = append(diffDurations, &heartRateDuration{
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 {
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)
505 average := float64(d.Min+d.Max) / 2.0
506 if d.Min <= restingHeartRate && restingHeartRate <= d.Max {
507 average = float64(restingHeartRate)
510 dataPoints = append(dataPoints, &fitness.DataPoint{
511 DataTypeName: dataSource.DataType.Name,
512 StartTimeNanos: startTime.UnixNano(),
513 EndTimeNanos: endTime.UnixNano(),
514 Value: []*fitness.Value{
519 FpVal: float64(d.Max),
522 FpVal: float64(d.Min),
530 if len(dataPoints) == 0 {
533 return c.DataSetPatch(ctx, dataSource.DataStreamId, dataPoints)