"fmt"
"io/ioutil"
"net/http"
+ "strings"
"time"
- "github.com/octo/gfitsync/app"
+ "github.com/octo/kraftakt/app"
"golang.org/x/oauth2"
oauth2fitbit "golang.org/x/oauth2/fitbit"
+ "google.golang.org/appengine"
"google.golang.org/appengine/log"
)
-var oauth2Config = &oauth2.Config{
- ClientID: "@FITBIT_CLIENT_ID@",
- ClientSecret: "@FITBIT_CLIENT_SECRET@",
- Endpoint: oauth2fitbit.Endpoint,
- RedirectURL: "https://kraftakt.octo.it/fitbit/grant",
- Scopes: []string{"activity", "heartrate", "profile"},
+func oauthConfig() *oauth2.Config {
+ return &oauth2.Config{
+ ClientID: app.Config.FitbitClientID,
+ ClientSecret: app.Config.FitbitClientSecret,
+ Endpoint: oauth2fitbit.Endpoint,
+ RedirectURL: "https://kraftakt.octo.it/fitbit/grant",
+ Scopes: []string{
+ "activity",
+ "heartrate",
+ "profile",
+ "sleep",
+ },
+ }
}
-const csrfToken = "@CSRFTOKEN@"
-
-func AuthURL() string {
- return oauth2Config.AuthCodeURL(csrfToken, oauth2.AccessTypeOffline)
+func AuthURL(ctx context.Context, u *app.User) string {
+ return oauthConfig().AuthCodeURL(u.Sign("Fitbit"), oauth2.AccessTypeOffline)
}
func ParseToken(ctx context.Context, r *http.Request, u *app.User) error {
- if state := r.FormValue("state"); state != csrfToken {
+ if state := r.FormValue("state"); state != u.Sign("Fitbit") {
return fmt.Errorf("invalid state parameter: %q", state)
}
- tok, err := oauth2Config.Exchange(ctx, r.FormValue("code"))
+ tok, err := oauthConfig().Exchange(ctx, r.FormValue("code"))
if err != nil {
return err
}
return false
}
- mac := hmac.New(sha1.New, []byte(oauth2Config.ClientSecret+"&"))
+ mac := hmac.New(sha1.New, []byte(oauthConfig().ClientSecret+"&"))
mac.Write(payload)
signatureWant := mac.Sum(nil)
}
type Activity struct {
- ActivityID int `json:"activityId"`
- ActivityParentID int `json:"activityParentId"`
- Calories int `json:"calories"`
- Description string `json:"description"`
- Distance float64 `json:"distance"`
- Duration int `json:"duration"`
- HasStartTime bool `json:"hasStartTime"`
- IsFavorite bool `json:"isFavorite"`
- LogID int `json:"logId"`
- Name string `json:"name"`
- StartTime string `json:"startTime"`
- Steps int `json:"steps"`
+ ActivityID int `json:"activityId"`
+ ActivityParentID int `json:"activityParentId"`
+ ActivityParentName string `json:"activityParentName"`
+ Calories int `json:"calories"`
+ Description string `json:"description"`
+ Distance float64 `json:"distance"`
+ Duration int `json:"duration"`
+ HasStartTime bool `json:"hasStartTime"`
+ IsFavorite bool `json:"isFavorite"`
+ LastModified time.Time `json:"lastModified"`
+ LogID int `json:"logId"`
+ Name string `json:"name"`
+ StartTime string `json:"startTime"`
+ StartDate string `json:"startDate"`
+ Steps int `json:"steps"`
}
type Distance struct {
SubscriptionID string `json:"subscriptionId"`
}
+func (s Subscription) String() string {
+ return fmt.Sprintf("https://api.fitbit.com/1/%s/%s/%s/apiSubscriptions/%s.json",
+ s.OwnerType, s.OwnerID, s.CollectionType, s.SubscriptionID)
+}
+
type Client struct {
fitbitUserID string
appUser *app.User
fitbitUserID = "-"
}
- c, err := u.OAuthClient(ctx, "Fitbit", oauth2Config)
+ c, err := u.OAuthClient(ctx, "Fitbit", oauthConfig())
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("OAuthClient(%q) = %v", "Fitbit", err)
}
return &Client{
}, nil
}
-func (c *Client) ActivitySummary(ctx context.Context, t time.Time) (*ActivitySummary, error) {
+func (c *Client) ActivitySummary(ctx context.Context, date string) (*ActivitySummary, error) {
url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/activities/date/%s.json",
- c.fitbitUserID, t.Format("2006-01-02"))
+ c.fitbitUserID, date)
res, err := c.client.Get(url)
if err != nil {
return &summary, nil
}
+func (c *Client) subscriberID(collection string) string {
+ return fmt.Sprintf("%s:%s", c.appUser.ID, collection)
+}
+
+func UserFromSubscriberID(ctx context.Context, subscriberID string) (*app.User, error) {
+ uid := strings.Split(subscriberID, ":")[0]
+ return app.UserByID(ctx, uid)
+}
+
func (c *Client) Subscribe(ctx context.Context, collection string) error {
- subscriberID, err := c.appUser.ID(ctx)
+ url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
+ c.fitbitUserID, collection, c.subscriberID(collection))
+ res, err := c.client.Post(url, "", nil)
if err != nil {
return err
}
+ defer res.Body.Close()
+
+ if res.StatusCode >= 400 && res.StatusCode != http.StatusConflict {
+ data, _ := ioutil.ReadAll(res.Body)
+ log.Errorf(ctx, "creating %q subscription failed: status %d %q", collection, res.StatusCode, data)
+ return fmt.Errorf("creating %q subscription failed", collection)
+ }
+ if res.StatusCode == http.StatusConflict {
+ log.Infof(ctx, "creating %q subscription: already exists", collection)
+ }
+ return nil
+}
+
+func (c *Client) Unsubscribe(ctx context.Context, collection string) error {
url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json",
- c.fitbitUserID, collection, subscriberID)
- res, err := c.client.Post(url, "", nil)
+ c.fitbitUserID, collection, c.subscriberID(collection))
+ req, err := http.NewRequest(http.MethodDelete, url, nil)
+ if err != nil {
+ return err
+ }
+
+ res, err := c.client.Do(req.WithContext(ctx))
if err != nil {
return err
}
defer res.Body.Close()
- if res.StatusCode >= 400 {
+ if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
data, _ := ioutil.ReadAll(res.Body)
- log.Errorf(ctx, "creating subscription failed: status %d %q", res.StatusCode, data)
- return fmt.Errorf("creating subscription failed")
+ log.Errorf(ctx, "deleting %q subscription failed: status %d %q", collection, res.StatusCode, data)
+ return fmt.Errorf("deleting %q subscription failed", collection)
+ }
+ if res.StatusCode == http.StatusNotFound {
+ log.Infof(ctx, "deleting %q subscription: not found", collection)
+ }
+
+ return nil
+}
+
+func (c *Client) UnsubscribeAll(ctx context.Context) error {
+ subs, err := c.ListSubscriptions(ctx)
+ if err != nil {
+ return err
+ }
+
+ var errs appengine.MultiError
+ for _, s := range subs {
+ if s.OwnerType != "user" {
+ log.Infof(ctx, "unexpected OwnerType: %q", s.OwnerType)
+ continue
+ }
+ if err := c.Unsubscribe(ctx, s.CollectionType); err != nil {
+ errs = append(errs, err)
+ }
+ }
+ if len(errs) != 0 {
+ return errs
}
return nil
}
+func (c *Client) ListSubscriptions(ctx context.Context) ([]Subscription, error) {
+ url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/apiSubscriptions.json", c.fitbitUserID)
+ res, err := c.client.Get(url)
+ if err != nil {
+ return nil, fmt.Errorf("Get(%q) = %v", url, err)
+ }
+ defer res.Body.Close()
+
+ if res.StatusCode >= 400 && res.StatusCode != http.StatusNotFound {
+ data, _ := ioutil.ReadAll(res.Body)
+ log.Errorf(ctx, "listing subscriptions failed: status %d %q", res.StatusCode, data)
+ return nil, fmt.Errorf("listing subscriptions failed")
+ }
+ if res.StatusCode == http.StatusNotFound {
+ log.Infof(ctx, "listing subscriptions: not found")
+ return nil, nil
+ }
+
+ var subscriptions []Subscription
+ if err := json.NewDecoder(res.Body).Decode(&subscriptions); err != nil {
+ return nil, err
+ }
+
+ for i, s := range subscriptions {
+ log.Debugf(ctx, "ListSubscriptions() = %d: %s", i, s)
+ }
+
+ return subscriptions, nil
+}
+
+func (c *Client) DeleteToken(ctx context.Context) error {
+ return c.appUser.DeleteToken(ctx, "Fitbit")
+}
+
type Profile struct {
Name string
Timezone *time.Location