X-Git-Url: https://git.octo.it/?a=blobdiff_plain;f=kraftakt.go;h=8d562996688c99d5fecb12bb23dcbbd6ae8dbd76;hb=5b245cc42860c980c321c1c1829cdc373d53ac53;hp=e0ad321e325d18b34d453c31893f74c3b8009b63;hpb=304308a757d192b9b80455017bda1cb82889d346;p=kraftakt.git
diff --git a/kraftakt.go b/kraftakt.go
index e0ad321..8d56299 100644
--- a/kraftakt.go
+++ b/kraftakt.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "html/template"
"io/ioutil"
"net/http"
"sync"
@@ -21,13 +22,25 @@ import (
var delayedHandleNotifications = delay.Func("handleNotifications", handleNotifications)
+var templates *template.Template
+
func init() {
- http.HandleFunc("/fitbit/setup", fitbitSetupHandler)
+ http.Handle("/login", AuthenticatedHandler(loginHandler))
+ http.Handle("/fitbit/connect", AuthenticatedHandler(fitbitConnectHandler))
http.Handle("/fitbit/grant", AuthenticatedHandler(fitbitGrantHandler))
- http.Handle("/fitbit/notify", ContextHandler(fitbitNotifyHandler))
- http.HandleFunc("/google/setup", googleSetupHandler)
+ http.Handle("/fitbit/disconnect", AuthenticatedHandler(fitbitDisconnectHandler))
+ http.Handle("/google/connect", AuthenticatedHandler(googleConnectHandler))
http.Handle("/google/grant", AuthenticatedHandler(googleGrantHandler))
- http.Handle("/", AuthenticatedHandler(indexHandler))
+ http.Handle("/google/disconnect", AuthenticatedHandler(googleDisconnectHandler))
+ // unauthenticated
+ http.Handle("/fitbit/notify", ContextHandler(fitbitNotifyHandler))
+ http.Handle("/", ContextHandler(indexHandler))
+
+ t, err := template.ParseGlob("templates/*.html")
+ if err != nil {
+ panic(err)
+ }
+ templates = t
}
// ContextHandler implements http.Handler
@@ -36,6 +49,11 @@ type ContextHandler func(context.Context, http.ResponseWriter, *http.Request) er
func (hndl ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
+ if err := app.LoadConfig(ctx); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
if err := hndl(ctx, w, r); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@@ -47,6 +65,11 @@ type AuthenticatedHandler func(context.Context, http.ResponseWriter, *http.Reque
func (hndl AuthenticatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
+ if err := app.LoadConfig(ctx); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
gaeUser := user.Current(ctx)
if gaeUser == nil {
url, err := user.LoginURL(ctx, r.URL.String())
@@ -70,58 +93,59 @@ func (hndl AuthenticatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Reques
}
}
-func indexHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
- _, err := u.Token(ctx, "Fitbit")
- if err != nil && err != datastore.ErrNoSuchEntity {
- return err
+func indexHandler(ctx context.Context, w http.ResponseWriter, _ *http.Request) error {
+ var templateData struct {
+ HaveFitbit bool
+ HaveGoogleFit bool
+ *app.User
}
- haveFitbitToken := err == nil
-
- _, err = u.Token(ctx, "Google")
- if err != nil && err != datastore.ErrNoSuchEntity {
- return err
- }
- haveGoogleToken := err == nil
-
- fmt.Fprintln(w, "
Kraftakt")
- fmt.Fprintln(w, "Kraftakt
")
+ templateName := "main.html"
- fmt.Fprintln(w, "Kraftakt copies your Fitbit data to Google Fit, seconds after you sync.
")
+ if gaeUser := user.Current(ctx); gaeUser != nil {
+ templateName = "loggedin.html"
- fmt.Fprintf(w, "Hello %s
\n", user.Current(ctx).Email)
- fmt.Fprintln(w, "")
+ u, err := app.NewUser(ctx, gaeUser.Email)
+ if err != nil {
+ return err
+ }
+ templateData.User = u
- fmt.Fprint(w, "- Fitbit: ")
- if haveFitbitToken {
- fmt.Fprint(w, `Authorized`)
- } else {
- fmt.Fprint(w, `Not authorized (Authorize)`)
- }
- fmt.Fprintln(w, "
")
+ _, err = u.Token(ctx, "Fitbit")
+ if err != nil && err != datastore.ErrNoSuchEntity {
+ return err
+ }
+ templateData.HaveFitbit = (err == nil)
- fmt.Fprint(w, "- Google Fit: ")
- if haveGoogleToken {
- fmt.Fprint(w, `Authorized`)
- } else {
- fmt.Fprint(w, `Not authorized (Authorize)`)
+ _, err = u.Token(ctx, "Google")
+ if err != nil && err != datastore.ErrNoSuchEntity {
+ return err
+ }
+ templateData.HaveGoogleFit = (err == nil)
}
- fmt.Fprintln(w, "
")
- fmt.Fprintln(w, "
")
- fmt.Fprintln(w, "")
+ return templates.ExecuteTemplate(w, templateName, &templateData)
+}
+func loginHandler(_ context.Context, w http.ResponseWriter, r *http.Request, _ *app.User) error {
+ // essentially a nop; all the heavy lifting (i.e. logging in) has been done by the AuthenticatedHandler wrapper.
+ redirectURL := r.URL
+ redirectURL.Path = "/"
+ redirectURL.RawQuery = ""
+ redirectURL.Fragment = ""
+ http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
return nil
}
-func fitbitSetupHandler(w http.ResponseWriter, r *http.Request) {
- http.Redirect(w, r, fitbit.AuthURL(), http.StatusTemporaryRedirect)
+func fitbitConnectHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
+ http.Redirect(w, r, fitbit.AuthURL(ctx, u), http.StatusTemporaryRedirect)
+ return nil
}
func fitbitGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
if err := fitbit.ParseToken(ctx, r, u); err != nil {
return err
}
- c, err := fitbit.NewClient(ctx, "-", u)
+ c, err := fitbit.NewClient(ctx, "", u)
if err != nil {
return err
}
@@ -141,8 +165,40 @@ func fitbitGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Requ
return nil
}
-func googleSetupHandler(w http.ResponseWriter, r *http.Request) {
- http.Redirect(w, r, gfit.AuthURL(), http.StatusTemporaryRedirect)
+func fitbitDisconnectHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
+ c, err := fitbit.NewClient(ctx, "", u)
+ if err != nil {
+ return err
+ }
+
+ var errs appengine.MultiError
+
+ for _, collection := range []string{"activities", "sleep"} {
+ if err := c.Unsubscribe(ctx, collection); err != nil {
+ errs = append(errs, fmt.Errorf("Unsubscribe(%q) = %v", collection, err))
+ continue
+ }
+ log.Infof(ctx, "Successfully unsubscribed from %q", collection)
+ }
+
+ if err := c.DeleteToken(ctx); err != nil {
+ errs = append(errs, fmt.Errorf("DeleteToken() = %v", err))
+ }
+ if len(errs) != 0 {
+ return errs
+ }
+
+ redirectURL := r.URL
+ redirectURL.Path = "/"
+ redirectURL.RawQuery = ""
+ redirectURL.Fragment = ""
+ http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
+ return nil
+}
+
+func googleConnectHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
+ http.Redirect(w, r, gfit.AuthURL(ctx, u), http.StatusTemporaryRedirect)
+ return nil
}
func googleGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
@@ -158,6 +214,24 @@ func googleGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Requ
return nil
}
+func googleDisconnectHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
+ c, err := gfit.NewClient(ctx, u)
+ if err != nil {
+ return err
+ }
+
+ if err := c.DeleteToken(ctx); err != nil {
+ return err
+ }
+
+ redirectURL := r.URL
+ redirectURL.Path = "/"
+ redirectURL.RawQuery = ""
+ redirectURL.Fragment = ""
+ http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
+ return nil
+}
+
// fitbitNotifyHandler is called by Fitbit whenever there are updates to a
// subscription. It verifies the payload, splits it into individual
// notifications and adds it to the taskqueue service.
@@ -171,7 +245,7 @@ func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Req
// this is used when setting up a new subscriber in the UI. Once set
// up, this code path should not be triggered.
if verify := r.FormValue("verify"); verify != "" {
- if verify == "@FITBIT_SUBSCRIBER_CODE@" {
+ if verify == app.Config.FitbitSubscriberCode {
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusNotFound)
@@ -187,6 +261,7 @@ func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Req
// Fitbit recommendation: "If signature verification fails, you should
// respond with a 404"
if !fitbit.CheckSignature(ctx, data, r.Header.Get("X-Fitbit-Signature")) {
+ log.Warningf(ctx, "signature mismatch")
w.WriteHeader(http.StatusNotFound)
return nil
}
@@ -202,6 +277,12 @@ func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Req
// handleNotifications parses fitbit notifications and requests the individual
// activities from Fitbit. It is executed asynchronously via the delay package.
func handleNotifications(ctx context.Context, payload []byte) error {
+ log.Debugf(ctx, "NOTIFY -> %s", payload)
+
+ if err := app.LoadConfig(ctx); err != nil {
+ return err
+ }
+
var subscriptions []fitbit.Subscription
if err := json.Unmarshal(payload, &subscriptions); err != nil {
return err
@@ -223,7 +304,7 @@ func handleNotifications(ctx context.Context, payload []byte) error {
}
func handleNotification(ctx context.Context, s *fitbit.Subscription) error {
- u, err := app.UserByID(ctx, s.SubscriptionID)
+ u, err := fitbit.UserFromSubscriberID(ctx, s.SubscriptionID)
if err != nil {
return err
}
@@ -307,7 +388,7 @@ func handleNotification(ctx context.Context, s *fitbit.Subscription) error {
break
}
if err := gfitClient.SetDistance(ctx, distanceMeters, tm); err != nil {
- errs = append(errs, fmt.Errorf("gfitClient.SetDistance(%d) = %v", distanceMeters, err))
+ errs = append(errs, fmt.Errorf("gfitClient.SetDistance(%g) = %v", distanceMeters, err))
return
}
}()