@webex/plugin-presence 0.0.0-ipv6-multi-turn-urls.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,277 @@
1
+ import {debounce} from 'lodash';
2
+
3
+ import {IGenericKeyValue, IWebex} from './interface';
4
+ import {
5
+ FETCH_DELAY,
6
+ GROUNDSKEEPER_INTERVAL,
7
+ SUBSCRIPTION_DELAY,
8
+ UPDATE_PRESENCE_DELAY,
9
+ EXPIRED_PRESENCE_TIME,
10
+ PREMATURE_EXPIRATION_SUBSCRIPTION_TIME,
11
+ DEFAULT_SUBSCRIPTION_TTL,
12
+ APHELEIA_SUBSCRIPTION_UPDATE,
13
+ PRESENCE_UPDATE,
14
+ ENVELOPE_TYPE,
15
+ } from './constants';
16
+
17
+ /**
18
+ * Presence Worker
19
+ * Manages fetches and subscriptions for presence
20
+ * @class
21
+ */
22
+ export default class PresenceWorker {
23
+ private presences: IGenericKeyValue; // current presence objects; updated time
24
+ private watchers: IGenericKeyValue; // counter of visible presence-required objects
25
+ private fetchers: IGenericKeyValue; // waiting to get presence object
26
+ private flights: IGenericKeyValue; // in flight to get presence object
27
+ private campers: IGenericKeyValue; // waiting to subscribe; updated time
28
+ private subscribers: IGenericKeyValue; // current subscriptions; expiration time
29
+ private webex: IWebex;
30
+
31
+ /**
32
+ * Constructs a presence worker to execute and
33
+ * maintain tasks related to presence upkeep.
34
+ */
35
+ constructor() {
36
+ this.presences = {};
37
+ this.watchers = {};
38
+ this.fetchers = {};
39
+ this.flights = {};
40
+ this.campers = {};
41
+ this.subscribers = {};
42
+ }
43
+
44
+ /**
45
+ * Connect to the mercury for presence and starts worker.
46
+ * @param {object} webex
47
+ * @returns {undefined}
48
+ */
49
+ initialize(webex: IWebex): void {
50
+ if (!webex || !webex.internal) {
51
+ throw new Error('Must initialize Presence Worker with webex!');
52
+ }
53
+
54
+ this.webex = webex;
55
+
56
+ const mercury = this.webex.internal.mercury.connected
57
+ ? Promise.resolve()
58
+ : this.webex.internal.mercury.connect();
59
+
60
+ mercury.then(() => {
61
+ this.webex.internal.mercury.on(
62
+ APHELEIA_SUBSCRIPTION_UPDATE,
63
+ this.subscriptionUpdate.bind(this)
64
+ );
65
+ });
66
+
67
+ setInterval(this.groundskeeper.bind(this), GROUNDSKEEPER_INTERVAL);
68
+ }
69
+
70
+ /**
71
+ * Trigger a subscription update event.
72
+ * @param {string} event
73
+ * @returns {undefined}
74
+ */
75
+ subscriptionUpdate(event): void {
76
+ this.presences[event.data.subject] = new Date().getTime();
77
+
78
+ this.webex.presence.emitEvent(PRESENCE_UPDATE, {
79
+ type: ENVELOPE_TYPE.SUBSCRIPTION,
80
+ payload: event.data,
81
+ });
82
+ }
83
+
84
+ /**
85
+ * Retrieves and subscribes to a user's presence.
86
+ * @param {string} id
87
+ * @returns {undefined}
88
+ */
89
+ enqueue(id: string) {
90
+ const now = new Date().getTime();
91
+
92
+ if (this.watchers[id]) {
93
+ this.watchers[id] += 1;
94
+ } else {
95
+ this.watchers[id] = 1;
96
+ }
97
+
98
+ if (this.subscribers[id]) {
99
+ return;
100
+ }
101
+
102
+ if (!this.campers[id]) {
103
+ this.campers[id] = now;
104
+ }
105
+
106
+ // Retrieve presence if:
107
+ // not in flight or
108
+ // don't already have the presence or
109
+ // presence has gone stale
110
+ if (
111
+ !this.flights[id] &&
112
+ (!this.presences[id] || this.presences[id] < now - UPDATE_PRESENCE_DELAY)
113
+ ) {
114
+ // @ts-ignore - Fix the type
115
+ this.fetchers[id] = id;
116
+ this.debouncedFetch();
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Retract from subscribing to a user's presence.
122
+ * @param {string} id
123
+ * @returns {undefined}
124
+ */
125
+ dequeue(id: string) {
126
+ if (this.watchers[id]) {
127
+ this.watchers[id] -= 1;
128
+
129
+ if (this.watchers[id] <= 0) {
130
+ delete this.watchers[id];
131
+ delete this.fetchers[id];
132
+ delete this.campers[id];
133
+ }
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Retrieve users' presences.
139
+ * @returns {undefined}
140
+ */
141
+ checkFetchers(): void {
142
+ const boarding = this.fetchers;
143
+
144
+ Object.assign(this.flights, boarding);
145
+ this.fetchers = {};
146
+
147
+ this.webex.presence.list(Object.keys(boarding)).then((response) => {
148
+ const now = new Date().getTime();
149
+
150
+ response.statusList.forEach((presence) => {
151
+ const id = presence.subject;
152
+
153
+ delete this.flights[id];
154
+ this.presences[id] = now;
155
+ });
156
+
157
+ this.webex.presence.emitEvent(PRESENCE_UPDATE, {
158
+ type: ENVELOPE_TYPE.PRESENCE,
159
+ payload: response,
160
+ });
161
+ });
162
+ }
163
+
164
+ debouncedFetch = debounce(this.checkFetchers, FETCH_DELAY);
165
+
166
+ /**
167
+ * Determine if we should subscribe to users' presences.
168
+ * @returns {Array}: User ids to subscribe.
169
+ */
170
+ checkCampers(): string[] {
171
+ const now = new Date().getTime();
172
+ const subscribers = [];
173
+
174
+ Object.entries(this.campers).forEach((camper) => {
175
+ const id = camper[0];
176
+ const time = camper[1];
177
+
178
+ // Subscribe if they've been camping for a minute
179
+ if (time < now - SUBSCRIPTION_DELAY) {
180
+ delete this.campers[id];
181
+ this.subscribers[id] = null;
182
+ subscribers.push(id);
183
+ }
184
+ });
185
+
186
+ return subscribers;
187
+ }
188
+
189
+ /**
190
+ * Determine if we should re-subscribe or remove users' subscriptions.
191
+ * @returns {Array}: User ids to re-subscribe.
192
+ */
193
+ checkSubscriptions(): string[] {
194
+ const now = new Date().getTime();
195
+
196
+ const renewIds = [];
197
+
198
+ Object.entries(this.subscribers).forEach((subscription) => {
199
+ const id = subscription[0];
200
+ const expiration = subscription[1];
201
+
202
+ if (expiration) {
203
+ // Renew subscription if they're about to expire
204
+ if (this.watchers[id] && now > expiration - PREMATURE_EXPIRATION_SUBSCRIPTION_TIME) {
205
+ renewIds.push(id);
206
+ } else if (now > expiration) {
207
+ delete this.subscribers[id];
208
+ }
209
+ }
210
+ });
211
+
212
+ return renewIds;
213
+ }
214
+
215
+ /**
216
+ * Remove expired presence objects.
217
+ * @returns {undefined}
218
+ */
219
+ cleanPresences(): void {
220
+ const trash = [];
221
+ const tenMinutesAgo = new Date().getTime() - EXPIRED_PRESENCE_TIME;
222
+
223
+ Object.entries(this.presences).forEach((presence) => {
224
+ const id = presence[0];
225
+ const lastUpdated = presence[1];
226
+
227
+ // Delete the object if it is stale
228
+ if (lastUpdated < tenMinutesAgo) {
229
+ delete this.presences[id];
230
+ trash.push(id);
231
+ }
232
+ });
233
+
234
+ // Tells client to delete it too
235
+ if (trash.length) {
236
+ this.webex.presence.emitEvent(PRESENCE_UPDATE, {
237
+ type: ENVELOPE_TYPE.DELETE,
238
+ payload: trash,
239
+ });
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Execute chores on an interval.
245
+ * Checks if we should make new subscribe,
246
+ * checks if we should re-subscribe,
247
+ * removes expired subscriptions,
248
+ * removes expired presence objects.
249
+ * @returns {undefined}
250
+ */
251
+ groundskeeper(): void {
252
+ const campers = this.checkCampers();
253
+ const renewSubscriptions = this.checkSubscriptions();
254
+
255
+ const ids = [...campers, ...renewSubscriptions];
256
+
257
+ if (ids.length) {
258
+ this.webex.presence.subscribe(ids).then((body) => {
259
+ const now = new Date().getTime();
260
+
261
+ body.responses.forEach((response) => {
262
+ if (response.responseCode === 200) {
263
+ const ttl = response.subscriptionTtl * 1000;
264
+
265
+ this.subscribers[response.subject] = now + ttl;
266
+ this.presences[response.status.subject] = now;
267
+ } else {
268
+ // If it errored for any reason, set the ttl so we clean it out eventually
269
+ this.subscribers[response.subject] = now + DEFAULT_SUBSCRIPTION_TTL;
270
+ }
271
+ });
272
+ });
273
+ }
274
+
275
+ this.cleanPresences();
276
+ }
277
+ }
@@ -0,0 +1,281 @@
1
+ /*!
2
+ * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.
3
+ */
4
+
5
+ import '@webex/internal-plugin-device';
6
+
7
+ import {WebexPlugin} from '@webex/webex-core';
8
+
9
+ import PresenceBatcher from './presence-batcher';
10
+ import PresenceWorker from './presence-worker';
11
+ import {IEventPayload, IPresence, IPresenceStatusObject} from './interface';
12
+
13
+ const defaultSubscriptionTtl = 600;
14
+ const USER = 'user';
15
+ const USER_PRESENCE_ENABLED = 'user-presence-enabled';
16
+
17
+ /**
18
+ * @class
19
+ * @extends WebexPlugin
20
+ */
21
+ const Presence: IPresence = WebexPlugin.extend({
22
+ namespace: 'Presence',
23
+
24
+ children: {
25
+ batcher: PresenceBatcher,
26
+ },
27
+
28
+ session: {
29
+ worker: {
30
+ default() {
31
+ return new PresenceWorker();
32
+ },
33
+ type: 'any',
34
+ },
35
+ },
36
+
37
+ /**
38
+ * Initialize the presence plugin
39
+ * @returns {undefined}
40
+ */
41
+ initialize(): void {
42
+ this.webex.once('ready', () => {
43
+ if (this.config.initializeWorker) {
44
+ this.worker.initialize(this.webex);
45
+ }
46
+ });
47
+ },
48
+
49
+ /**
50
+ * Initializes the presence worker.
51
+ * @returns {undefined}
52
+ */
53
+ initializeWorker(): void {
54
+ if (this.webex.ready) {
55
+ this.worker.initialize(this.webex);
56
+ } else {
57
+ this.webex.once('ready', () => {
58
+ this.worker.initialize(this.webex);
59
+ });
60
+ }
61
+ },
62
+
63
+ /**
64
+ * Trigger an event.
65
+ * @param {string} event
66
+ * @param {string} payload
67
+ * @returns {undefined}
68
+ */
69
+ emitEvent(event: string, payload: IEventPayload): void {
70
+ if (payload.type && payload.payload) {
71
+ this.trigger(event, payload);
72
+ }
73
+ },
74
+
75
+ /**
76
+ * Enables presence feature
77
+ * @returns {Promise<boolean>} resolves with true, if successful
78
+ */
79
+ enable(): Promise<boolean> {
80
+ return this.webex.internal.feature
81
+ .setFeature(USER, USER_PRESENCE_ENABLED, true)
82
+ .then((response) => response.value);
83
+ },
84
+
85
+ /**
86
+ * Disables presence feature
87
+ * @returns {Promise<boolean>} resolves with false, if successful
88
+ */
89
+ disable(): Promise<boolean> {
90
+ return this.webex.internal.feature
91
+ .setFeature(USER, USER_PRESENCE_ENABLED, false)
92
+ .then((response) => response.value);
93
+ },
94
+
95
+ /**
96
+ * Returns true if presence is enabled, false otherwise
97
+ * @returns {Promise<boolean>} resolves with true if presence is enabled
98
+ */
99
+ isEnabled(): Promise<boolean> {
100
+ return this.webex.internal.feature.getFeature(USER, USER_PRESENCE_ENABLED);
101
+ },
102
+
103
+ /**
104
+ * The status object
105
+ * @typedef {Object} PresenceStatusObject
106
+ * @property {string} url: Public resource identifier for presence
107
+ * @property {string} subject: User ID for the user the returned composed presence represents
108
+ * @property {string} status: Current composed presence state
109
+ * @property {string} statusTime: DateTime in RFC3339 format that the current status began
110
+ * @property {string} lastActive: DateTime in RFC3339 format that the service last saw activity from the user.
111
+ * @property {string} expires: DEPRECATED - DateTime in RFC3339 format that represents when the current
112
+ * status will expire. Will not exist if expiresTTL is -1.
113
+ * @property {Number} expiresTTL: TTL in seconds until the status will expire. If TTL is -1 the current
114
+ * status has no known expiration.
115
+ * @property {string} expiresTime: DateTime in RFC3339 format that the current status will expire. Missing
116
+ * field means no known expiration.
117
+ * @property {Object} vectorCounters: Used for packet ordering and tracking.
118
+ * @property {Boolean} suppressNotifications: Indicates if notification suppression is recommended for this status.
119
+ * @property {string} lastSeenDeviceUrl: Resource Identifier of the last device to post presence activity for
120
+ * this user.
121
+ */
122
+
123
+ /**
124
+ * Gets the current presence status of a given person id
125
+ * @param {string} personId
126
+ * @returns {Promise<PresenceStatusObject>} resolves with status object of person
127
+ */
128
+ get(personId: string): Promise<IPresenceStatusObject> {
129
+ if (!personId) {
130
+ return Promise.reject(new Error('A person id is required'));
131
+ }
132
+
133
+ return this.webex
134
+ .request({
135
+ method: 'GET',
136
+ service: 'apheleia',
137
+ resource: `compositions?userId=${personId}`,
138
+ })
139
+ .then((response) => response.body);
140
+ },
141
+
142
+ /**
143
+ * @typedef {Object} PresenceStatusesObject
144
+ * @property {Array.<PresenceStatusObject>} statusList
145
+ */
146
+ /**
147
+ * Gets the current presence statuses of an array of people ids
148
+ * @param {Array} personIds
149
+ * @returns {Promise<PresenceStatusesObject>} resolves with an object with key of `statusList` array
150
+ */
151
+ list(personIds: string[]): Promise<{statusList: IPresenceStatusObject[]}> {
152
+ if (!personIds || !Array.isArray(personIds)) {
153
+ return Promise.reject(new Error('An array of person ids is required'));
154
+ }
155
+
156
+ return Promise.all(personIds.map((id) => this.batcher.request(id))).then((presences) => ({
157
+ statusList: presences,
158
+ }));
159
+ },
160
+
161
+ /**
162
+ * Subscribes to a person's presence status updates
163
+ * Updates are sent via mercury events `apheleia.subscription_update`
164
+ * @param {string | Array} personIds
165
+ * @param {number} subscriptionTtl - Requested length of subscriptions in seconds.
166
+ * @returns {Promise}
167
+ */
168
+ subscribe(
169
+ personIds: string | string[],
170
+ subscriptionTtl = defaultSubscriptionTtl
171
+ ): Promise<{responses: any[]}> {
172
+ let subjects;
173
+ const batches = [];
174
+ const batchLimit = 50;
175
+
176
+ if (!personIds) {
177
+ return Promise.reject(new Error('A person id is required'));
178
+ }
179
+ if (Array.isArray(personIds)) {
180
+ subjects = personIds;
181
+ } else {
182
+ subjects = [personIds];
183
+ }
184
+ // Limit batches to 50 ids per request
185
+ for (let i = 0; i < subjects.length; i += batchLimit) {
186
+ batches.push(subjects.slice(i, i + batchLimit));
187
+ }
188
+
189
+ return Promise.all(
190
+ batches.map((ids) =>
191
+ this.webex
192
+ .request({
193
+ method: 'POST',
194
+ api: 'apheleia',
195
+ resource: 'subscriptions',
196
+ body: {
197
+ subjects: ids,
198
+ subscriptionTtl,
199
+ includeStatus: true,
200
+ },
201
+ })
202
+ .then((response) => response.body.responses)
203
+ )
204
+ ).then((idBatches) => ({responses: [].concat(...idBatches)}));
205
+ },
206
+
207
+ /**
208
+ * Unsubscribes from a person or group of people's presence subscription
209
+ * @param {string | Array} personIds
210
+ * @returns {Promise}
211
+ */
212
+ unsubscribe(personIds: string | string[]): Promise<{responses: any}> {
213
+ let subjects: string | string[];
214
+
215
+ if (!personIds) {
216
+ return Promise.reject(new Error('A person id is required'));
217
+ }
218
+ if (Array.isArray(personIds)) {
219
+ subjects = personIds;
220
+ } else {
221
+ subjects = [personIds];
222
+ }
223
+
224
+ return this.webex.request({
225
+ method: 'POST',
226
+ api: 'apheleia',
227
+ resource: 'subscriptions',
228
+ body: {
229
+ subjects,
230
+ subscriptionTtl: 0,
231
+ includeStatus: true,
232
+ },
233
+ });
234
+ },
235
+
236
+ /**
237
+ * Sets the status of the current user
238
+ * @param {string} status - active | inactive | ooo | dnd
239
+ * @param {number} ttl - Time To Live for the event in seconds.
240
+ * @returns {Promise}
241
+ */
242
+ setStatus(status: string, ttl: number): Promise<any> {
243
+ if (!status) {
244
+ return Promise.reject(new Error('A status is required'));
245
+ }
246
+
247
+ return this.webex
248
+ .request({
249
+ method: 'POST',
250
+ api: 'apheleia',
251
+ resource: 'events',
252
+ body: {
253
+ subject: this.webex.internal.device.userId,
254
+ eventType: status,
255
+ ...(status !== 'dnd' && {label: this.webex.internal.device.userId}),
256
+ ttl,
257
+ },
258
+ })
259
+ .then((response) => response.body);
260
+ },
261
+
262
+ /**
263
+ * Retrieves and subscribes to a user's presence.
264
+ * @param {string} id
265
+ * @returns {undefined}
266
+ */
267
+ enqueue(id: string): void {
268
+ return this.worker.enqueue(id);
269
+ },
270
+
271
+ /**
272
+ * Retract from subscribing to a user's presence.
273
+ * @param {string} id
274
+ * @returns {undefined}
275
+ */
276
+ dequeue(id: string): void {
277
+ return this.worker.dequeue(id);
278
+ },
279
+ });
280
+
281
+ export default Presence;