12 "github.com/octo/kraftakt/app"
13 "github.com/octo/kraftakt/fitbit"
14 "github.com/octo/kraftakt/gfit"
15 "google.golang.org/appengine"
16 "google.golang.org/appengine/datastore"
17 "google.golang.org/appengine/delay"
18 "google.golang.org/appengine/log"
19 "google.golang.org/appengine/user"
22 var delayedHandleNotifications = delay.Func("handleNotifications", handleNotifications)
25 http.HandleFunc("/fitbit/setup", fitbitSetupHandler)
26 http.Handle("/fitbit/grant", AuthenticatedHandler(fitbitGrantHandler))
27 http.Handle("/fitbit/notify", ContextHandler(fitbitNotifyHandler))
28 http.HandleFunc("/google/setup", googleSetupHandler)
29 http.Handle("/google/grant", AuthenticatedHandler(googleGrantHandler))
30 http.Handle("/", AuthenticatedHandler(indexHandler))
32 if err := app.LoadConfig(context.Background()); err != nil {
37 // ContextHandler implements http.Handler
38 type ContextHandler func(context.Context, http.ResponseWriter, *http.Request) error
40 func (hndl ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
41 ctx := appengine.NewContext(r)
43 if err := hndl(ctx, w, r); err != nil {
44 http.Error(w, err.Error(), http.StatusInternalServerError)
49 type AuthenticatedHandler func(context.Context, http.ResponseWriter, *http.Request, *app.User) error
51 func (hndl AuthenticatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
52 ctx := appengine.NewContext(r)
54 gaeUser := user.Current(ctx)
56 url, err := user.LoginURL(ctx, r.URL.String())
58 http.Error(w, err.Error(), http.StatusInternalServerError)
61 http.Redirect(w, r, url, http.StatusTemporaryRedirect)
65 u, err := app.NewUser(ctx, gaeUser.Email)
67 http.Error(w, err.Error(), http.StatusInternalServerError)
71 if err := hndl(ctx, w, r, u); err != nil {
72 http.Error(w, err.Error(), http.StatusInternalServerError)
77 func indexHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
78 _, err := u.Token(ctx, "Fitbit")
79 if err != nil && err != datastore.ErrNoSuchEntity {
82 haveFitbitToken := err == nil
84 _, err = u.Token(ctx, "Google")
85 if err != nil && err != datastore.ErrNoSuchEntity {
88 haveGoogleToken := err == nil
90 fmt.Fprintln(w, "<html><head><title>Kraftakt</title></head>")
91 fmt.Fprintln(w, "<body><h1>Kraftakt</h1>")
93 fmt.Fprintln(w, "<p><strong>Kraftakt</strong> copies your <em>Fitbit</em> data to <em>Google Fit</em>, seconds after you sync.</p>")
95 fmt.Fprintf(w, "<p>Hello %s</p>\n", user.Current(ctx).Email)
96 fmt.Fprintln(w, "<ul>")
98 fmt.Fprint(w, "<li>Fitbit: ")
100 fmt.Fprint(w, `<strong style="color: DarkGreen;">Authorized</strong>`)
102 fmt.Fprint(w, `<strong style="color: DarkRed;">Not authorized</strong> (<a href="/fitbit/setup">Authorize</a>)`)
104 fmt.Fprintln(w, "</li>")
106 fmt.Fprint(w, "<li>Google Fit: ")
108 fmt.Fprint(w, `<strong style="color: DarkGreen;">Authorized</strong>`)
110 fmt.Fprint(w, `<strong style="color: DarkRed;">Not authorized</strong> (<a href="/google/setup">Authorize</a>)`)
112 fmt.Fprintln(w, "</li>")
114 fmt.Fprintln(w, "</ul>")
115 fmt.Fprintln(w, "</body></html>")
120 func fitbitSetupHandler(w http.ResponseWriter, r *http.Request) {
121 http.Redirect(w, r, fitbit.AuthURL(), http.StatusTemporaryRedirect)
124 func fitbitGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
125 if err := fitbit.ParseToken(ctx, r, u); err != nil {
128 c, err := fitbit.NewClient(ctx, "-", u)
133 for _, collection := range []string{"activities", "sleep"} {
134 if err := c.Subscribe(ctx, collection); err != nil {
135 return fmt.Errorf("c.Subscribe(%q) = %v", collection, err)
137 log.Infof(ctx, "Successfully subscribed to %q", collection)
141 redirectURL.Path = "/"
142 redirectURL.RawQuery = ""
143 redirectURL.Fragment = ""
144 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
148 func googleSetupHandler(w http.ResponseWriter, r *http.Request) {
149 http.Redirect(w, r, gfit.AuthURL(), http.StatusTemporaryRedirect)
152 func googleGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
153 if err := gfit.ParseToken(ctx, r, u); err != nil {
158 redirectURL.Path = "/"
159 redirectURL.RawQuery = ""
160 redirectURL.Fragment = ""
161 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
165 // fitbitNotifyHandler is called by Fitbit whenever there are updates to a
166 // subscription. It verifies the payload, splits it into individual
167 // notifications and adds it to the taskqueue service.
168 func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
171 fitbitTimeout := 3 * time.Second
172 ctx, cancel := context.WithTimeout(ctx, fitbitTimeout)
175 // this is used when setting up a new subscriber in the UI. Once set
176 // up, this code path should not be triggered.
177 if verify := r.FormValue("verify"); verify != "" {
178 if verify == app.Config.FitbitSubscriberCode {
179 w.WriteHeader(http.StatusNoContent)
181 w.WriteHeader(http.StatusNotFound)
186 data, err := ioutil.ReadAll(r.Body)
191 // Fitbit recommendation: "If signature verification fails, you should
192 // respond with a 404"
193 if !fitbit.CheckSignature(ctx, data, r.Header.Get("X-Fitbit-Signature")) {
194 w.WriteHeader(http.StatusNotFound)
198 if err := delayedHandleNotifications.Call(ctx, data); err != nil {
202 w.WriteHeader(http.StatusCreated)
206 // handleNotifications parses fitbit notifications and requests the individual
207 // activities from Fitbit. It is executed asynchronously via the delay package.
208 func handleNotifications(ctx context.Context, payload []byte) error {
209 var subscriptions []fitbit.Subscription
210 if err := json.Unmarshal(payload, &subscriptions); err != nil {
214 for _, s := range subscriptions {
215 if s.CollectionType != "activities" {
216 log.Warningf(ctx, "ignoring collection type %q", s.CollectionType)
220 if err := handleNotification(ctx, &s); err != nil {
221 log.Errorf(ctx, "handleNotification() = %v", err)
229 func handleNotification(ctx context.Context, s *fitbit.Subscription) error {
230 u, err := app.UserByID(ctx, s.SubscriptionID)
235 fitbitClient, err := fitbit.NewClient(ctx, s.OwnerID, u)
241 wg = &sync.WaitGroup{}
242 errs appengine.MultiError
243 summary *fitbit.ActivitySummary
244 profile *fitbit.Profile
250 summary, err = fitbitClient.ActivitySummary(ctx, s.Date)
252 errs = append(errs, fmt.Errorf("fitbitClient.ActivitySummary(%q) = %v", s.Date, err))
260 profile, err = fitbitClient.Profile(ctx)
262 errs = append(errs, fmt.Errorf("fitbitClient.Profile(%q) = %v", s.Date, err))
272 tm, err := time.ParseInLocation("2006-01-02", s.Date, profile.Timezone)
277 log.Debugf(ctx, "%s (%s) took %d steps on %s",
278 profile.Name, u.Email, summary.Summary.Steps, tm)
280 gfitClient, err := gfit.NewClient(ctx, u)
287 if err := gfitClient.SetSteps(ctx, summary.Summary.Steps, tm); err != nil {
288 errs = append(errs, fmt.Errorf("gfitClient.SetSteps(%d) = %v", summary.Summary.Steps, err))
295 if err := gfitClient.SetCalories(ctx, summary.Summary.CaloriesOut, tm); err != nil {
296 errs = append(errs, fmt.Errorf("gfitClient.SetCalories(%d) = %v", summary.Summary.CaloriesOut, err))
305 var distanceMeters float64
306 for _, d := range summary.Summary.Distances {
307 if d.Activity != "total" {
310 distanceMeters = 1000.0 * d.Distance
313 if err := gfitClient.SetDistance(ctx, distanceMeters, tm); err != nil {
314 errs = append(errs, fmt.Errorf("gfitClient.SetDistance(%d) = %v", distanceMeters, err))
321 if err := gfitClient.SetHeartRate(ctx, summary.Summary.HeartRateZones, summary.Summary.RestingHeartRate, tm); err != nil {
322 errs = append(errs, fmt.Errorf("gfitClient.SetHeartRate() = %v", err))
331 var activities []gfit.Activity
332 for _, a := range summary.Activities {
337 startTime, err := time.ParseInLocation("2006-01-02T15:04", a.StartDate+"T"+a.StartTime, profile.Timezone)
339 errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))
342 endTime := startTime.Add(time.Duration(a.Duration) * time.Millisecond)
344 activities = append(activities, gfit.Activity{
347 Type: gfit.ParseFitbitActivity(a.Name),
350 if err := gfitClient.SetActivities(ctx, activities, tm); err != nil {
351 errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))