15 legacy_context "golang.org/x/net/context"
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"
25 const csrfToken = "@CSRFTOKEN@"
27 // var delayedHandleNotifications = delay.Func("handleNotifications", func(ctx legacy_context.Context, payload []byte) error {
28 // return handleNotifications(ctx, payload)
30 var delayedHandleNotifications = delay.Func("handleNotifications", handleNotifications)
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"},
40 type storedToken struct {
46 http.HandleFunc("/setup", setupHandler)
47 http.Handle("/fitbit/grant", AuthenticatedHandler(fitbitGrantHandler))
48 http.Handle("/fitbit/notify", ContextHandler(fitbitNotifyHandler))
49 http.Handle("/", AuthenticatedHandler(indexHandler))
52 // ContextHandler implements http.Handler
53 type ContextHandler func(context.Context, http.ResponseWriter, *http.Request) error
55 func (hndl ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
56 ctx := appengine.NewContext(r)
58 if err := hndl(ctx, w, r); err != nil {
59 http.Error(w, err.Error(), http.StatusInternalServerError)
64 type AuthenticatedHandler func(context.Context, http.ResponseWriter, *http.Request, *user.User) error
66 func (hndl AuthenticatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
67 ctx := appengine.NewContext(r)
69 u := user.Current(ctx)
71 url, err := user.LoginURL(ctx, r.URL.String())
73 http.Error(w, err.Error(), http.StatusInternalServerError)
76 http.Redirect(w, r, url, http.StatusTemporaryRedirect)
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
85 _, err := datastore.Put(ctx, key, &struct{}{})
89 http.Error(w, err.Error(), http.StatusInternalServerError)
93 if err := hndl(ctx, w, r, u); err != nil {
94 http.Error(w, err.Error(), http.StatusInternalServerError)
99 func RootKey(ctx context.Context, u *user.User) *datastore.Key {
100 return datastore.NewKey(ctx, "User", u.Email, 0, nil)
103 func indexHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *user.User) error {
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 {
118 fmt.Fprintf(w, "u = %v, tok = %v, haveToken = %v\n", u, tok, haveToken)
120 // TODO(octo): print summary to user
124 func setupHandler(w http.ResponseWriter, r *http.Request) {
125 url := oauthConfig.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
126 http.Redirect(w, r, url, http.StatusTemporaryRedirect)
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)
134 tok, err := oauthConfig.Exchange(ctx, r.FormValue("code"))
139 key := datastore.NewKey(ctx, "Token", "Fitbit", 0, RootKey(ctx, u))
140 if _, err := datastore.Put(ctx, key, tok); err != nil {
144 c := oauthConfig.Client(ctx, tok)
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)
153 defer res.Body.Close()
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")
162 redirectURL.Path = "/"
163 redirectURL.RawQuery = ""
164 redirectURL.Fragment = ""
165 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
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"`
177 func (n *fitbitNotification) URLValues() 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},
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)
192 func checkSignature(ctx context.Context, payload []byte, rawSig string) bool {
193 base64Sig, err := url.QueryUnescape(rawSig)
195 log.Errorf(ctx, "QueryUnescape(%q) = %v", rawSig, err)
198 signatureGot, err := base64.StdEncoding.DecodeString(base64Sig)
200 log.Errorf(ctx, "base64.StdEncoding.DecodeString(%q) = %v", base64Sig, err)
204 mac := hmac.New(sha1.New, []byte(oauthConfig.ClientSecret+"&"))
206 signatureWant := mac.Sum(nil)
208 return hmac.Equal(signatureGot, signatureWant)
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 {
217 fitbitTimeout := 3 * time.Second
218 ctx, cancel := context.WithTimeout(ctx, fitbitTimeout)
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)
227 w.WriteHeader(http.StatusNotFound)
232 data, err := ioutil.ReadAll(r.Body)
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)
244 if err := delayedHandleNotifications.Call(ctx, data); err != nil {
248 w.WriteHeader(http.StatusCreated)
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 {
260 for _, n := range notifications {
261 if n.CollectionType != "activities" {
265 if err := handleNotification(ctx, &n); err != nil {
266 log.Errorf(ctx, "handleNotification() = %v", err)
274 func handleNotification(ctx context.Context, n *fitbitNotification) error {
275 rootKey, err := datastore.DecodeKey(n.SubscriptionID)
279 key := datastore.NewKey(ctx, "Token", "Fitbit", 0, rootKey)
282 if err := datastore.Get(ctx, key, &tok); err != nil {
286 c := oauthConfig.Client(ctx, &tok)
287 res, err := c.Get(n.URL())
292 log.Infof(ctx, "GET %s = %v", n.URL(), res)