"github.com/octo/kraftakt/app"
"golang.org/x/oauth2"
oauth2fitbit "golang.org/x/oauth2/fitbit"
+ "google.golang.org/appengine"
"google.golang.org/appengine/log"
)
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
c, err := u.OAuthClient(ctx, "Fitbit", oauthConfig())
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("OAuthClient(%q) = %v", "Fitbit", err)
}
return &Client{
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")
}
return err
}
- var errs appengine.MultiError
-
- for _, collection := range []string{"activities", "sleep"} {
- if err := c.Unsubscribe(ctx, collection); err != nil {
- errs = append(errs, fmt.Errorf("Unsubscribe(%q) = %v", collection, err))
- continue
- }
- log.Infof(ctx, "Successfully unsubscribed from %q", collection)
- }
-
- if err := c.DeleteToken(ctx); err != nil {
- errs = append(errs, fmt.Errorf("DeleteToken() = %v", err))
- }
- if len(errs) != 0 {
- return errs
+ if err := c.UnsubscribeAll(ctx); err != nil {
+ log.Errorf(ctx, "UnsubscribeAll() = %v", err)
+ return fmt.Errorf("deleting all subscriptions failed")
}
redirectURL := r.URL