modified lib-jitsi-meet dev repo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

strophe.jingle.js 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. /* global $, $build, __filename */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { $iq, Strophe } from 'strophe.js';
  4. import * as MediaType from '../../service/RTC/MediaType';
  5. import {
  6. ACTION_JINGLE_TR_RECEIVED,
  7. ACTION_JINGLE_TR_SUCCESS,
  8. createJingleEvent
  9. } from '../../service/statistics/AnalyticsEvents';
  10. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  11. import Statistics from '../statistics/statistics';
  12. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  13. import RandomUtil from '../util/RandomUtil';
  14. import ConnectionPlugin from './ConnectionPlugin';
  15. import JingleSessionPC from './JingleSessionPC';
  16. const logger = getLogger(__filename);
  17. // XXX Strophe is build around the idea of chaining function calls so allow long
  18. // function call chains.
  19. /* eslint-disable newline-per-chained-call */
  20. /**
  21. * Creates a "source" XML element for the source described in compact JSON format in [sourceCompactJson].
  22. * @param {*} owner the endpoint ID of the owner of the source.
  23. * @param {*} sourceCompactJson the compact JSON representation of the source.
  24. * @returns the created "source" XML element.
  25. */
  26. function _createSourceExtension(owner, sourceCompactJson) {
  27. const node = $build('source', {
  28. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  29. ssrc: sourceCompactJson.s
  30. });
  31. if (sourceCompactJson.m) {
  32. node.c('parameter', {
  33. name: 'msid',
  34. value: sourceCompactJson.m
  35. }).up();
  36. }
  37. node.c('ssrc-info', {
  38. xmlns: 'http://jitsi.org/jitmeet',
  39. owner
  40. }).up();
  41. return node.node;
  42. }
  43. /**
  44. * Creates an "ssrc-group" XML element for the SSRC group described in compact JSON format in [ssrcGroupCompactJson].
  45. * @param {*} ssrcGroupCompactJson the compact JSON representation of the SSRC group.
  46. * @returns the created "ssrc-group" element.
  47. */
  48. function _createSsrcGroupExtension(ssrcGroupCompactJson) {
  49. const node = $build('ssrc-group', {
  50. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  51. semantics: _getSemantics(ssrcGroupCompactJson[0])
  52. });
  53. for (let i = 1; i < ssrcGroupCompactJson.length; i++) {
  54. node.c('source', {
  55. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0',
  56. ssrc: ssrcGroupCompactJson[i]
  57. }).up();
  58. }
  59. return node.node;
  60. }
  61. /**
  62. * Reads a JSON-encoded message (from a "json-message" element) and extracts source descriptions. Adds the extracted
  63. * source descriptions to the given Jingle IQ in the standard Jingle format.
  64. *
  65. * Encoding sources in this compact JSON format instead of standard Jingle was introduced in order to reduce the
  66. * network traffic and load on the XMPP server. The format is described in Jicofo [TODO: insert link].
  67. *
  68. * @param {*} iq the IQ to which source descriptions will be added.
  69. * @param {*} jsonMessageXml The XML node for the "json-message" element.
  70. * @returns {Map<string, Array<string>} The audio and video ssrcs extracted from the JSON-encoded message with remote
  71. * endpoint id as the key.
  72. */
  73. function _expandSourcesFromJson(iq, jsonMessageXml) {
  74. let json;
  75. try {
  76. json = JSON.parse(jsonMessageXml.textContent);
  77. } catch (error) {
  78. logger.error(`json-message XML contained invalid JSON, ignoring: ${jsonMessageXml.textContent}`);
  79. return null;
  80. }
  81. if (!json?.sources) {
  82. // It might be a message of a different type, no need to log.
  83. return null;
  84. }
  85. // This is where we'll add "source" and "ssrc-group" elements. Create them elements if they don't exist.
  86. const audioRtpDescription = _getOrCreateRtpDescription(iq, MediaType.AUDIO);
  87. const videoRtpDescription = _getOrCreateRtpDescription(iq, MediaType.VIDEO);
  88. const ssrcMap = new Map();
  89. for (const owner in json.sources) {
  90. if (json.sources.hasOwnProperty(owner)) {
  91. const ssrcs = [];
  92. const ownerSources = json.sources[owner];
  93. // The video sources, video ssrc-groups, audio sources and audio ssrc-groups are encoded in that order in
  94. // the elements of the array.
  95. const videoSources = ownerSources?.length && ownerSources[0];
  96. const videoSsrcGroups = ownerSources?.length > 1 && ownerSources[1];
  97. const audioSources = ownerSources?.length > 2 && ownerSources[2];
  98. const audioSsrcGroups = ownerSources?.length > 3 && ownerSources[3];
  99. if (videoSources?.length) {
  100. for (let i = 0; i < videoSources.length; i++) {
  101. videoRtpDescription.appendChild(_createSourceExtension(owner, videoSources[i]));
  102. }
  103. // Log only the first video ssrc per endpoint.
  104. ssrcs.push(videoSources[0]?.s);
  105. }
  106. if (videoSsrcGroups?.length) {
  107. for (let i = 0; i < videoSsrcGroups.length; i++) {
  108. videoRtpDescription.appendChild(_createSsrcGroupExtension(videoSsrcGroups[i]));
  109. }
  110. }
  111. if (audioSources?.length) {
  112. for (let i = 0; i < audioSources.length; i++) {
  113. audioRtpDescription.appendChild(_createSourceExtension(owner, audioSources[i]));
  114. }
  115. ssrcs.push(audioSources[0]?.s);
  116. }
  117. if (audioSsrcGroups?.length) {
  118. for (let i = 0; i < audioSsrcGroups.length; i++) {
  119. audioRtpDescription.appendChild(_createSsrcGroupExtension(audioSsrcGroups[i]));
  120. }
  121. }
  122. ssrcMap.set(owner, ssrcs);
  123. }
  124. }
  125. return ssrcMap;
  126. }
  127. /**
  128. * Finds in a Jingle IQ the RTP description element with the given media type. If one does not exists, create it (as
  129. * well as the required "content" parent element) and adds it to the IQ.
  130. * @param {*} iq
  131. * @param {*} mediaType The media type, "audio" or "video".
  132. * @returns the RTP description element with the given media type.
  133. */
  134. function _getOrCreateRtpDescription(iq, mediaType) {
  135. const jingle = $(iq).find('jingle')[0];
  136. let content = $(jingle).find(`content[name="${mediaType}"]`);
  137. let description;
  138. if (content.length) {
  139. content = content[0];
  140. } else {
  141. // I'm not suree if "creator" and "senders" are required.
  142. content = $build('content', {
  143. name: mediaType
  144. }).node;
  145. jingle.appendChild(content);
  146. }
  147. description = $(content).find('description');
  148. if (description.length) {
  149. description = description[0];
  150. } else {
  151. description = $build('description', {
  152. xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  153. media: mediaType
  154. }).node;
  155. content.appendChild(description);
  156. }
  157. return description;
  158. }
  159. /**
  160. * Converts the short string representing SSRC group semantics in compact JSON format to the standard representation
  161. * (i.e. convert "f" to "FID" and "s" to "SIM").
  162. * @param {*} str the compact JSON format representation of an SSRC group's semantics.
  163. * @returns the SSRC group semantics corresponding to [str].
  164. */
  165. function _getSemantics(str) {
  166. if (str === 'f') {
  167. return 'FID';
  168. } else if (str === 's') {
  169. return 'SIM';
  170. }
  171. return null;
  172. }
  173. /**
  174. * Parses the transport XML element and returns the list of ICE candidates formatted as text.
  175. *
  176. * @param {*} transport Transport XML element extracted from the IQ.
  177. * @returns {Array<string>}
  178. */
  179. function _parseIceCandidates(transport) {
  180. const candidates = $(transport).find('>candidate');
  181. const parseCandidates = [];
  182. // Extract the candidate information from the IQ.
  183. candidates.each((_, candidate) => {
  184. const attributes = candidate.attributes;
  185. const candidateAttrs = [];
  186. for (let i = 0; i < attributes.length; i++) {
  187. const attr = attributes[i];
  188. candidateAttrs.push(`${attr.name}: ${attr.value}`);
  189. }
  190. parseCandidates.push(candidateAttrs.join(' '));
  191. });
  192. return parseCandidates;
  193. }
  194. /**
  195. *
  196. */
  197. export default class JingleConnectionPlugin extends ConnectionPlugin {
  198. /**
  199. * Creates new <tt>JingleConnectionPlugin</tt>
  200. * @param {XMPP} xmpp
  201. * @param {EventEmitter} eventEmitter
  202. * @param {Object} iceConfig an object that holds the iceConfig to be passed
  203. * to the p2p and the jvb <tt>PeerConnection</tt>.
  204. */
  205. constructor(xmpp, eventEmitter, iceConfig) {
  206. super();
  207. this.xmpp = xmpp;
  208. this.eventEmitter = eventEmitter;
  209. this.sessions = {};
  210. this.jvbIceConfig = iceConfig.jvb;
  211. this.p2pIceConfig = iceConfig.p2p;
  212. this.mediaConstraints = {
  213. offerToReceiveAudio: true,
  214. offerToReceiveVideo: true
  215. };
  216. }
  217. /**
  218. *
  219. * @param connection
  220. */
  221. init(connection) {
  222. super.init(connection);
  223. this.connection.addHandler(this.onJingle.bind(this),
  224. 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  225. }
  226. /**
  227. *
  228. * @param iq
  229. */
  230. onJingle(iq) {
  231. const sid = $(iq).find('jingle').attr('sid');
  232. const action = $(iq).find('jingle').attr('action');
  233. const fromJid = iq.getAttribute('from');
  234. // send ack first
  235. const ack = $iq({ type: 'result',
  236. to: fromJid,
  237. id: iq.getAttribute('id')
  238. });
  239. let sess = this.sessions[sid];
  240. if (action !== 'session-initiate') {
  241. if (!sess) {
  242. ack.attrs({ type: 'error' });
  243. ack.c('error', { type: 'cancel' })
  244. .c('item-not-found', {
  245. xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
  246. })
  247. .up()
  248. .c('unknown-session', {
  249. xmlns: 'urn:xmpp:jingle:errors:1'
  250. });
  251. logger.warn(`invalid session id: ${sid}`);
  252. logger.debug(iq);
  253. this.connection.send(ack);
  254. return true;
  255. }
  256. // local jid is not checked
  257. if (fromJid !== sess.remoteJid) {
  258. logger.warn(
  259. 'jid mismatch for session id', sid, sess.remoteJid, iq);
  260. ack.attrs({ type: 'error' });
  261. ack.c('error', { type: 'cancel' })
  262. .c('item-not-found', {
  263. xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
  264. })
  265. .up()
  266. .c('unknown-session', {
  267. xmlns: 'urn:xmpp:jingle:errors:1'
  268. });
  269. this.connection.send(ack);
  270. return true;
  271. }
  272. } else if (sess !== undefined) {
  273. // Existing session with same session id. This might be out-of-order
  274. // if the sess.remoteJid is the same as from.
  275. ack.attrs({ type: 'error' });
  276. ack.c('error', { type: 'cancel' })
  277. .c('service-unavailable', {
  278. xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
  279. })
  280. .up();
  281. logger.warn('duplicate session id', sid, iq);
  282. this.connection.send(ack);
  283. return true;
  284. }
  285. const now = window.performance.now();
  286. // FIXME that should work most of the time, but we'd have to
  287. // think how secure it is to assume that user with "focus"
  288. // nickname is Jicofo.
  289. const isP2P = Strophe.getResourceFromJid(fromJid) !== 'focus';
  290. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  291. const jsonMessages = $(iq).find('jingle>json-message');
  292. if (jsonMessages?.length) {
  293. let audioVideoSsrcs;
  294. logger.info(`Found a JSON-encoded element in ${action}, translating to standard Jingle.`);
  295. for (let i = 0; i < jsonMessages.length; i++) {
  296. // Currently there is always a single json-message in the IQ with the source information.
  297. audioVideoSsrcs = _expandSourcesFromJson(iq, jsonMessages[i]);
  298. }
  299. if (audioVideoSsrcs?.size) {
  300. const logMessage = [];
  301. for (const endpoint of audioVideoSsrcs.keys()) {
  302. logMessage.push(`${endpoint}:[${audioVideoSsrcs.get(endpoint)}]`);
  303. }
  304. logger.debug(`Received ${action} from ${fromJid} with sources=${logMessage.join(', ')}`);
  305. }
  306. // TODO: is there a way to remove the json-message elements once we've extracted the information?
  307. // removeChild doesn't seem to work.
  308. }
  309. switch (action) {
  310. case 'session-initiate': {
  311. logger.log('(TIME) received session-initiate:\t', now);
  312. const startMuted = $(iq).find('jingle>startmuted');
  313. isP2P && logger.debug(`Received ${action} from ${fromJid}`);
  314. if (startMuted?.length) {
  315. const audioMuted = startMuted.attr(MediaType.AUDIO);
  316. const videoMuted = startMuted.attr(MediaType.VIDEO);
  317. this.eventEmitter.emit(
  318. XMPPEvents.START_MUTED_FROM_FOCUS,
  319. audioMuted === 'true',
  320. videoMuted === 'true');
  321. }
  322. const pcConfig = isP2P ? this.p2pIceConfig : this.jvbIceConfig;
  323. sess
  324. = new JingleSessionPC(
  325. $(iq).find('jingle').attr('sid'),
  326. $(iq).attr('to'),
  327. fromJid,
  328. this.connection,
  329. this.mediaConstraints,
  330. // Makes a copy in order to prevent exception thrown on RN when either this.p2pIceConfig or
  331. // this.jvbIceConfig is modified and there's a PeerConnection instance holding a reference
  332. JSON.parse(JSON.stringify(pcConfig)),
  333. isP2P,
  334. /* initiator */ false);
  335. this.sessions[sess.sid] = sess;
  336. this.eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess, $(iq).find('>jingle'), now);
  337. break;
  338. }
  339. case 'session-accept': {
  340. const ssrcs = [];
  341. const contents = $(iq).find('jingle>content');
  342. // Extract the SSRCs from the session-accept received from a p2p peer.
  343. for (const content of contents) {
  344. const ssrc = $(content).find('description').attr('ssrc');
  345. ssrc && ssrcs.push(ssrc);
  346. }
  347. logger.debug(`Received ${action} from ${fromJid} with ssrcs=${ssrcs}`);
  348. this.eventEmitter.emit(XMPPEvents.CALL_ACCEPTED, sess, $(iq).find('>jingle'));
  349. break;
  350. }
  351. case 'content-modify': {
  352. const height = $(iq).find('jingle>content[name="video"]>max-frame-height');
  353. logger.debug(`Received ${action} from ${fromJid} with a max-frame-height=${height?.text()}`);
  354. sess.modifyContents($(iq).find('>jingle'));
  355. break;
  356. }
  357. case 'transport-info': {
  358. const candidates = _parseIceCandidates($(iq).find('jingle>content>transport'));
  359. logger.debug(`Received ${action} from ${fromJid} for candidates=${candidates.join(', ')}`);
  360. this.eventEmitter.emit(XMPPEvents.TRANSPORT_INFO, sess, $(iq).find('>jingle'));
  361. break;
  362. }
  363. case 'session-terminate': {
  364. logger.log('terminating...', sess.sid);
  365. let reasonCondition = null;
  366. let reasonText = null;
  367. if ($(iq).find('>jingle>reason').length) {
  368. reasonCondition
  369. = $(iq).find('>jingle>reason>:first')[0].tagName;
  370. reasonText = $(iq).find('>jingle>reason>text').text();
  371. }
  372. logger.debug(`Received ${action} from ${fromJid} disconnect reason=${reasonText}`);
  373. this.terminate(sess.sid, reasonCondition, reasonText);
  374. this.eventEmitter.emit(XMPPEvents.CALL_ENDED, sess, reasonCondition, reasonText);
  375. break;
  376. }
  377. case 'transport-replace': {
  378. logger.info('(TIME) Start transport replace:\t', now);
  379. const transport = $(iq).find('jingle>content>transport');
  380. const candidates = _parseIceCandidates(transport);
  381. const iceUfrag = $(transport).attr('ufrag');
  382. const icePwd = $(transport).attr('pwd');
  383. const dtlsFingerprint = $(transport).find('>fingerprint')?.text();
  384. logger.debug(`Received ${action} from ${fromJid} with iceUfrag=${iceUfrag},`
  385. + ` icePwd=${icePwd}, DTLS fingerprint=${dtlsFingerprint}, candidates=${candidates.join(', ')}`);
  386. Statistics.sendAnalytics(createJingleEvent(
  387. ACTION_JINGLE_TR_RECEIVED,
  388. {
  389. p2p: isP2P,
  390. value: now
  391. }));
  392. sess.replaceTransport($(iq).find('>jingle'), () => {
  393. const successTime = window.performance.now();
  394. logger.info('(TIME) Transport replace success:\t', successTime);
  395. Statistics.sendAnalytics(createJingleEvent(
  396. ACTION_JINGLE_TR_SUCCESS,
  397. {
  398. p2p: isP2P,
  399. value: successTime
  400. }));
  401. }, error => {
  402. GlobalOnErrorHandler.callErrorHandler(error);
  403. logger.error('Transport replace failed', error);
  404. sess.sendTransportReject();
  405. });
  406. break;
  407. }
  408. case 'source-add':
  409. sess.addRemoteStream($(iq).find('>jingle>content'));
  410. break;
  411. case 'source-remove':
  412. sess.removeRemoteStream($(iq).find('>jingle>content'));
  413. break;
  414. default:
  415. logger.warn('jingle action not implemented', action);
  416. ack.attrs({ type: 'error' });
  417. ack.c('error', { type: 'cancel' })
  418. .c('bad-request',
  419. { xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas' })
  420. .up();
  421. break;
  422. }
  423. this.connection.send(ack);
  424. return true;
  425. }
  426. /**
  427. * Creates new <tt>JingleSessionPC</tt> meant to be used in a direct P2P
  428. * connection, configured as 'initiator'.
  429. * @param {string} me our JID
  430. * @param {string} peer remote participant's JID
  431. * @return {JingleSessionPC}
  432. */
  433. newP2PJingleSession(me, peer) {
  434. const sess
  435. = new JingleSessionPC(
  436. RandomUtil.randomHexString(12),
  437. me,
  438. peer,
  439. this.connection,
  440. this.mediaConstraints,
  441. this.p2pIceConfig,
  442. /* P2P */ true,
  443. /* initiator */ true);
  444. this.sessions[sess.sid] = sess;
  445. return sess;
  446. }
  447. /**
  448. *
  449. * @param sid
  450. * @param reasonCondition
  451. * @param reasonText
  452. */
  453. terminate(sid, reasonCondition, reasonText) {
  454. if (this.sessions.hasOwnProperty(sid)) {
  455. if (this.sessions[sid].state !== 'ended') {
  456. this.sessions[sid].onTerminated(reasonCondition, reasonText);
  457. }
  458. delete this.sessions[sid];
  459. }
  460. }
  461. /**
  462. *
  463. */
  464. getStunAndTurnCredentials() {
  465. // get stun and turn configuration from server via xep-0215
  466. // uses time-limited credentials as described in
  467. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  468. //
  469. // See https://modules.prosody.im/mod_turncredentials.html
  470. // for a prosody module which implements this.
  471. // Or the new implementation https://modules.prosody.im/mod_external_services which will be in prosody 0.12
  472. //
  473. // Currently, this doesn't work with updateIce and therefore credentials
  474. // with a long validity have to be fetched before creating the
  475. // peerconnection.
  476. // TODO: implement refresh via updateIce as described in
  477. // https://code.google.com/p/webrtc/issues/detail?id=1650
  478. this.connection.sendIQ(
  479. $iq({ type: 'get',
  480. to: this.xmpp.options.hosts.domain })
  481. .c('services', { xmlns: 'urn:xmpp:extdisco:2' }),
  482. v2Res => this.onReceiveStunAndTurnCredentials(v2Res),
  483. v2Err => {
  484. logger.warn('getting turn credentials with extdisco:2 failed, trying extdisco:1', v2Err);
  485. this.connection.sendIQ(
  486. $iq({ type: 'get',
  487. to: this.xmpp.options.hosts.domain })
  488. .c('services', { xmlns: 'urn:xmpp:extdisco:1' }),
  489. v1Res => this.onReceiveStunAndTurnCredentials(v1Res),
  490. v1Err => {
  491. logger.warn('getting turn credentials failed', v1Err);
  492. logger.warn('is mod_turncredentials or similar installed and configured?');
  493. }
  494. );
  495. });
  496. }
  497. /**
  498. * Parses response when querying for services using urn:xmpp:extdisco:1 or urn:xmpp:extdisco:2.
  499. * Stores results in jvbIceConfig and p2pIceConfig.
  500. * @param res The response iq.
  501. * @return {boolean} Whether something was processed from the supplied message.
  502. */
  503. onReceiveStunAndTurnCredentials(res) {
  504. const iceservers = [];
  505. $(res).find('>services>service').each((idx, el) => {
  506. // eslint-disable-next-line no-param-reassign
  507. el = $(el);
  508. const dict = {};
  509. const type = el.attr('type');
  510. switch (type) {
  511. case 'stun':
  512. dict.urls = `stun:${el.attr('host')}`;
  513. if (el.attr('port')) {
  514. dict.urls += `:${el.attr('port')}`;
  515. }
  516. iceservers.push(dict);
  517. break;
  518. case 'turn':
  519. case 'turns': {
  520. dict.urls = `${type}:`;
  521. dict.username = el.attr('username');
  522. dict.urls += el.attr('host');
  523. const port = el.attr('port');
  524. if (port) {
  525. dict.urls += `:${el.attr('port')}`;
  526. }
  527. const transport = el.attr('transport');
  528. if (transport && transport !== 'udp') {
  529. dict.urls += `?transport=${transport}`;
  530. }
  531. dict.credential = el.attr('password')
  532. || dict.credential;
  533. iceservers.push(dict);
  534. break;
  535. }
  536. }
  537. });
  538. const options = this.xmpp.options;
  539. // Shuffle ICEServers for loadbalancing
  540. for (let i = iceservers.length - 1; i > 0; i--) {
  541. const j = Math.floor(Math.random() * (i + 1));
  542. const temp = iceservers[i];
  543. iceservers[i] = iceservers[j];
  544. iceservers[j] = temp;
  545. }
  546. let filter;
  547. if (options.useTurnUdp) {
  548. filter = s => s.urls.startsWith('turn');
  549. } else {
  550. // By default we filter out STUN and TURN/UDP and leave only TURN/TCP.
  551. filter = s => s.urls.startsWith('turn') && (s.urls.indexOf('transport=tcp') >= 0);
  552. }
  553. this.jvbIceConfig.iceServers = iceservers.filter(filter);
  554. this.p2pIceConfig.iceServers = iceservers;
  555. return iceservers.length > 0;
  556. }
  557. /**
  558. * Returns the data saved in 'updateLog' in a format to be logged.
  559. */
  560. getLog() {
  561. const data = {};
  562. Object.keys(this.sessions).forEach(sid => {
  563. const session = this.sessions[sid];
  564. const pc = session.peerconnection;
  565. if (pc && pc.updateLog) {
  566. // FIXME: should probably be a .dump call
  567. data[`jingle_${sid}`] = {
  568. updateLog: pc.updateLog,
  569. stats: pc.stats,
  570. url: window.location.href
  571. };
  572. }
  573. });
  574. return data;
  575. }
  576. }
  577. /* eslint-enable newline-per-chained-call */