1 // Package fitbit implements functions to interact with the Fitbit API.
17 "github.com/octo/kraftakt/app"
19 oauth2fitbit "golang.org/x/oauth2/fitbit"
20 "google.golang.org/appengine"
21 "google.golang.org/appengine/log"
24 func oauthConfig() *oauth2.Config {
25 return &oauth2.Config{
26 ClientID: app.Config.FitbitClientID,
27 ClientSecret: app.Config.FitbitClientSecret,
28 Endpoint: oauth2fitbit.Endpoint,
29 RedirectURL: "https://kraftakt.octo.it/fitbit/grant",
39 // AuthURL returns the URL of the Fitbit consent screen. Users are redirected
40 // there to approve Fitbit minting an OAuth2 token for us.
41 func AuthURL(ctx context.Context, u *app.User) string {
42 return oauthConfig().AuthCodeURL(u.Sign("Fitbit"), oauth2.AccessTypeOffline)
45 // ParseToken parses the request of the user being redirected back from the
46 // consent screen. The parsed token is stored in u using SetToken().
47 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
48 if state := r.FormValue("state"); state != u.Sign("Fitbit") {
49 return fmt.Errorf("invalid state parameter: %q", state)
52 tok, err := oauthConfig().Exchange(ctx, r.FormValue("code"))
57 return u.SetToken(ctx, "Fitbit", tok)
60 // CheckSignature validates that rawSig is a valid signature of payload. This
61 // is used by the Fitbit API to ansure that the receiver can verify that the
62 // sender has access to the OAuth2 client secret.
63 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
64 signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
66 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", rawSig, err)
70 mac := hmac.New(sha1.New, []byte(oauthConfig().ClientSecret+"&"))
72 signatureWant := mac.Sum(nil)
74 if !hmac.Equal(signatureGot, signatureWant) {
75 log.Debugf(ctx, "CheckSignature(): got %q, want %q",
76 hex.EncodeToString(signatureGot),
77 hex.EncodeToString(signatureWant))
80 return hmac.Equal(signatureGot, signatureWant)
83 type Activity struct {
84 ActivityID int `json:"activityId"`
85 ActivityParentID int `json:"activityParentId"`
86 ActivityParentName string `json:"activityParentName"`
87 Calories int `json:"calories"`
88 Description string `json:"description"`
89 Distance float64 `json:"distance"`
90 Duration int `json:"duration"`
91 HasStartTime bool `json:"hasStartTime"`
92 IsFavorite bool `json:"isFavorite"`
93 LastModified time.Time `json:"lastModified"`
94 LogID int `json:"logId"`
95 Name string `json:"name"`
96 StartTime string `json:"startTime"`
97 StartDate string `json:"startDate"`
98 Steps int `json:"steps"`
101 type Distance struct {
102 Activity string `json:"activity"`
103 Distance float64 `json:"distance"`
106 type HeartRateZone struct {
107 Name string `json:"name"`
110 Minutes int `json:"minutes"`
111 CaloriesOut float64 `json:"caloriesOut"`
114 type ActivitySummary struct {
115 Activities []Activity `json:"activities"`
117 CaloriesOut int `json:"caloriesOut"`
118 Distance float64 `json:"distance"`
119 Floors int `json:"floors"`
120 Steps int `json:"steps"`
123 ActiveScore int `json:"activeScore"`
124 ActivityCalories int `json:"activityCalories"`
125 CaloriesBMR int `json:"caloriesBMR"`
126 CaloriesOut float64 `json:"caloriesOut"`
127 Distances []Distance `json:"distances"`
128 Elevation float64 `json:"elevation"`
129 Floors int `json:"floors"`
130 HeartRateZones []HeartRateZone `json:"heartRateZones"`
131 CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"`
132 MarginalCalories int `json:"marginalCalories"`
133 RestingHeartRate int `json:"restingHeartRate"`
134 Steps int `json:"steps"`
135 SedentaryMinutes int `json:"sedentaryMinutes"`
136 LightlyActiveMinutes int `json:"lightlyActiveMinutes"`
137 FairlyActiveMinutes int `json:"fairlyActiveMinutes"`
138 VeryActiveMinutes int `json:"veryActiveMinutes"`
142 type Subscription struct {
143 CollectionType string `json:"collectionType"`
144 Date string `json:"date"`
145 OwnerID string `json:"ownerId"`
146 OwnerType string `json:"ownerType"`
147 SubscriptionID string `json:"subscriptionId"`
150 func (s Subscription) String() string {
151 return fmt.Sprintf("https://api.fitbit.com/1/%s/%s/%s/apiSubscriptions/%s.json",
152 s.OwnerType, s.OwnerID, s.CollectionType, s.SubscriptionID)
161 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
162 if fitbitUserID == "" {
166 c, err := u.OAuthClient(ctx, "Fitbit", oauthConfig())
168 return nil, fmt.Errorf("OAuthClient(%q) = %v", "Fitbit", err)
172 fitbitUserID: fitbitUserID,
178 // ActivitySummary returns the daily activity summary.
180 // See https://dev.fitbit.com/build/reference/web-api/activity/#get-daily-activity-summary for details.
181 func (c *Client) ActivitySummary(ctx context.Context, date string) (*ActivitySummary, error) {
182 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
183 c.fitbitUserID, date)
185 res, err := c.client.Get(url)
189 defer res.Body.Close()
191 data, err := ioutil.ReadAll(res.Body)
195 log.Debugf(ctx, "GET %s -> %s", url, data)
197 var summary ActivitySummary
198 if err := json.Unmarshal(data, &summary); err != nil {
205 func (c *Client) subscriberID(collection string) string {
206 return fmt.Sprintf("%s:%s", c.appUser.ID, collection)
209 // UserFromSubscriberID parses the user ID from the subscriber ID and calls
210 // app.UserByID() with the user ID.
211 func UserFromSubscriberID(ctx context.Context, subscriberID string) (*app.User, error) {
212 uid := strings.Split(subscriberID, ":")[0]
213 return app.UserByID(ctx, uid)
216 // Subscribe subscribes to one collection of the user. It uses a per-collection
217 // subscription ID so that we can subscribe to more than one collection.
219 // See https://dev.fitbit.com/build/reference/web-api/subscriptions/#adding-a-subscription for details.
220 func (c *Client) Subscribe(ctx context.Context, collection string) error {
221 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
222 c.fitbitUserID, collection, c.subscriberID(collection))
223 res, err := c.client.Post(url, "", nil)
227 defer res.Body.Close()
229 if res.StatusCode >= 400 && res.StatusCode != http.StatusConflict {
230 data, _ := ioutil.ReadAll(res.Body)
231 return fmt.Errorf("creating %q subscription failed: status %d %q", collection, res.StatusCode, data)
233 if res.StatusCode == http.StatusConflict {
234 log.Infof(ctx, "creating %q subscription: already exists", collection)
240 func (c *Client) unsubscribe(ctx context.Context, userID, collection, subscriptionID string) error {
242 userID = c.fitbitUserID
245 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
246 userID, collection, subscriptionID)
247 req, err := http.NewRequest(http.MethodDelete, url, nil)
252 res, err := c.client.Do(req.WithContext(ctx))
256 defer res.Body.Close()
258 if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
259 data, _ := ioutil.ReadAll(res.Body)
260 return fmt.Errorf("deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
262 if res.StatusCode == http.StatusNotFound {
263 log.Infof(ctx, "deleting %q subscription: not found", collection)
269 // UnsubscribeAll gets a list of all subscriptions we have with the user's
270 // account and deletes all found subscriptions.
272 // See https://dev.fitbit.com/build/reference/web-api/subscriptions/#deleting-a-subscription for details.
273 func (c *Client) UnsubscribeAll(ctx context.Context) error {
274 var errs appengine.MultiError
276 for _, collection := range []string{"activities", "sleep"} {
277 subs, err := c.ListSubscriptions(ctx, collection)
279 errs = append(errs, err)
283 for _, sub := range subs {
284 if err := c.unsubscribe(ctx, sub.OwnerID, sub.CollectionType, sub.SubscriptionID); err != nil {
285 errs = append(errs, err)
296 // ListSubscriptions returns a list of all subscriptions for a given collection
297 // the OAuth2 client has to a user's account.
298 func (c *Client) ListSubscriptions(ctx context.Context, collection string) ([]Subscription, error) {
299 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions.json", c.fitbitUserID, collection)
300 res, err := c.client.Get(url)
302 return nil, fmt.Errorf("Get(%q) = %v", url, err)
304 defer res.Body.Close()
306 if res.StatusCode == http.StatusNotFound {
307 log.Infof(ctx, "get %q subscription: not found", collection)
311 data, err := ioutil.ReadAll(res.Body)
315 log.Debugf(ctx, "GET %s -> %s", url, data)
317 if res.StatusCode >= 400 {
318 return nil, fmt.Errorf("Get(%q) = %d", url, res.StatusCode)
322 Subscriptions []Subscription `json:"apiSubscriptions"`
324 if err := json.Unmarshal(data, &parsed); err != nil {
328 var errs appengine.MultiError
329 var ret []Subscription
330 for _, sub := range parsed.Subscriptions {
331 if sub.CollectionType != collection {
332 errs = append(errs, fmt.Errorf("unexpected collection type: got %q, want %q", sub.CollectionType, collection))
335 if sub.SubscriptionID == "" {
336 errs = append(errs, fmt.Errorf("missing subscription ID: %+v", sub))
339 if sub.OwnerID == "" {
340 sub.OwnerID = c.fitbitUserID
342 ret = append(ret, sub)
345 if len(ret) == 0 && len(errs) != 0 {
349 for _, err := range errs {
350 log.Warningf(ctx, "%v", err)
356 // DeleteToken deletes the Fitbit OAuth2 token.
357 func (c *Client) DeleteToken(ctx context.Context) error {
358 return c.appUser.DeleteToken(ctx, "Fitbit")
361 // Provile contains data about the user.
362 // It only contains the subset of fields required by Kraftakt.
363 type Profile struct {
365 Timezone *time.Location
368 // Profile returns the profile information of the user.
369 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
370 res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
374 defer res.Body.Close()
376 if res.StatusCode >= 400 {
377 data, _ := ioutil.ReadAll(res.Body)
378 return nil, fmt.Errorf("reading profile failed: %s", data)
384 OffsetFromUTCMillis int
388 if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
392 loc, err := time.LoadLocation(data.User.Timezone)
394 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
398 Name: data.User.FullName,