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