-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathdevice.js
More file actions
1035 lines (881 loc) · 29.2 KB
/
device.js
File metadata and controls
1035 lines (881 loc) · 29.2 KB
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
// Internal Dependencies
import {deprecated, oneFlight} from '@webex/common';
import {persist, waitForValue, WebexPlugin} from '@webex/webex-core';
import {safeSetTimeout} from '@webex/common-timers';
import {orderBy} from 'lodash';
import uuid from 'uuid';
import METRICS from './metrics';
import {FEATURE_COLLECTION_NAMES, DEVICE_EVENT_REGISTRATION_SUCCESS} from './constants';
import FeaturesModel from './features/features-model';
import IpNetworkDetector from './ipNetworkDetector';
import {CatalogDetails} from './types';
/**
* Determine if the plugin should be initialized based on cached storage.
*
* @returns {boolean} - If the device is ephemeral.
*/
function decider() {
return !this.config.ephemeral;
}
const Device = WebexPlugin.extend({
// Ampersand property members.
namespace: 'Device',
// Allow for extra properties to prevent the plugin from failing due to
// **WDM** service DTO changes.
extraProperties: 'allow',
idAttribute: 'url',
children: {
/**
* The class object that contains all of the feature collections.
*
* @type {FeaturesModel}
*/
features: FeaturesModel,
/**
* Helper class for detecting what IP network version (ipv4, ipv6) we're on.
*
* @type {IpNetworkDetector}
*/
ipNetworkDetector: IpNetworkDetector,
},
/**
* A collection of device properties mostly assigned by the retrieved DTO from
* the **WDM** service that are mapped against the ampersand properties.
*
* @type {Object}
*/
props: {
/**
* This property determines whether or not giphy support is enabled.
*
* @type {'ALLOW' | 'BLOCK'}
*/
clientMessagingGiphy: 'string',
/**
* This property should store the company name.
*
* @type {string}
*/
customerCompanyName: 'string',
/**
* This property should store the logo url.
*
* @type {string}
*/
customerLogoUrl: 'string',
/**
* This property doesn't have any real values, but is sent during device
* refresh to prevent the **wdm** service from falling back to an iOS device
* type.
*
* @type {string}
*/
deviceType: 'string',
/**
* This property should store the help url.
*
* @type {string}
*/
helpUrl: 'string',
/**
* This property should store the intranet inactivity timer duration.
*
* @type {number}
*/
intranetInactivityDuration: 'number',
/**
* This property stores the url required to validate if the device is able
* to actively reach the intranet network.
*
* @type {string}
*/
intranetInactivityCheckUrl: 'string',
/**
* This property stores the inactivity timer duration, and could possibly
* deprecate the `intranetInactivityDuration` property.
*
* @type {number}
*/
inNetworkInactivityDuration: 'number',
/**
* This property stores the ECM (external content management) enabled value
* for the whole organization.
*
* @type {boolean}
*/
ecmEnabledForAllUsers: ['boolean', false, false],
/**
* This property stores an array of ECM (external content management)
* providers that are currently available.
*
* @returns {Array<string>}
*/
ecmSupportedStorageProviders: ['array', false, () => []],
/**
* This property stores the modification time value retrieved from the
* **WDM** endpoint formatted as ISO 8601.
*
* @type {string}
*/
modificationTime: 'string',
/**
* This property stores the navigation bar color.
*
* @type {string}
*/
navigationBarColor: 'string',
/**
* This property stores the partner company's name when available.
*
* @type {string}
*/
partnerCompanyName: 'string',
/**
* This property stores the partner company's logo when available.
*
* @type {string}
*/
partnerLogoUrl: 'string',
/**
* This property stores the availability of people data from the **WDM**
* service.
*
* @type {boolean}
*/
peopleInsightsEnabled: 'boolean',
/**
* This property stores the reporting site's description when available.
*
* @type {string}
*/
reportingSiteDesc: 'string',
/**
* This property stores the reporting site's access url when available.
*
* @type {string}
*/
reportingSiteUrl: 'string',
/**
* This property stores the encryption key url when available.
*
* @type {string}
*/
searchEncryptionKeyUrl: 'string',
/**
* This property stores the availability of support-provided text from the
* **WDM** service.
*
* @type {boolean}
*/
showSupportText: 'boolean',
/**
* This property stores the support provider's company name when available.
*
* @type {string}
*/
supportProviderCompanyName: 'string',
/**
* This property stores the support provider's logo url when available.
*
* @type {string}
*/
supportProviderLogoUrl: 'string',
/**
* This property stores the device's url retrieved from a registration
* request. This property gets set via the initial registration process by a
* `this.set()` method.
*
* @type {string}
*/
url: 'string',
/**
* This property stores the device's userId uuid value, which can also be
* derived from the device's registerd user's userId retrieved from
* the **Hydra** service.
*
* @type {string}
*/
userId: 'string',
/**
* This property stores whether or not file sharing is enabled
*
* @type {'BLOCK_BOTH' | 'BLOCK_UPLOAD'}
*/
webFileShareControl: 'string',
/**
* This property stores the current web socket url used by the registered
* device.
*
* @type {string}
*/
webSocketUrl: 'string',
/**
* This property stores the value indicating whether or not white board file
* sharing is enabled for the current device.
*
* @type {'ALLOW' | 'BLOCK'}
*/
whiteboardFileShareControl: 'string',
},
/**
* A list of derived properties that populate based when their parent data
* available via the device's properties.
*
* @type {Object}
*/
derived: {
/**
* This property determines if the current device is registered.
*
* @type {boolean}
*/
registered: {
deps: ['url'],
/**
* Checks if the device is registered by validating that the url exists.
* Amperstand does not allow this to method to be written as an arrow
* function.
*
* @returns {boolean}
*/
fn() {
return !!this.url;
},
},
},
/**
* Stores timer data as well as other state details.
*
* @type {Object}
*/
session: {
/**
* This property stores the logout timer object
*
* @type {any}
*/
logoutTimer: 'any',
/**
* This property stores the date for the last activity the user made
* with the current device.
*
* @type {number}
*/
lastUserActivityDate: 'number',
/**
* This property stores whether or not the reachability check has been
* performed to prevent the reachability check from performing its
* operation more than once after a successful check.
*
* @returns {boolean}
*/
isReachabilityChecked: ['boolean', false, false],
/**
* This property stores whether or not the next refresh or register request should request energy forecast data
* in order to prevent over fetching energy forecasts
*
* @type {boolean}
*/
energyForecastConfig: 'boolean',
/**
* This property stores whether or not the current device is in a meeting
* to prevent an unneeded timeout of a meeting due to inactivity.
*
* @type {boolean}
*/
isInMeeting: 'boolean',
/**
* This property identifies if the device is currently in network to prevent
* the `resetLogoutTimer()` method from being called repeatedly once its
* known client is connected to the organization's internal network.
*
* @type {boolean}
*/
isInNetwork: 'boolean',
},
// Event method members.
/**
* Trigger meeting started event for webex instance. Used by web-client team.
*
* @returns {void}
*/
meetingStarted() {
this.webex.trigger('meeting started');
},
/**
* Trigger meeting ended event for webex instance. Used by web-client team.
*
* @returns {void}
*/
meetingEnded() {
this.webex.trigger('meeting ended');
},
/**
* Set the value of energy forecast config for the current registered device.
* @param {boolean} [energyForecastConfig=false] - fetch an energy forecast on the next refresh/register
* @returns {void}
*/
setEnergyForecastConfig(energyForecastConfig = false) {
this.energyForecastConfig = energyForecastConfig;
},
// Registration method members
/**
* Refresh the current registered device if able.
*
* @param {DeviceRegistrationOptions} options - The options for refresh.
* @param {CatalogDetails} options.includeDetails - The details to include in the refresh/register request.
* @returns {Promise<void, Error>}
*/
@oneFlight
@waitForValue('@')
refresh(deviceRegistrationOptions = {}) {
this.logger.info('device: refreshing');
// Validate that the device can be registered.
return this.canRegister().then(() => {
// Validate if the device is not registered and register instead.
if (!this.registered) {
this.logger.info('device: device not registered, registering');
return this.register(deviceRegistrationOptions);
}
// Merge body configurations, overriding defaults.
const body = {
...this.serialize(),
...(this.config.body ? this.config.body : {}),
};
// Remove unneeded properties from the body object.
delete body.features;
delete body.mediaCluster;
delete body.etag;
// Append a ttl value if the device is marked as ephemeral.
if (this.config.ephemeral) {
body.ttl = this.config.ephemeralDeviceTTL;
}
// Merge header configurations, overriding defaults.
const headers = {
...(this.config.defaults.headers ? this.config.defaults.headers : {}),
...(this.config.headers ? this.config.headers : {}),
// If etag is sent, WDM will not send developer feature toggles unless they have changed
...(this.etag ? {'If-None-Match': this.etag} : {}),
};
const {includeDetails = CatalogDetails.all} = deviceRegistrationOptions;
const requestId = uuid.v4();
this.set('refresh-request-id', requestId);
return this.request({
method: 'PUT',
uri: this.url,
body,
headers,
qs: {
includeUpstreamServices: `${includeDetails}${
this.config.energyForecast && this.energyForecastConfig ? ',energyforecast' : ''
}`,
},
})
.then((response) => {
// If we've signed out in the mean time, the request ID will have changed
if (this.get('refresh-request-id') !== requestId) {
this.logger.info('device: refresh request ID mismatch, ignoring response');
return Promise.resolve();
}
return this.processRegistrationSuccess(response);
})
.catch((reason) => {
// Handle a 404 error, which indicates that the device is no longer
// valid and needs to be registered as a new device.
if (reason.statusCode === 404) {
this.logger.info('device: refresh failed, device is not valid');
this.logger.info('device: attempting to register a new device');
this.clear();
return this.register(deviceRegistrationOptions);
}
return Promise.reject(reason);
});
});
},
/**
* Fetches the web devices and deletes the third of them which are not recent devices in use
* @returns {Promise<void, Error>}
*/
deleteDevices() {
// Fetch devices with a GET request
return this.request({
method: 'GET',
service: 'wdm',
resource: 'devices',
})
.then((response) => {
const {devices} = response.body;
const {deviceType} = this._getBody();
// Filter devices of type deviceType
const webDevices = devices.filter((item) => item.deviceType === deviceType);
const sortedDevices = orderBy(webDevices, [(item) => new Date(item.modificationTime)]);
// If there are more than two devices, delete the last third
if (sortedDevices.length > 2) {
const totalItems = sortedDevices.length;
const countToDelete = Math.ceil(totalItems / 3);
const urlsToDelete = sortedDevices.slice(0, countToDelete).map((item) => item.url);
return Promise.race(
urlsToDelete.map((url) => {
return this.request({
uri: url,
method: 'DELETE',
});
})
);
}
return Promise.resolve();
})
.catch((error) => {
this.logger.error('Failed to retrieve devices:', error);
return Promise.reject(error);
});
},
/**
* Registers and when fails deletes devices
*/
@waitForValue('@')
register(deviceRegistrationOptions = {}) {
this.logger.info('device: registering');
this.webex.internal.newMetrics.callDiagnosticMetrics.setDeviceInfo(this);
// Validate that the device can be registered.
return this.canRegister().then(() => {
// Validate if the device is already registered and refresh instead.
if (this.registered) {
this.logger.info('device: device already registered, refreshing');
return this.refresh(deviceRegistrationOptions);
}
return this._registerInternal(deviceRegistrationOptions).catch((error) => {
if (error?.body?.message === 'User has excessive device registrations') {
return this.deleteDevices().then(() => {
return this._registerInternal(deviceRegistrationOptions);
});
}
throw error;
});
});
},
_getBody() {
return {
...(this.config.defaults.body ? this.config.defaults.body : {}),
...(this.config.body ? this.config.body : {}),
};
},
/**
* Register or refresh a device depending on the current device state. Device
* registration utilizes the services plugin to send the request to the
* **WDM** service.
*
* @param {Object} options - The options for registration.
* @param {CatalogDetails} options.includeDetails - The details to include in the refresh/register request.
* @returns {Promise<void, Error>}
*/
@oneFlight
@waitForValue('@')
_registerInternal(deviceRegistrationOptions = {}) {
this.logger.info('device: making registration request');
// Merge body configurations, overriding defaults.
const body = this._getBody();
// Merge header configurations, overriding defaults.
const headers = {
...(this.config.defaults.headers ? this.config.defaults.headers : {}),
...(this.config.headers ? this.config.headers : {}),
};
// Append a ttl value if the device is marked as ephemeral
if (this.config.ephemeral) {
body.ttl = this.config.ephemeralDeviceTTL;
}
this.webex.internal.newMetrics.submitInternalEvent({
name: 'internal.register.device.request',
});
const {includeDetails = CatalogDetails.all} = deviceRegistrationOptions;
const requestId = uuid.v4();
this.set('register-request-id', requestId);
// This will be replaced by a `create()` method.
return this.request({
method: 'POST',
service: 'wdm',
resource: 'devices',
body,
headers,
qs: {
includeUpstreamServices: `${includeDetails}${
this.config.energyForecast && this.energyForecastConfig ? ',energyforecast' : ''
}`,
},
})
.catch((error) => {
this.webex.internal.newMetrics.submitInternalEvent({
name: 'internal.register.device.response',
});
throw error;
})
.then((response) => {
// If we've signed out in the mean time, the request ID will have changed
if (this.get('register-request-id') !== requestId) {
this.logger.info('device: register request ID mismatch, ignoring response');
return Promise.resolve();
}
// Do not add any processing of response above this as that will affect timestamp
this.webex.internal.newMetrics.submitInternalEvent({
name: 'internal.register.device.response',
});
this.webex.internal.metrics.submitClientMetrics(METRICS.JS_SDK_WDM_REGISTRATION_SUCCESSFUL);
return this.processRegistrationSuccess(response);
})
.catch((error) => {
this.webex.internal.metrics.submitClientMetrics(METRICS.JS_SDK_WDM_REGISTRATION_FAILED, {
fields: {error},
});
throw error;
});
},
/**
* Unregister the current registered device if available. Unregistering a
* device utilizes the services plugin to send the request to the **WDM**
* service.
*
* @returns {Promise<void, Error>}
*/
@oneFlight
@waitForValue('@')
unregister() {
this.logger.info('device: unregistering');
if (!this.registered) {
this.logger.warn('device: not registered');
return Promise.resolve();
}
return this.request({
uri: this.url,
method: 'DELETE',
})
.then(() => this.clear())
.catch((reason) => {
if (reason.statusCode === 404) {
this.logger.info(
'device: 404 when deleting device, device is already deleted, clearing device'
);
this.clear();
}
throw reason;
});
},
/* eslint-enable require-jsdoc */
// Helper method members
/**
* Determine if registration methods can be performed. This method utilizes
* the `services` plugin to confirm if the appropriate service urls are
* available for device registration.
*
* @returns {Promise<void, Error>}
*/
canRegister() {
this.logger.info('device: validating if registration can occur');
// Destructure the services plugin for ease of reference.
const {services} = this.webex.internal;
// Wait for the postauth catalog to populate.
return services.waitForCatalog('postauth', this.config.canRegisterWaitDuration).then(() =>
// Validate that the service exists after waiting for the catalog.
services.get('wdm')
? Promise.resolve()
: Promise.reject(
new Error(
[
'device: cannot register,',
"'wdm' service is not available from the postauth catalog",
].join(' ')
)
)
);
},
/**
* Check if the device can currently reach the inactivity check url.
*
* @returns {Promise<void, Error>}
*/
checkNetworkReachability() {
this.logger.info('device: checking network reachability');
// Validate if the device has been checked and reset the logout timer.
if (this.isReachabilityChecked) {
return Promise.resolve(this.resetLogoutTimer());
}
this.isReachabilityChecked = true;
// Validate if the device has a intranet checking url.
if (!this.intranetInactivityCheckUrl) {
this.isInNetwork = false;
return Promise.resolve(this.resetLogoutTimer());
}
// Clear unnecessary headers for reachability request.
const headers = {
'cisco-no-http-redirect': null,
'spark-user-agent': null,
trackingid: null,
};
// Send the network reachability request.
return this.request({
headers,
method: 'GET',
uri: this.intranetInactivityCheckUrl,
})
.then(() => {
this.isInNetwork = true;
return Promise.resolve(this.resetLogoutTimer());
})
.catch(() => {
this.logger.info('device: did not reach ping endpoint');
this.logger.info('device: triggering off-network timer');
this.isInNetwork = false;
return Promise.resolve(this.resetLogoutTimer());
});
},
/**
* Clears the registration ttl value if available.
*
* @param {Object} options - Values to be cleared.
* @returns {void}
*/
clear(...args) {
this.logger.info('device: clearing registered device');
// Prototype the extended class in order to preserve the parent member.
Reflect.apply(WebexPlugin.prototype.clear, this, args);
},
/**
* Get the current websocket url with the appropriate priority host.
*
* @param {boolean} [wait=false] - Willing to wait on a valid url.
* @returns {Promise<string, Error>} - The priority-mapped web socket url.
*/
getWebSocketUrl(wait = false) {
this.logger.info('device: getting the current websocket url');
// Destructure the services plugin for ease of reference.
const {services} = this.webex.internal;
// Validate if the method should wait for registration.
if (wait) {
return this.waitForRegistration()
.then(() => services.convertUrlToPriorityHostUrl(this.webSocketUrl))
.catch((error) => {
this.logger.warn(error.message);
return Promise.reject(new Error('device: failed to get the current websocket url'));
});
}
// Validate if the device is registered.
if (!this.registered) {
return Promise.reject(
new Error('device: cannot get websocket url, device is not registered')
);
}
// Attempt to collect the priority-host-mapped web socket URL.
const wsUrl = services.convertUrlToPriorityHostUrl(this.webSocketUrl);
// Validate that the url was collected.
if (wsUrl) {
return Promise.resolve(wsUrl);
}
return Promise.reject(new Error('device: failed to get the current websocket url'));
},
/**
* Get sanitized processed debug features from session storage
* these should be JSON encoded and in the form {feature1: true, feature2: false}
*
* @returns {Array<Object>} - Array of sanitized debug feature toggles
*/
getDebugFeatures() {
const sanitizedDebugFeatures = [];
if (this.config.debugFeatureTogglesKey) {
const debugFeaturesString = this.webex
.getWindow()
.sessionStorage.getItem(this.config.debugFeatureTogglesKey);
if (debugFeaturesString) {
const debugFeatures = JSON.parse(debugFeaturesString);
Object.entries(debugFeatures).forEach(([key, value]) => {
sanitizedDebugFeatures.push({
key,
val: value ? 'true' : 'false',
mutable: true,
lastModified: new Date().toISOString(),
});
});
}
}
return sanitizedDebugFeatures;
},
/**
* Process a successful device registration.
*
* @param {Object} response - response object from registration success.
* @returns {void}
*/
processRegistrationSuccess(response) {
this.logger.info('device: received registration payload');
// Clone the response body for service cleaning.
const body = {...response.body};
// Clean service data.
delete body.services;
delete body.serviceHostMap;
const {etag} = response.headers || {};
if (this.etag && etag && this.etag === etag) {
// If current etag matches the previous one and we have sent
// If-None-Match header the developer and entitlement feature
// toggles will not be returned
const {features} = body;
delete body.features;
// When using the etag feature cache, user and entitlement features are still returned
this.features.user.reset(features.user);
this.features.entitlement.reset(features.entitlement);
} else if (this.config.debugFeatureTogglesKey && body?.features?.developer) {
// Add the debug feature toggles from session storage if available
try {
const debugFeatures = this.getDebugFeatures();
body.features.developer.push(...debugFeatures);
} catch (error) {
this.logger.error('Failed to parse debug feature toggles from session storage:', error);
}
}
// Assign the recieved DTO from **WDM** to this device.
this.set(body);
// Assign the new etag to this device.
this.set({etag});
// Validate if device is ephemeral and setup refresh timer.
if (this.config.ephemeral) {
this.logger.info('device: enqueuing device refresh');
const delay = (this.config.ephemeralDeviceTTL / 2 + 60) * 1000;
this.refreshTimer = safeSetTimeout(() => this.refresh(), delay);
}
// Emit the registration:success event.
this.trigger(DEVICE_EVENT_REGISTRATION_SUCCESS, this);
},
/**
* Reset the current local logout timer for the registered device if
* registered.
*
* @returns {void}
*/
resetLogoutTimer() {
this.logger.info('device: resetting logout timer');
// Clear current logout timer.
clearTimeout(this.logoutTimer);
// Remove last activity date event listener.
this.off('change:lastUserActivityDate');
// Remove the logout timer.
this.unset('logoutTimer');
// Validate if the device is currently in a meeting and is configured to
// required inactivity enforcement.
if (
!this.isInMeeting &&
this.config.enableInactivityEnforcement &&
this.isReachabilityChecked
) {
if (this.isInNetwork) {
this.setLogoutTimer(this.inNetworkInactivityDuration);
} else {
this.setLogoutTimer(this.intranetInactivityDuration);
}
}
},
/**
* Set the value of the logout timer for the current registered device.
*
* @param {number} duration - Value in seconds of the new logout timer.
* @returns {void}
*/
setLogoutTimer(duration) {
this.logger.info('device: setting logout timer');
if (!duration || duration <= 0) {
return;
}
// Setup user activity date event listener.
this.on('change:lastUserActivityDate', () => {
this.resetLogoutTimer();
});
// Initialize a new timer.
this.logoutTimer = safeSetTimeout(() => {
this.webex.logout();
}, duration * 1000);
},
/**
* Wait for the device to be registered.
*
* @param {number} [timeout=10] - The maximum duration to wait, in seconds.
* @returns {Promise<void, Error>}
*/
waitForRegistration(timeout = 10) {
this.logger.info('device: waiting for registration');
return new Promise((resolve, reject) => {
if (this.registered) {
resolve();
}
const timeoutTimer = safeSetTimeout(
() => reject(new Error('device: timeout occured while waiting for registration')),
timeout * 1000
);
this.once(DEVICE_EVENT_REGISTRATION_SUCCESS, () => {
clearTimeout(timeoutTimer);
resolve();
});
});
},
// Deprecated methods.
/**
* Mark a url as failed and get the next priority host url.
*
* @param {string} url - The url to mark as failed.
* @returns {Promise<string>} - The next priority url.
*/
@deprecated('device#markUrlFailedAndGetNew(): Use services#markFailedUrl()')
markUrlFailedAndGetNew(url) {
return Promise.resolve(this.webex.internal.services.markFailedUrl(url));
},
// Ampersand method members
/* eslint-disable require-jsdoc */
/**
* Initializer method for the device plugin.
*
* @override
* @param {Array<any>} args - An array of items to be mapped as properties.
* @returns {void}
*/
@persist('@', decider)
initialize(...args) {
// Prototype the extended class in order to preserve the parent member.
Reflect.apply(WebexPlugin.prototype.initialize, this, args);
this.listenToOnce(this.webex, 'change:config', () => {
// If debug feature toggles exist, clear the etag to ensure developer feature toggles are fetched
if (this.getDebugFeatures(this.config.debugFeatureTogglesKey).length > 0) {
this.set('etag', undefined);
}
});
// Initialize feature events and listeners.
FEATURE_COLLECTION_NAMES.forEach((collectionName) => {
this.features.on(`change:${collectionName}`, (model, value, options) => {
this.trigger('change', this, options);
this.trigger('change:features', this, this.features, options);
});
});
// Initialize network reachability checking event for url change.