13 "github.com/octo/kraftakt/app"
14 "github.com/octo/kraftakt/fitbit"
15 "github.com/octo/kraftakt/gfit"
16 "google.golang.org/appengine"
17 "google.golang.org/appengine/datastore"
18 "google.golang.org/appengine/delay"
19 "google.golang.org/appengine/log"
20 "google.golang.org/appengine/user"
23 var delayedHandleNotifications = delay.Func("handleNotifications", handleNotifications)
25 var templates *template.Template
28 http.Handle("/login", AuthenticatedHandler(loginHandler))
29 http.Handle("/fitbit/connect", AuthenticatedHandler(fitbitConnectHandler))
30 http.Handle("/fitbit/grant", AuthenticatedHandler(fitbitGrantHandler))
31 http.Handle("/fitbit/disconnect", AuthenticatedHandler(fitbitDisconnectHandler))
32 http.Handle("/google/connect", AuthenticatedHandler(googleConnectHandler))
33 http.Handle("/google/grant", AuthenticatedHandler(googleGrantHandler))
34 http.Handle("/google/disconnect", AuthenticatedHandler(googleDisconnectHandler))
36 http.Handle("/fitbit/notify", ContextHandler(fitbitNotifyHandler))
37 http.Handle("/", ContextHandler(indexHandler))
39 t, err := template.ParseGlob("templates/*.html")
46 // ContextHandler implements http.Handler
47 type ContextHandler func(context.Context, http.ResponseWriter, *http.Request) error
49 func (hndl ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
50 ctx := appengine.NewContext(r)
52 if err := app.LoadConfig(ctx); err != nil {
53 http.Error(w, err.Error(), http.StatusInternalServerError)
57 if err := hndl(ctx, w, r); err != nil {
58 http.Error(w, err.Error(), http.StatusInternalServerError)
63 type AuthenticatedHandler func(context.Context, http.ResponseWriter, *http.Request, *app.User) error
65 func (hndl AuthenticatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
66 ctx := appengine.NewContext(r)
68 if err := app.LoadConfig(ctx); err != nil {
69 http.Error(w, err.Error(), http.StatusInternalServerError)
73 gaeUser := user.Current(ctx)
75 url, err := user.LoginURL(ctx, r.URL.String())
77 http.Error(w, err.Error(), http.StatusInternalServerError)
80 http.Redirect(w, r, url, http.StatusTemporaryRedirect)
84 u, err := app.NewUser(ctx, gaeUser.Email)
86 http.Error(w, err.Error(), http.StatusInternalServerError)
90 if err := hndl(ctx, w, r, u); err != nil {
91 http.Error(w, err.Error(), http.StatusInternalServerError)
96 func indexHandler(ctx context.Context, w http.ResponseWriter, _ *http.Request) error {
97 var templateData struct {
102 templateName := "main.html"
104 if gaeUser := user.Current(ctx); gaeUser != nil {
105 templateName = "loggedin.html"
107 u, err := app.NewUser(ctx, gaeUser.Email)
111 templateData.User = u
113 _, err = u.Token(ctx, "Fitbit")
114 if err != nil && err != datastore.ErrNoSuchEntity {
117 templateData.HaveFitbit = (err == nil)
119 _, err = u.Token(ctx, "Google")
120 if err != nil && err != datastore.ErrNoSuchEntity {
123 templateData.HaveGoogleFit = (err == nil)
126 return templates.ExecuteTemplate(w, templateName, &templateData)
129 func loginHandler(_ context.Context, w http.ResponseWriter, r *http.Request, _ *app.User) error {
130 // essentially a nop; all the heavy lifting (i.e. logging in) has been done by the AuthenticatedHandler wrapper.
132 redirectURL.Path = "/"
133 redirectURL.RawQuery = ""
134 redirectURL.Fragment = ""
135 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
139 func fitbitConnectHandler(_ context.Context, w http.ResponseWriter, r *http.Request, _ *app.User) error {
140 http.Redirect(w, r, fitbit.AuthURL(), http.StatusTemporaryRedirect)
144 func fitbitGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
145 if err := fitbit.ParseToken(ctx, r, u); err != nil {
148 c, err := fitbit.NewClient(ctx, "", u)
153 for _, collection := range []string{"activities", "sleep"} {
154 if err := c.Subscribe(ctx, collection); err != nil {
155 return fmt.Errorf("c.Subscribe(%q) = %v", collection, err)
157 log.Infof(ctx, "Successfully subscribed to %q", collection)
161 redirectURL.Path = "/"
162 redirectURL.RawQuery = ""
163 redirectURL.Fragment = ""
164 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
168 func fitbitDisconnectHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
169 c, err := fitbit.NewClient(ctx, "", u)
174 var errs appengine.MultiError
176 for _, collection := range []string{"activities", "sleep"} {
177 if err := c.Unsubscribe(ctx, collection); err != nil {
178 errs = append(errs, fmt.Errorf("Unsubscribe(%q) = %v", collection, err))
180 log.Infof(ctx, "Successfully unsubscribed from %q", collection)
183 if err := c.DeleteToken(ctx); err != nil {
184 errs = append(errs, fmt.Errorf("DeleteToken() = %v", err))
191 redirectURL.Path = "/"
192 redirectURL.RawQuery = ""
193 redirectURL.Fragment = ""
194 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
198 func googleConnectHandler(_ context.Context, w http.ResponseWriter, r *http.Request, _ *app.User) error {
199 http.Redirect(w, r, gfit.AuthURL(), http.StatusTemporaryRedirect)
203 func googleGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
204 if err := gfit.ParseToken(ctx, r, u); err != nil {
209 redirectURL.Path = "/"
210 redirectURL.RawQuery = ""
211 redirectURL.Fragment = ""
212 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
216 func googleDisconnectHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
217 c, err := gfit.NewClient(ctx, u)
222 if err := c.DeleteToken(ctx); err != nil {
227 redirectURL.Path = "/"
228 redirectURL.RawQuery = ""
229 redirectURL.Fragment = ""
230 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
234 // fitbitNotifyHandler is called by Fitbit whenever there are updates to a
235 // subscription. It verifies the payload, splits it into individual
236 // notifications and adds it to the taskqueue service.
237 func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
240 fitbitTimeout := 3 * time.Second
241 ctx, cancel := context.WithTimeout(ctx, fitbitTimeout)
244 // this is used when setting up a new subscriber in the UI. Once set
245 // up, this code path should not be triggered.
246 if verify := r.FormValue("verify"); verify != "" {
247 if verify == app.Config.FitbitSubscriberCode {
248 w.WriteHeader(http.StatusNoContent)
250 w.WriteHeader(http.StatusNotFound)
255 data, err := ioutil.ReadAll(r.Body)
260 // Fitbit recommendation: "If signature verification fails, you should
261 // respond with a 404"
262 if !fitbit.CheckSignature(ctx, data, r.Header.Get("X-Fitbit-Signature")) {
263 log.Warningf(ctx, "signature mismatch")
264 w.WriteHeader(http.StatusNotFound)
268 if err := delayedHandleNotifications.Call(ctx, data); err != nil {
272 w.WriteHeader(http.StatusCreated)
276 // handleNotifications parses fitbit notifications and requests the individual
277 // activities from Fitbit. It is executed asynchronously via the delay package.
278 func handleNotifications(ctx context.Context, payload []byte) error {
279 if err := app.LoadConfig(ctx); err != nil {
283 var subscriptions []fitbit.Subscription
284 if err := json.Unmarshal(payload, &subscriptions); err != nil {
288 for _, s := range subscriptions {
289 if s.CollectionType != "activities" {
290 log.Warningf(ctx, "ignoring collection type %q", s.CollectionType)
294 if err := handleNotification(ctx, &s); err != nil {
295 log.Errorf(ctx, "handleNotification() = %v", err)
303 func handleNotification(ctx context.Context, s *fitbit.Subscription) error {
304 u, err := app.UserByID(ctx, s.SubscriptionID)
309 fitbitClient, err := fitbit.NewClient(ctx, s.OwnerID, u)
315 wg = &sync.WaitGroup{}
316 errs appengine.MultiError
317 summary *fitbit.ActivitySummary
318 profile *fitbit.Profile
324 summary, err = fitbitClient.ActivitySummary(ctx, s.Date)
326 errs = append(errs, fmt.Errorf("fitbitClient.ActivitySummary(%q) = %v", s.Date, err))
334 profile, err = fitbitClient.Profile(ctx)
336 errs = append(errs, fmt.Errorf("fitbitClient.Profile(%q) = %v", s.Date, err))
346 tm, err := time.ParseInLocation("2006-01-02", s.Date, profile.Timezone)
351 log.Debugf(ctx, "%s (%s) took %d steps on %s",
352 profile.Name, u.Email, summary.Summary.Steps, tm)
354 gfitClient, err := gfit.NewClient(ctx, u)
361 if err := gfitClient.SetSteps(ctx, summary.Summary.Steps, tm); err != nil {
362 errs = append(errs, fmt.Errorf("gfitClient.SetSteps(%d) = %v", summary.Summary.Steps, err))
369 if err := gfitClient.SetCalories(ctx, summary.Summary.CaloriesOut, tm); err != nil {
370 errs = append(errs, fmt.Errorf("gfitClient.SetCalories(%d) = %v", summary.Summary.CaloriesOut, err))
379 var distanceMeters float64
380 for _, d := range summary.Summary.Distances {
381 if d.Activity != "total" {
384 distanceMeters = 1000.0 * d.Distance
387 if err := gfitClient.SetDistance(ctx, distanceMeters, tm); err != nil {
388 errs = append(errs, fmt.Errorf("gfitClient.SetDistance(%g) = %v", distanceMeters, err))
395 if err := gfitClient.SetHeartRate(ctx, summary.Summary.HeartRateZones, summary.Summary.RestingHeartRate, tm); err != nil {
396 errs = append(errs, fmt.Errorf("gfitClient.SetHeartRate() = %v", err))
405 var activities []gfit.Activity
406 for _, a := range summary.Activities {
411 startTime, err := time.ParseInLocation("2006-01-02T15:04", a.StartDate+"T"+a.StartTime, profile.Timezone)
413 errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))
416 endTime := startTime.Add(time.Duration(a.Duration) * time.Millisecond)
418 activities = append(activities, gfit.Activity{
421 Type: gfit.ParseFitbitActivity(a.Name),
424 if err := gfitClient.SetActivities(ctx, activities, tm); err != nil {
425 errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))