-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathindex.ts
347 lines (323 loc) · 11.4 KB
/
index.ts
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
/**
* @module Test/Connectivity
* @preferred
*
* Defines the methods required for the Connectivity Test Flow
*/
/**
* Connectivity Test Flow
*/
import axios from 'axios';
import * as Promise from 'promise';
/* tslint:disable */
import OTKAnalytics = require('opentok-solutions-logging');
/* tslint:enable */
import {
NetworkTestOptions,
} from '../index';
import { OT } from '../types/opentok';
import * as e from './errors';
import { OTErrorType, errorHasName } from '../errors/types';
import { mapErrors, FailureCase } from './errors/mapping';
import { getOr } from '../util';
type AV = 'audio' | 'video';
type CreateLocalPublisherResults = { publisher: OT.Publisher };
type PublishToSessionResults = { session: OT.Session } & CreateLocalPublisherResults;
type SubscribeToSessionResults = { subscriber: OT.Subscriber } & PublishToSessionResults;
type DeviceMap = { [deviceId: string]: OT.Device };
type AvailableDevices = { audio: DeviceMap, video: DeviceMap };
export type ConnectivityTestResults = {
success: boolean,
failedTests: FailureCase[],
};
/**
* Disconnect from a session. Once disconnected, remove all session
* event listeners and invoke the provided callback function.
*/
function disconnectFromSession(session: OT.Session) {
return new Promise((resolve, reject) => {
session.on('sessionDisconnected', () => {
session.off();
resolve();
});
session.disconnect();
});
}
/**
* Clean subscriber objects before disconnecting from the session
* @param session
* @param subscriber
*/
function cleanSubscriber(session: OT.Session, subscriber: OT.Subscriber) {
return new Promise((resolve, reject) => {
subscriber.on('destroyed', () => {
resolve();
});
if (!subscriber) {
resolve();
}
session.unsubscribe(subscriber);
});
}
function cleanPublisher(publisher: OT.Publisher) {
return new Promise((resolve, reject) => {
publisher.on('destroyed', () => {
resolve();
});
if (!publisher) {
resolve();
}
publisher.destroy();
});
}
/**
* Attempt to connect to the OpenTok sessionope
*/
function connectToSession(
OT: OT.Client,
{ apiKey, sessionId, token }: OT.SessionCredentials,
options?: NetworkTestOptions,
): Promise<OT.Session> {
return new Promise((resolve, reject) => {
let sessionOptions: OT.InitSessionOptions = {};
if (options && options.initSessionOptions) {
sessionOptions = options.initSessionOptions;
}
if (options && options.proxyServerUrl) {
if (!OT.hasOwnProperty('setProxyUrl')) { // Fallback for OT.version < 2.17.4
sessionOptions.proxyUrl = options.proxyServerUrl;
}
}
const session = OT.initSession(apiKey, sessionId, sessionOptions);
session.connect(token, (error?: OT.OTError) => {
if (errorHasName(error, OTErrorType.OT_AUTHENTICATION_ERROR)) {
reject(new e.ConnectToSessionTokenError());
} else if (errorHasName(error, OTErrorType.OT_INVALID_SESSION_ID)) {
reject(new e.ConnectToSessionSessionIdError());
} else if (errorHasName(error, OTErrorType.OT_CONNECT_FAILED)) {
reject(new e.ConnectToSessionNetworkError());
} else if (errorHasName(error, OTErrorType.OT_INVALID_HTTP_STATUS)) {
reject(new e.APIConnectivityError());
} else if (error) {
reject(new e.ConnectToSessionError());
} else {
resolve(session);
}
});
});
}
/**
* Ensure that audio and video devices are available
*/
function validateDevices(OT: OT.Client): Promise<AvailableDevices> {
return new Promise((resolve, reject) => {
OT.getDevices((error?: OT.OTError, devices: OT.Device[] = []) => {
if (error) {
reject(new e.FailedToObtainMediaDevices());
} else {
const availableDevices: AvailableDevices = devices.reduce(
(acc: AvailableDevices, device: OT.Device) => {
const type: AV = device.kind === 'audioInput' ? 'audio' : 'video';
return { ...acc, [type]: { ...acc[type], [device.deviceId]: device } };
},
{ audio: {}, video: {} },
);
if (!Object.keys(availableDevices.audio).length && !Object.keys(availableDevices.video).length) {
reject(new e.FailedToObtainMediaDevices());
} else {
resolve(availableDevices);
}
}
});
});
}
/**
* Create a local publisher object using any specified device options
*/
function checkCreateLocalPublisher(
OT: OT.Client,
options?: NetworkTestOptions,
): Promise<CreateLocalPublisherResults> {
return new Promise((resolve, reject) => {
validateDevices(OT)
.then((availableDevices: AvailableDevices) => {
const publisherDiv = document.createElement('div');
publisherDiv.style.position = 'fixed';
publisherDiv.style.bottom = '-1px';
publisherDiv.style.width = '1px';
publisherDiv.style.height = '1px';
publisherDiv.style.opacity = '0.01';
document.body.appendChild(publisherDiv);
const publisherOptions: OT.PublisherProperties = {
width: '100%',
height: '100%',
insertMode: 'append',
showControls: false,
};
if (options && options.audioSource) {
publisherOptions.audioSource = options.audioSource;
}
if (options && options.videoSource) {
publisherOptions.videoSource = options.videoSource;
}
if (options && options.audioOnly) {
publisherOptions.videoSource = null;
}
if (!Object.keys(availableDevices.audio).length) {
publisherOptions.audioSource = null;
}
if (!Object.keys(availableDevices.video).length) {
publisherOptions.videoSource = null;
}
const publisher = OT.initPublisher(publisherDiv, publisherOptions, (error?: OT.OTError) => {
if (!error) {
resolve({ publisher });
} else if (errorHasName(error, OTErrorType.OT_USER_MEDIA_ACCESS_DENIED)) {
reject(new e.MediaPermissionsDeniedError())
} else {
reject(new e.FailedToCreateLocalPublisher());
}
});
publisher.on('streamCreated', () => {
publisherDiv.style.visibility = 'hidden';
});
})
.catch(reject);
});
}
/**
* Attempt to publish to the session
*/
function checkPublishToSession(
OT: OT.Client, session: OT.Session,
options?: NetworkTestOptions,
): Promise<PublishToSessionResults> {
return new Promise((resolve, reject) => {
const disconnectAndReject = (rejectError: Error) => {
disconnectFromSession(session).then(() => {
reject(rejectError);
});
};
checkCreateLocalPublisher(OT, options)
.then(({ publisher }: CreateLocalPublisherResults) => {
session.publish(publisher, (error?: OT.OTError) => {
if (error) {
if (errorHasName(error, OTErrorType.NOT_CONNECTED)) {
disconnectAndReject(new e.PublishToSessionNotConnectedError());
} else if (errorHasName(error, OTErrorType.UNABLE_TO_PUBLISH)) {
disconnectAndReject(
new e.PublishToSessionPermissionOrTimeoutError());
} else if (error) {
disconnectAndReject(new e.PublishToSessionError());
}
} else {
resolve({ ...{ session }, ...{ publisher } });
}
});
}).catch((error: e.ConnectivityError) => {
disconnectAndReject(error);
});
});
}
/**
* Attempt to subscribe to our publisher
*/
function checkSubscribeToSession({ session, publisher }: PublishToSessionResults): Promise<SubscribeToSessionResults> {
return new Promise((resolve, reject) => {
const config = { testNetwork: true, audioVolume: 0 };
const disconnectAndReject = (rejectError: Error) => {
cleanPublisher(publisher)
.then(() => disconnectFromSession(session))
.then(() => {
reject(rejectError);
});
};
if (!publisher.stream) {
disconnectAndReject(new e.SubscribeToSessionError());
} else {
const subscriberDiv = document.createElement('div');
const subscriber = session.subscribe(publisher.stream, subscriberDiv, config, (error?: OT.OTError) => {
if (error) {
disconnectAndReject(new e.SubscribeToSessionError());
} else {
resolve({ ...{ session }, ...{ publisher }, ...{ subscriber } });
}
});
}
});
}
/**
* Attempt to connect to the tokbox client logging server
*/
function checkLoggingServer(OT: OT.Client, options?: NetworkTestOptions, input?: SubscribeToSessionResults):
Promise<SubscribeToSessionResults> {
return new Promise((resolve, reject) => {
const loggingUrl = `${getOr('', 'properties.loggingURL', OT)}/logging/ClientEvent`; // https://hlg.tokbox.com/prod
const url = options && options.proxyServerUrl &&
`${options.proxyServerUrl}/${loggingUrl.replace('https://', '')}` || loggingUrl;
const handleError = () => reject(new e.LoggingServerConnectionError());
axios.post(url)
.then(response => response.status === 200 ? resolve(input) : handleError())
.catch(handleError);
});
}
/**
* This method checks to see if the client can connect to TokBox servers required for using OpenTok
*/
export function testConnectivity(
OT: OT.Client,
credentials: OT.SessionCredentials,
otLogging: OTKAnalytics,
options?: NetworkTestOptions,
): Promise<ConnectivityTestResults> {
return new Promise((resolve, reject) => {
const onSuccess = (flowResults: SubscribeToSessionResults) => {
const results: ConnectivityTestResults = {
success: true,
failedTests: [],
};
otLogging.logEvent({ action: 'testConnectivity', variation: 'Success' });
return cleanSubscriber(flowResults.session, flowResults.subscriber)
.then(() => cleanPublisher(flowResults.publisher))
.then(() => disconnectFromSession(flowResults.session))
.then(() => resolve(results));
};
const onFailure = (error: Error) => {
const handleResults = (...errors: e.ConnectivityError[]) => {
/**
* If we have a messaging server failure, we will also fail the media
* server test by default.
*/
const baseFailures: FailureCase[] = mapErrors(...errors);
const messagingFailure = baseFailures.find(c => c.type === 'messaging');
const failedTests = [
...baseFailures,
...messagingFailure ? mapErrors(new e.FailedMessagingServerTestError()) : [],
];
const results = {
failedTests,
success: false,
};
otLogging.logEvent({ action: 'testConnectivity', variation: 'Success' });
resolve(results);
};
/**
* If we encounter an error before testing the connection to the logging server, let's perform
* that test as well before returning results.
*/
if (error.name === 'LoggingServerConnectionError') {
handleResults(error);
} else {
checkLoggingServer(OT, options)
.then(() => handleResults(error))
.catch((loggingError: e.LoggingServerConnectionError) => handleResults(error, loggingError));
}
};
connectToSession(OT, credentials, options)
.then((session: OT.Session) => checkPublishToSession(OT, session, options))
.then(checkSubscribeToSession)
.then((results: SubscribeToSessionResults) => checkLoggingServer(OT, options, results))
.then(onSuccess)
.catch(onFailure);
});
}