Implement a /login handler.
[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         if err := c.Unsubscribe(ctx); err != nil {
176                 errs = append(errs, fmt.Errorf("Unsubscribe() = %v", err))
177         }
178
179         if err := c.DeleteToken(ctx); err != nil {
180                 errs = append(errs, fmt.Errorf("DeleteToken() = %v", err))
181         }
182         if len(errs) != 0 {
183                 return errs
184         }
185
186         redirectURL := r.URL
187         redirectURL.Path = "/"
188         redirectURL.RawQuery = ""
189         redirectURL.Fragment = ""
190         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
191         return nil
192 }
193
194 func googleConnectHandler(_ context.Context, w http.ResponseWriter, r *http.Request, _ *app.User) error {
195         http.Redirect(w, r, gfit.AuthURL(), http.StatusTemporaryRedirect)
196         return nil
197 }
198
199 func googleGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
200         if err := gfit.ParseToken(ctx, r, u); err != nil {
201                 return err
202         }
203
204         redirectURL := r.URL
205         redirectURL.Path = "/"
206         redirectURL.RawQuery = ""
207         redirectURL.Fragment = ""
208         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
209         return nil
210 }
211
212 func googleDisconnectHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
213         c, err := gfit.NewClient(ctx, u)
214         if err != nil {
215                 return err
216         }
217
218         if err := c.DeleteToken(ctx); err != nil {
219                 return err
220         }
221
222         redirectURL := r.URL
223         redirectURL.Path = "/"
224         redirectURL.RawQuery = ""
225         redirectURL.Fragment = ""
226         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
227         return nil
228 }
229
230 // fitbitNotifyHandler is called by Fitbit whenever there are updates to a
231 // subscription. It verifies the payload, splits it into individual
232 // notifications and adds it to the taskqueue service.
233 func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
234         defer r.Body.Close()
235
236         fitbitTimeout := 3 * time.Second
237         ctx, cancel := context.WithTimeout(ctx, fitbitTimeout)
238         defer cancel()
239
240         // this is used when setting up a new subscriber in the UI. Once set
241         // up, this code path should not be triggered.
242         if verify := r.FormValue("verify"); verify != "" {
243                 if verify == app.Config.FitbitSubscriberCode {
244                         w.WriteHeader(http.StatusNoContent)
245                 } else {
246                         w.WriteHeader(http.StatusNotFound)
247                 }
248                 return nil
249         }
250
251         data, err := ioutil.ReadAll(r.Body)
252         if err != nil {
253                 return err
254         }
255
256         // Fitbit recommendation: "If signature verification fails, you should
257         // respond with a 404"
258         if !fitbit.CheckSignature(ctx, data, r.Header.Get("X-Fitbit-Signature")) {
259                 log.Warningf(ctx, "signature mismatch")
260                 w.WriteHeader(http.StatusNotFound)
261                 return nil
262         }
263
264         if err := delayedHandleNotifications.Call(ctx, data); err != nil {
265                 return err
266         }
267
268         w.WriteHeader(http.StatusCreated)
269         return nil
270 }
271
272 // handleNotifications parses fitbit notifications and requests the individual
273 // activities from Fitbit. It is executed asynchronously via the delay package.
274 func handleNotifications(ctx context.Context, payload []byte) error {
275         if err := app.LoadConfig(ctx); err != nil {
276                 return err
277         }
278
279         var subscriptions []fitbit.Subscription
280         if err := json.Unmarshal(payload, &subscriptions); err != nil {
281                 return err
282         }
283
284         for _, s := range subscriptions {
285                 if s.CollectionType != "activities" {
286                         log.Warningf(ctx, "ignoring collection type %q", s.CollectionType)
287                         continue
288                 }
289
290                 if err := handleNotification(ctx, &s); err != nil {
291                         log.Errorf(ctx, "handleNotification() = %v", err)
292                         continue
293                 }
294         }
295
296         return nil
297 }
298
299 func handleNotification(ctx context.Context, s *fitbit.Subscription) error {
300         u, err := app.UserByID(ctx, s.SubscriptionID)
301         if err != nil {
302                 return err
303         }
304
305         fitbitClient, err := fitbit.NewClient(ctx, s.OwnerID, u)
306         if err != nil {
307                 return err
308         }
309
310         var (
311                 wg      = &sync.WaitGroup{}
312                 errs    appengine.MultiError
313                 summary *fitbit.ActivitySummary
314                 profile *fitbit.Profile
315         )
316
317         wg.Add(1)
318         go func() {
319                 var err error
320                 summary, err = fitbitClient.ActivitySummary(ctx, s.Date)
321                 if err != nil {
322                         errs = append(errs, fmt.Errorf("fitbitClient.ActivitySummary(%q) = %v", s.Date, err))
323                 }
324                 wg.Done()
325         }()
326
327         wg.Add(1)
328         go func() {
329                 var err error
330                 profile, err = fitbitClient.Profile(ctx)
331                 if err != nil {
332                         errs = append(errs, fmt.Errorf("fitbitClient.Profile(%q) = %v", s.Date, err))
333                 }
334                 wg.Done()
335         }()
336
337         wg.Wait()
338         if len(errs) != 0 {
339                 return errs
340         }
341
342         tm, err := time.ParseInLocation("2006-01-02", s.Date, profile.Timezone)
343         if err != nil {
344                 return err
345         }
346
347         log.Debugf(ctx, "%s (%s) took %d steps on %s",
348                 profile.Name, u.Email, summary.Summary.Steps, tm)
349
350         gfitClient, err := gfit.NewClient(ctx, u)
351         if err != nil {
352                 return err
353         }
354
355         wg.Add(1)
356         go func() {
357                 if err := gfitClient.SetSteps(ctx, summary.Summary.Steps, tm); err != nil {
358                         errs = append(errs, fmt.Errorf("gfitClient.SetSteps(%d) = %v", summary.Summary.Steps, err))
359                 }
360                 wg.Done()
361         }()
362
363         wg.Add(1)
364         go func() {
365                 if err := gfitClient.SetCalories(ctx, summary.Summary.CaloriesOut, tm); err != nil {
366                         errs = append(errs, fmt.Errorf("gfitClient.SetCalories(%d) = %v", summary.Summary.CaloriesOut, err))
367                 }
368                 wg.Done()
369         }()
370
371         wg.Add(1)
372         go func() {
373                 defer wg.Done()
374
375                 var distanceMeters float64
376                 for _, d := range summary.Summary.Distances {
377                         if d.Activity != "total" {
378                                 continue
379                         }
380                         distanceMeters = 1000.0 * d.Distance
381                         break
382                 }
383                 if err := gfitClient.SetDistance(ctx, distanceMeters, tm); err != nil {
384                         errs = append(errs, fmt.Errorf("gfitClient.SetDistance(%g) = %v", distanceMeters, err))
385                         return
386                 }
387         }()
388
389         wg.Add(1)
390         go func() {
391                 if err := gfitClient.SetHeartRate(ctx, summary.Summary.HeartRateZones, summary.Summary.RestingHeartRate, tm); err != nil {
392                         errs = append(errs, fmt.Errorf("gfitClient.SetHeartRate() = %v", err))
393                 }
394                 wg.Done()
395         }()
396
397         wg.Add(1)
398         go func() {
399                 defer wg.Done()
400
401                 var activities []gfit.Activity
402                 for _, a := range summary.Activities {
403                         if !a.HasStartTime {
404                                 continue
405                         }
406
407                         startTime, err := time.ParseInLocation("2006-01-02T15:04", a.StartDate+"T"+a.StartTime, profile.Timezone)
408                         if err != nil {
409                                 errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))
410                                 return
411                         }
412                         endTime := startTime.Add(time.Duration(a.Duration) * time.Millisecond)
413
414                         activities = append(activities, gfit.Activity{
415                                 Start: startTime,
416                                 End:   endTime,
417                                 Type:  gfit.ParseFitbitActivity(a.Name),
418                         })
419                 }
420                 if err := gfitClient.SetActivities(ctx, activities, tm); err != nil {
421                         errs = append(errs, fmt.Errorf("gfitClient.SetActivities() = %v", err))
422                         return
423                 }
424         }()
425
426         wg.Wait()
427
428         if len(errs) != 0 {
429                 return errs
430         }
431         return nil
432 }