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