14 "github.com/octo/kraftakt/app"
16 oauth2fitbit "golang.org/x/oauth2/fitbit"
17 "google.golang.org/appengine/log"
20 var oauth2Config = &oauth2.Config{
21 ClientID: app.Config.FitbitClientID,
22 ClientSecret: app.Config.FitbitClientSecret,
23 Endpoint: oauth2fitbit.Endpoint,
24 RedirectURL: "https://kraftakt.octo.it/fitbit/grant",
33 const csrfToken = "@CSRFTOKEN@"
35 func AuthURL() string {
36 return oauth2Config.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
39 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
40 if state := r.FormValue("state"); state != csrfToken {
41 return fmt.Errorf("invalid state parameter: %q", state)
44 tok, err := oauth2Config.Exchange(ctx, r.FormValue("code"))
49 return u.SetToken(ctx, "Fitbit", tok)
52 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
53 signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
55 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", rawSig, err)
59 mac := hmac.New(sha1.New, []byte(oauth2Config.ClientSecret+"&"))
61 signatureWant := mac.Sum(nil)
63 return hmac.Equal(signatureGot, signatureWant)
66 type Activity struct {
67 ActivityID int `json:"activityId"`
68 ActivityParentID int `json:"activityParentId"`
69 ActivityParentName string `json:"activityParentName"`
70 Calories int `json:"calories"`
71 Description string `json:"description"`
72 Distance float64 `json:"distance"`
73 Duration int `json:"duration"`
74 HasStartTime bool `json:"hasStartTime"`
75 IsFavorite bool `json:"isFavorite"`
76 LastModified time.Time `json:"lastModified"`
77 LogID int `json:"logId"`
78 Name string `json:"name"`
79 StartTime string `json:"startTime"`
80 StartDate string `json:"startDate"`
81 Steps int `json:"steps"`
84 type Distance struct {
85 Activity string `json:"activity"`
86 Distance float64 `json:"distance"`
89 type HeartRateZone struct {
90 Name string `json:"name"`
93 Minutes int `json:"minutes"`
94 CaloriesOut float64 `json:"caloriesOut"`
97 type ActivitySummary struct {
98 Activities []Activity `json:"activities"`
100 CaloriesOut int `json:"caloriesOut"`
101 Distance float64 `json:"distance"`
102 Floors int `json:"floors"`
103 Steps int `json:"steps"`
106 ActiveScore int `json:"activeScore"`
107 ActivityCalories int `json:"activityCalories"`
108 CaloriesBMR int `json:"caloriesBMR"`
109 CaloriesOut float64 `json:"caloriesOut"`
110 Distances []Distance `json:"distances"`
111 Elevation float64 `json:"elevation"`
112 Floors int `json:"floors"`
113 HeartRateZones []HeartRateZone `json:"heartRateZones"`
114 CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"`
115 MarginalCalories int `json:"marginalCalories"`
116 RestingHeartRate int `json:"restingHeartRate"`
117 Steps int `json:"steps"`
118 SedentaryMinutes int `json:"sedentaryMinutes"`
119 LightlyActiveMinutes int `json:"lightlyActiveMinutes"`
120 FairlyActiveMinutes int `json:"fairlyActiveMinutes"`
121 VeryActiveMinutes int `json:"veryActiveMinutes"`
125 type Subscription struct {
126 CollectionType string `json:"collectionType"`
127 Date string `json:"date"`
128 OwnerID string `json:"ownerId"`
129 OwnerType string `json:"ownerType"`
130 SubscriptionID string `json:"subscriptionId"`
139 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
140 if fitbitUserID == "" {
144 c, err := u.OAuthClient(ctx, "Fitbit", oauth2Config)
150 fitbitUserID: fitbitUserID,
156 func (c *Client) ActivitySummary(ctx context.Context, date string) (*ActivitySummary, error) {
157 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
158 c.fitbitUserID, date)
160 res, err := c.client.Get(url)
164 defer res.Body.Close()
166 data, _ := ioutil.ReadAll(res.Body)
167 log.Debugf(ctx, "GET %s -> %s", url, data)
169 var summary ActivitySummary
170 if err := json.Unmarshal(data, &summary); err != nil {
177 func (c *Client) Subscribe(ctx context.Context, collection string) error {
178 subscriberID, err := c.appUser.ID(ctx)
183 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
184 c.fitbitUserID, collection, subscriberID)
185 res, err := c.client.Post(url, "", nil)
189 defer res.Body.Close()
191 if res.StatusCode >= 400 && res.StatusCode != http.StatusConflict {
192 data, _ := ioutil.ReadAll(res.Body)
193 log.Errorf(ctx, "creating subscription failed: status %d %q", res.StatusCode, data)
194 return fmt.Errorf("creating subscription failed")
200 type Profile struct {
202 Timezone *time.Location
205 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
206 res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
210 defer res.Body.Close()
212 if res.StatusCode >= 400 {
213 data, _ := ioutil.ReadAll(res.Body)
214 log.Errorf(ctx, "reading profile failed: %s", data)
215 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
221 OffsetFromUTCMillis int
225 if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
229 loc, err := time.LoadLocation(data.User.Timezone)
231 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
235 Name: data.User.FullName,