Packages fitbit and gfit: Initialize oauth2.Config at runtime.
[kraftakt.git] / fitbit / fitbit.go
1 package fitbit
2
3 import (
4         "context"
5         "crypto/hmac"
6         "crypto/sha1"
7         "encoding/base64"
8         "encoding/json"
9         "fmt"
10         "io/ioutil"
11         "net/http"
12         "time"
13
14         "github.com/octo/kraftakt/app"
15         "golang.org/x/oauth2"
16         oauth2fitbit "golang.org/x/oauth2/fitbit"
17         "google.golang.org/appengine/log"
18 )
19
20
21 func oauthConfig() *oauth2.Config {
22         return &oauth2.Config{
23                 ClientID:     app.Config.FitbitClientID,
24                 ClientSecret: app.Config.FitbitClientSecret,
25                 Endpoint:     oauth2fitbit.Endpoint,
26                 RedirectURL:  "https://kraftakt.octo.it/fitbit/grant",
27                 Scopes: []string{
28                         "activity",
29                         "heartrate",
30                         "profile",
31                         "sleep",
32                 },
33         }
34 }
35
36 const csrfToken = "@CSRFTOKEN@"
37
38 func AuthURL() string {
39         return oauthConfig().AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
40 }
41
42 func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
43         if state := r.FormValue("state"); state != csrfToken {
44                 return fmt.Errorf("invalid state parameter: %q", state)
45         }
46
47         tok, err := oauthConfig().Exchange(ctx, r.FormValue("code"))
48         if err != nil {
49                 return err
50         }
51
52         return u.SetToken(ctx, "Fitbit", tok)
53 }
54
55 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
56         signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
57         if err != nil {
58                 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", rawSig, err)
59                 return false
60         }
61
62         mac := hmac.New(sha1.New, []byte(oauthConfig().ClientSecret+"&"))
63         mac.Write(payload)
64         signatureWant := mac.Sum(nil)
65
66         return hmac.Equal(signatureGot, signatureWant)
67 }
68
69 type Activity struct {
70         ActivityID         int       `json:"activityId"`
71         ActivityParentID   int       `json:"activityParentId"`
72         ActivityParentName string    `json:"activityParentName"`
73         Calories           int       `json:"calories"`
74         Description        string    `json:"description"`
75         Distance           float64   `json:"distance"`
76         Duration           int       `json:"duration"`
77         HasStartTime       bool      `json:"hasStartTime"`
78         IsFavorite         bool      `json:"isFavorite"`
79         LastModified       time.Time `json:"lastModified"`
80         LogID              int       `json:"logId"`
81         Name               string    `json:"name"`
82         StartTime          string    `json:"startTime"`
83         StartDate          string    `json:"startDate"`
84         Steps              int       `json:"steps"`
85 }
86
87 type Distance struct {
88         Activity string  `json:"activity"`
89         Distance float64 `json:"distance"`
90 }
91
92 type HeartRateZone struct {
93         Name        string  `json:"name"`
94         Min         int     `json:"min"`
95         Max         int     `json:"max"`
96         Minutes     int     `json:"minutes"`
97         CaloriesOut float64 `json:"caloriesOut"`
98 }
99
100 type ActivitySummary struct {
101         Activities []Activity `json:"activities"`
102         Goals      struct {
103                 CaloriesOut int     `json:"caloriesOut"`
104                 Distance    float64 `json:"distance"`
105                 Floors      int     `json:"floors"`
106                 Steps       int     `json:"steps"`
107         } `json:"goals"`
108         Summary struct {
109                 ActiveScore          int             `json:"activeScore"`
110                 ActivityCalories     int             `json:"activityCalories"`
111                 CaloriesBMR          int             `json:"caloriesBMR"`
112                 CaloriesOut          float64         `json:"caloriesOut"`
113                 Distances            []Distance      `json:"distances"`
114                 Elevation            float64         `json:"elevation"`
115                 Floors               int             `json:"floors"`
116                 HeartRateZones       []HeartRateZone `json:"heartRateZones"`
117                 CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"`
118                 MarginalCalories     int             `json:"marginalCalories"`
119                 RestingHeartRate     int             `json:"restingHeartRate"`
120                 Steps                int             `json:"steps"`
121                 SedentaryMinutes     int             `json:"sedentaryMinutes"`
122                 LightlyActiveMinutes int             `json:"lightlyActiveMinutes"`
123                 FairlyActiveMinutes  int             `json:"fairlyActiveMinutes"`
124                 VeryActiveMinutes    int             `json:"veryActiveMinutes"`
125         } `json:"summary"`
126 }
127
128 type Subscription struct {
129         CollectionType string `json:"collectionType"`
130         Date           string `json:"date"`
131         OwnerID        string `json:"ownerId"`
132         OwnerType      string `json:"ownerType"`
133         SubscriptionID string `json:"subscriptionId"`
134 }
135
136 type Client struct {
137         fitbitUserID string
138         appUser      *app.User
139         client       *http.Client
140 }
141
142 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
143         if fitbitUserID == "" {
144                 fitbitUserID = "-"
145         }
146
147         c, err := u.OAuthClient(ctx, "Fitbit", oauthConfig())
148         if err != nil {
149                 return nil, err
150         }
151
152         return &Client{
153                 fitbitUserID: fitbitUserID,
154                 appUser:      u,
155                 client:       c,
156         }, nil
157 }
158
159 func (c *Client) ActivitySummary(ctx context.Context, date string) (*ActivitySummary, error) {
160         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
161                 c.fitbitUserID, date)
162
163         res, err := c.client.Get(url)
164         if err != nil {
165                 return nil, err
166         }
167         defer res.Body.Close()
168
169         data, _ := ioutil.ReadAll(res.Body)
170         log.Debugf(ctx, "GET %s -> %s", url, data)
171
172         var summary ActivitySummary
173         if err := json.Unmarshal(data, &summary); err != nil {
174                 return nil, err
175         }
176
177         return &summary, nil
178 }
179
180 func (c *Client) Subscribe(ctx context.Context, collection string) error {
181         subscriberID, err := c.appUser.ID(ctx)
182         if err != nil {
183                 return err
184         }
185
186         url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
187                 c.fitbitUserID, collection, subscriberID)
188         res, err := c.client.Post(url, "", nil)
189         if err != nil {
190                 return err
191         }
192         defer res.Body.Close()
193
194         if res.StatusCode >= 400 && res.StatusCode != http.StatusConflict {
195                 data, _ := ioutil.ReadAll(res.Body)
196                 log.Errorf(ctx, "creating subscription failed: status %d %q", res.StatusCode, data)
197                 return fmt.Errorf("creating subscription failed")
198         }
199
200         return nil
201 }
202
203 type Profile struct {
204         Name     string
205         Timezone *time.Location
206 }
207
208 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
209         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
210         if err != nil {
211                 return nil, err
212         }
213         defer res.Body.Close()
214
215         if res.StatusCode >= 400 {
216                 data, _ := ioutil.ReadAll(res.Body)
217                 log.Errorf(ctx, "reading profile failed: %s", data)
218                 return nil, fmt.Errorf("HTTP %d error", res.StatusCode)
219         }
220
221         var data struct {
222                 User struct {
223                         FullName            string
224                         OffsetFromUTCMillis int
225                         Timezone            string
226                 }
227         }
228         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
229                 return nil, err
230         }
231
232         loc, err := time.LoadLocation(data.User.Timezone)
233         if err != nil {
234                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
235         }
236
237         return &Profile{
238                 Name:     data.User.FullName,
239                 Timezone: loc,
240         }, nil
241 }