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))
33 // ContextHandler implements http.Handler
34 type ContextHandler func(context.Context, http.ResponseWriter, *http.Request) error
36 func (hndl ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
37 ctx := appengine.NewContext(r)
39 if err := app.LoadConfig(ctx); err != nil {
40 http.Error(w, err.Error(), http.StatusInternalServerError)
44 if err := hndl(ctx, w, r); err != nil {
45 http.Error(w, err.Error(), http.StatusInternalServerError)
50 type AuthenticatedHandler func(context.Context, http.ResponseWriter, *http.Request, *app.User) error
52 func (hndl AuthenticatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
53 ctx := appengine.NewContext(r)
55 if err := app.LoadConfig(ctx); err != nil {
56 http.Error(w, err.Error(), http.StatusInternalServerError)
60 gaeUser := user.Current(ctx)
62 url, err := user.LoginURL(ctx, r.URL.String())
64 http.Error(w, err.Error(), http.StatusInternalServerError)
67 http.Redirect(w, r, url, http.StatusTemporaryRedirect)
71 u, err := app.NewUser(ctx, gaeUser.Email)
73 http.Error(w, err.Error(), http.StatusInternalServerError)
77 if err := hndl(ctx, w, r, u); err != nil {
78 http.Error(w, err.Error(), http.StatusInternalServerError)
83 func indexHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
84 _, err := u.Token(ctx, "Fitbit")
85 if err != nil && err != datastore.ErrNoSuchEntity {
88 haveFitbitToken := err == nil
90 _, err = u.Token(ctx, "Google")
91 if err != nil && err != datastore.ErrNoSuchEntity {
94 haveGoogleToken := err == nil
96 fmt.Fprintln(w, "<html><head><title>Kraftakt</title></head>")
97 fmt.Fprintln(w, "<body><h1>Kraftakt</h1>")
99 fmt.Fprintln(w, "<p><strong>Kraftakt</strong> copies your <em>Fitbit</em> data to <em>Google Fit</em>, seconds after you sync.</p>")
101 fmt.Fprintf(w, "<p>Hello %s</p>\n", user.Current(ctx).Email)
102 fmt.Fprintln(w, "<ul>")
104 fmt.Fprint(w, "<li>Fitbit: ")
106 fmt.Fprint(w, `<strong style="color: DarkGreen;">Authorized</strong>`)
108 fmt.Fprint(w, `<strong style="color: DarkRed;">Not authorized</strong> (<a href="/fitbit/setup">Authorize</a>)`)
110 fmt.Fprintln(w, "</li>")
112 fmt.Fprint(w, "<li>Google Fit: ")
114 fmt.Fprint(w, `<strong style="color: DarkGreen;">Authorized</strong>`)
116 fmt.Fprint(w, `<strong style="color: DarkRed;">Not authorized</strong> (<a href="/google/setup">Authorize</a>)`)
118 fmt.Fprintln(w, "</li>")
120 fmt.Fprintln(w, "</ul>")
121 fmt.Fprintln(w, "</body></html>")
126 func fitbitSetupHandler(w http.ResponseWriter, r *http.Request) {
127 http.Redirect(w, r, fitbit.AuthURL(), http.StatusTemporaryRedirect)
130 func fitbitGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
131 if err := fitbit.ParseToken(ctx, r, u); err != nil {
134 c, err := fitbit.NewClient(ctx, "-", u)
139 for _, collection := range []string{"activities", "sleep"} {
140 if err := c.Subscribe(ctx, collection); err != nil {
141 return fmt.Errorf("c.Subscribe(%q) = %v", collection, err)
143 log.Infof(ctx, "Successfully subscribed to %q", collection)
147 redirectURL.Path = "/"
148 redirectURL.RawQuery = ""
149 redirectURL.Fragment = ""
150 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
154 func googleSetupHandler(w http.ResponseWriter, r *http.Request) {
155 http.Redirect(w, r, gfit.AuthURL(), http.StatusTemporaryRedirect)
158 func googleGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
159 if err := gfit.ParseToken(ctx, r, u); err != nil {
164 redirectURL.Path = "/"
165 redirectURL.RawQuery = ""
166 redirectURL.Fragment = ""
167 http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
171 // fitbitNotifyHandler is called by Fitbit whenever there are updates to a
172 // subscription. It verifies the payload, splits it into individual
173 // notifications and adds it to the taskqueue service.
174 func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
177 fitbitTimeout := 3 * time.Second
178 ctx, cancel := context.WithTimeout(ctx, fitbitTimeout)
181 // this is used when setting up a new subscriber in the UI. Once set
182 // up, this code path should not be triggered.
183 if verify := r.FormValue("verify"); verify != "" {
184 if verify == app.Config.FitbitSubscriberCode {
185 w.WriteHeader(http.StatusNoContent)
187 w.WriteHeader(http.StatusNotFound)
192 data, err := ioutil.ReadAll(r.Body)
197 // Fitbit recommendation: "If signature verification fails, you should
198 // respond with a 404"
199 if !fitbit.CheckSignature(ctx, data, r.Header.Get("X-Fitbit-Signature")) {
200 log.Warningf(ctx, "signature mismatch")
201 w.WriteHeader(http.StatusNotFound)
205 if err := delayedHandleNotifications.Call(ctx, data); err != nil {
209 w.WriteHeader(http.StatusCreated)
213 // handleNotifications parses fitbit notifications and requests the individual
214 // activities from Fitbit. It is executed asynchronously via the delay package.
215 func handleNotifications(ctx context.Context, payload []byte) error {
216 if err := app.LoadConfig(ctx); err != nil {
220 var subscriptions []fitbit.Subscription
221 if err := json.Unmarshal(payload, &subscriptions); err != nil {
225 for _, s := range subscriptions {
226 if s.CollectionType != "activities" {
227 log.Warningf(ctx, "ignoring collection type %q", s.CollectionType)
231 if err := handleNotification(ctx, &s); err != nil {
232 log.Errorf(ctx, "handleNotification() = %v", err)
240 func handleNotification(ctx context.Context, s *fitbit.Subscription) error {
241 u, err := app.UserByID(ctx, s.SubscriptionID)
246 fitbitClient, err := fitbit.NewClient(ctx, s.OwnerID, u)
252 wg = &sync.WaitGroup{}
253 errs appengine.MultiError
254 summary *fitbit.ActivitySummary
255 profile *fitbit.Profile
261 summary, err = fitbitClient.ActivitySummary(ctx, s.Date)
263 errs = append(errs, fmt.Errorf("fitbitClient.ActivitySummary(%q) = %v", s.Date, err))
271 profile, err = fitbitClient.Profile(ctx)
273 errs = append(errs, fmt.Errorf("fitbitClient.Profile(%q) = %v", s.Date, err))
283 tm, err := time.ParseInLocation("2006-01-02", s.Date, profile.Timezone)
288 log.Debugf(ctx, "%s (%s) took %d steps on %s",
289 profile.Name, u.Email, summary.Summary.Steps, tm)
291 gfitClient, err := gfit.NewClient(ctx, u)
298 if err := gfitClient.SetSteps(ctx, summary.Summary.Steps, tm); err != nil {
299 errs = append(errs, fmt.Errorf("gfitClient.SetSteps(%d) = %v", summary.Summary.Steps, err))
306 if err := gfitClient.SetCalories(ctx, summary.Summary.CaloriesOut, tm); err != nil {
307 errs = append(errs, fmt.Errorf("gfitClient.SetCalories(%d) = %v", summary.Summary.CaloriesOut, err))
316 var distanceMeters float64
317 for _, d := range summary.Summary.Distances {
318 if d.Activity != "total" {
321 distanceMeters = 1000.0 * d.Distance
324 if err := gfitClient.SetDistance(ctx, distanceMeters, tm); err != nil {
325 errs = append(errs, fmt.Errorf("gfitClient.SetDistance(%g) = %v", distanceMeters, err))
332 if err := gfitClient.SetHeartRate(ctx, summary.Summary.HeartRateZones, summary.Summary.RestingHeartRate, tm); err != nil {
333 errs = append(errs, fmt.Errorf("gfitClient.SetHeartRate() = %v", err))
342 var activities []gfit.Activity
343 for _, a := range summary.Activities {
348 startTime, err := time.ParseInLocation("2006-01-02T15:04", a.StartDate+"T"+a.StartTime, profile.Timezone)
350 errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))
353 endTime := startTime.Add(time.Duration(a.Duration) * time.Millisecond)
355 activities = append(activities, gfit.Activity{
358 Type: gfit.ParseFitbitActivity(a.Name),
361 if err := gfitClient.SetActivities(ctx, activities, tm); err != nil {
362 errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))