@webex/plugin-presence 0.0.0-next.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,266 @@
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 worker for client
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
+ * Trigger an event.
51
+ * @param {string} event
52
+ * @param {string} payload
53
+ * @returns {undefined}
54
+ */
55
+ emitEvent(event: string, payload: IEventPayload): void {
56
+ if (payload.type && payload.payload) {
57
+ this.trigger(event, payload);
58
+ }
59
+ },
60
+
61
+ /**
62
+ * Enables presence feature
63
+ * @returns {Promise<boolean>} resolves with true, if successful
64
+ */
65
+ enable(): Promise<boolean> {
66
+ return this.webex.internal.feature
67
+ .setFeature(USER, USER_PRESENCE_ENABLED, true)
68
+ .then((response) => response.value);
69
+ },
70
+
71
+ /**
72
+ * Disables presence feature
73
+ * @returns {Promise<boolean>} resolves with false, if successful
74
+ */
75
+ disable(): Promise<boolean> {
76
+ return this.webex.internal.feature
77
+ .setFeature(USER, USER_PRESENCE_ENABLED, false)
78
+ .then((response) => response.value);
79
+ },
80
+
81
+ /**
82
+ * Returns true if presence is enabled, false otherwise
83
+ * @returns {Promise<boolean>} resolves with true if presence is enabled
84
+ */
85
+ isEnabled(): Promise<boolean> {
86
+ return this.webex.internal.feature.getFeature(USER, USER_PRESENCE_ENABLED);
87
+ },
88
+
89
+ /**
90
+ * The status object
91
+ * @typedef {Object} PresenceStatusObject
92
+ * @property {string} url: Public resource identifier for presence
93
+ * @property {string} subject: User ID for the user the returned composed presence represents
94
+ * @property {string} status: Current composed presence state
95
+ * @property {string} statusTime: DateTime in RFC3339 format that the current status began
96
+ * @property {string} lastActive: DateTime in RFC3339 format that the service last saw activity from the user.
97
+ * @property {string} expires: DEPRECATED - DateTime in RFC3339 format that represents when the current
98
+ * status will expire. Will not exist if expiresTTL is -1.
99
+ * @property {Number} expiresTTL: TTL in seconds until the status will expire. If TTL is -1 the current
100
+ * status has no known expiration.
101
+ * @property {string} expiresTime: DateTime in RFC3339 format that the current status will expire. Missing
102
+ * field means no known expiration.
103
+ * @property {Object} vectorCounters: Used for packet ordering and tracking.
104
+ * @property {Boolean} suppressNotifications: Indicates if notification suppression is recommended for this status.
105
+ * @property {string} lastSeenDeviceUrl: Resource Identifier of the last device to post presence activity for
106
+ * this user.
107
+ */
108
+
109
+ /**
110
+ * Gets the current presence status of a given person id
111
+ * @param {string} personId
112
+ * @returns {Promise<PresenceStatusObject>} resolves with status object of person
113
+ */
114
+ get(personId: string): Promise<IPresenceStatusObject> {
115
+ if (!personId) {
116
+ return Promise.reject(new Error('A person id is required'));
117
+ }
118
+
119
+ return this.webex
120
+ .request({
121
+ method: 'GET',
122
+ service: 'apheleia',
123
+ resource: `compositions?userId=${personId}`,
124
+ })
125
+ .then((response) => response.body);
126
+ },
127
+
128
+ /**
129
+ * @typedef {Object} PresenceStatusesObject
130
+ * @property {Array.<PresenceStatusObject>} statusList
131
+ */
132
+ /**
133
+ * Gets the current presence statuses of an array of people ids
134
+ * @param {Array} personIds
135
+ * @returns {Promise<PresenceStatusesObject>} resolves with an object with key of `statusList` array
136
+ */
137
+ list(personIds: string[]): Promise<{statusList: IPresenceStatusObject[]}> {
138
+ if (!personIds || !Array.isArray(personIds)) {
139
+ return Promise.reject(new Error('An array of person ids is required'));
140
+ }
141
+
142
+ return Promise.all(personIds.map((id) => this.batcher.request(id))).then((presences) => ({
143
+ statusList: presences,
144
+ }));
145
+ },
146
+
147
+ /**
148
+ * Subscribes to a person's presence status updates
149
+ * Updates are sent via mercury events `apheleia.subscription_update`
150
+ * @param {string | Array} personIds
151
+ * @param {number} subscriptionTtl - Requested length of subscriptions in seconds.
152
+ * @returns {Promise}
153
+ */
154
+ subscribe(
155
+ personIds: string | string[],
156
+ subscriptionTtl = defaultSubscriptionTtl
157
+ ): Promise<{responses: any[]}> {
158
+ let subjects;
159
+ const batches = [];
160
+ const batchLimit = 50;
161
+
162
+ if (!personIds) {
163
+ return Promise.reject(new Error('A person id is required'));
164
+ }
165
+ if (Array.isArray(personIds)) {
166
+ subjects = personIds;
167
+ } else {
168
+ subjects = [personIds];
169
+ }
170
+ // Limit batches to 50 ids per request
171
+ for (let i = 0; i < subjects.length; i += batchLimit) {
172
+ batches.push(subjects.slice(i, i + batchLimit));
173
+ }
174
+
175
+ return Promise.all(
176
+ batches.map((ids) =>
177
+ this.webex
178
+ .request({
179
+ method: 'POST',
180
+ api: 'apheleia',
181
+ resource: 'subscriptions',
182
+ body: {
183
+ subjects: ids,
184
+ subscriptionTtl,
185
+ includeStatus: true,
186
+ },
187
+ })
188
+ .then((response) => response.body.responses)
189
+ )
190
+ ).then((idBatches) => ({responses: [].concat(...idBatches)}));
191
+ },
192
+
193
+ /**
194
+ * Unsubscribes from a person or group of people's presence subscription
195
+ * @param {string | Array} personIds
196
+ * @returns {Promise}
197
+ */
198
+ unsubscribe(personIds: string | string[]): Promise<{responses: any}> {
199
+ let subjects: string | string[];
200
+
201
+ if (!personIds) {
202
+ return Promise.reject(new Error('A person id is required'));
203
+ }
204
+ if (Array.isArray(personIds)) {
205
+ subjects = personIds;
206
+ } else {
207
+ subjects = [personIds];
208
+ }
209
+
210
+ return this.webex.request({
211
+ method: 'POST',
212
+ api: 'apheleia',
213
+ resource: 'subscriptions',
214
+ body: {
215
+ subjects,
216
+ subscriptionTtl: 0,
217
+ includeStatus: true,
218
+ },
219
+ });
220
+ },
221
+
222
+ /**
223
+ * Sets the status of the current user
224
+ * @param {string} status - active | inactive | ooo | dnd
225
+ * @param {number} ttl - Time To Live for the event in seconds.
226
+ * @returns {Promise}
227
+ */
228
+ setStatus(status: string, ttl: number): Promise<any> {
229
+ if (!status) {
230
+ return Promise.reject(new Error('A status is required'));
231
+ }
232
+
233
+ return this.webex
234
+ .request({
235
+ method: 'POST',
236
+ api: 'apheleia',
237
+ resource: 'events',
238
+ body: {
239
+ subject: this.webex.internal.device.userId,
240
+ eventType: status,
241
+ ttl,
242
+ },
243
+ })
244
+ .then((response) => response.body);
245
+ },
246
+
247
+ /**
248
+ * Retrieves and subscribes to a user's presence.
249
+ * @param {string} id
250
+ * @returns {undefined}
251
+ */
252
+ enqueue(id: string): void {
253
+ return this.worker.enqueue(id);
254
+ },
255
+
256
+ /**
257
+ * Retract from subscribing to a user's presence.
258
+ * @param {string} id
259
+ * @returns {undefined}
260
+ */
261
+ dequeue(id: string): void {
262
+ return this.worker.dequeue(id);
263
+ },
264
+ });
265
+
266
+ export default Presence;