From 082997b663188efe938adea91660eb994405e62a Mon Sep 17 00:00:00 2001 From: Florian Forster Date: Tue, 30 Jan 2018 22:08:08 +0100 Subject: [PATCH] Package fitbit: Append the collection type to the subscriber ID. Turns out, subscriber IDs must be unique, even for subscriptions to multiple collections of the same user. --- fitbit/fitbit.go | 20 ++++++++++++++++++-- kraftakt.go | 2 +- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/fitbit/fitbit.go b/fitbit/fitbit.go index 36242d1..e960438 100644 --- a/fitbit/fitbit.go +++ b/fitbit/fitbit.go @@ -9,6 +9,7 @@ import ( "fmt" "io/ioutil" "net/http" + "strings" "time" "github.com/octo/kraftakt/app" @@ -174,9 +175,18 @@ func (c *Client) ActivitySummary(ctx context.Context, date string) (*ActivitySum 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 { url := fmt.Sprintf("https://api.fitbit.com/1/user/%s/%s/apiSubscriptions/%s.json", - c.fitbitUserID, collection, c.appUser.ID) + c.fitbitUserID, collection, c.subscriberID(collection)) res, err := c.client.Post(url, "", nil) if err != nil { return err @@ -188,13 +198,16 @@ func (c *Client) Subscribe(ctx context.Context, collection string) error { 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, c.appUser.ID) + c.fitbitUserID, collection, c.subscriberID(collection)) req, err := http.NewRequest(http.MethodDelete, url, nil) if err != nil { return err @@ -211,6 +224,9 @@ func (c *Client) Unsubscribe(ctx context.Context, collection string) error { 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 } diff --git a/kraftakt.go b/kraftakt.go index f6b3d9c..092cad3 100644 --- a/kraftakt.go +++ b/kraftakt.go @@ -314,7 +314,7 @@ func handleNotifications(ctx context.Context, payload []byte) error { } func handleNotification(ctx context.Context, s *fitbit.Subscription) error { - u, err := app.UserByID(ctx, s.SubscriptionID) + u, err := fitbit.UserFromSubscriberID(ctx, s.SubscriptionID) if err != nil { return err } -- 2.11.0