10 "github.com/octo/kraftakt/app"
11 "github.com/octo/kraftakt/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"
23 dataTypeNameCalories = "com.google.calories.expended"
24 dataTypeNameDistance = "com.google.distance.delta"
25 dataTypeNameSteps = "com.google.step_count.delta"
26 dataTypeNameHeartrate = "com.google.heart_rate.summary"
27 dataTypeNameActivitySegment = "com.google.activity.segment"
30 func oauthConfig() *oauth2.Config {
31 return &oauth2.Config{
32 ClientID: app.Config.GoogleClientID,
33 ClientSecret: app.Config.GoogleClientSecret,
34 Endpoint: oauth2google.Endpoint,
35 RedirectURL: "https://kraftakt.octo.it/google/grant",
37 fitness.FitnessActivityWriteScope,
38 fitness.FitnessBodyWriteScope,
39 fitness.FitnessLocationWriteScope,
44 func AuthURL(ctx context.Context, u *app.User) string {
45 return oauthConfig().AuthCodeURL(u.Sign("Google"), oauth2.AccessTypeOffline)
48 func Application(ctx context.Context) *fitness.Application {
49 return &fitness.Application{
51 Version: appengine.VersionID(ctx),
52 DetailsUrl: "", // optional
56 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
57 if state := r.FormValue("state"); state != u.Sign("Google") {
58 return fmt.Errorf("invalid state parameter: %q", state)
61 tok, err := oauthConfig().Exchange(ctx, r.FormValue("code"))
66 return u.SetToken(ctx, "Google", tok)
74 func NewClient(ctx context.Context, u *app.User) (*Client, error) {
75 c, err := u.OAuthClient(ctx, "Google", oauthConfig())
80 service, err := fitness.New(c)
91 func (c *Client) DeleteToken(ctx context.Context) error {
92 return c.appUser.DeleteToken(ctx, "Google")
95 func DataStreamID(dataSource *fitness.DataSource) string {
98 dataSource.DataType.Name,
99 app.Config.ProjectNumber,
102 if dev := dataSource.Device; dev != nil {
103 if dev.Manufacturer != "" {
104 fields = append(fields, dev.Manufacturer)
107 fields = append(fields, dev.Model)
110 fields = append(fields, dev.Uid)
114 if dataSource.DataStreamName != "" {
115 fields = append(fields, dataSource.DataStreamName)
118 return strings.Join(fields, ":")
121 func (c *Client) DataSourceCreate(ctx context.Context, dataSource *fitness.DataSource) (string, error) {
122 res, err := c.Service.Users.DataSources.Create(userID, dataSource).Context(ctx).Do()
124 if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == http.StatusConflict {
125 if dataSource.DataStreamId != "" {
126 return dataSource.DataStreamId, nil
128 return DataStreamID(dataSource), nil
130 return "", fmt.Errorf("DataSources.Create(%q) = %v", DataStreamID(dataSource), err)
133 return res.DataStreamId, nil
136 func (c *Client) DatasetGet(ctx context.Context, dataSourceID string, startTime, endTime time.Time) (*fitness.Dataset, error) {
137 datasetID := fmt.Sprintf("%d-%d", startTime.UnixNano(), endTime.UnixNano())
139 res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataSourceID, datasetID).Context(ctx).Do()
141 return nil, fmt.Errorf("DataSources.Datasets.Get(%q, %q) = %v", dataSourceID, datasetID, err)
146 func (c *Client) DatasetPatch(ctx context.Context, dataSourceID string, points []*fitness.DataPoint) error {
147 startTimeNanos, endTimeNanos := int64(-1), int64(-1)
148 for _, p := range points {
149 if startTimeNanos == -1 || startTimeNanos > p.StartTimeNanos {
150 startTimeNanos = p.StartTimeNanos
152 if endTimeNanos == -1 || endTimeNanos < p.EndTimeNanos {
153 endTimeNanos = p.EndTimeNanos
156 datasetID := fmt.Sprintf("%d-%d", startTimeNanos, endTimeNanos)
158 dataset := &fitness.Dataset{
159 DataSourceId: dataSourceID,
160 MinStartTimeNs: startTimeNanos,
161 MaxEndTimeNs: endTimeNanos,
165 _, err := c.Service.Users.DataSources.Datasets.Patch(userID, dataSourceID, datasetID, dataset).Context(ctx).Do()
167 log.Errorf(ctx, "DataSources.Datasets.Patch(%q, %q) = %v", dataSourceID, datasetID, err)
173 func (c *Client) SetDistance(ctx context.Context, meters float64, startOfDay time.Time) error {
174 return c.updateIncremental(ctx,
176 Application: Application(ctx),
177 DataType: &fitness.DataType{
178 Field: []*fitness.DataTypeField{
179 &fitness.DataTypeField{
181 Format: "floatPoint",
184 Name: dataTypeNameDistance,
186 Name: "Distance covered",
195 func (c *Client) SetSteps(ctx context.Context, totalSteps int, startOfDay time.Time) error {
196 return c.updateIncremental(ctx,
198 Application: Application(ctx),
199 DataType: &fitness.DataType{
200 Field: []*fitness.DataTypeField{
201 &fitness.DataTypeField{
206 Name: dataTypeNameSteps,
212 IntVal: int64(totalSteps),
217 func (c *Client) SetCalories(ctx context.Context, totalCalories float64, startOfDay time.Time) error {
218 return c.updateIncremental(ctx,
220 Application: Application(ctx),
221 DataType: &fitness.DataType{
222 Field: []*fitness.DataTypeField{
223 &fitness.DataTypeField{
225 Format: "floatPoint",
228 Name: dataTypeNameCalories,
230 Name: "Calories expended",
234 FpVal: totalCalories,
239 type Activity struct {
245 func (a Activity) String() string {
246 return fmt.Sprintf("%s-%s %q", a.Start.Format("15:04:05"), a.End.Format("15:04:05"), a.Type)
249 func (c *Client) SetActivities(ctx context.Context, activities []Activity, startOfDay time.Time) error {
250 if len(activities) == 0 {
254 dataStreamID, err := c.DataSourceCreate(ctx, &fitness.DataSource{
255 Application: Application(ctx),
256 DataType: &fitness.DataType{
257 Field: []*fitness.DataTypeField{
258 &fitness.DataTypeField{
263 Name: dataTypeNameActivitySegment,
271 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
273 dataset, err := c.DatasetGet(ctx, dataStreamID, startOfDay, endOfDay)
278 var dataPoints []*fitness.DataPoint
280 for _, a := range activities {
281 startTimeNanos := a.Start.UnixNano()
282 endTimeNanos := a.End.UnixNano()
283 activityType := ParseFitbitActivity(a.Type)
285 for _, p := range dataset.Point {
286 if p.StartTimeNanos == startTimeNanos && p.EndTimeNanos == endTimeNanos && p.Value[0].IntVal == activityType {
287 log.Debugf(ctx, "activity %s already stored in Google Fit", a)
292 log.Debugf(ctx, "activity %s will be added to Google Fit", a)
293 dataPoints = append(dataPoints, &fitness.DataPoint{
294 DataTypeName: dataTypeNameActivitySegment,
295 StartTimeNanos: startTimeNanos,
296 EndTimeNanos: endTimeNanos,
297 Value: []*fitness.Value{
298 &fitness.Value{IntVal: activityType},
303 if len(dataPoints) == 0 {
307 return c.DatasetPatch(ctx, dataStreamID, dataPoints)
310 func (c *Client) updateIncremental(ctx context.Context, dataSource *fitness.DataSource, rawValue *fitness.Value, startOfDay time.Time) error {
311 switch f := dataSource.DataType.Field[0].Format; f {
313 if rawValue.IntVal == 0 {
317 if rawValue.FpVal == 0 {
321 return fmt.Errorf("unexpected data type field format %q", f)
324 dataSourceID, err := c.DataSourceCreate(ctx, dataSource)
328 dataSource.DataStreamId = dataSourceID
330 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
331 storedValue, startTime, err := c.readIncremental(ctx, dataSource, startOfDay, endOfDay)
336 var diffValue fitness.Value
337 if dataSource.DataType.Field[0].Format == "integer" {
338 if storedValue.IntVal > rawValue.IntVal {
339 log.Warningf(ctx, "stored value (%d) is larger than new value (%d)", storedValue.IntVal, rawValue.IntVal)
342 if rawValue.IntVal == storedValue.IntVal {
345 diffValue.IntVal = rawValue.IntVal - storedValue.IntVal
346 } else { // if dataSource.DataType.Field[0].Format == "floatPoint"
347 if storedValue.FpVal > rawValue.FpVal {
348 log.Warningf(ctx, "stored value (%g) is larger than new value (%g)", storedValue.FpVal, rawValue.FpVal)
351 if rawValue.FpVal == storedValue.FpVal {
354 diffValue.FpVal = rawValue.FpVal - storedValue.FpVal
358 if now := time.Now().In(startOfDay.Location()); now.Before(endOfDay) {
361 log.Debugf(ctx, "add cumulative data %s until %v: %+v", dataSource.DataStreamId, endTime, diffValue)
363 return c.DatasetPatch(ctx, dataSource.DataStreamId, []*fitness.DataPoint{
365 DataTypeName: dataSource.DataType.Name,
366 StartTimeNanos: startTime.UnixNano(),
367 EndTimeNanos: endTime.UnixNano(),
368 Value: []*fitness.Value{&diffValue},
373 func (c *Client) readIncremental(ctx context.Context, dataSource *fitness.DataSource, startTime, endTime time.Time) (*fitness.Value, time.Time, error) {
374 dataset, err := c.DatasetGet(ctx, dataSource.DataStreamId, startTime, endTime)
376 return nil, time.Time{}, err
379 if len(dataset.Point) == 0 {
380 log.Debugf(ctx, "read cumulative data %s until %v: []", dataSource.DataStreamId, endTime)
381 return &fitness.Value{}, startTime, nil
384 var sum fitness.Value
385 maxEndTime := startTime
386 for _, p := range dataset.Point {
387 switch f := dataSource.DataType.Field[0].Format; f {
389 sum.IntVal += p.Value[0].IntVal
391 sum.FpVal += p.Value[0].FpVal
393 return nil, time.Time{}, fmt.Errorf("unexpected data type field format %q", f)
396 pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
397 if maxEndTime.Before(pointEndTime) {
398 maxEndTime = pointEndTime
402 log.Debugf(ctx, "read cumulative data %s until %v: %+v", dataSource.DataStreamId, maxEndTime, sum)
403 return &sum, maxEndTime, nil
406 type heartRateDuration struct {
409 Duration time.Duration
412 type heartRateDurations []*heartRateDuration
414 func (res heartRateDurations) find(min, max int) (*heartRateDuration, bool) {
415 for _, d := range res {
416 if d.Min != min || d.Max != max {
425 func (c *Client) heartRate(ctx context.Context, dataSource *fitness.DataSource, startTime, endTime time.Time) (heartRateDurations, time.Time, error) {
426 dataset, err := c.DatasetGet(ctx, dataSource.DataStreamId, startTime, endTime)
428 return nil, time.Time{}, err
431 if len(dataset.Point) == 0 {
432 return nil, startTime, nil
435 var results heartRateDurations
436 maxEndTime := startTime
437 for _, p := range dataset.Point {
438 max := int(p.Value[1].FpVal)
439 min := int(p.Value[2].FpVal)
440 duration := time.Unix(0, p.EndTimeNanos).Sub(time.Unix(0, p.StartTimeNanos))
442 if d, ok := results.find(min, max); ok {
443 d.Duration += duration
445 results = append(results, &heartRateDuration{
452 pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
453 if maxEndTime.Before(pointEndTime) {
454 maxEndTime = pointEndTime
458 return results, maxEndTime, nil
461 func (c *Client) SetHeartRate(ctx context.Context, totalDurations []fitbit.HeartRateZone, restingHeartRate int, startOfDay time.Time) error {
462 dataSource := &fitness.DataSource{
463 Application: Application(ctx),
464 DataType: &fitness.DataType{
465 Field: []*fitness.DataTypeField{
466 &fitness.DataTypeField{
468 Format: "floatPoint",
470 &fitness.DataTypeField{
472 Format: "floatPoint",
474 &fitness.DataTypeField{
476 Format: "floatPoint",
479 Name: dataTypeNameHeartrate,
481 Name: "Heart rate summary",
485 dataSourceID, err := c.DataSourceCreate(ctx, dataSource)
489 dataSource.DataStreamId = dataSourceID
491 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
492 prevDurations, startTime, err := c.heartRate(ctx, dataSource, startOfDay, endOfDay)
494 // calculate the difference between the durations mentioned in
495 // totalDurations and prevDurations and store it in diffDurations.
496 var diffDurations heartRateDurations
497 for _, d := range totalDurations {
498 total := time.Duration(d.Minutes) * time.Minute
500 var prev time.Duration
501 if res, ok := prevDurations.find(d.Min, d.Max); ok {
510 if res, ok := diffDurations.find(d.Min, d.Max); ok {
513 diffDurations = append(diffDurations, &heartRateDuration{
521 // create a fitness.DataPoint for each non-zero duration difference.
522 var dataPoints []*fitness.DataPoint
523 for _, d := range diffDurations {
524 if d.Duration < time.Nanosecond {
528 endTime := startTime.Add(d.Duration)
529 if endTime.After(endOfDay) {
530 log.Warningf(ctx, "heart rate durations exceed one day (current end time: %v)", endTime)
534 average := float64(d.Min+d.Max) / 2.0
535 if d.Min <= restingHeartRate && restingHeartRate <= d.Max {
536 average = float64(restingHeartRate)
539 dataPoints = append(dataPoints, &fitness.DataPoint{
540 DataTypeName: dataSource.DataType.Name,
541 StartTimeNanos: startTime.UnixNano(),
542 EndTimeNanos: endTime.UnixNano(),
543 Value: []*fitness.Value{
548 FpVal: float64(d.Max),
551 FpVal: float64(d.Min),
559 if len(dataPoints) == 0 {
562 return c.DatasetPatch(ctx, dataSource.DataStreamId, dataPoints)