1 // Package fitbit implements functions to interact with the Fitbit API.
16 "github.com/octo/kraftakt/app"
18 oauth2fitbit "golang.org/x/oauth2/fitbit"
19 "google.golang.org/appengine"
20 "google.golang.org/appengine/log"
23 func oauthConfig() *oauth2.Config {
24 return &oauth2.Config{
25 ClientID: app.Config.FitbitClientID,
26 ClientSecret: app.Config.FitbitClientSecret,
27 Endpoint: oauth2fitbit.Endpoint,
28 RedirectURL: "https://kraftakt.octo.it/fitbit/grant",
38 // AuthURL returns the URL of the Fitbit consent screen. Users are redirected
39 // there to approve Fitbit minting an OAuth2 token for us.
40 func AuthURL(ctx context.Context, u *app.User) string {
41 return oauthConfig().AuthCodeURL(u.Sign("Fitbit"), oauth2.AccessTypeOffline)
44 // ParseToken parses the request of the user being redirected back from the
45 // consent screen. The parsed token is stored in u using SetToken().
46 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
47 if state := r.FormValue("state"); state != u.Sign("Fitbit") {
48 return fmt.Errorf("invalid state parameter: %q", state)
51 tok, err := oauthConfig().Exchange(ctx, r.FormValue("code"))
56 return u.SetToken(ctx, "Fitbit", tok)
59 // CheckSignature validates that rawSig is a valid signature of payload. This
60 // is used by the Fitbit API to ansure that the receiver can verify that the
61 // sender has access to the OAuth2 client secret.
62 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
63 signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
65 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", rawSig, err)
69 mac := hmac.New(sha1.New, []byte(oauthConfig().ClientSecret+"&"))
71 signatureWant := mac.Sum(nil)
73 return hmac.Equal(signatureGot, signatureWant)
76 type Activity struct {
77 ActivityID int `json:"activityId"`
78 ActivityParentID int `json:"activityParentId"`
79 ActivityParentName string `json:"activityParentName"`
80 Calories int `json:"calories"`
81 Description string `json:"description"`
82 Distance float64 `json:"distance"`
83 Duration int `json:"duration"`
84 HasStartTime bool `json:"hasStartTime"`
85 IsFavorite bool `json:"isFavorite"`
86 LastModified time.Time `json:"lastModified"`
87 LogID int `json:"logId"`
88 Name string `json:"name"`
89 StartTime string `json:"startTime"`
90 StartDate string `json:"startDate"`
91 Steps int `json:"steps"`
94 type Distance struct {
95 Activity string `json:"activity"`
96 Distance float64 `json:"distance"`
99 type HeartRateZone struct {
100 Name string `json:"name"`
103 Minutes int `json:"minutes"`
104 CaloriesOut float64 `json:"caloriesOut"`
107 type ActivitySummary struct {
108 Activities []Activity `json:"activities"`
110 CaloriesOut int `json:"caloriesOut"`
111 Distance float64 `json:"distance"`
112 Floors int `json:"floors"`
113 Steps int `json:"steps"`
116 ActiveScore int `json:"activeScore"`
117 ActivityCalories int `json:"activityCalories"`
118 CaloriesBMR int `json:"caloriesBMR"`
119 CaloriesOut float64 `json:"caloriesOut"`
120 Distances []Distance `json:"distances"`
121 Elevation float64 `json:"elevation"`
122 Floors int `json:"floors"`
123 HeartRateZones []HeartRateZone `json:"heartRateZones"`
124 CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"`
125 MarginalCalories int `json:"marginalCalories"`
126 RestingHeartRate int `json:"restingHeartRate"`
127 Steps int `json:"steps"`
128 SedentaryMinutes int `json:"sedentaryMinutes"`
129 LightlyActiveMinutes int `json:"lightlyActiveMinutes"`
130 FairlyActiveMinutes int `json:"fairlyActiveMinutes"`
131 VeryActiveMinutes int `json:"veryActiveMinutes"`
135 type Subscription struct {
136 CollectionType string `json:"collectionType"`
137 Date string `json:"date"`
138 OwnerID string `json:"ownerId"`
139 OwnerType string `json:"ownerType"`
140 SubscriptionID string `json:"subscriptionId"`
143 func (s Subscription) String() string {
144 return fmt.Sprintf("https://api.fitbit.com/1/%s/%s/%s/apiSubscriptions/%s.json",
145 s.OwnerType, s.OwnerID, s.CollectionType, s.SubscriptionID)
154 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
155 if fitbitUserID == "" {
159 c, err := u.OAuthClient(ctx, "Fitbit", oauthConfig())
161 return nil, fmt.Errorf("OAuthClient(%q) = %v", "Fitbit", err)
165 fitbitUserID: fitbitUserID,
171 // ActivitySummary returns the daily activity summary.
173 // See https://dev.fitbit.com/build/reference/web-api/activity/#get-daily-activity-summary for details.
174 func (c *Client) ActivitySummary(ctx context.Context, date string) (*ActivitySummary, error) {
175 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
176 c.fitbitUserID, date)
178 res, err := c.client.Get(url)
182 defer res.Body.Close()
184 data, err := ioutil.ReadAll(res.Body)
188 log.Debugf(ctx, "GET %s -> %s", url, data)
190 var summary ActivitySummary
191 if err := json.Unmarshal(data, &summary); err != nil {
198 func (c *Client) subscriberID(collection string) string {
199 return fmt.Sprintf("%s:%s", c.appUser.ID, collection)
202 // UserFromSubscriberID parses the user ID from the subscriber ID and calls
203 // app.UserByID() with the user ID.
204 func UserFromSubscriberID(ctx context.Context, subscriberID string) (*app.User, error) {
205 uid := strings.Split(subscriberID, ":")[0]
206 return app.UserByID(ctx, uid)
209 // Subscribe subscribes to one collection of the user. It uses a per-collection
210 // subscription ID so that we can subscribe to more than one collection.
212 // See https://dev.fitbit.com/build/reference/web-api/subscriptions/#adding-a-subscription for details.
213 func (c *Client) Subscribe(ctx context.Context, collection string) error {
214 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
215 c.fitbitUserID, collection, c.subscriberID(collection))
216 res, err := c.client.Post(url, "", nil)
220 defer res.Body.Close()
222 if res.StatusCode >= 400 && res.StatusCode != http.StatusConflict {
223 data, _ := ioutil.ReadAll(res.Body)
224 log.Errorf(ctx, "creating %q subscription failed: status %d %q", collection, res.StatusCode, data)
225 return fmt.Errorf("creating %q subscription failed", collection)
227 if res.StatusCode == http.StatusConflict {
228 log.Infof(ctx, "creating %q subscription: already exists", collection)
234 func (c *Client) unsubscribe(ctx context.Context, userID, collection, subscriptionID string) error {
236 userID = c.fitbitUserID
239 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
240 userID, collection, subscriptionID)
241 req, err := http.NewRequest(http.MethodDelete, url, nil)
246 res, err := c.client.Do(req.WithContext(ctx))
250 defer res.Body.Close()
252 if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
253 data, _ := ioutil.ReadAll(res.Body)
254 log.Errorf(ctx, "deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
255 return fmt.Errorf("deleting %q subscription failed", collection)
257 if res.StatusCode == http.StatusNotFound {
258 log.Infof(ctx, "deleting %q subscription: not found", collection)
264 // UnsubscribeAll gets a list of all subscriptions we have with the user's
265 // account and deletes all found subscriptions.
267 // See https://dev.fitbit.com/build/reference/web-api/subscriptions/#deleting-a-subscription for details.
268 func (c *Client) UnsubscribeAll(ctx context.Context) error {
269 var errs appengine.MultiError
271 for _, collection := range []string{"activities", "sleep"} {
272 subs, err := c.ListSubscriptions(ctx, collection)
274 errs = append(errs, err)
278 for _, sub := range subs {
279 if err := c.unsubscribe(ctx, sub.OwnerID, sub.CollectionType, sub.SubscriptionID); err != nil {
280 errs = append(errs, err)
291 // ListSubscriptions returns a list of all subscriptions for a given collection
292 // the OAuth2 client has to a user's account.
293 func (c *Client) ListSubscriptions(ctx context.Context, collection string) ([]Subscription, error) {
294 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions.json", c.fitbitUserID, collection)
295 res, err := c.client.Get(url)
297 return nil, fmt.Errorf("Get(%q) = %v", url, err)
299 defer res.Body.Close()
301 if res.StatusCode == http.StatusNotFound {
302 log.Infof(ctx, "get %q subscription: not found", collection)
306 data, err := ioutil.ReadAll(res.Body)
310 log.Debugf(ctx, "GET %s -> %s", url, data)
312 if res.StatusCode >= 400 {
313 return nil, fmt.Errorf("Get(%q) = %d", url, res.StatusCode)
317 Subscriptions []Subscription `json:"apiSubscriptions"`
319 if err := json.Unmarshal(data, &parsed); err != nil {
323 var errs appengine.MultiError
324 var ret []Subscription
325 for _, sub := range parsed.Subscriptions {
326 if sub.CollectionType != collection {
327 errs = append(errs, fmt.Errorf("unexpected collection type: got %q, want %q", sub.CollectionType, collection))
330 if sub.SubscriptionID == "" {
331 errs = append(errs, fmt.Errorf("missing subscription ID: %+v", sub))
334 if sub.OwnerID == "" {
335 sub.OwnerID = c.fitbitUserID
337 ret = append(ret, sub)
340 if len(ret) == 0 && len(errs) != 0 {
344 for _, err := range errs {
345 log.Warningf(ctx, "%v", err)
351 // DeleteToken deletes the Fitbit OAuth2 token.
352 func (c *Client) DeleteToken(ctx context.Context) error {
353 return c.appUser.DeleteToken(ctx, "Fitbit")
356 // Provile contains data about the user.
357 // It only contains the subset of fields required by Kraftakt.
358 type Profile struct {
360 Timezone *time.Location
363 // Profile returns the profile information of the user.
364 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
365 res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
369 defer res.Body.Close()
371 if res.StatusCode >= 400 {
372 data, _ := ioutil.ReadAll(res.Body)
373 log.Errorf(ctx, "reading profile failed: %s", data)
374 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
380 OffsetFromUTCMillis int
384 if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
388 loc, err := time.LoadLocation(data.User.Timezone)
390 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
394 Name: data.User.FullName,