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