21f764be528e1d7e36c7814de1447bace88650f4
[kraftakt.git] / gfitsync.go
1 package gfitsync
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         "net/url"
13         "time"
14
15         legacy_context "golang.org/x/net/context"
16         "golang.org/x/oauth2"
17         "golang.org/x/oauth2/fitbit"
18         "google.golang.org/appengine"
19         "google.golang.org/appengine/datastore"
20         "google.golang.org/appengine/delay"
21         "google.golang.org/appengine/log"
22         "google.golang.org/appengine/user"
23 )
24
25 const csrfToken = "@CSRFTOKEN@"
26
27 // var delayedHandleNotifications = delay.Func("handleNotifications", func(ctx legacy_context.Context, payload []byte) error {
28 //      return handleNotifications(ctx, payload)
29 // })
30 var delayedHandleNotifications = delay.Func("handleNotifications", handleNotifications)
31
32 var oauthConfig = &oauth2.Config{
33         ClientID:     "@FITBIT_CLIENT_ID@",
34         ClientSecret: "@FITBIT_CLIENT_SECRET@",
35         Endpoint:     fitbit.Endpoint,
36         RedirectURL:  "https://fitbit-gfit-sync.appspot.com/fitbit/grant", // TODO(octo): make full URL
37         Scopes:       []string{"activity"},
38 }
39
40 type storedToken struct {
41         Email string
42         oauth2.Token
43 }
44
45 func init() {
46         http.HandleFunc("/setup", setupHandler)
47         http.Handle("/fitbit/grant", AuthenticatedHandler(fitbitGrantHandler))
48         http.Handle("/fitbit/notify", ContextHandler(fitbitNotifyHandler))
49         http.Handle("/", AuthenticatedHandler(indexHandler))
50 }
51
52 // ContextHandler implements http.Handler
53 type ContextHandler func(context.Context, http.ResponseWriter, *http.Request) error
54
55 func (hndl ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
56         ctx := appengine.NewContext(r)
57
58         if err := hndl(ctx, w, r); err != nil {
59                 http.Error(w, err.Error(), http.StatusInternalServerError)
60                 return
61         }
62 }
63
64 type AuthenticatedHandler func(context.Context, http.ResponseWriter, *http.Request, *user.User) error
65
66 func (hndl AuthenticatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
67         ctx := appengine.NewContext(r)
68
69         u := user.Current(ctx)
70         if u == nil {
71                 url, err := user.LoginURL(ctx, r.URL.String())
72                 if err != nil {
73                         http.Error(w, err.Error(), http.StatusInternalServerError)
74                         return
75                 }
76                 http.Redirect(w, r, url, http.StatusTemporaryRedirect)
77                 return
78         }
79
80         err := datastore.RunInTransaction(ctx, func(ctx legacy_context.Context) error {
81                 key := RootKey(ctx, u)
82                 if err := datastore.Get(ctx, key, &struct{}{}); err != datastore.ErrNoSuchEntity {
83                         return err // may be nil
84                 }
85                 _, err := datastore.Put(ctx, key, &struct{}{})
86                 return err
87         }, nil)
88         if err != nil {
89                 http.Error(w, err.Error(), http.StatusInternalServerError)
90                 return
91         }
92
93         if err := hndl(ctx, w, r, u); err != nil {
94                 http.Error(w, err.Error(), http.StatusInternalServerError)
95                 return
96         }
97 }
98
99 func RootKey(ctx context.Context, u *user.User) *datastore.Key {
100         return datastore.NewKey(ctx, "User", u.Email, 0, nil)
101 }
102
103 func indexHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *user.User) error {
104         var (
105                 tok       oauth2.Token
106                 haveToken bool
107         )
108
109         key := datastore.NewKey(ctx, "Token", "Fitbit", 0, RootKey(ctx, u))
110         err := datastore.Get(ctx, key, &tok)
111         if err != nil && err != datastore.ErrNoSuchEntity {
112                 return err
113         }
114         if err == nil {
115                 haveToken = true
116         }
117
118         fmt.Fprintf(w, "u = %v, tok = %v, haveToken = %v\n", u, tok, haveToken)
119
120         // TODO(octo): print summary to user
121         return nil
122 }
123
124 func setupHandler(w http.ResponseWriter, r *http.Request) {
125         url := oauthConfig.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
126         http.Redirect(w, r, url, http.StatusTemporaryRedirect)
127 }
128
129 func fitbitGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *user.User) error {
130         if state := r.FormValue("state"); state != csrfToken {
131                 return fmt.Errorf("invalid state parameter: %q", state)
132         }
133
134         tok, err := oauthConfig.Exchange(ctx, r.FormValue("code"))
135         if err != nil {
136                 return err
137         }
138
139         key := datastore.NewKey(ctx, "Token", "Fitbit", 0, RootKey(ctx, u))
140         if _, err := datastore.Put(ctx, key, tok); err != nil {
141                 return err
142         }
143
144         c := oauthConfig.Client(ctx, tok)
145
146         // create a subscription
147         url := fmt.Sprintf("https://api.fitbit.com/1/user/-/activities/apiSubscriptions/%s.json",
148                 RootKey(ctx, u).Encode())
149         res, err := c.Post(url, "", nil)
150         if err != nil {
151                 return err
152         }
153         defer res.Body.Close()
154
155         redirectURL := r.URL
156         redirectURL.Path = "/"
157         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
158         return nil
159 }
160
161 type fitbitNotification struct {
162         CollectionType string `json:"collectionType"`
163         Date           string `json:"date"`
164         OwnerID        string `json:"ownerId"`
165         OwnerType      string `json:"ownerType"`
166         SubscriptionID string `json:"subscriptionId"`
167 }
168
169 func (n *fitbitNotification) URLValues() url.Values {
170         return url.Values{
171                 "CollectionType": []string{n.CollectionType},
172                 "Date":           []string{n.Date},
173                 "OwnerID":        []string{n.OwnerID},
174                 "OwnerType":      []string{n.OwnerType},
175                 "SubscriptionID": []string{n.SubscriptionID},
176         }
177 }
178
179 func (n *fitbitNotification) URL() string {
180         return fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/date/%s.json",
181                 n.OwnerID, n.CollectionType, n.Date)
182 }
183
184 func checkSignature(ctx context.Context, payload []byte, rawSig string) bool {
185         base64Sig, err := url.QueryUnescape(rawSig)
186         if err != nil {
187                 log.Errorf(ctx, "QueryUnescape(%q) = %v", rawSig, err)
188                 return false
189         }
190         signatureGot, err := base64.StdEncoding.DecodeString(base64Sig)
191         if err != nil {
192                 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", base64Sig, err)
193                 return false
194         }
195
196         mac := hmac.New(sha1.New, []byte(oauthConfig.ClientSecret+"&"))
197         mac.Write(payload)
198         signatureWant := mac.Sum(nil)
199
200         return hmac.Equal(signatureGot, signatureWant)
201 }
202
203 // fitbitNotifyHandler is called by Fitbit whenever there are updates to a
204 // subscription. It verifies the payload, splits it into individual
205 // notifications and adds it to the taskqueue service.
206 func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
207         defer r.Body.Close()
208
209         fitbitTimeout := 3 * time.Second
210         ctx, cancel := context.WithTimeout(ctx, fitbitTimeout)
211         defer cancel()
212
213         // this is used when setting up a new subscriber in the UI. Once set
214         // up, this code path should not be triggered.
215         if verify := r.FormValue("verify"); verify != "" {
216                 if verify == "@FITBIT_SUBSCRIBER_CODE@" {
217                         w.WriteHeader(http.StatusNoContent)
218                 } else {
219                         w.WriteHeader(http.StatusNotFound)
220                 }
221                 return nil
222         }
223
224         data, err := ioutil.ReadAll(r.Body)
225         if err != nil {
226                 return err
227         }
228
229         // Fitbit recommendation: "If signature verification fails, you should
230         // respond with a 404"
231         if !checkSignature(ctx, data, r.Header.Get("X-Fitbit-Signature")) {
232                 w.WriteHeader(http.StatusNotFound)
233                 return nil
234         }
235
236         if err := delayedHandleNotifications.Call(ctx, data); err != nil {
237                 return err
238         }
239
240         w.WriteHeader(http.StatusCreated)
241         return nil
242 }
243
244 // handleNotifications parses fitbit notifications and requests the individual
245 // activities from Fitbit. It is executed asynchronously via the delay package.
246 func handleNotifications(ctx context.Context, payload []byte) error {
247         var notifications []fitbitNotification
248         if err := json.Unmarshal(payload, notifications); err != nil {
249                 return err
250         }
251
252         for _, n := range notifications {
253                 if n.CollectionType != "activities" {
254                         continue
255                 }
256
257                 if err := handleNotification(ctx, &n); err != nil {
258                         log.Errorf(ctx, "handleNotification() = %v", err)
259                         continue
260                 }
261         }
262
263         return nil
264 }
265
266 func handleNotification(ctx context.Context, n *fitbitNotification) error {
267         rootKey, err := datastore.DecodeKey(n.SubscriptionID)
268         if err != nil {
269                 return err
270         }
271         key := datastore.NewKey(ctx, "Token", "Fitbit", 0, rootKey)
272
273         var tok oauth2.Token
274         if err := datastore.Get(ctx, key, &tok); err != nil {
275                 return err
276         }
277
278         c := oauthConfig.Client(ctx, &tok)
279         res, err := c.Get(n.URL())
280         if err != nil {
281                 return err
282         }
283
284         log.Infof(ctx, "GET %s = %v", n.URL(), res)
285         return nil
286 }