Connect handlers: don't call {fitbit,gfit}.NewClient().
[kraftakt.git] / kraftakt.go
index 95d7b46..8d56299 100644 (file)
@@ -136,8 +136,8 @@ func loginHandler(_ context.Context, w http.ResponseWriter, r *http.Request, _ *
        return nil
 }
 
-func fitbitConnectHandler(_ context.Context, w http.ResponseWriter, r *http.Request, _ *app.User) error {
-       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
 }
 
@@ -172,8 +172,13 @@ func fitbitDisconnectHandler(ctx context.Context, w http.ResponseWriter, r *http
        }
 
        var errs appengine.MultiError
-       if err := c.Unsubscribe(ctx); err != nil {
-               errs = append(errs, fmt.Errorf("Unsubscribe() = %v", err))
+
+       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 {
@@ -191,8 +196,8 @@ func fitbitDisconnectHandler(ctx context.Context, w http.ResponseWriter, r *http
        return nil
 }
 
-func googleConnectHandler(_ context.Context, w http.ResponseWriter, r *http.Request, _ *app.User) error {
-       http.Redirect(w, r, gfit.AuthURL(), http.StatusTemporaryRedirect)
+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
 }
 
@@ -272,6 +277,8 @@ 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
        }
@@ -297,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
        }