Check status code when calling the subscription API.
[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         if res.StatusCode >= 400 {
156                 data, _ := ioutil.ReadAll(r.Body)
157                 log.Errorf(ctx, "creating subscription failed: status %d %q", res.StatusCode, data)
158                 return fmt.Errorf("creating subscription failed")
159         }
160
161         redirectURL := r.URL
162         redirectURL.Path = "/"
163         redirectURL.RawQuery = ""
164         redirectURL.Fragment = ""
165         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
166         return nil
167 }
168
169 type fitbitNotification struct {
170         CollectionType string `json:"collectionType"`
171         Date           string `json:"date"`
172         OwnerID        string `json:"ownerId"`
173         OwnerType      string `json:"ownerType"`
174         SubscriptionID string `json:"subscriptionId"`
175 }
176
177 func (n *fitbitNotification) URLValues() url.Values {
178         return url.Values{
179                 "CollectionType": []string{n.CollectionType},
180                 "Date":           []string{n.Date},
181                 "OwnerID":        []string{n.OwnerID},
182                 "OwnerType":      []string{n.OwnerType},
183                 "SubscriptionID": []string{n.SubscriptionID},
184         }
185 }
186
187 func (n *fitbitNotification) URL() string {
188         return fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/date/%s.json",
189                 n.OwnerID, n.CollectionType, n.Date)
190 }
191
192 func checkSignature(ctx context.Context, payload []byte, rawSig string) bool {
193         base64Sig, err := url.QueryUnescape(rawSig)
194         if err != nil {
195                 log.Errorf(ctx, "QueryUnescape(%q) = %v", rawSig, err)
196                 return false
197         }
198         signatureGot, err := base64.StdEncoding.DecodeString(base64Sig)
199         if err != nil {
200                 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", base64Sig, err)
201                 return false
202         }
203
204         mac := hmac.New(sha1.New, []byte(oauthConfig.ClientSecret+"&"))
205         mac.Write(payload)
206         signatureWant := mac.Sum(nil)
207
208         return hmac.Equal(signatureGot, signatureWant)
209 }
210
211 // fitbitNotifyHandler is called by Fitbit whenever there are updates to a
212 // subscription. It verifies the payload, splits it into individual
213 // notifications and adds it to the taskqueue service.
214 func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
215         defer r.Body.Close()
216
217         fitbitTimeout := 3 * time.Second
218         ctx, cancel := context.WithTimeout(ctx, fitbitTimeout)
219         defer cancel()
220
221         // this is used when setting up a new subscriber in the UI. Once set
222         // up, this code path should not be triggered.
223         if verify := r.FormValue("verify"); verify != "" {
224                 if verify == "@FITBIT_SUBSCRIBER_CODE@" {
225                         w.WriteHeader(http.StatusNoContent)
226                 } else {
227                         w.WriteHeader(http.StatusNotFound)
228                 }
229                 return nil
230         }
231
232         data, err := ioutil.ReadAll(r.Body)
233         if err != nil {
234                 return err
235         }
236
237         // Fitbit recommendation: "If signature verification fails, you should
238         // respond with a 404"
239         if !checkSignature(ctx, data, r.Header.Get("X-Fitbit-Signature")) {
240                 w.WriteHeader(http.StatusNotFound)
241                 return nil
242         }
243
244         if err := delayedHandleNotifications.Call(ctx, data); err != nil {
245                 return err
246         }
247
248         w.WriteHeader(http.StatusCreated)
249         return nil
250 }
251
252 // handleNotifications parses fitbit notifications and requests the individual
253 // activities from Fitbit. It is executed asynchronously via the delay package.
254 func handleNotifications(ctx context.Context, payload []byte) error {
255         var notifications []fitbitNotification
256         if err := json.Unmarshal(payload, notifications); err != nil {
257                 return err
258         }
259
260         for _, n := range notifications {
261                 if n.CollectionType != "activities" {
262                         continue
263                 }
264
265                 if err := handleNotification(ctx, &n); err != nil {
266                         log.Errorf(ctx, "handleNotification() = %v", err)
267                         continue
268                 }
269         }
270
271         return nil
272 }
273
274 func handleNotification(ctx context.Context, n *fitbitNotification) error {
275         rootKey, err := datastore.DecodeKey(n.SubscriptionID)
276         if err != nil {
277                 return err
278         }
279         key := datastore.NewKey(ctx, "Token", "Fitbit", 0, rootKey)
280
281         var tok oauth2.Token
282         if err := datastore.Get(ctx, key, &tok); err != nil {
283                 return err
284         }
285
286         c := oauthConfig.Client(ctx, &tok)
287         res, err := c.Get(n.URL())
288         if err != nil {
289                 return err
290         }
291
292         log.Infof(ctx, "GET %s = %v", n.URL(), res)
293         return nil
294 }