10 "github.com/octo/gfitsync/app"
12 oauth2google "golang.org/x/oauth2/google"
13 fitness "google.golang.org/api/fitness/v1"
14 "google.golang.org/api/googleapi"
15 "google.golang.org/appengine"
16 "google.golang.org/appengine/log"
20 csrfToken = "@CSRFTOKEN@"
23 dataTypeNameCalories = "com.google.calories.expended"
24 dataTypeNameSteps = "com.google.step_count.delta"
27 var oauthConfig = &oauth2.Config{
28 ClientID: "@GOOGLE_CLIENT_ID@",
29 ClientSecret: "@GOOGLE_CLIENT_SECRET@",
30 Endpoint: oauth2google.Endpoint,
31 RedirectURL: "https://fitbit-gfit-sync.appspot.com/google/grant",
33 fitness.FitnessActivityWriteScope,
34 fitness.FitnessBodyWriteScope,
38 func Application(ctx context.Context) *fitness.Application {
39 return &fitness.Application{
40 Name: "Fitbit to Google Fit sync",
41 Version: appengine.VersionID(ctx),
42 DetailsUrl: "", // optional
46 func AuthURL() string {
47 return oauthConfig.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
50 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
51 if state := r.FormValue("state"); state != csrfToken {
52 return fmt.Errorf("invalid state parameter: %q", state)
55 tok, err := oauthConfig.Exchange(ctx, r.FormValue("code"))
60 return u.SetToken(ctx, "Google", tok)
67 func NewClient(ctx context.Context, u *app.User) (*Client, error) {
68 c, err := u.OAuthClient(ctx, "Google", oauthConfig)
73 service, err := fitness.New(c)
83 func DataStreamID(dataSource *fitness.DataSource) string {
86 dataSource.DataType.Name,
87 "@PROJECT_NUMBER@", // FIXME
90 if dev := dataSource.Device; dev != nil {
91 if dev.Manufacturer != "" {
92 fields = append(fields, dev.Manufacturer)
95 fields = append(fields, dev.Model)
98 fields = append(fields, dev.Uid)
102 return strings.Join(fields, ":")
105 func (c *Client) DataSourceCreate(ctx context.Context, dataSource *fitness.DataSource) (string, error) {
106 res, err := c.Service.Users.DataSources.Create(userID, dataSource).Context(ctx).Do()
108 if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == http.StatusConflict {
109 if dataSource.DataStreamId != "" {
110 return dataSource.DataStreamId, nil
112 return DataStreamID(dataSource), nil
114 log.Errorf(ctx, "c.Service.Users.DataSources.Create() = (%+v, %v)", res, err)
117 return res.DataStreamId, nil
120 func (c *Client) DataSetPatch(ctx context.Context, dataSourceID string, points []*fitness.DataPoint) error {
121 startTimeNanos, endTimeNanos := int64(-1), int64(-1)
122 for _, p := range points {
123 if startTimeNanos == -1 || startTimeNanos > p.StartTimeNanos {
124 startTimeNanos = p.StartTimeNanos
126 if endTimeNanos == -1 || endTimeNanos < p.EndTimeNanos {
127 endTimeNanos = p.EndTimeNanos
130 datasetID := fmt.Sprintf("%d-%d", startTimeNanos, endTimeNanos)
132 dataset := &fitness.Dataset{
133 DataSourceId: dataSourceID,
134 MinStartTimeNs: startTimeNanos,
135 MaxEndTimeNs: endTimeNanos,
139 _, err := c.Service.Users.DataSources.Datasets.Patch(userID, dataSourceID, datasetID, dataset).Context(ctx).Do()
141 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Patch() = %v", err)
147 func (c *Client) SetSteps(ctx context.Context, totalSteps int, startOfDay time.Time) error {
148 return c.updateCumulative(ctx,
150 Application: Application(ctx),
151 DataType: &fitness.DataType{
152 Field: []*fitness.DataTypeField{
153 &fitness.DataTypeField{
158 Name: dataTypeNameSteps,
164 IntVal: int64(totalSteps),
169 func (c *Client) SetCalories(ctx context.Context, totalCalories float64, startOfDay time.Time) error {
170 return c.updateCumulative(ctx,
172 Application: Application(ctx),
173 DataType: &fitness.DataType{
174 Field: []*fitness.DataTypeField{
175 &fitness.DataTypeField{
177 Format: "floatPoint",
180 Name: dataTypeNameCalories,
182 Name: "Calories expended",
186 FpVal: totalCalories,
191 func (c *Client) updateCumulative(ctx context.Context, dataSource *fitness.DataSource, rawValue *fitness.Value, startOfDay time.Time) error {
192 switch f := dataSource.DataType.Field[0].Format; f {
194 if rawValue.IntVal == 0 {
198 if rawValue.FpVal == 0 {
202 return fmt.Errorf("unexpected data type field format %q", f)
205 dataSourceID, err := c.DataSourceCreate(ctx, dataSource)
209 dataSource.DataStreamId = dataSourceID
211 endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
212 currValue, startTime, err := c.readCumulative(ctx, dataSource, startOfDay, endOfDay)
214 var diffValue fitness.Value
215 if dataSource.DataType.Field[0].Format == "integer" {
216 if rawValue.IntVal == currValue.IntVal {
219 diffValue.IntVal = rawValue.IntVal - currValue.IntVal
220 if diffValue.IntVal < 0 {
221 log.Warningf(ctx, "stored value (%d) is larger than new value (%d); assuming count was reset", currValue.IntVal, rawValue.IntVal)
222 diffValue.IntVal = rawValue.IntVal
224 } else { // if dataSource.DataType.Field[0].Format == "floatPoint"
225 if rawValue.FpVal == currValue.FpVal {
228 diffValue.FpVal = rawValue.FpVal - currValue.FpVal
229 if diffValue.FpVal < 0 {
230 log.Warningf(ctx, "stored value (%g) is larger than new value (%g); assuming count was reset", currValue.FpVal, rawValue.FpVal)
231 diffValue.FpVal = rawValue.FpVal
236 if now := time.Now().In(startOfDay.Location()); now.Before(endOfDay) {
239 log.Debugf(ctx, "adding cumulative data point: %v-%v %+v", startTime, endTime, diffValue)
241 return c.DataSetPatch(ctx, dataSource.DataStreamId, []*fitness.DataPoint{
243 DataTypeName: dataSource.DataType.Name,
244 StartTimeNanos: startTime.UnixNano(),
245 EndTimeNanos: endTime.UnixNano(),
246 Value: []*fitness.Value{&diffValue},
251 func (c *Client) readCumulative(ctx context.Context, dataSource *fitness.DataSource, startTime, endTime time.Time) (*fitness.Value, time.Time, error) {
252 datasetID := fmt.Sprintf("%d-%d", startTime.UnixNano(), endTime.UnixNano())
254 res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataSource.DataStreamId, datasetID).Context(ctx).Do()
256 log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataSource.DataStreamId, datasetID, err)
257 return nil, time.Time{}, err
260 if len(res.Point) == 0 {
261 return &fitness.Value{}, startTime, nil
264 var sum fitness.Value
265 maxEndTime := startTime
266 for _, p := range res.Point {
267 switch f := dataSource.DataType.Field[0].Format; f {
269 sum.IntVal += p.Value[0].IntVal
271 sum.FpVal += p.Value[0].FpVal
273 return nil, time.Time{}, fmt.Errorf("unexpected data type field format %q", f)
276 pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
277 if maxEndTime.Before(pointEndTime) {
278 maxEndTime = pointEndTime
282 log.Debugf(ctx, "read cumulative data %s until %v: %+v", dataSource.DataStreamId, maxEndTime, sum)
283 return &sum, maxEndTime, nil