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