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
175 if err := c.Unsubscribe(ctx); err != nil {
176 errs = append(errs, fmt.Errorf("Unsubscribe() = %v", err))
179 if err := c.DeleteToken(ctx); err != nil {
180 errs = append(errs, fmt.Errorf("DeleteToken() = %v", err))
187 redirectURL.Path = "/"
188 redirectURL.RawQuery = ""
189 redirectURL.Fragment = ""
190 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
194 func googleConnectHandler(_ context.Context, w http.ResponseWriter, r *http.Request, _ *app.User) error {
195 http.Redirect(w, r, gfit.AuthURL(), http.StatusTemporaryRedirect)
199 func googleGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
200 if err := gfit.ParseToken(ctx, r, u); err != nil {
205 redirectURL.Path = "/"
206 redirectURL.RawQuery = ""
207 redirectURL.Fragment = ""
208 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
212 func googleDisconnectHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
213 c, err := gfit.NewClient(ctx, u)
218 if err := c.DeleteToken(ctx); err != nil {
223 redirectURL.Path = "/"
224 redirectURL.RawQuery = ""
225 redirectURL.Fragment = ""
226 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
230 // fitbitNotifyHandler is called by Fitbit whenever there are updates to a
231 // subscription. It verifies the payload, splits it into individual
232 // notifications and adds it to the taskqueue service.
233 func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
236 fitbitTimeout := 3 * time.Second
237 ctx, cancel := context.WithTimeout(ctx, fitbitTimeout)
240 // this is used when setting up a new subscriber in the UI. Once set
241 // up, this code path should not be triggered.
242 if verify := r.FormValue("verify"); verify != "" {
243 if verify == app.Config.FitbitSubscriberCode {
244 w.WriteHeader(http.StatusNoContent)
246 w.WriteHeader(http.StatusNotFound)
251 data, err := ioutil.ReadAll(r.Body)
256 // Fitbit recommendation: "If signature verification fails, you should
257 // respond with a 404"
258 if !fitbit.CheckSignature(ctx, data, r.Header.Get("X-Fitbit-Signature")) {
259 log.Warningf(ctx, "signature mismatch")
260 w.WriteHeader(http.StatusNotFound)
264 if err := delayedHandleNotifications.Call(ctx, data); err != nil {
268 w.WriteHeader(http.StatusCreated)
272 // handleNotifications parses fitbit notifications and requests the individual
273 // activities from Fitbit. It is executed asynchronously via the delay package.
274 func handleNotifications(ctx context.Context, payload []byte) error {
275 if err := app.LoadConfig(ctx); err != nil {
279 var subscriptions []fitbit.Subscription
280 if err := json.Unmarshal(payload, &subscriptions); err != nil {
284 for _, s := range subscriptions {
285 if s.CollectionType != "activities" {
286 log.Warningf(ctx, "ignoring collection type %q", s.CollectionType)
290 if err := handleNotification(ctx, &s); err != nil {
291 log.Errorf(ctx, "handleNotification() = %v", err)
299 func handleNotification(ctx context.Context, s *fitbit.Subscription) error {
300 u, err := app.UserByID(ctx, s.SubscriptionID)
305 fitbitClient, err := fitbit.NewClient(ctx, s.OwnerID, u)
311 wg = &sync.WaitGroup{}
312 errs appengine.MultiError
313 summary *fitbit.ActivitySummary
314 profile *fitbit.Profile
320 summary, err = fitbitClient.ActivitySummary(ctx, s.Date)
322 errs = append(errs, fmt.Errorf("fitbitClient.ActivitySummary(%q) = %v", s.Date, err))
330 profile, err = fitbitClient.Profile(ctx)
332 errs = append(errs, fmt.Errorf("fitbitClient.Profile(%q) = %v", s.Date, err))
342 tm, err := time.ParseInLocation("2006-01-02", s.Date, profile.Timezone)
347 log.Debugf(ctx, "%s (%s) took %d steps on %s",
348 profile.Name, u.Email, summary.Summary.Steps, tm)
350 gfitClient, err := gfit.NewClient(ctx, u)
357 if err := gfitClient.SetSteps(ctx, summary.Summary.Steps, tm); err != nil {
358 errs = append(errs, fmt.Errorf("gfitClient.SetSteps(%d) = %v", summary.Summary.Steps, err))
365 if err := gfitClient.SetCalories(ctx, summary.Summary.CaloriesOut, tm); err != nil {
366 errs = append(errs, fmt.Errorf("gfitClient.SetCalories(%d) = %v", summary.Summary.CaloriesOut, err))
375 var distanceMeters float64
376 for _, d := range summary.Summary.Distances {
377 if d.Activity != "total" {
380 distanceMeters = 1000.0 * d.Distance
383 if err := gfitClient.SetDistance(ctx, distanceMeters, tm); err != nil {
384 errs = append(errs, fmt.Errorf("gfitClient.SetDistance(%g) = %v", distanceMeters, err))
391 if err := gfitClient.SetHeartRate(ctx, summary.Summary.HeartRateZones, summary.Summary.RestingHeartRate, tm); err != nil {
392 errs = append(errs, fmt.Errorf("gfitClient.SetHeartRate() = %v", err))
401 var activities []gfit.Activity
402 for _, a := range summary.Activities {
407 startTime, err := time.ParseInLocation("2006-01-02T15:04", a.StartDate+"T"+a.StartTime, profile.Timezone)
409 errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))
412 endTime := startTime.Add(time.Duration(a.Duration) * time.Millisecond)
414 activities = append(activities, gfit.Activity{
417 Type: gfit.ParseFitbitActivity(a.Name),
420 if err := gfitClient.SetActivities(ctx, activities, tm); err != nil {
421 errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))