Disconnect handler: don't print success message after failure.
[kraftakt.git] / kraftakt.go
1 package kraftakt
2
3 import (
4         "context"
5         "encoding/json"
6         "fmt"
7         "html/template"
8         "io/ioutil"
9         "net/http"
10         "sync"
11         "time"
12
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"
21 )
22
23 var delayedHandleNotifications = delay.Func("handleNotifications", handleNotifications)
24
25 var templates *template.Template
26
27 func init() {
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))
35         // unauthenticated
36         http.Handle("/fitbit/notify", ContextHandler(fitbitNotifyHandler))
37         http.Handle("/", ContextHandler(indexHandler))
38
39         t, err := template.ParseGlob("templates/*.html")
40         if err != nil {
41                 panic(err)
42         }
43         templates = t
44 }
45
46 // ContextHandler implements http.Handler
47 type ContextHandler func(context.Context, http.ResponseWriter, *http.Request) error
48
49 func (hndl ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
50         ctx := appengine.NewContext(r)
51
52         if err := app.LoadConfig(ctx); err != nil {
53                 http.Error(w, err.Error(), http.StatusInternalServerError)
54                 return
55         }
56
57         if err := hndl(ctx, w, r); err != nil {
58                 http.Error(w, err.Error(), http.StatusInternalServerError)
59                 return
60         }
61 }
62
63 type AuthenticatedHandler func(context.Context, http.ResponseWriter, *http.Request, *app.User) error
64
65 func (hndl AuthenticatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
66         ctx := appengine.NewContext(r)
67
68         if err := app.LoadConfig(ctx); err != nil {
69                 http.Error(w, err.Error(), http.StatusInternalServerError)
70                 return
71         }
72
73         gaeUser := user.Current(ctx)
74         if gaeUser == nil {
75                 url, err := user.LoginURL(ctx, r.URL.String())
76                 if err != nil {
77                         http.Error(w, err.Error(), http.StatusInternalServerError)
78                         return
79                 }
80                 http.Redirect(w, r, url, http.StatusTemporaryRedirect)
81                 return
82         }
83
84         u, err := app.NewUser(ctx, gaeUser.Email)
85         if err != nil {
86                 http.Error(w, err.Error(), http.StatusInternalServerError)
87                 return
88         }
89
90         if err := hndl(ctx, w, r, u); err != nil {
91                 http.Error(w, err.Error(), http.StatusInternalServerError)
92                 return
93         }
94 }
95
96 func indexHandler(ctx context.Context, w http.ResponseWriter, _ *http.Request) error {
97         var templateData struct {
98                 HaveFitbit    bool
99                 HaveGoogleFit bool
100                 *app.User
101         }
102         templateName := "main.html"
103
104         if gaeUser := user.Current(ctx); gaeUser != nil {
105                 templateName = "loggedin.html"
106
107                 u, err := app.NewUser(ctx, gaeUser.Email)
108                 if err != nil {
109                         return err
110                 }
111                 templateData.User = u
112
113                 _, err = u.Token(ctx, "Fitbit")
114                 if err != nil && err != datastore.ErrNoSuchEntity {
115                         return err
116                 }
117                 templateData.HaveFitbit = (err == nil)
118
119                 _, err = u.Token(ctx, "Google")
120                 if err != nil && err != datastore.ErrNoSuchEntity {
121                         return err
122                 }
123                 templateData.HaveGoogleFit = (err == nil)
124         }
125
126         return templates.ExecuteTemplate(w, templateName, &templateData)
127 }
128
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.
131         redirectURL := r.URL
132         redirectURL.Path = "/"
133         redirectURL.RawQuery = ""
134         redirectURL.Fragment = ""
135         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
136         return nil
137 }
138
139 func fitbitConnectHandler(_ context.Context, w http.ResponseWriter, r *http.Request, _ *app.User) error {
140         http.Redirect(w, r, fitbit.AuthURL(), http.StatusTemporaryRedirect)
141         return nil
142 }
143
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 {
146                 return err
147         }
148         c, err := fitbit.NewClient(ctx, "", u)
149         if err != nil {
150                 return err
151         }
152
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)
156                 }
157                 log.Infof(ctx, "Successfully subscribed to %q", collection)
158         }
159
160         redirectURL := r.URL
161         redirectURL.Path = "/"
162         redirectURL.RawQuery = ""
163         redirectURL.Fragment = ""
164         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
165         return nil
166 }
167
168 func fitbitDisconnectHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
169         c, err := fitbit.NewClient(ctx, "", u)
170         if err != nil {
171                 return err
172         }
173
174         var errs appengine.MultiError
175
176         for _, collection := range []string{"activities", "sleep"} {
177                 if err := c.Unsubscribe(ctx, collection); err != nil {
178                         errs = append(errs, fmt.Errorf("Unsubscribe(%q) = %v", collection, err))
179                         continue
180                 }
181                 log.Infof(ctx, "Successfully unsubscribed from %q", collection)
182         }
183
184         if err := c.DeleteToken(ctx); err != nil {
185                 errs = append(errs, fmt.Errorf("DeleteToken() = %v", err))
186         }
187         if len(errs) != 0 {
188                 return errs
189         }
190
191         redirectURL := r.URL
192         redirectURL.Path = "/"
193         redirectURL.RawQuery = ""
194         redirectURL.Fragment = ""
195         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
196         return nil
197 }
198
199 func googleConnectHandler(_ context.Context, w http.ResponseWriter, r *http.Request, _ *app.User) error {
200         http.Redirect(w, r, gfit.AuthURL(), http.StatusTemporaryRedirect)
201         return nil
202 }
203
204 func googleGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
205         if err := gfit.ParseToken(ctx, r, u); err != nil {
206                 return err
207         }
208
209         redirectURL := r.URL
210         redirectURL.Path = "/"
211         redirectURL.RawQuery = ""
212         redirectURL.Fragment = ""
213         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
214         return nil
215 }
216
217 func googleDisconnectHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
218         c, err := gfit.NewClient(ctx, u)
219         if err != nil {
220                 return err
221         }
222
223         if err := c.DeleteToken(ctx); err != nil {
224                 return err
225         }
226
227         redirectURL := r.URL
228         redirectURL.Path = "/"
229         redirectURL.RawQuery = ""
230         redirectURL.Fragment = ""
231         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
232         return nil
233 }
234
235 // fitbitNotifyHandler is called by Fitbit whenever there are updates to a
236 // subscription. It verifies the payload, splits it into individual
237 // notifications and adds it to the taskqueue service.
238 func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
239         defer r.Body.Close()
240
241         fitbitTimeout := 3 * time.Second
242         ctx, cancel := context.WithTimeout(ctx, fitbitTimeout)
243         defer cancel()
244
245         // this is used when setting up a new subscriber in the UI. Once set
246         // up, this code path should not be triggered.
247         if verify := r.FormValue("verify"); verify != "" {
248                 if verify == app.Config.FitbitSubscriberCode {
249                         w.WriteHeader(http.StatusNoContent)
250                 } else {
251                         w.WriteHeader(http.StatusNotFound)
252                 }
253                 return nil
254         }
255
256         data, err := ioutil.ReadAll(r.Body)
257         if err != nil {
258                 return err
259         }
260
261         // Fitbit recommendation: "If signature verification fails, you should
262         // respond with a 404"
263         if !fitbit.CheckSignature(ctx, data, r.Header.Get("X-Fitbit-Signature")) {
264                 log.Warningf(ctx, "signature mismatch")
265                 w.WriteHeader(http.StatusNotFound)
266                 return nil
267         }
268
269         if err := delayedHandleNotifications.Call(ctx, data); err != nil {
270                 return err
271         }
272
273         w.WriteHeader(http.StatusCreated)
274         return nil
275 }
276
277 // handleNotifications parses fitbit notifications and requests the individual
278 // activities from Fitbit. It is executed asynchronously via the delay package.
279 func handleNotifications(ctx context.Context, payload []byte) error {
280         if err := app.LoadConfig(ctx); err != nil {
281                 return err
282         }
283
284         var subscriptions []fitbit.Subscription
285         if err := json.Unmarshal(payload, &subscriptions); err != nil {
286                 return err
287         }
288
289         for _, s := range subscriptions {
290                 if s.CollectionType != "activities" {
291                         log.Warningf(ctx, "ignoring collection type %q", s.CollectionType)
292                         continue
293                 }
294
295                 if err := handleNotification(ctx, &s); err != nil {
296                         log.Errorf(ctx, "handleNotification() = %v", err)
297                         continue
298                 }
299         }
300
301         return nil
302 }
303
304 func handleNotification(ctx context.Context, s *fitbit.Subscription) error {
305         u, err := app.UserByID(ctx, s.SubscriptionID)
306         if err != nil {
307                 return err
308         }
309
310         fitbitClient, err := fitbit.NewClient(ctx, s.OwnerID, u)
311         if err != nil {
312                 return err
313         }
314
315         var (
316                 wg      = &sync.WaitGroup{}
317                 errs    appengine.MultiError
318                 summary *fitbit.ActivitySummary
319                 profile *fitbit.Profile
320         )
321
322         wg.Add(1)
323         go func() {
324                 var err error
325                 summary, err = fitbitClient.ActivitySummary(ctx, s.Date)
326                 if err != nil {
327                         errs = append(errs, fmt.Errorf("fitbitClient.ActivitySummary(%q) = %v", s.Date, err))
328                 }
329                 wg.Done()
330         }()
331
332         wg.Add(1)
333         go func() {
334                 var err error
335                 profile, err = fitbitClient.Profile(ctx)
336                 if err != nil {
337                         errs = append(errs, fmt.Errorf("fitbitClient.Profile(%q) = %v", s.Date, err))
338                 }
339                 wg.Done()
340         }()
341
342         wg.Wait()
343         if len(errs) != 0 {
344                 return errs
345         }
346
347         tm, err := time.ParseInLocation("2006-01-02", s.Date, profile.Timezone)
348         if err != nil {
349                 return err
350         }
351
352         log.Debugf(ctx, "%s (%s) took %d steps on %s",
353                 profile.Name, u.Email, summary.Summary.Steps, tm)
354
355         gfitClient, err := gfit.NewClient(ctx, u)
356         if err != nil {
357                 return err
358         }
359
360         wg.Add(1)
361         go func() {
362                 if err := gfitClient.SetSteps(ctx, summary.Summary.Steps, tm); err != nil {
363                         errs = append(errs, fmt.Errorf("gfitClient.SetSteps(%d) = %v", summary.Summary.Steps, err))
364                 }
365                 wg.Done()
366         }()
367
368         wg.Add(1)
369         go func() {
370                 if err := gfitClient.SetCalories(ctx, summary.Summary.CaloriesOut, tm); err != nil {
371                         errs = append(errs, fmt.Errorf("gfitClient.SetCalories(%d) = %v", summary.Summary.CaloriesOut, err))
372                 }
373                 wg.Done()
374         }()
375
376         wg.Add(1)
377         go func() {
378                 defer wg.Done()
379
380                 var distanceMeters float64
381                 for _, d := range summary.Summary.Distances {
382                         if d.Activity != "total" {
383                                 continue
384                         }
385                         distanceMeters = 1000.0 * d.Distance
386                         break
387                 }
388                 if err := gfitClient.SetDistance(ctx, distanceMeters, tm); err != nil {
389                         errs = append(errs, fmt.Errorf("gfitClient.SetDistance(%g) = %v", distanceMeters, err))
390                         return
391                 }
392         }()
393
394         wg.Add(1)
395         go func() {
396                 if err := gfitClient.SetHeartRate(ctx, summary.Summary.HeartRateZones, summary.Summary.RestingHeartRate, tm); err != nil {
397                         errs = append(errs, fmt.Errorf("gfitClient.SetHeartRate() = %v", err))
398                 }
399                 wg.Done()
400         }()
401
402         wg.Add(1)
403         go func() {
404                 defer wg.Done()
405
406                 var activities []gfit.Activity
407                 for _, a := range summary.Activities {
408                         if !a.HasStartTime {
409                                 continue
410                         }
411
412                         startTime, err := time.ParseInLocation("2006-01-02T15:04", a.StartDate+"T"+a.StartTime, profile.Timezone)
413                         if err != nil {
414                                 errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))
415                                 return
416                         }
417                         endTime := startTime.Add(time.Duration(a.Duration) * time.Millisecond)
418
419                         activities = append(activities, gfit.Activity{
420                                 Start: startTime,
421                                 End:   endTime,
422                                 Type:  gfit.ParseFitbitActivity(a.Name),
423                         })
424                 }
425                 if err := gfitClient.SetActivities(ctx, activities, tm); err != nil {
426                         errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))
427                         return
428                 }
429         }()
430
431         wg.Wait()
432
433         if len(errs) != 0 {
434                 return errs
435         }
436         return nil
437 }