04c50cd8f5d476b67f6a8994b96a3c17c47776be
[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/gfitsync/app"
15         "golang.org/x/oauth2"
16         oauth2fitbit "golang.org/x/oauth2/fitbit"
17         "google.golang.org/appengine/log"
18 )
19
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"},
26 }
27
28 const csrfToken = "@CSRFTOKEN@"
29
30 func AuthURL() string {
31         return oauth2Config.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
32 }
33
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)
37         }
38
39         tok, err := oauth2Config.Exchange(ctx, r.FormValue("code"))
40         if err != nil {
41                 return err
42         }
43
44         return u.SetToken(ctx, "Fitbit", tok)
45 }
46
47 func CheckSignature(ctx context.Context, payload []byte, rawSig string) bool {
48         signatureGot, err := base64.StdEncoding.DecodeString(rawSig)
49         if err != nil {
50                 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", rawSig, err)
51                 return false
52         }
53
54         mac := hmac.New(sha1.New, []byte(oauth2Config.ClientSecret+"&"))
55         mac.Write(payload)
56         signatureWant := mac.Sum(nil)
57
58         return hmac.Equal(signatureGot, signatureWant)
59 }
60
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"`
77 }
78
79 type Distance struct {
80         Activity string  `json:"activity"`
81         Distance float64 `json:"distance"`
82 }
83
84 type HeartRateZone struct {
85         Name        string  `json:"name"`
86         Min         int     `json:"min"`
87         Max         int     `json:"max"`
88         Minutes     int     `json:"minutes"`
89         CaloriesOut float64 `json:"caloriesOut"`
90 }
91
92 type ActivitySummary struct {
93         Activities []Activity `json:"activities"`
94         Goals      struct {
95                 CaloriesOut int     `json:"caloriesOut"`
96                 Distance    float64 `json:"distance"`
97                 Floors      int     `json:"floors"`
98                 Steps       int     `json:"steps"`
99         } `json:"goals"`
100         Summary struct {
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"`
117         } `json:"summary"`
118 }
119
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"`
126 }
127
128 type Client struct {
129         fitbitUserID string
130         appUser      *app.User
131         client       *http.Client
132 }
133
134 func NewClient(ctx context.Context, fitbitUserID string, u *app.User) (*Client, error) {
135         if fitbitUserID == "" {
136                 fitbitUserID = "-"
137         }
138
139         c, err := u.OAuthClient(ctx, "Fitbit", oauth2Config)
140         if err != nil {
141                 return nil, err
142         }
143
144         return &Client{
145                 fitbitUserID: fitbitUserID,
146                 appUser:      u,
147                 client:       c,
148         }, nil
149 }
150
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)
154
155         res, err := c.client.Get(url)
156         if err != nil {
157                 return nil, err
158         }
159         defer res.Body.Close()
160
161         data, _ := ioutil.ReadAll(res.Body)
162         log.Debugf(ctx, "GET %s -> %s", url, data)
163
164         var summary ActivitySummary
165         if err := json.Unmarshal(data, &summary); err != nil {
166                 return nil, err
167         }
168
169         return &summary, nil
170 }
171
172 func (c *Client) Subscribe(ctx context.Context, collection string) error {
173         subscriberID, err := c.appUser.ID(ctx)
174         if err != nil {
175                 return err
176         }
177
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)
181         if err != nil {
182                 return err
183         }
184         defer res.Body.Close()
185
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")
190         }
191
192         return nil
193 }
194
195 type Profile struct {
196         Name     string
197         Timezone *time.Location
198 }
199
200 func (c *Client) Profile(ctx context.Context) (*Profile, error) {
201         res, err := c.client.Get("https://api.fitbit.com/1/user/-/profile.json")
202         if err != nil {
203                 return nil, err
204         }
205         defer res.Body.Close()
206
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)
211         }
212
213         var data struct {
214                 User struct {
215                         FullName            string
216                         OffsetFromUTCMillis int
217                         Timezone            string
218                 }
219         }
220         if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
221                 return nil, err
222         }
223
224         loc, err := time.LoadLocation(data.User.Timezone)
225         if err != nil {
226                 loc = time.FixedZone("Fitbit preference", data.User.OffsetFromUTCMillis/1000)
227         }
228
229         return &Profile{
230                 Name:     data.User.FullName,
231                 Timezone: loc,
232         }, nil
233 }