Package gfit: API fixes.
[kraftakt.git] / gfitsync.go
1 package gfitsync
2
3 import (
4         "context"
5         "encoding/json"
6         "fmt"
7         "io/ioutil"
8         "net/http"
9         "time"
10
11         "github.com/octo/gfitsync/app"
12         "github.com/octo/gfitsync/fitbit"
13         "github.com/octo/gfitsync/gfit"
14         "google.golang.org/appengine"
15         "google.golang.org/appengine/datastore"
16         "google.golang.org/appengine/delay"
17         "google.golang.org/appengine/log"
18         "google.golang.org/appengine/user"
19 )
20
21 var delayedHandleNotifications = delay.Func("handleNotifications", handleNotifications)
22
23 func init() {
24         http.HandleFunc("/fitbit/setup", fitbitSetupHandler)
25         http.Handle("/fitbit/grant", AuthenticatedHandler(fitbitGrantHandler))
26         http.Handle("/fitbit/notify", ContextHandler(fitbitNotifyHandler))
27         http.HandleFunc("/google/setup", googleSetupHandler)
28         http.Handle("/google/grant", AuthenticatedHandler(googleGrantHandler))
29         http.Handle("/", AuthenticatedHandler(indexHandler))
30 }
31
32 // ContextHandler implements http.Handler
33 type ContextHandler func(context.Context, http.ResponseWriter, *http.Request) error
34
35 func (hndl ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
36         ctx := appengine.NewContext(r)
37
38         if err := hndl(ctx, w, r); err != nil {
39                 http.Error(w, err.Error(), http.StatusInternalServerError)
40                 return
41         }
42 }
43
44 type AuthenticatedHandler func(context.Context, http.ResponseWriter, *http.Request, *app.User) error
45
46 func (hndl AuthenticatedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
47         ctx := appengine.NewContext(r)
48
49         gaeUser := user.Current(ctx)
50         if gaeUser == nil {
51                 url, err := user.LoginURL(ctx, r.URL.String())
52                 if err != nil {
53                         http.Error(w, err.Error(), http.StatusInternalServerError)
54                         return
55                 }
56                 http.Redirect(w, r, url, http.StatusTemporaryRedirect)
57                 return
58         }
59
60         u, err := app.NewUser(ctx, gaeUser.Email)
61         if err != nil {
62                 http.Error(w, err.Error(), http.StatusInternalServerError)
63                 return
64         }
65
66         if err := hndl(ctx, w, r, u); err != nil {
67                 http.Error(w, err.Error(), http.StatusInternalServerError)
68                 return
69         }
70 }
71
72 func indexHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
73         _, err := u.Token(ctx, "Fitbit")
74         if err != nil && err != datastore.ErrNoSuchEntity {
75                 return err
76         }
77         haveFitbitToken := err == nil
78
79         _, err = u.Token(ctx, "Google")
80         if err != nil && err != datastore.ErrNoSuchEntity {
81                 return err
82         }
83         haveGoogleToken := err == nil
84
85         fmt.Fprintln(w, "<html><body><h1>Fitbit to Google Fit sync</h1>")
86         fmt.Fprintf(w, "<p>Hello %s</p>\n", user.Current(ctx).Email)
87         fmt.Fprintln(w, "<ul>")
88
89         fmt.Fprint(w, "<li>Fitbit: ")
90         if haveFitbitToken {
91                 fmt.Fprint(w, `<strong style="color: DarkGreen;">Authorized</strong>`)
92         } else {
93                 fmt.Fprint(w, `<strong style="color: DarkRed;">Not authorized</strong> (<a href="/fitbit/setup">Authorize</a>)`)
94         }
95         fmt.Fprintln(w, "</li>")
96
97         fmt.Fprint(w, "<li>Google: ")
98         if haveGoogleToken {
99                 fmt.Fprint(w, `<strong style="color: DarkGreen;">Authorized</strong>`)
100         } else {
101                 fmt.Fprint(w, `<strong style="color: DarkRed;">Not authorized</strong> (<a href="/google/setup">Authorize</a>)`)
102         }
103         fmt.Fprintln(w, "</li>")
104
105         fmt.Fprintln(w, "</ul>")
106         fmt.Fprintln(w, "</body></html>")
107
108         return nil
109 }
110
111 func fitbitSetupHandler(w http.ResponseWriter, r *http.Request) {
112         http.Redirect(w, r, fitbit.AuthURL(), http.StatusTemporaryRedirect)
113 }
114
115 func fitbitGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
116         if err := fitbit.ParseToken(ctx, r, u); err != nil {
117                 return err
118         }
119         c, err := fitbit.NewClient(ctx, "-", u)
120         if err != nil {
121                 return err
122         }
123
124         if err := c.Subscribe(ctx, "activities"); err != nil {
125                 return fmt.Errorf("c.Subscribe() = %v", err)
126         }
127
128         redirectURL := r.URL
129         redirectURL.Path = "/"
130         redirectURL.RawQuery = ""
131         redirectURL.Fragment = ""
132         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
133         return nil
134 }
135
136 func googleSetupHandler(w http.ResponseWriter, r *http.Request) {
137         http.Redirect(w, r, gfit.AuthURL(), http.StatusTemporaryRedirect)
138 }
139
140 func googleGrantHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, u *app.User) error {
141         if err := gfit.ParseToken(ctx, r, u); err != nil {
142                 return err
143         }
144
145         redirectURL := r.URL
146         redirectURL.Path = "/"
147         redirectURL.RawQuery = ""
148         redirectURL.Fragment = ""
149         http.Redirect(w, r, redirectURL.String(), http.StatusTemporaryRedirect)
150         return nil
151 }
152
153 // fitbitNotifyHandler is called by Fitbit whenever there are updates to a
154 // subscription. It verifies the payload, splits it into individual
155 // notifications and adds it to the taskqueue service.
156 func fitbitNotifyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
157         defer r.Body.Close()
158
159         fitbitTimeout := 3 * time.Second
160         ctx, cancel := context.WithTimeout(ctx, fitbitTimeout)
161         defer cancel()
162
163         // this is used when setting up a new subscriber in the UI. Once set
164         // up, this code path should not be triggered.
165         if verify := r.FormValue("verify"); verify != "" {
166                 if verify == "@FITBIT_SUBSCRIBER_CODE@" {
167                         w.WriteHeader(http.StatusNoContent)
168                 } else {
169                         w.WriteHeader(http.StatusNotFound)
170                 }
171                 return nil
172         }
173
174         data, err := ioutil.ReadAll(r.Body)
175         if err != nil {
176                 return err
177         }
178
179         // Fitbit recommendation: "If signature verification fails, you should
180         // respond with a 404"
181         if !fitbit.CheckSignature(ctx, data, r.Header.Get("X-Fitbit-Signature")) {
182                 w.WriteHeader(http.StatusNotFound)
183                 return nil
184         }
185
186         if err := delayedHandleNotifications.Call(ctx, data); err != nil {
187                 return err
188         }
189
190         w.WriteHeader(http.StatusCreated)
191         return nil
192 }
193
194 // handleNotifications parses fitbit notifications and requests the individual
195 // activities from Fitbit. It is executed asynchronously via the delay package.
196 func handleNotifications(ctx context.Context, payload []byte) error {
197         var subscriptions []fitbit.Subscription
198         if err := json.Unmarshal(payload, &subscriptions); err != nil {
199                 return err
200         }
201
202         for _, s := range subscriptions {
203                 if s.CollectionType != "activities" {
204                         continue
205                 }
206
207                 if err := handleNotification(ctx, &s); err != nil {
208                         log.Errorf(ctx, "handleNotification() = %v", err)
209                         continue
210                 }
211         }
212
213         return nil
214 }
215
216 func handleNotification(ctx context.Context, s *fitbit.Subscription) error {
217         u, err := app.UserByID(ctx, s.SubscriptionID)
218         if err != nil {
219                 return err
220         }
221
222         tm, err := time.Parse("2006-01-02", s.Date)
223         if err != nil {
224                 return err
225         }
226
227         fitbitClient, err := fitbit.NewClient(ctx, s.OwnerID, u)
228         if err != nil {
229                 return err
230         }
231
232         summary, err := fitbitClient.ActivitySummary(tm)
233         if err != nil {
234                 return err
235         }
236         log.Debugf(ctx, "ActivitySummary for %s = %+v", u.Email, summary)
237
238         gfitClient, err := gfit.NewClient(ctx, u)
239         if err != nil {
240                 return err
241         }
242
243         if err := gfitClient.SetSteps(ctx, summary.Summary.Steps, tm); err != nil {
244                 return fmt.Errorf("gfitClient.SetSteps(%d) = %v", summary.Summary.Steps, err)
245         }
246
247         return nil
248 }