-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
1179 lines (1083 loc) · 37.7 KB
/
index.js
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
// == BSD2 LICENSE ==
// Copyright (c) 2014, Tidepool Project
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the associated License, which is identical to the BSD 2-Clause
// License as published by the Open Source Initiative at opensource.org.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the License for more details.
//
// You should have received a copy of the License along with this program; if
// not, you can obtain one from Tidepool Project at tidepool.org.
// == BSD2 LICENSE ==
'use strict';
var _ = require('lodash');
var uuidv4 = require('uuid/v4');
var id = require('./lib/id.js');
function requireProperty(objectName, obj, property) {
var value = obj[property];
if (value == null) {
throw new Error('Property [' + property + '] required on ' + objectName);
}
return value;
}
var requireConfig = requireProperty.bind(null, 'config');
var requireDep = requireProperty.bind(null, 'deps');
module.exports = function (config, deps) {
var superagent = requireDep(deps, 'superagent');
var log = requireDep(deps, 'log');
config = _.clone(config);
requireConfig(config, 'host');
requireConfig(config, 'metricsSource');
requireConfig(config, 'metricsVersion');
// now clean up source so that it doesn't have any dashes
// this way, the first dash in the eventname will be the separator for the source
config.metricsSource = config.metricsSource.replace(/-/g, ' ');
var common = require('./lib/common.js')(config, deps);
var confirm = require('./confirm.js')( common, {superagent:superagent, findProfile: findProfile});
var user = require('./user.js')( common, config, deps);
var prescription = require('./prescription.js')( common, {superagent:superagent});
var devices = require('./devices.js')( common, {superagent:superagent});
var clinics = require('./clinics.js')( common, {superagent:superagent});
/**
* Add a new or update an existing metadata for a user
*
* @param {String} userId id of the user you are updating the profile of
* @param {Object} payload object
* @param {String} type the type of metadata collection (e.g., preferences, profile, or settings)
* @param cb
* @returns {cb} cb(err, response)
*/
function addOrUpdateMetadata(userId, payload, type, cb) {
if (userId == null) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a userId' });
}
common.assertArgumentsSize(arguments, 4);
common.doPutWithToken(
'/metadata/' + userId + '/' + type,
payload,
cb
);
}
/**
* Find a user's metadata collection
*
* @param {String} userId id of the user you are finding the preferences of
* @param {String} type the type of metadata collection (e.g., preferences, profile, or settings)
* @param cb
* @returns {cb} cb(err, response)
*/
function findMetadata(userId, type, cb) {
if (userId == null) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a userId' });
}
common.assertArgumentsSize(arguments, 3);
common.doGetWithToken('/metadata/' + userId + '/' + type, cb);
}
/**
* Find a user's profile
*
* @param {String} userId id of the user you are finding the profile of
* @param cb
* @returns {cb} cb(err, response)
*/
function findProfile (userId, cb) {
findMetadata(userId, 'profile', cb);
}
/**
* format error with response body and session token
*
* @param {Error} err with the response body
* @returns {Error}
*/
function formatError (err) {
if (err.response && err.response.body) {
var error = err.response.body;
error.sessionToken = user.getUserToken();
return error;
}
return err;
}
return {
/**
* Do any requied initialization
*/
initialize: function(cb){
return user.initialize(cb);
},
/**
* Url used for uploads to the platform
*
* @returns {String} url for uploads
*/
getUploadUrl: common.getUploadUrl,
hasDataHost: common.hasDataHost,
setApiHost: common.setApiHost,
setUploadHost: common.setUploadHost,
setDataHost: common.setDataHost,
setBlipHost: common.setBlipHost,
makeBlipUrl: common.makeBlipUrl,
/**
* Post something to metrics.
* This call never errors, so the callback is optional; it will be called if supplied.
* This call also doesn't wait for the metrics call to return but returns immediately,
* so if the metrics site is down you won't know it.
* This call automatically adds a property client: true to the property list.
*
* @param eventname String name of event to post to kissmetrics
* @param properties Object list of key/value pairs to post as properties.
* @param cb If provided, is called without arguments after posting; this call never errors, so callback is optional.
* @returns {cb} cb()
*/
trackMetric: function (eventname, properties, cb) {
properties = _.assign({}, properties);
properties.sourceVersion = config.metricsVersion;
var doNothingCB = function() {
if (cb) {
cb();
}
};
if (!eventname) {
eventname = 'generic';
}
common.serviceCallChecks(
doNothingCB,
function(token){
superagent
.get(common.makeAPIUrl('/metrics/thisuser/' + config.metricsSource + ' - ' + eventname))
.set(common.SESSION_TOKEN_HEADER, token)
.set(common.TRACE_SESSION_HEADER, common.getSessionTrace())
.query(properties)
.retry()
.end(doNothingCB);
}
);
},
/**
* Post an application error so that it can be logged
*
* This call never errors, so the callback is optional; it will be called if supplied.
* This call also doesn't wait for the call to return but returns immediately.
*
* This call automatically adds a property client: true to the property list.
*
* @param error Object the error that will be logged
* @param message String an optional message
* @param properties Object list of key/value pairs to post as properties.
* @param cb If provided, is called without arguments after posting; this call never errors, so callback is optional.
* @returns {cb} cb()
*/
logAppError: function (error, message, properties, cb) {
properties = _.assign({}, properties);
properties.sourceVersion = config.metricsVersion;
properties.error = error;
if(message){
properties.message = message;
}
var eventname = 'application error';
var doNothingCB = function() {
if (cb) {
cb();
}
};
common.serviceCallChecks(
doNothingCB,
function(token){
superagent
.get(common.makeAPIUrl('/metrics/thisuser/' + config.metricsSource + ' - ' + eventname))
.set(common.SESSION_TOKEN_HEADER, token)
.set(common.TRACE_SESSION_HEADER, common.getSessionTrace())
.query(properties)
.retry()
.end(doNothingCB);
}
);
},
/**
* Add a new or update an existing preferences for a user
*
* @param {String} userId id of the user you are updating the preferences of
* @param {Object} preferences object
* @param cb
* @returns {cb} cb(err, response)
*/
addOrUpdatePreferences: function (userId, preferences, cb) {
addOrUpdateMetadata(userId, preferences, 'preferences', cb);
},
/**
* Add a new or update an existing profile for a user
*
* @param {String} userId id of the user you are updating the profile of
* @param {Object} profile object
* @param cb
* @returns {cb} cb(err, response)
*/
addOrUpdateProfile: function (userId, profile, cb) {
addOrUpdateMetadata(userId, profile, 'profile', cb);
},
/**
* Add a new or update an existing settings for a user
*
* @param {String} userId id of the user you are updating the settings of
* @param {Object} settings object
* @param cb
* @returns {cb} cb(err, response)
*/
addOrUpdateSettings: function (userId, settings, cb) {
addOrUpdateMetadata(userId, settings, 'settings', cb);
},
/**
* Find a user's preferences
*
* @param {String} userId id of the user you are finding the preferences of
* @param cb
* @returns {cb} cb(err, response)
*/
findPreferences: function (userId, cb) {
findMetadata(userId, 'preferences', cb);
},
/**
* Find a user's profile
*
* @param {String} userId id of the user you are finding the profile of
* @param cb
* @returns {cb} cb(err, response)
*/
findProfile: findProfile,
/**
* Find a user's settings
*
* @param {String} userId id of the user you are finding the settings of
* @param cb
* @returns {cb} cb(err, response)
*/
findSettings: function (userId, cb) {
findMetadata(userId, 'settings', cb);
},
/**
* Get the users 'team'
*
* @param {String} userId id of the user
* @param cb
* @returns {cb} cb(err, response)
*/
getTeamMembers: function (userId, cb) {
if (userId == null) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a userId' });
}
common.assertArgumentsSize(arguments, 2);
common.doGetWithToken(
'/access/' + userId,
{200: function(res){ return res.body; }, 404: null},
cb
);
},
/**
* Get the users 'patients'
*
* @param {String} userId id of the user
* @param cb
* @returns {cb} cb(err, response)
*/
getViewableUsers: function (userId, cb) {
if (userId == null) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a userId' });
}
common.assertArgumentsSize(arguments, 2);
common.doGetWithToken(
'/access/groups/' + userId,
{ 200: function(res){ return res.body; }, 404: null },
cb
);
},
/**
* Get the users 'patients' and their associated data
* includes profile, permissions and metadata
*
* @param {String} userId id of the user
* @param cb
* @returns {cb} cb(err, response)
*/
getAssociatedUsersDetails: function (userId, cb) {
if (userId == null) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a userId' });
}
common.assertArgumentsSize(arguments, 2);
common.doGetWithToken(
'/metadata/users/' + userId + '/users',
{ 200: function(res){ return res.body; }, 404: null },
cb
);
},
/**
* Get the users 'patients' to whom they can upload for.
*
* @param {String} userId of the user
* @param cb
* @returns {cb} cb(err, response)
*/
getUploadGroups: function (userId, cb) {
common.assertArgumentsSize(arguments, 2);
common.doGetWithToken(
'/access/groups/' + userId,
{ 200: function(res){
var groups = res.body;
var filter = {};
for(var i in groups) {
var group = groups[i];
if (group.root || group.upload) {
filter[i] = group;
}
}
return filter;
}, 404: null },
cb
);
},
/**
* Sets the access permissions for a specific user on the group for the currently logged in user
*
* @param userId - userId to have access permissions set for
* @param permissions - permissions to set
* @param cb - function(err, perms), called with error if exists and permissions as updated
*/
setAccessPermissions: function(userId, permissions, cb) {
if (userId == null) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a userId'});
}
common.doPostWithToken(
'/access/' + user.getUserId() + '/' + userId,
permissions,
cb
);
},
/**
* Sets the access permissions for a specific user on the given group
*
* @param groupId - the groupId we are setting user permissions on
* @param userId - userId to have access permissions set for
* @param permissions - permissions to set
* @param cb - function(err, perms), called with error if exists and permissions as updated
*/
setAccessPermissionsOnGroup: function(groupId, userId, permissions, cb) {
common.assertArgumentsSize(arguments, 4);
common.doPostWithToken(
'/access/' + groupId + '/' + userId,
permissions,
cb
);
},
/**
* Get the access permissions for a specific user on the given group
*
* @param groupId - the groupId we want permissions for
* @param userId - userId that has those permissions
* @param cb - function(err, perms), called with error if exists and permissions object
*/
getAccessPermissionsForGroup: function(groupId, userId, cb) {
common.assertArgumentsSize(arguments, 3);
common.doGetWithToken(
'/access/' + groupId + '/' + userId,
{ 200: function(res){ return res.body; }, 404: null },
cb
);
},
/**
* Get the listed users public info
*
* @param {Array} patientIds array of id's that we want the public info for
* @param cb
* @returns {cb} cb(err, response)
*/
getPatientsInfo: function (patientIds, cb) {
if (patientIds == null) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'Must specify a patientIds' });
}
common.assertArgumentsSize(arguments, 2);
var idList = _(patientIds).uniq().join(',');
common.doGetWithToken(
'/metadata/publicinfo?users=' + idList,
{ 200: function(res){ return res.body; }, 404: null },
cb
);
},
/**
* Get raw device data for the user
*
* @param {String} userId of the user to get the device data for
* @param {Object} options for the query
* @param cb
* @returns {cb} cb(err, response)
*/
getDeviceDataForUser: function (userId, options, cb) {
common.assertArgumentsSize(arguments, 3);
var allowedParams = [
'carelink',
'dexcom',
'medtronic',
'startDate',
'endDate',
'latest',
'type',
'uploadId',
'deviceId',
'subType',
];
// Generate url with any valid provided params
var url = common.appendUrlParamsFromOptions('/data/' + userId, options, allowedParams);
common.doGetWithToken(
url,
{ 200: function(res){ return res.body; }, 404: [] },
cb
);
},
/**
* Check the expected minimum versions for uploading
*
* @param cb
* @returns {cb} cb(err, response)
* e.g. {versions: {schema: 3, uploaderMinimum: '0.333.0'}}
*/
checkUploadVersions: function (cb) {
common.assertArgumentsSize(arguments, 1);
superagent
.get(common.makeUploadUrl('/info'))
.retry()
.end(
function (err, res) {
if (err != null) {
return cb(err);
}
return cb(null,res.body);
});
},
/**
* Get server time
*
* @param cb
* @returns {cb} cb(err, response)
*/
getTime: function (cb) {
superagent
.get(common.makeDataUrl('/v1/time'))
.retry()
.end(
function (err, res) {
if (err != null) {
return cb(err);
}
return cb(null,res.body);
});
},
/**
* Get the data sources for a given user
*
* @param {String} userId of the user to get the data sources for
* @param cb
* @returns {cb} cb(err, response)
*/
getDataSourcesForUser: function(userId, cb) {
common.assertArgumentsSize(arguments, 2);
common.doGetWithToken(
'/v1/users/' + userId + '/data_sources',
{ 200: function(res) { return res.body; } },
cb
);
},
/**
* Create a dataset for the given user
*
* @param {String} userId of the user to create the dataset for
* @param {Object} info for the dataset
* @param cb
* @returns {cb} cb(err, response)
*/
createDatasetForUser: function (userId, info, cb) {
common.assertArgumentsSize(arguments, 3);
if (!common.hasDataHost()) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'The data host needs to be configured' });
}
superagent
.post(common.makeDataUrl('/v1/users/' + userId + '/datasets'))
.send(info)
.set(common.SESSION_TOKEN_HEADER, user.getUserToken())
.set(common.TRACE_SESSION_HEADER, common.getSessionTrace())
.retry()
.end(
function (err, res) {
if (err != null) {
if (err.status !== 201) {
return cb(formatError(err));
}
return cb(err);
} else if (res.error === true) {
if(_.isObject(res.body)) {
return cb(res.body); // for our custom error arrays
} else {
return cb(res.error);
}
} else if (res.status !== 201) {
return cb(new Error('Unexpected HTTP response: ' + res.status));
}
return cb(null, res.body);
});
},
/**
* Finalize the given dataset (close and post-process)
*
* @param {String} datasetId of the dataset to finalize
* @param cb
* @returns {cb} cb(err, response)
*/
finalizeDataset: function (datasetId, cb) {
common.assertArgumentsSize(arguments, 2);
if (!common.hasDataHost()) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'The data host needs to be configured' });
}
superagent
.put(common.makeDataUrl('/v1/datasets/' + datasetId))
.send({dataState: 'closed'})
.set(common.SESSION_TOKEN_HEADER, user.getUserToken())
.set(common.TRACE_SESSION_HEADER, common.getSessionTrace())
.retry()
.end(
function (err, res) {
if (err != null) {
if (err.status !== 200) {
return cb(formatError(err));
}
return cb(err);
} else if (res.status !== 200) {
return cb(res.body);
}
return cb();
});
},
/**
* Add data to the given dataset
*
* @param {String} datasetId of the dataset to add data
* @param {Object} data to be added
* @param cb
* @returns {cb} cb(err, response)
*/
addDataToDataset: function (datasetId, data, cb) {
common.assertArgumentsSize(arguments, 3);
if (!common.hasDataHost()) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'The data host needs to be configured' });
}
superagent
.post(common.makeDataUrl('/v1/datasets/' + datasetId + '/data'))
.send(data)
.set(common.SESSION_TOKEN_HEADER, user.getUserToken())
.set(common.TRACE_SESSION_HEADER, common.getSessionTrace())
.retry()
.end(
function (err, res) {
if (err != null) {
if (err.status !== 200) {
return cb(formatError(err));
}
return cb(err);
} else if (res.status !== 200) {
return cb(res.body);
}
return cb(null,res.body);
});
},
/**
* Upload device data for the given user
*
* @param {String} userId of the user to get the device data for
* @param {Object} data to be uploaded
* @param cb
* @returns {cb} cb(err, response)
*/
uploadDeviceDataForUser: function (userId, data, cb) {
common.assertArgumentsSize(arguments, 3);
if (_.isEmpty(common.getUploadUrl())) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'The upload api needs to be configured' });
}
superagent
.post(common.makeUploadUrl('/data/'+userId))
.send(data)
.set(common.SESSION_TOKEN_HEADER, user.getUserToken())
.set(common.TRACE_SESSION_HEADER, common.getSessionTrace())
.retry()
.end(
function (err, res) {
if (err != null) {
if (err.status !== 200) {
return cb((err.response && err.response.body) || err);
}
return cb(err);
} else if (res.status !== 200) {
return cb(res.body);
}
return cb(null,res.body);
});
},
/**
* Upload blob data for the given user
*
* @param {String} userId of the user to get the device data for
* @param {Object} blob to be uploaded
* @param {String} contentType of blob, e.g. 'application/json'
* @param cb
* @returns {cb} cb(err, response)
*/
uploadBlobForUser: function (userId, blob, contentType, digest, cb) {
common.assertArgumentsSize(arguments, 5);
if (!common.hasDataHost()) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'The data host needs to be configured' });
}
superagent
.post(common.makeAPIUrl('/v1/users/' + userId + '/blobs'))
.send(blob)
.set(common.SESSION_TOKEN_HEADER, user.getUserToken())
.set(common.TRACE_SESSION_HEADER, common.getSessionTrace())
.set(common.DIGEST_HEADER, digest)
.type(contentType)
.retry()
.end(
function (err, res) {
if (err != null) {
if (err.status !== 201) {
return cb(formatError(err));
}
return cb(err);
} else if (res.error === true) {
return cb(res.error);
} else if (res.status !== 201) {
return cb(new Error('Unexpected HTTP response: ' + res.status));
}
return cb(null, res.body);
});
},
/**
* Start an device upload session by generating an uploadMeta record
*
* @param {Object} sessionInfo to initialise the upload session
* @param cb
* @returns {cb} cb(err, uploadMeta)
*/
startUploadSession: function (sessionInfo, cb) {
common.assertArgumentsSize(arguments, 2);
var fields = ['version', 'deviceTags', 'deviceManufacturers',
'deviceModel', 'deviceSerialNumber', 'deviceId'];
_.each(fields, function(field) {
if (!_.has(sessionInfo, field)) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'sessionInfo is missing "' + field +'"' });
}
});
if (_.isEmpty(sessionInfo.start) || _.isEmpty(sessionInfo.tzName)) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'sessionInfo must contain both tzName and start' });
}
try {
var uploadMeta = _.pick(sessionInfo, fields);
uploadMeta.type = 'upload';
uploadMeta.time = sessionInfo.start;
uploadMeta.timezone = sessionInfo.tzName;
uploadMeta.uploadId = id.generateId([sessionInfo.deviceId, sessionInfo.start]);
uploadMeta.byUser = user.getUserId();
// this is to permit us to continue to identify carelink data
if (sessionInfo.source) {
uploadMeta.source = sessionInfo.source;
}
return cb(null,uploadMeta);
} catch (error) {
return cb(error);
}
},
/**
* Upload carelink data for the logged in user
*
* @param {Object} formData for the carelink upload
* @param cb
* @returns {cb} cb(err, response)
*/
uploadCarelinkDataForUser: function (formData, cb) {
common.assertArgumentsSize(arguments, 2);
//waiting for our task to finish
function waitForSyncTaskWithIdToFinish(syncTaskId,callback){
// Polling frequency, in milliseconds
var pollingInterval = 3 * 1000;
// When to give up, in milliseconds
var pollingTimeout = 5 * 60 * 1000;
var pollingTimedOut = false;
setTimeout(function () {
pollingTimedOut = true;
}, pollingTimeout);
// Start long-polling
log.info('Starting sync task long polling with id', syncTaskId);
(function poll(done) {
setTimeout(function () {
superagent
.get(common.makeUploadUrl('/v1/synctasks/' + syncTaskId))
.set(common.SESSION_TOKEN_HEADER, user.getUserToken())
.set(common.TRACE_SESSION_HEADER, common.getSessionTrace())
.retry()
.end(
function (err, res) {
if (!_.isEmpty(err)) {
err.body = (err.response && err.response.body) || '';
log.info('Sync failed', JSON.stringify(err));
return done(err);
}
if (res.status !== 200) {
return common.handleHttpError(res, done);
}
var syncTask = res.body;
log.info('Sync task poll complete', syncTask);
if (syncTask.status === 'error') {
return done({message: 'Sync task failed', error: syncTask.error});
}
if (syncTask.status === 'success') {
log.info('Carelink download success');
return done(null, syncTask);
}
poll(done);
});
}, pollingInterval);
}(callback));
}
//download the file and returns its contents
superagent
.post(common.makeUploadUrl('/v1/device/upload/cl'))
.send(formData)
.type('form')
.set(common.SESSION_TOKEN_HEADER, user.getUserToken())
.set(common.TRACE_SESSION_HEADER, common.getSessionTrace())
.retry()
.end(
function (err, res) {
if (!_.isEmpty(err)) {
err.body = (err.response && err.response.body) || '';
log.info('Upload Failed');
return cb(err);
}
if (res.status !== 200) {
log.info('Upload Failed');
return common.handleHttpError(res, cb);
}
var syncTask = res.body;
var syncTaskId = syncTask.id;
if (!syncTaskId) {
log.info('Upload Failed');
return cb({message: 'No sync task id'});
}
waitForSyncTaskWithIdToFinish(syncTaskId,function(err,data){
if (!_.isEmpty(err)) {
log.info('Return failure from uploadCarelinkDataForUser');
return cb(err);
}
return cb(null,data);
});
});
},
/**
* Upload carelink data for the logged in user
*
* @param {string} dataId for the carelink upload
* @param cb
* @returns {cb} cb(err, response)
*/
getCarelinkData: function (dataId, cb) {
common.assertArgumentsSize(arguments, 2);
//get the contents of the carelink csv file
superagent
.get(common.makeUploadUrl('/v1/device/data/' + dataId))
.set(common.SESSION_TOKEN_HEADER, user.getUserToken())
.set(common.TRACE_SESSION_HEADER, common.getSessionTrace())
.retry()
.end(
function (err, res) {
if (err) {
err.body = (err.response && err.response.body) || '';
return cb(err);
}
if (res.status !== 200) {
return common.handleHttpError(res, cb);
}
return cb(null, res.text);
});
},
/**
* Get upload records for the given user and device
*
* @param {String} userId of the user
* @param {String} deviceId of the device
* @param {String} size of the array to return
* @param cb
* @returns {cb} cb(err, response)
*/
getUploadRecordsForDevice: function (userId, deviceId, size, cb) {
common.assertArgumentsSize(arguments, 4);
if (!common.hasDataHost()) {
return cb({ status : common.STATUS_BAD_REQUEST, message: 'The data host needs to be configured' });
}
superagent
.get(common.makeDataUrl('/v1/users/' + userId + '/data_sets?deviceId=' + deviceId + '&size=' + size))
.set(common.SESSION_TOKEN_HEADER, user.getUserToken())
.set(common.TRACE_SESSION_HEADER, common.getSessionTrace())
.retry()
.end(
function (err, res) {
if (err) {
err.body = (err.response && err.response.body) || '';
return cb(err);
}
if (res.status !== 200) {
return common.handleHttpError(res, cb);
}
return cb(null, res.body);
});
},
/**
* Get messages for a team between the given dates
*
* @param {String} userId of the user to get the messages for
* @param {Object} options
* @param {String} options.start [start=''] the start date is optional
* @param {String} options.end [end=''] the end date is optional
* @param cb
* @returns {cb} cb(err, response)
*/
getAllMessagesForUser: function (userId, options, cb) {
common.assertArgumentsSize(arguments, 3);
options = options || {};
var start = options.start || '';
var end = options.end || '';
common.doGetWithToken(
'/message/all/' + userId + '?starttime=' + start + '&endtime=' + end,
{ 200: function(res){ return res.body.messages; }, 404: [] },
cb
);
},
/**
* Get all notes within a specified date range
*
* @param {String} userId of the user to get the notes for
* @param {Object} options
* @param {String} options.start [start=''] the start date is optional
* @param {String} options.end [end=''] the end date is optional
* @param cb
* @returns {cb} cb(err, response)
*/
getNotesForUser: function (userId, options, cb) {
common.assertArgumentsSize(arguments, 3);
options = options || {};
var start = options.start || '';
var end = options.end || '';
common.doGetWithToken(
'/message/notes/' + userId + '?starttime=' + start + '&endtime=' + end,
{ 200: function(res){ return res.body.messages; }, 404: [] },
cb
);
},
/**
* Reply to a specfic message thread
*
* @param {Object} comment on the message thread
* @param {String} comment.timestamp
* @param {String} comment.messagetext
* @param {String} comment.groupid
* @param {String} comment.userid
* @param {String} comment.parentmessage
* @param cb
* @returns {cb} cb(err, response)
*/
replyToMessageThread: function (comment, cb) {
common.assertArgumentsSize(arguments, 2);
common.doPostWithToken(
'/message/reply/' + comment.parentmessage,
{ message: _.assign(comment, {guid: uuidv4()}) },
{ 201: function(res){ return res.body.id; }},
cb
);
},
/**
* Start a new message thread
*
* @param {Object} message that is the start of a new thread
* @param {String} message.messagetext
* @param {String} message.timestamp
* @param {String} message.groupid
* @param {String} message.userid
* @param cb