-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathnokiahealth.go
1024 lines (864 loc) · 31.9 KB
/
nokiahealth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package nokiahealth
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/jrmycanady/nokiahealth/enum/status"
"golang.org/x/oauth2"
nokiaOauth2 "golang.org/x/oauth2/nokiahealth"
)
const (
getIntradayActivitiesURL = "https://api.health.nokia.com/v2/measure"
getActivityMeasuresURL = "https://api.health.nokia.com/v2/measure"
getWorkoutsURL = "https://api.health.nokia.com/v2/measure"
getBodyMeasureURL = "https://api.health.nokia.com/measure"
getSleepMeasureURL = "https://api.health.nokia.com/v2/sleep"
getSleepSummaryURL = "https://api.health.nokia.com/v2/sleep"
createNotficationURL = "https://api.health.nokia.com/notify"
listNotificationsURL = "https://api.health.nokia.com/notify"
getNotificationInformationURL = "https://api.health.nokia.com/notify"
revokeNotificationURL = "https://api.health.nokia.com/notify"
)
// Scope defines the types of scopes accepted by the API.
type Scope string
const (
// ScopeUserMetrics provides access to the Getmeas actions.
ScopeUserMetrics Scope = "user.metrics"
// ScopeUserInfo provides access to the user information.
ScopeUserInfo Scope = "user.info"
// ScopeUserActivity provides access to the users activity data.
ScopeUserActivity Scope = "user.activity"
)
// Rand provides a function type to allow passing in custom random functions
// used for state generation.
type Rand func() (string, error)
// generateRandomString generates a new random string using crytpo/rand. The
// result is base64 encoded for use in URLs.
func generateRandomString() (string, error) {
buf := make([]byte, 64)
_, err := rand.Read(buf)
return base64.URLEncoding.EncodeToString(buf), err
}
// Client contains all the required information to interact with the nokia API.
type Client struct {
OAuth2Config *oauth2.Config
SaveRawResponse bool
IncludePath bool
Rand Rand
Timeout time.Duration
}
// NewClient creates a new client using the Ouath2 information provided. The
// required parameters can be obtained when developers register with Nokia
// to use the API.
func NewClient(clientID string, clientSecret string, redirectURL string) Client {
return Client{
OAuth2Config: &oauth2.Config{
RedirectURL: redirectURL,
ClientID: clientID,
ClientSecret: clientSecret,
// Scopes: []string{"user.metrics", "user.activity"},
Scopes: []string{"user.activity,user.metrics,user.info"},
Endpoint: nokiaOauth2.Endpoint,
},
Rand: generateRandomString,
Timeout: 5 * time.Second,
}
}
// SetScope allows for setting the scope of the client which is used during
// authorization requests for new users. By default the scope will be all
// scopes. This is also not thread safe.
func (c *Client) SetScope(scopes ...string) {
c.OAuth2Config.Scopes = []string{strings.Join([]string(scopes), ",")}
}
// getContext returns a context set to time out after the duration specified
// in the client.
func (c *Client) getContext() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), c.Timeout)
}
// AuthCodeURL generates the URL user authorization URL. Users should be redirected
// to this URL so they can allow your application. They will then be directed back
// to the redirectURL provided when the client was created. This redirection
// will contain the authentication code needed to generate an access token.
//
// The state parameter of the request is generated using crypto/rand
// and returned as state. The random generation function can be replaced
// by assigning a new function to Client.Rand.
func (c *Client) AuthCodeURL() (url string, state string, err error) {
state, err = c.Rand()
return c.OAuth2Config.AuthCodeURL(state), state, err
}
// GenerateAccessToken generates the access token from the authorization code. The
// authorization code is the one provided in the parameters of the redirect request
// from the URL generated by AuthCodeURL. Generally this isn't directly called and
// create user is used instead. The state is also not validated and is left for the
// calling methods.
func (c *Client) GenerateAccessToken(ctx context.Context, code string) (*oauth2.Token, error) {
return c.OAuth2Config.Exchange(ctx, code)
}
// User is a Nokia Health user account that can be interacted with via the
// api.
type User struct {
Client *Client
TokenSource oauth2.TokenSource
HTTPClient *http.Client
CurrentRefreshToken string
refreshTokenReplaced bool
}
// NewUserFromAuthCode generates a new user by requesting the token using the
// authentication code provided. This is generally only used after a user
// has just authorized access and the client is processing the redirect.
func (c *Client) NewUserFromAuthCode(ctx context.Context, code string) (*User, error) {
t, err := c.OAuth2Config.Exchange(ctx, code)
if err != nil {
return nil, fmt.Errorf("failed to obtain token: %s", err)
}
return &User{
TokenSource: c.OAuth2Config.TokenSource(ctx, t),
Client: c,
HTTPClient: c.OAuth2Config.Client(ctx, t),
CurrentRefreshToken: t.RefreshToken,
// HTTPClient: &http.Client{},
}, nil
}
// NewUserFromRefreshToken generates a new user that the refresh token is for.
// Upon creation a new access token is also generated. If the generation of the
// access token fails, an error is returned.
func (c *Client) NewUserFromRefreshToken(ctx context.Context, accessToken string, refreshToken string) (*User, error) {
t := oauth2.Token{
RefreshToken: refreshToken,
AccessToken: accessToken,
Expiry: time.Now().AddDate(0, 0, -1),
}
u := User{
Client: c,
TokenSource: c.OAuth2Config.TokenSource(ctx, &t),
HTTPClient: c.OAuth2Config.Client(ctx, &t),
CurrentRefreshToken: t.RefreshToken,
// HTTPClient: &http.Client{},
}
return &u, nil
}
// RefreshTokenReplaced returns true if the refresh token has been replaced.
func (u *User) RefreshTokenReplaced() bool {
return u.refreshTokenReplaced
}
// Token returns the user token retrieving a new one via the refresh if expired. If a new one is provided
// User.RefreshTokenReplaced() will return true noting the refresh token should be saved.
func (u *User) Token() (*oauth2.Token, error) {
t, err := u.TokenSource.Token()
if err != nil {
return t, err
}
if t.RefreshToken != u.CurrentRefreshToken {
u.CurrentRefreshToken = t.RefreshToken
u.refreshTokenReplaced = true
}
return t, nil
}
// GetIntradayActivity is the same as GetIntraDayActivityCtx but doesn't require a context to be provided.
func (u *User) GetIntradayActivity(params *IntradayActivityQueryParam) (IntradayActivityResp, error) {
ctx, cancel := u.Client.getContext()
defer cancel()
return u.GetIntradayActivityCtx(ctx, params)
}
// GetIntradayActivityCtx retreieves intraday activites from the API. Special permissions provided by
// Nokia Health are required to use this resource.
func (u *User) GetIntradayActivityCtx(ctx context.Context, params *IntradayActivityQueryParam) (IntradayActivityResp, error) {
intraDayActivityResponse := IntradayActivityResp{}
// Building query params
v := url.Values{}
t, err := u.Token()
if err != nil {
return intraDayActivityResponse, fmt.Errorf("failed to obtain token: %s", err)
}
v.Add("access_token", t.AccessToken)
v.Add("action", "getintradayactivity")
if params != nil {
if params.StartDate != nil {
v.Add(GetFieldName(*params, "StartDate"), strconv.FormatInt(params.StartDate.Unix(), 10))
}
if params.EndDate != nil {
v.Add(GetFieldName(*params, "EndDate"), strconv.FormatInt(params.EndDate.Unix(), 10))
}
}
// Sending request to the API.
path := fmt.Sprintf("%s?%s", getIntradayActivitiesURL, v.Encode())
if u.Client.IncludePath {
intraDayActivityResponse.Path = path
}
req, err := http.NewRequest("GET", path, nil)
req = req.WithContext(ctx)
if err != nil {
return intraDayActivityResponse, fmt.Errorf("failed to build request: %s", err)
}
resp, err := u.HTTPClient.Do(req)
if err != nil {
return intraDayActivityResponse, err
}
defer resp.Body.Close()
// Processing API response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return intraDayActivityResponse, err
}
if u.Client.SaveRawResponse {
intraDayActivityResponse.RawResponse = body
}
err = json.Unmarshal(body, &intraDayActivityResponse)
if err != nil {
return intraDayActivityResponse, err
}
if intraDayActivityResponse.Status != status.OperationWasSuccessful {
return intraDayActivityResponse, fmt.Errorf("api returned an error: %s", intraDayActivityResponse.Error)
}
return intraDayActivityResponse, nil
}
// GetActivityMeasures is the same as GetActivityMeasuresCtx but doesn't require a context to be provided.
func (u *User) GetActivityMeasures(params *ActivityMeasuresQueryParam) (ActivitiesMeasuresResp, error) {
ctx, cancel := u.Client.getContext()
defer cancel()
return u.GetActivityMeasuresCtx(ctx, params)
}
// GetActivityMeasuresCtx retrieves the activity measurements as specified by the config
// provided. If the start time is missing the current time minus one day will be used.
// If the end time is missing the current day will be used.
func (u *User) GetActivityMeasuresCtx(ctx context.Context, params *ActivityMeasuresQueryParam) (ActivitiesMeasuresResp, error) {
activityMeasureResponse := ActivitiesMeasuresResp{}
// Building the query params
v := url.Values{}
t, err := u.Token()
if err != nil {
return activityMeasureResponse, fmt.Errorf("failed to obtain token: %s", err)
}
v.Add("access_token", t.AccessToken)
v.Add("action", "getactivity")
if params != nil {
// if params.Date != nil {
// v.Add(GetFieldName(*params, "Date"), params.Date.Format("2006-01-02"))
// }
if params.StartDateYMD != nil {
v.Add(GetFieldName(*params, "StartDateYMD"), params.StartDateYMD.Format("2006-01-02"))
} else {
v.Add(GetFieldName(*params, "StartDateYMD"), time.Now().AddDate(0, 0, -1).Format("2006-01-02"))
}
if params.EndDateYMD != nil {
v.Add(GetFieldName(*params, "EndDateYMD"), params.EndDateYMD.Format("2006-01-02"))
} else {
v.Add(GetFieldName(*params, "EndDateYMD"), time.Now().Format("2006-01-02"))
}
if params.LasteUpdate != nil {
v.Add(GetFieldName(*params, "LasteUpdate"), strconv.FormatInt(params.LasteUpdate.Unix(), 10))
}
} else {
params = &ActivityMeasuresQueryParam{}
v.Add(GetFieldName(*params, "StartDateYMD"), time.Now().AddDate(0, 0, -1).Format("2006-01-02"))
v.Add(GetFieldName(*params, "EndDateYMD"), time.Now().Format("2006-01-02"))
}
// Sending request to the API.
path := fmt.Sprintf("%s?%s", getActivityMeasuresURL, v.Encode())
if u.Client.IncludePath {
activityMeasureResponse.Path = path
}
req, err := http.NewRequest("GET", path, nil)
req = req.WithContext(ctx)
if err != nil {
return activityMeasureResponse, fmt.Errorf("failed to build request: %s", err)
}
resp, err := u.HTTPClient.Do(req)
if err != nil {
return activityMeasureResponse, err
}
defer resp.Body.Close()
// Processing API response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return activityMeasureResponse, err
}
if u.Client.SaveRawResponse {
activityMeasureResponse.RawResponse = body
}
err = json.Unmarshal(body, &activityMeasureResponse)
if err != nil {
return activityMeasureResponse, err
}
if activityMeasureResponse.Status != status.OperationWasSuccessful {
return activityMeasureResponse, fmt.Errorf("api returned an error: %s", activityMeasureResponse.Error)
}
// Parse date time if possible.
if activityMeasureResponse.Body.Date != nil && activityMeasureResponse.Body.TimeZone != nil {
location, err := time.LoadLocation(*activityMeasureResponse.Body.TimeZone)
if err != nil {
return activityMeasureResponse, err
}
t, err := time.Parse("2006-01-02", *activityMeasureResponse.Body.Date)
if err != nil {
return activityMeasureResponse, err
}
t = t.In(location)
activityMeasureResponse.Body.ParsedDate = &t
activityMeasureResponse.Body.SingleValue = true
}
for aID := range activityMeasureResponse.Body.Activities {
location, err := time.LoadLocation(activityMeasureResponse.Body.Activities[aID].TimeZone)
if err != nil {
return activityMeasureResponse, err
}
t, err := time.Parse("2006-01-02", activityMeasureResponse.Body.Activities[aID].Date)
if err != nil {
return activityMeasureResponse, err
}
t = t.In(location)
activityMeasureResponse.Body.Activities[aID].ParsedDate = &t
}
return activityMeasureResponse, nil
}
// GetWorkouts is the same as GetWorkoutsCTX but doesn't require a context to be provided.
func (u *User) GetWorkouts(params *WorkoutsQueryParam) (WorkoutResponse, error) {
ctx, cancel := u.Client.getContext()
defer cancel()
return u.GetWorkoutsCtx(ctx, params)
}
// GetWorkoutsCtx retrieves all the workouts for a given date range based on the values
// provided by params.
func (u *User) GetWorkoutsCtx(ctx context.Context, params *WorkoutsQueryParam) (WorkoutResponse, error) {
workoutResponse := WorkoutResponse{}
// Building query params
v := url.Values{}
t, err := u.Token()
if err != nil {
return workoutResponse, fmt.Errorf("failed to obtain token: %s", err)
}
fmt.Printf("%v, %s, %s", t.Valid(), t.AccessToken, t.RefreshToken)
if err != nil {
return workoutResponse, fmt.Errorf("failed to obtain token: %s", err)
}
v.Add("access_token", t.AccessToken)
v.Add("action", "getworkouts")
if params != nil {
if params.StartDateYMD != nil {
v.Add(GetFieldName(*params, "StartDateYMD"), params.StartDateYMD.Format("2006-01-02"))
}
if params.EndDateYMD != nil {
v.Add(GetFieldName(*params, "EndDateYMD"), params.EndDateYMD.Format("2006-01-02"))
}
}
// Sending request to the API.
path := fmt.Sprintf("%s?%s", getWorkoutsURL, v.Encode())
if u.Client.IncludePath {
workoutResponse.Path = path
}
req, err := http.NewRequest("GET", path, nil)
req = req.WithContext(ctx)
if err != nil {
return workoutResponse, fmt.Errorf("failed to build request: %s", err)
}
resp, err := u.HTTPClient.Do(req)
if err != nil {
return workoutResponse, err
}
defer resp.Body.Close()
// Processing API response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return workoutResponse, nil
}
if u.Client.SaveRawResponse {
workoutResponse.RawResponse = body
}
err = json.Unmarshal(body, &workoutResponse)
if err != nil {
return workoutResponse, err
}
if workoutResponse.Status != status.OperationWasSuccessful {
return workoutResponse, fmt.Errorf("api returned an error: %s", workoutResponse.Error)
}
// Parse dates if possible
if workoutResponse.Body != nil {
for i := range workoutResponse.Body.Series {
d := time.Unix(workoutResponse.Body.Series[i].StartDate, 0)
workoutResponse.Body.Series[i].StartDateParsed = &d
d = time.Unix(workoutResponse.Body.Series[i].EndDate, 0)
workoutResponse.Body.Series[i].EndDateParsed = &d
location, err := time.LoadLocation(workoutResponse.Body.Series[i].TimeZone)
if err != nil {
return workoutResponse, err
}
t, err := time.Parse("2006-01-02", workoutResponse.Body.Series[i].Date)
if err != nil {
return workoutResponse, err
}
t = t.In(location)
workoutResponse.Body.Series[i].DateParsed = &t
}
}
return workoutResponse, nil
}
// GetBodyMeasures is the same as GetBodyMeasuresCtx but doesn't require a context to be provided.
func (u *User) GetBodyMeasures(params *BodyMeasuresQueryParams) (BodyMeasuresResp, error) {
ctx, cancel := u.Client.getContext()
defer cancel()
return u.GetBodyMeasuresCtx(ctx, params)
}
// GetBodyMeasuresCtx retrieves the body measurements as specified by the config
// provided.
func (u *User) GetBodyMeasuresCtx(ctx context.Context, params *BodyMeasuresQueryParams) (BodyMeasuresResp, error) {
bodyMeasureResponse := BodyMeasuresResp{}
// Building query params
v := url.Values{}
v.Add("action", "getmeas")
t, err := u.Token()
if err != nil {
return bodyMeasureResponse, fmt.Errorf("failed to obtain token: %s", err)
}
v.Add("access_token", t.AccessToken)
if params != nil {
if params.StartDate != nil {
v.Add(GetFieldName(*params, "StartDate"), strconv.FormatInt(params.StartDate.Unix(), 10))
}
if params.EndDate != nil {
v.Add(GetFieldName(*params, "EndDate"), strconv.FormatInt(params.EndDate.Unix(), 10))
}
if params.LastUpdate != nil {
v.Add(GetFieldName(*params, "LastUpdate"), strconv.FormatInt(params.EndDate.Unix(), 10))
}
if params.DevType != nil {
v.Add(GetFieldName(*params, "DevType"), strconv.Itoa(int(*params.DevType)))
}
if params.MeasType != nil {
v.Add(GetFieldName(*params, "MeasType"), strconv.Itoa(int(*params.MeasType)))
}
if params.Category != nil {
v.Add(GetFieldName(*params, "Category"), strconv.Itoa(*params.Category))
}
if params.Limit != nil {
v.Add(GetFieldName(*params, "Limit"), strconv.Itoa(*params.Limit))
}
if params.Offset != nil {
v.Add(GetFieldName(*params, "Offset"), strconv.Itoa(*params.Offset))
}
}
// Sending request to the API.
path := fmt.Sprintf("%s?%s", getBodyMeasureURL, v.Encode())
if u.Client.IncludePath {
bodyMeasureResponse.Path = path
}
req, err := http.NewRequest("GET", path, nil)
req = req.WithContext(ctx)
if err != nil {
return bodyMeasureResponse, fmt.Errorf("failed to build request: %s", err)
}
resp, err := u.HTTPClient.Do(req)
if err != nil {
return bodyMeasureResponse, err
}
defer resp.Body.Close()
// Processing API response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return bodyMeasureResponse, err
}
if u.Client.SaveRawResponse {
bodyMeasureResponse.RawResponse = body
}
err = json.Unmarshal(body, &bodyMeasureResponse)
if err != nil {
return bodyMeasureResponse, err
}
if bodyMeasureResponse.Status != status.OperationWasSuccessful {
return bodyMeasureResponse, fmt.Errorf("api returned an error: %s", bodyMeasureResponse.Error)
}
if params != nil && params.ParseResponse {
bodyMeasureResponse.ParsedResponse = bodyMeasureResponse.ParseData()
}
return bodyMeasureResponse, nil
}
// GetSleepMeasures is the same as GetSleepMeasuresCtx but doesn't require a context to be provided.
func (u *User) GetSleepMeasures(params *SleepMeasuresQueryParam) (SleepMeasuresResp, error) {
ctx, cancel := u.Client.getContext()
defer cancel()
return u.GetSleepMeasuresCtx(ctx, params)
}
// GetSleepMeasuresCtx retrieves the sleep measurements as specified by the config
// provided. Start and end dates are requires so if the param is not provided
// one is generated for the past 24 hour timeframe.
func (u *User) GetSleepMeasuresCtx(ctx context.Context, params *SleepMeasuresQueryParam) (SleepMeasuresResp, error) {
sleepMeasureRepsonse := SleepMeasuresResp{}
// Building query params
v := url.Values{}
t, err := u.Token()
if err != nil {
return sleepMeasureRepsonse, fmt.Errorf("failed to obtain token: %s", err)
}
v.Add("access_token", t.AccessToken)
v.Add("action", "get")
// Params are required for this api call. To be consident we handle empty params and build
// one with sensible defaults if needed.
if params == nil {
params = &SleepMeasuresQueryParam{}
params.StartDate = time.Now()
params.EndDate = time.Now().AddDate(0, 0, -1)
}
v.Add(GetFieldName(*params, "StartDate"), strconv.FormatInt(params.StartDate.Unix(), 10))
v.Add(GetFieldName(*params, "EndDate"), strconv.FormatInt(params.EndDate.Unix(), 10))
// Sending request to the API.
path := fmt.Sprintf("%s?%s", getSleepMeasureURL, v.Encode())
if u.Client.IncludePath {
sleepMeasureRepsonse.Path = path
}
req, err := http.NewRequest("GET", path, nil)
req = req.WithContext(ctx)
if err != nil {
return sleepMeasureRepsonse, fmt.Errorf("failed to build request: %s", err)
}
resp, err := u.HTTPClient.Do(req)
if err != nil {
return sleepMeasureRepsonse, err
}
defer resp.Body.Close()
// Processing API response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return sleepMeasureRepsonse, err
}
if u.Client.SaveRawResponse {
sleepMeasureRepsonse.RawResponse = body
}
err = json.Unmarshal(body, &sleepMeasureRepsonse)
if err != nil {
return sleepMeasureRepsonse, err
}
if sleepMeasureRepsonse.Status != status.OperationWasSuccessful {
return sleepMeasureRepsonse, fmt.Errorf("api returned an error: %s", sleepMeasureRepsonse.Error)
}
// Parse dates
if sleepMeasureRepsonse.Body != nil {
for i := range sleepMeasureRepsonse.Body.Series {
t := time.Unix(sleepMeasureRepsonse.Body.Series[i].StartDate, 0)
sleepMeasureRepsonse.Body.Series[i].StartDateParsed = &t
t = time.Unix(sleepMeasureRepsonse.Body.Series[i].EndDate, 0)
sleepMeasureRepsonse.Body.Series[i].EndDateParsed = &t
}
}
return sleepMeasureRepsonse, nil
}
// GetSleepSummary is the same as GetSleepSummaryCtx but doesn't require a context to be provided.
func (u *User) GetSleepSummary(params *SleepSummaryQueryParam) (SleepSummaryResp, error) {
ctx, cancel := u.Client.getContext()
defer cancel()
return u.GetSleepSummaryCtx(ctx, params)
}
// GetSleepSummaryCtx retrieves the sleep summary information provided. A SleepSummaryQueryParam is
// required as a timeframe is needed by the API. If null is provided the last 24 hours will be used.
func (u *User) GetSleepSummaryCtx(ctx context.Context, params *SleepSummaryQueryParam) (SleepSummaryResp, error) {
sleepSummaryResponse := SleepSummaryResp{}
// Building query params
v := url.Values{}
t, err := u.Token()
if err != nil {
return sleepSummaryResponse, fmt.Errorf("failed to obtain token: %s", err)
}
v.Add("access_token", t.AccessToken)
v.Add("action", "getsummary")
// Params are required for this api call. To be consident we handle empty params and build
// one with sensible defaults if needed.
if params == nil {
params = &SleepSummaryQueryParam{}
t1 := time.Now()
t2 := time.Now().AddDate(0, 0, -1)
params.StartDateYMD = &t1
params.EndDateYMD = &t2
}
// Although the API currently says the type is a UNIX time stamp the reality is it's a date string.
v.Add(GetFieldName(*params, "StartDateYMD"), params.StartDateYMD.Format("2006-01-02"))
v.Add(GetFieldName(*params, "EndDateYMD"), params.EndDateYMD.Format("2006-01-02"))
// Sending request to the API.
path := fmt.Sprintf("%s?%s", getSleepSummaryURL, v.Encode())
if u.Client.IncludePath {
sleepSummaryResponse.Path = path
}
req, err := http.NewRequest("GET", path, nil)
req = req.WithContext(ctx)
if err != nil {
return sleepSummaryResponse, fmt.Errorf("failed to build request: %s", err)
}
resp, err := u.HTTPClient.Do(req)
if err != nil {
return sleepSummaryResponse, err
}
defer resp.Body.Close()
// Processing API response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return sleepSummaryResponse, err
}
if u.Client.SaveRawResponse {
sleepSummaryResponse.RawResponse = body
}
err = json.Unmarshal(body, &sleepSummaryResponse)
if err != nil {
return sleepSummaryResponse, err
}
if sleepSummaryResponse.Status != status.OperationWasSuccessful {
return sleepSummaryResponse, fmt.Errorf("api returned an error: %s", sleepSummaryResponse.Error)
}
// Parse all the date fields.
if sleepSummaryResponse.Body != nil {
for i := range sleepSummaryResponse.Body.Series {
// Parse the normal UNIX time stamps.
startDate := time.Unix(sleepSummaryResponse.Body.Series[i].StartDate, 0)
endDate := time.Unix(sleepSummaryResponse.Body.Series[i].EndDate, 0)
sleepSummaryResponse.Body.Series[i].StartDateParsed = &startDate
sleepSummaryResponse.Body.Series[i].EndDateParsed = &endDate
// Parse the goofy YYYY-MM-DD plus location date.
location, err := time.LoadLocation(sleepSummaryResponse.Body.Series[i].TimeZone)
if err != nil {
return sleepSummaryResponse, err
}
t, err := time.Parse("2006-01-02", sleepSummaryResponse.Body.Series[i].Date)
if err != nil {
return sleepSummaryResponse, err
}
t = t.In(location)
sleepSummaryResponse.Body.Series[i].DateParsed = &t
}
}
return sleepSummaryResponse, nil
}
// CreateNotification is the same as CreateNotificationCtx but doesn't require a context to be provided.
func (u *User) CreateNotification(params *CreateNotificationParam) (CreateNotificationResp, error) {
ctx, cancel := u.Client.getContext()
defer cancel()
return u.CreateNotificationCtx(ctx, params)
}
// CreateNotificationCtx creates a new notification.
func (u *User) CreateNotificationCtx(ctx context.Context, params *CreateNotificationParam) (CreateNotificationResp, error) {
createNotificationResponse := CreateNotificationResp{}
// Build a params if nil as it is required.
if params == nil {
params = &CreateNotificationParam{}
}
// Building query params.
v := url.Values{}
t, err := u.Token()
if err != nil {
return createNotificationResponse, fmt.Errorf("failed to obtain token: %s", err)
}
v.Add("access_token", t.AccessToken)
v.Add("action", "subscribe")
v.Add(GetFieldName(*params, "CallbackURL"), params.CallbackURL.String())
v.Add(GetFieldName(*params, "Comment"), params.Comment)
v.Add(GetFieldName(*params, "Appli"), strconv.Itoa(params.Appli))
// Sending request to the API.
path := fmt.Sprintf("%s?%s", createNotficationURL, v.Encode())
if u.Client.IncludePath {
createNotificationResponse.Path = path
}
req, err := http.NewRequest("GET", path, nil)
req = req.WithContext(ctx)
if err != nil {
return createNotificationResponse, fmt.Errorf("failed to build request: %s", err)
}
resp, err := u.HTTPClient.Do(req)
if err != nil {
return createNotificationResponse, err
}
defer resp.Body.Close()
// Processing API response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return createNotificationResponse, err
}
if u.Client.SaveRawResponse {
createNotificationResponse.RawResponse = body
}
err = json.Unmarshal(body, &createNotificationResponse)
if err != nil {
return createNotificationResponse, err
}
if createNotificationResponse.Status != status.OperationWasSuccessful {
return createNotificationResponse, fmt.Errorf("api returned an error: %s", createNotificationResponse.Error)
}
return createNotificationResponse, nil
}
// ListNotifications is the same as ListNotificationsCtx but doesn't require a context to be provided.
func (u *User) ListNotifications(params *ListNotificationsParam) (ListNotificationsResp, error) {
ctx, cancel := u.Client.getContext()
defer cancel()
return u.ListNotificationsCtx(ctx, params)
}
// ListNotificationsCtx lists all the notifications found for the user.
func (u *User) ListNotificationsCtx(ctx context.Context, params *ListNotificationsParam) (ListNotificationsResp, error) {
listNotificationResponse := ListNotificationsResp{}
// Building query params.
v := url.Values{}
t, err := u.Token()
if err != nil {
return listNotificationResponse, fmt.Errorf("failed to obtain token: %s", err)
}
v.Add("access_token", t.AccessToken)
v.Add("action", "list")
if params != nil {
if params.Appli != nil {
v.Add(GetFieldName(*params, "Appli"), strconv.Itoa(*params.Appli))
}
}
// Sending request to the API.
path := fmt.Sprintf("%s?%s", listNotificationsURL, v.Encode())
if u.Client.IncludePath {
listNotificationResponse.Path = path
}
req, err := http.NewRequest("GET", path, nil)
req = req.WithContext(ctx)
if err != nil {
return listNotificationResponse, fmt.Errorf("failed to build request: %s", err)
}
resp, err := u.HTTPClient.Do(req)
if err != nil {
return listNotificationResponse, err
}
defer resp.Body.Close()
// Processing API response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return listNotificationResponse, err
}
if u.Client.SaveRawResponse {
listNotificationResponse.RawResponse = body
}
err = json.Unmarshal(body, &listNotificationResponse)
if err != nil {
return listNotificationResponse, err
}
if listNotificationResponse.Status != status.OperationWasSuccessful {
return listNotificationResponse, fmt.Errorf("api returned error: %s", listNotificationResponse.Error)
}
// Parse dates
if listNotificationResponse.Body != nil {
for i := range listNotificationResponse.Body.Profiles {
d := time.Unix(listNotificationResponse.Body.Profiles[0].Expires, 0)
listNotificationResponse.Body.Profiles[i].ExpiresParsed = &d
}
}
return listNotificationResponse, nil
}
// GetNotificationInformation is the same as GetNotificationInformationCtx but doesn't require a context to be provided.
func (u *User) GetNotificationInformation(params *NotificationInfoParam) (NotificationInfoResp, error) {
ctx, cancel := u.Client.getContext()
defer cancel()
return u.GetNotificationInformationCtx(ctx, params)
}
// GetNotificationInformationCtx lists all the notifications found for the user.
func (u *User) GetNotificationInformationCtx(ctx context.Context, params *NotificationInfoParam) (NotificationInfoResp, error) {
notificationInfoResponse := NotificationInfoResp{}
// Building query params.
v := url.Values{}
t, err := u.Token()
if err != nil {
return notificationInfoResponse, fmt.Errorf("failed to obtain token: %s", err)
}
v.Add("access_token", t.AccessToken)
v.Add("action", "get")
if params == nil {
params = &NotificationInfoParam{}
}
v.Add(GetFieldName(*params, "CallbackURL"), params.CallbackURL.String())
v.Add(GetFieldName(*params, "Appli"), strconv.Itoa(*params.Appli))
// Sending reqeust to the API.
path := fmt.Sprintf("%s?%s", getNotificationInformationURL, v.Encode())
if u.Client.IncludePath {
notificationInfoResponse.Path = path
}
req, err := http.NewRequest("GET", path, nil)
req = req.WithContext(ctx)
if err != nil {
return notificationInfoResponse, fmt.Errorf("failed to build request: %s", err)
}
resp, err := u.HTTPClient.Do(req)
if err != nil {
return notificationInfoResponse, err
}
defer resp.Body.Close()
// Processing API response.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return notificationInfoResponse, err
}
if u.Client.SaveRawResponse {
notificationInfoResponse.RawResponse = body
}
err = json.Unmarshal(body, ¬ificationInfoResponse)
if err != nil {
return notificationInfoResponse, err
}
if notificationInfoResponse.Status != status.OperationWasSuccessful {
return notificationInfoResponse, fmt.Errorf("api returned an error: %s", notificationInfoResponse.Error)
}
// Parse dates
if notificationInfoResponse.Body != nil {
d := time.Unix(notificationInfoResponse.Body.Expires, 0)
notificationInfoResponse.Body.ExpiresParsed = &d
}
return notificationInfoResponse, nil
}
// RevokeNotification is the same as RevokeNotificationCtx but doesn't require a context to be provided.
func (u *User) RevokeNotification(params *RevokeNotificationParam) (RevokeNotificationResp, error) {
ctx, cancel := u.Client.getContext()
defer cancel()
return u.RevokeNotificationCtx(ctx, params)
}
// RevokeNotificationCtx revokes a notification so it no longer sends.
func (u *User) RevokeNotificationCtx(ctx context.Context, params *RevokeNotificationParam) (RevokeNotificationResp, error) {
revokeResponse := RevokeNotificationResp{}
// Building query params.
v := url.Values{}
t, err := u.Token()
if err != nil {
return revokeResponse, fmt.Errorf("failed to obtain token: %s", err)
}
v.Add("access_token", t.AccessToken)
v.Add("action", "revoke")
if params == nil {
params = &RevokeNotificationParam{}
}
v.Add(GetFieldName(*params, "CallbackURL"), params.CallbackURL.String())
v.Add(GetFieldName(*params, "Appli"), strconv.Itoa(*params.Appli))
// Sending request to the API.
path := fmt.Sprintf("%s?%s", revokeNotificationURL, v.Encode())
if u.Client.IncludePath {
revokeResponse.Path = path
}
req, err := http.NewRequest("GET", path, nil)
req = req.WithContext(ctx)
if err != nil {
return revokeResponse, fmt.Errorf("failed to build request: %s", err)
}
resp, err := u.HTTPClient.Do(req)
if err != nil {