14 "github.com/octo/gfitsync/app"
16 oauth2fitbit "golang.org/x/oauth2/fitbit"
17 "google.golang.org/appengine/log"
20 var oauth2Config = &oauth2.Config{
21 ClientID: "@FITBIT_CLIENT_ID@",
22 ClientSecret: "@FITBIT_CLIENT_SECRET@",
23 Endpoint: oauth2fitbit.Endpoint,
24 RedirectURL: "https://kraftakt.octo.it/fitbit/grant",
25 Scopes: []string{"activity", "heartrate", "profile"},
28 const csrfToken = "@CSRFTOKEN@"
30 func AuthURL() string {
31 return oauth2Config.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
34 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
35 if state := r.FormValue("state"); state != csrfToken {
36 return fmt.Errorf("invalid state parameter: %q", state)
39 tok, err := oauth2Config.Exchange(ctx, r.FormValue("code"))
44 return u.SetToken(ctx, "Fitbit", tok)
47 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
48 signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
50 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", rawSig, err)
54 mac := hmac.New(sha1.New, []byte(oauth2Config.ClientSecret+"&"))
56 signatureWant := mac.Sum(nil)
58 return hmac.Equal(signatureGot, signatureWant)
61 type Activity struct {
62 ActivityID int `json:"activityId"`
63 ActivityParentID int `json:"activityParentId"`
64 ActivityParentName string `json:"activityParentName"`
65 Calories int `json:"calories"`
66 Description string `json:"description"`
67 Distance float64 `json:"distance"`
68 Duration int `json:"duration"`
69 HasStartTime bool `json:"hasStartTime"`
70 IsFavorite bool `json:"isFavorite"`
71 LastModified time.Time `json:"lastModified"`
72 LogID int `json:"logId"`
73 Name string `json:"name"`
74 StartTime string `json:"startTime"`
75 StartDate string `json:"startDate"`
76 Steps int `json:"steps"`
79 type Distance struct {
80 Activity string `json:"activity"`
81 Distance float64 `json:"distance"`
84 type HeartRateZone struct {
85 Name string `json:"name"`
88 Minutes int `json:"minutes"`
89 CaloriesOut float64 `json:"caloriesOut"`
92 type ActivitySummary struct {
93 Activities []Activity `json:"activities"`
95 CaloriesOut int `json:"caloriesOut"`
96 Distance float64 `json:"distance"`
97 Floors int `json:"floors"`
98 Steps int `json:"steps"`
101 ActiveScore int `json:"activeScore"`
102 ActivityCalories int `json:"activityCalories"`
103 CaloriesBMR int `json:"caloriesBMR"`
104 CaloriesOut float64 `json:"caloriesOut"`
105 Distances []Distance `json:"distances"`
106 Elevation float64 `json:"elevation"`
107 Floors int `json:"floors"`
108 HeartRateZones []HeartRateZone `json:"heartRateZones"`
109 CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"`
110 MarginalCalories int `json:"marginalCalories"`
111 RestingHeartRate int `json:"restingHeartRate"`
112 Steps int `json:"steps"`
113 SedentaryMinutes int `json:"sedentaryMinutes"`
114 LightlyActiveMinutes int `json:"lightlyActiveMinutes"`
115 FairlyActiveMinutes int `json:"fairlyActiveMinutes"`
116 VeryActiveMinutes int `json:"veryActiveMinutes"`
120 type Subscription struct {
121 CollectionType string `json:"collectionType"`
122 Date string `json:"date"`
123 OwnerID string `json:"ownerId"`
124 OwnerType string `json:"ownerType"`
125 SubscriptionID string `json:"subscriptionId"`
134 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
135 if fitbitUserID == "" {
139 c, err := u.OAuthClient(ctx, "Fitbit", oauth2Config)
145 fitbitUserID: fitbitUserID,
151 func (c *Client) ActivitySummary(ctx context.Context, date string) (*ActivitySummary, error) {
152 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
153 c.fitbitUserID, date)
155 res, err := c.client.Get(url)
159 defer res.Body.Close()
161 data, _ := ioutil.ReadAll(res.Body)
162 log.Debugf(ctx, "GET %s -> %s", url, data)
164 var summary ActivitySummary
165 if err := json.Unmarshal(data, &summary); err != nil {
172 func (c *Client) Subscribe(ctx context.Context, collection string) error {
173 subscriberID, err := c.appUser.ID(ctx)
178 url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
179 c.fitbitUserID, collection, subscriberID)
180 res, err := c.client.Post(url, "", nil)
184 defer res.Body.Close()
186 if res.StatusCode >= 400 {
187 data, _ := ioutil.ReadAll(res.Body)
188 log.Errorf(ctx, "creating subscription failed: status %d %q", res.StatusCode, data)
189 return fmt.Errorf("creating subscription failed")
195 type Profile struct {
197 Timezone *time.Location
200 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
201 res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
205 defer res.Body.Close()
207 if res.StatusCode >= 400 {
208 data, _ := ioutil.ReadAll(res.Body)
209 log.Errorf(ctx, "reading profile failed: %s", data)
210 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
216 OffsetFromUTCMillis int
220 if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
224 loc, err := time.LoadLocation(data.User.Timezone)
226 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
230 Name: data.User.FullName,