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