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.

statistics.js 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. import EventEmitter from 'events';
  2. import * as JitsiConferenceEvents from '../../JitsiConferenceEvents';
  3. import JitsiTrackError from '../../JitsiTrackError';
  4. import { JitsiTrackEvents } from '../../JitsiTrackEvents';
  5. import { FEEDBACK } from '../../service/statistics/AnalyticsEvents';
  6. import * as StatisticsEvents from '../../service/statistics/Events';
  7. import browser from '../browser';
  8. import ScriptUtil from '../util/ScriptUtil';
  9. import analytics from './AnalyticsAdapter';
  10. import CallStats from './CallStats';
  11. import LocalStats from './LocalStatsCollector';
  12. import { PerformanceObserverStats } from './PerformanceObserverStats';
  13. import RTPStats from './RTPStatsCollector';
  14. import { CALLSTATS_SCRIPT_URL } from './constants';
  15. const logger = require('@jitsi/logger').getLogger(__filename);
  16. /**
  17. * Stores all active {@link Statistics} instances.
  18. * @type {Set<Statistics>}
  19. */
  20. let _instances;
  21. /**
  22. * True if callstats API is loaded
  23. */
  24. let isCallstatsLoaded = false;
  25. /**
  26. * Since callstats.io is a third party, we cannot guarantee the quality of their
  27. * service. More specifically, their server may take noticeably long time to
  28. * respond. Consequently, it is in our best interest (in the sense that the
  29. * intergration of callstats.io is pretty important to us but not enough to
  30. * allow it to prevent people from joining a conference) to (1) start
  31. * downloading their API as soon as possible and (2) do the downloading
  32. * asynchronously.
  33. *
  34. * @param {StatisticsOptions} options - Options to use for downloading and
  35. * initializing callstats backend.
  36. */
  37. function loadCallStatsAPI(options) {
  38. if (!isCallstatsLoaded) {
  39. ScriptUtil.loadScript(
  40. options.customScriptUrl || CALLSTATS_SCRIPT_URL,
  41. /* async */ true,
  42. /* prepend */ true,
  43. /* relativeURL */ undefined,
  44. /* loadCallback */ () => _initCallStatsBackend(options)
  45. );
  46. isCallstatsLoaded = true;
  47. }
  48. }
  49. /**
  50. * Initializes Callstats backend.
  51. *
  52. * @param {StatisticsOptions} options - The options to use for initializing
  53. * callstats backend.
  54. * @private
  55. */
  56. function _initCallStatsBackend(options) {
  57. if (CallStats.isBackendInitialized()) {
  58. return;
  59. }
  60. if (!CallStats.initBackend({
  61. callStatsID: options.callStatsID,
  62. callStatsSecret: options.callStatsSecret,
  63. userName: options.userName,
  64. aliasName: options.aliasName,
  65. applicationName: options.applicationName,
  66. getWiFiStatsMethod: options.getWiFiStatsMethod,
  67. confID: options.confID,
  68. siteID: options.siteID,
  69. configParams: options.configParams
  70. })) {
  71. logger.error('CallStats Backend initialization failed bad');
  72. }
  73. }
  74. /**
  75. * callstats strips any additional fields from Error except for "name", "stack",
  76. * "message" and "constraintName". So we need to bundle additional information
  77. * from JitsiTrackError into error passed to callstats to preserve valuable
  78. * information about error.
  79. * @param {JitsiTrackError} error
  80. */
  81. function formatJitsiTrackErrorForCallStats(error) {
  82. const err = new Error();
  83. // Just copy original stack from error
  84. err.stack = error.stack;
  85. // Combine name from error's name plus (possibly) name of original GUM error
  86. err.name = (error.name || 'Unknown error') + (error.gum && error.gum.error
  87. && error.gum.error.name ? ` - ${error.gum.error.name}` : '');
  88. // Put all constraints into this field. For constraint failed errors we will
  89. // still know which exactly constraint failed as it will be a part of
  90. // message.
  91. err.constraintName = error.gum && error.gum.constraints
  92. ? JSON.stringify(error.gum.constraints) : '';
  93. // Just copy error's message.
  94. err.message = error.message;
  95. return err;
  96. }
  97. /**
  98. * Init statistic options
  99. * @param options
  100. */
  101. Statistics.init = function(options) {
  102. Statistics.audioLevelsEnabled = !options.disableAudioLevels;
  103. if (typeof options.pcStatsInterval === 'number') {
  104. Statistics.pcStatsInterval = options.pcStatsInterval;
  105. }
  106. if (typeof options.audioLevelsInterval === 'number') {
  107. Statistics.audioLevelsInterval = options.audioLevelsInterval;
  108. }
  109. if (typeof options.longTasksStatsInterval === 'number') {
  110. Statistics.longTasksStatsInterval = options.longTasksStatsInterval;
  111. }
  112. Statistics.disableThirdPartyRequests = options.disableThirdPartyRequests;
  113. };
  114. /**
  115. * The options to configure Statistics.
  116. * @typedef {Object} StatisticsOptions
  117. * @property {string} applicationName - The application name to pass to
  118. * callstats.
  119. * @property {string} aliasName - The alias name to use when initializing callstats.
  120. * @property {string} userName - The user name to use when initializing callstats.
  121. * @property {string} confID - The callstats conference ID to use.
  122. * @property {string} callStatsID - Callstats credentials - the id.
  123. * @property {string} callStatsSecret - Callstats credentials - the secret.
  124. * @property {string} customScriptUrl - A custom lib url to use when downloading
  125. * callstats library.
  126. * @property {string} roomName - The room name we are currently in.
  127. * @property {string} configParams - The set of parameters
  128. * to enable/disable certain features in the library. See CallStats docs for more info.
  129. */
  130. /**
  131. *
  132. * @param xmpp
  133. * @param {StatisticsOptions} options - The options to use creating the
  134. * Statistics.
  135. */
  136. export default function Statistics(xmpp, options) {
  137. /**
  138. * {@link RTPStats} mapped by {@link TraceablePeerConnection.id} which
  139. * collect RTP statistics for each peerconnection.
  140. * @type {Map<string, RTPStats}
  141. */
  142. this.rtpStatsMap = new Map();
  143. this.eventEmitter = new EventEmitter();
  144. this.xmpp = xmpp;
  145. this.options = options || {};
  146. this.callStatsIntegrationEnabled
  147. = this.options.callStatsID && this.options.callStatsSecret && this.options.enableCallStats
  148. // Even though AppID and AppSecret may be specified, the integration
  149. // of callstats.io may be disabled because of globally-disallowed
  150. // requests to any third parties.
  151. && (Statistics.disableThirdPartyRequests !== true);
  152. if (this.callStatsIntegrationEnabled) {
  153. this.callStatsApplicationLogsDisabled
  154. = this.options.callStatsApplicationLogsDisabled;
  155. if (browser.isReactNative()) {
  156. _initCallStatsBackend(this.options);
  157. } else {
  158. loadCallStatsAPI(this.options);
  159. }
  160. if (!this.options.confID) {
  161. logger.warn('"confID" is not defined');
  162. }
  163. }
  164. /**
  165. * Stores {@link CallStats} instances for each
  166. * {@link TraceablePeerConnection} (one {@link CallStats} instance serves
  167. * one TPC). The instances are mapped by {@link TraceablePeerConnection.id}.
  168. * @type {Map<number, CallStats>}
  169. */
  170. this.callsStatsInstances = new Map();
  171. Statistics.instances.add(this);
  172. }
  173. Statistics.audioLevelsEnabled = false;
  174. Statistics.audioLevelsInterval = 200;
  175. Statistics.pcStatsInterval = 10000;
  176. Statistics.disableThirdPartyRequests = false;
  177. Statistics.analytics = analytics;
  178. Object.defineProperty(Statistics, 'instances', {
  179. /**
  180. * Returns the Set holding all active {@link Statistics} instances. Lazily
  181. * initializes the Set to allow any Set polyfills to be applied.
  182. * @type {Set<Statistics>}
  183. */
  184. get() {
  185. if (!_instances) {
  186. _instances = new Set();
  187. }
  188. return _instances;
  189. }
  190. });
  191. /**
  192. * Starts collecting RTP stats for given peerconnection.
  193. * @param {TraceablePeerConnection} peerconnection
  194. */
  195. Statistics.prototype.startRemoteStats = function(peerconnection) {
  196. this.stopRemoteStats(peerconnection);
  197. try {
  198. const rtpStats
  199. = new RTPStats(
  200. peerconnection,
  201. Statistics.audioLevelsInterval,
  202. Statistics.pcStatsInterval,
  203. this.eventEmitter);
  204. rtpStats.start(Statistics.audioLevelsEnabled);
  205. this.rtpStatsMap.set(peerconnection.id, rtpStats);
  206. } catch (e) {
  207. logger.error(`Failed to start collecting remote statistics: ${e}`);
  208. }
  209. };
  210. Statistics.localStats = [];
  211. Statistics.startLocalStats = function(track, callback) {
  212. if (browser.isIosBrowser()) {
  213. // On iOS browsers audio is lost if the audio input device is in use by another app
  214. // https://bugs.webkit.org/show_bug.cgi?id=233473
  215. // The culprit was using the AudioContext, so now we close the AudioContext during
  216. // the track being muted, and re-instantiate it afterwards.
  217. track.addEventListener(
  218. JitsiTrackEvents.NO_DATA_FROM_SOURCE,
  219. /**
  220. * Closes AudioContext on no audio data, and enables it on data received again.
  221. *
  222. * @param {boolean} value - Whether we receive audio data or not.
  223. */
  224. async value => {
  225. if (value) {
  226. for (const localStat of Statistics.localStats) {
  227. localStat.stop();
  228. }
  229. await LocalStats.disconnectAudioContext();
  230. } else {
  231. LocalStats.connectAudioContext();
  232. for (const localStat of Statistics.localStats) {
  233. localStat.start();
  234. }
  235. }
  236. });
  237. }
  238. if (!Statistics.audioLevelsEnabled) {
  239. return;
  240. }
  241. track.addEventListener(
  242. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  243. () => {
  244. Statistics.stopLocalStats(track);
  245. });
  246. const stream = track.getOriginalStream();
  247. const localStats = new LocalStats(stream, Statistics.audioLevelsInterval,
  248. callback);
  249. this.localStats.push(localStats);
  250. localStats.start();
  251. };
  252. Statistics.prototype.addAudioLevelListener = function(listener) {
  253. if (!Statistics.audioLevelsEnabled) {
  254. return;
  255. }
  256. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  257. };
  258. Statistics.prototype.removeAudioLevelListener = function(listener) {
  259. if (!Statistics.audioLevelsEnabled) {
  260. return;
  261. }
  262. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  263. };
  264. Statistics.prototype.addBeforeDisposedListener = function(listener) {
  265. this.eventEmitter.on(StatisticsEvents.BEFORE_DISPOSED, listener);
  266. };
  267. Statistics.prototype.removeBeforeDisposedListener = function(listener) {
  268. this.eventEmitter.removeListener(
  269. StatisticsEvents.BEFORE_DISPOSED, listener);
  270. };
  271. Statistics.prototype.addConnectionStatsListener = function(listener) {
  272. this.eventEmitter.on(StatisticsEvents.CONNECTION_STATS, listener);
  273. };
  274. Statistics.prototype.removeConnectionStatsListener = function(listener) {
  275. this.eventEmitter.removeListener(
  276. StatisticsEvents.CONNECTION_STATS,
  277. listener);
  278. };
  279. Statistics.prototype.addByteSentStatsListener = function(listener) {
  280. this.eventEmitter.on(StatisticsEvents.BYTE_SENT_STATS, listener);
  281. };
  282. Statistics.prototype.removeByteSentStatsListener = function(listener) {
  283. this.eventEmitter.removeListener(StatisticsEvents.BYTE_SENT_STATS,
  284. listener);
  285. };
  286. /**
  287. * Add a listener that would be notified on a LONG_TASKS_STATS event.
  288. *
  289. * @param {Function} listener a function that would be called when notified.
  290. * @returns {void}
  291. */
  292. Statistics.prototype.addLongTasksStatsListener = function(listener) {
  293. this.eventEmitter.on(StatisticsEvents.LONG_TASKS_STATS, listener);
  294. };
  295. /**
  296. * Creates an instance of {@link PerformanceObserverStats} and starts the
  297. * observer that records the stats periodically.
  298. *
  299. * @returns {void}
  300. */
  301. Statistics.prototype.attachLongTasksStats = function(conference) {
  302. if (!browser.supportsPerformanceObserver()) {
  303. logger.warn('Performance observer for long tasks not supported by browser!');
  304. return;
  305. }
  306. this.performanceObserverStats = new PerformanceObserverStats(
  307. this.eventEmitter,
  308. Statistics.longTasksStatsInterval);
  309. conference.on(
  310. JitsiConferenceEvents.CONFERENCE_JOINED,
  311. () => this.performanceObserverStats.startObserver());
  312. conference.on(
  313. JitsiConferenceEvents.CONFERENCE_LEFT,
  314. () => this.performanceObserverStats.stopObserver());
  315. };
  316. /**
  317. * Obtains the current value of the LongTasks event statistics.
  318. *
  319. * @returns {Object|null} stats object if the observer has been
  320. * created, null otherwise.
  321. */
  322. Statistics.prototype.getLongTasksStats = function() {
  323. return this.performanceObserverStats
  324. ? this.performanceObserverStats.getLongTasksStats()
  325. : null;
  326. };
  327. /**
  328. * Removes the given listener for the LONG_TASKS_STATS event.
  329. *
  330. * @param {Function} listener the listener we want to remove.
  331. * @returns {void}
  332. */
  333. Statistics.prototype.removeLongTasksStatsListener = function(listener) {
  334. this.eventEmitter.removeListener(StatisticsEvents.LONG_TASKS_STATS, listener);
  335. };
  336. /**
  337. * Updates the list of speakers for which the audio levels are to be calculated. This is needed for the jvb pc only.
  338. *
  339. * @param {Array<string>} speakerList The list of remote endpoint ids.
  340. * @returns {void}
  341. */
  342. Statistics.prototype.setSpeakerList = function(speakerList) {
  343. for (const rtpStats of Array.from(this.rtpStatsMap.values())) {
  344. if (!rtpStats.peerconnection.isP2P) {
  345. rtpStats.setSpeakerList(speakerList);
  346. }
  347. }
  348. };
  349. Statistics.prototype.dispose = function() {
  350. try {
  351. // NOTE Before reading this please see the comment in stopCallStats...
  352. //
  353. // Here we prevent from emitting the event twice in case it will be
  354. // triggered from stopCallStats.
  355. // If the event is triggered from here it means that the logs will not
  356. // be submitted anyway (because there is no CallStats instance), but
  357. // we're doing that for the sake of some kind of consistency.
  358. if (!this.callsStatsInstances.size) {
  359. this.eventEmitter.emit(StatisticsEvents.BEFORE_DISPOSED);
  360. }
  361. for (const callStats of this.callsStatsInstances.values()) {
  362. this.stopCallStats(callStats.tpc);
  363. }
  364. for (const tpcId of this.rtpStatsMap.keys()) {
  365. this._stopRemoteStats(tpcId);
  366. }
  367. if (this.eventEmitter) {
  368. this.eventEmitter.removeAllListeners();
  369. }
  370. } finally {
  371. Statistics.instances.delete(this);
  372. }
  373. };
  374. Statistics.stopLocalStats = function(track) {
  375. if (!Statistics.audioLevelsEnabled) {
  376. return;
  377. }
  378. const stream = track.getOriginalStream();
  379. for (let i = 0; i < Statistics.localStats.length; i++) {
  380. if (Statistics.localStats[i].stream === stream) {
  381. const localStats = Statistics.localStats.splice(i, 1);
  382. localStats[0].stop();
  383. break;
  384. }
  385. }
  386. };
  387. /**
  388. * Stops remote RTP stats for given peerconnection ID.
  389. * @param {string} tpcId {@link TraceablePeerConnection.id}
  390. * @private
  391. */
  392. Statistics.prototype._stopRemoteStats = function(tpcId) {
  393. const rtpStats = this.rtpStatsMap.get(tpcId);
  394. if (rtpStats) {
  395. rtpStats.stop();
  396. this.rtpStatsMap.delete(tpcId);
  397. }
  398. };
  399. /**
  400. * Stops collecting RTP stats for given peerconnection
  401. * @param {TraceablePeerConnection} tpc
  402. */
  403. Statistics.prototype.stopRemoteStats = function(tpc) {
  404. this._stopRemoteStats(tpc.id);
  405. };
  406. // CALSTATS METHODS
  407. /**
  408. * Initializes the callstats.io API.
  409. * @param {TraceablePeerConnection} tpc the {@link TraceablePeerConnection}
  410. * instance for which CalStats will be started.
  411. * @param {string} remoteUserID
  412. */
  413. Statistics.prototype.startCallStats = function(tpc, remoteUserID) {
  414. if (!this.callStatsIntegrationEnabled) {
  415. return;
  416. } else if (this.callsStatsInstances.has(tpc.id)) {
  417. logger.error('CallStats instance for ${tpc} exists already');
  418. return;
  419. }
  420. let confID = this.options.confID;
  421. // confID - domain/tenant/roomName
  422. // roomName - meeting name or breakout room ID
  423. // For breakout rooms we change the conference ID used for callstats to use
  424. // the room ID instead of the meeting name
  425. if (!confID.endsWith(this.options.roomName)) {
  426. confID = `${this.options.confID.slice(0, this.options.confID.lastIndexOf('/'))}/${this.options.roomName}`;
  427. }
  428. logger.info(`Starting CallStats for ${tpc}...`);
  429. const newInstance
  430. = new CallStats(
  431. tpc,
  432. {
  433. confID,
  434. remoteUserID
  435. });
  436. this.callsStatsInstances.set(tpc.id, newInstance);
  437. };
  438. /**
  439. * Obtains the list of *all* {@link CallStats} instances collected from every
  440. * valid {@link Statistics} instance.
  441. * @return {Set<CallStats>}
  442. * @private
  443. */
  444. Statistics._getAllCallStatsInstances = function() {
  445. const csInstances = new Set();
  446. for (const statistics of Statistics.instances) {
  447. for (const cs of statistics.callsStatsInstances.values()) {
  448. csInstances.add(cs);
  449. }
  450. }
  451. return csInstances;
  452. };
  453. /**
  454. * Removes the callstats.io instances.
  455. */
  456. Statistics.prototype.stopCallStats = function(tpc) {
  457. const callStatsInstance = this.callsStatsInstances.get(tpc.id);
  458. if (callStatsInstance) {
  459. // FIXME the original purpose of adding BEFORE_DISPOSED event was to be
  460. // able to submit the last log batch from jitsi-meet to CallStats. After
  461. // recent changes we dispose the CallStats earlier
  462. // (before Statistics.dispose), so we need to emit this event here to
  463. // give this last chance for final log batch submission.
  464. //
  465. // Eventually there should be a separate module called "log storage"
  466. // which should emit proper events when it's underlying
  467. // CallStats instance is going away.
  468. if (this.callsStatsInstances.size === 1) {
  469. this.eventEmitter.emit(StatisticsEvents.BEFORE_DISPOSED);
  470. }
  471. this.callsStatsInstances.delete(tpc.id);
  472. // The fabric needs to be terminated when being stopped
  473. callStatsInstance.sendTerminateEvent();
  474. }
  475. };
  476. /**
  477. * Returns true if the callstats integration is enabled, otherwise returns
  478. * false.
  479. *
  480. * @returns true if the callstats integration is enabled, otherwise returns
  481. * false.
  482. */
  483. Statistics.prototype.isCallstatsEnabled = function() {
  484. return this.callStatsIntegrationEnabled;
  485. };
  486. /**
  487. * Logs either resume or hold event for the given peer connection.
  488. * @param {TraceablePeerConnection} tpc the connection for which event will be
  489. * reported
  490. * @param {boolean} isResume true for resume or false for hold
  491. */
  492. Statistics.prototype.sendConnectionResumeOrHoldEvent = function(tpc, isResume) {
  493. const instance = this.callsStatsInstances.get(tpc.id);
  494. if (instance) {
  495. instance.sendResumeOrHoldEvent(isResume);
  496. }
  497. };
  498. /**
  499. * Notifies CallStats and analytics (if present) for ice connection failed
  500. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  501. */
  502. Statistics.prototype.sendIceConnectionFailedEvent = function(tpc) {
  503. const instance = this.callsStatsInstances.get(tpc.id);
  504. if (instance) {
  505. instance.sendIceConnectionFailedEvent();
  506. }
  507. };
  508. /**
  509. * Notifies CallStats for mute events
  510. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  511. * @param {boolean} muted true for muted and false for not muted
  512. * @param {String} type "audio"/"video"
  513. */
  514. Statistics.prototype.sendMuteEvent = function(tpc, muted, type) {
  515. const instance = tpc && this.callsStatsInstances.get(tpc.id);
  516. CallStats.sendMuteEvent(muted, type, instance);
  517. };
  518. /**
  519. * Notifies CallStats for screen sharing events
  520. * @param start {boolean} true for starting screen sharing and
  521. * false for not stopping
  522. * @param {string|null} ssrc - optional ssrc value, used only when
  523. * starting screen sharing.
  524. */
  525. Statistics.prototype.sendScreenSharingEvent
  526. = function(start, ssrc) {
  527. for (const cs of this.callsStatsInstances.values()) {
  528. cs.sendScreenSharingEvent(start, ssrc);
  529. }
  530. };
  531. /**
  532. * Notifies the statistics module that we are now the dominant speaker of the
  533. * conference.
  534. * @param {String} roomJid - The room jid where the speaker event occurred.
  535. */
  536. Statistics.prototype.sendDominantSpeakerEvent = function(roomJid) {
  537. for (const cs of this.callsStatsInstances.values()) {
  538. cs.sendDominantSpeakerEvent();
  539. }
  540. // xmpp send dominant speaker event
  541. this.xmpp.sendDominantSpeakerEvent(roomJid);
  542. };
  543. /**
  544. * Notifies about active device.
  545. * @param {{deviceList: {String:String}}} devicesData - list of devices with
  546. * their data
  547. */
  548. Statistics.sendActiveDeviceListEvent = function(devicesData) {
  549. const globalSet = Statistics._getAllCallStatsInstances();
  550. if (globalSet.size) {
  551. for (const cs of globalSet) {
  552. CallStats.sendActiveDeviceListEvent(devicesData, cs);
  553. }
  554. } else {
  555. CallStats.sendActiveDeviceListEvent(devicesData, null);
  556. }
  557. };
  558. /* eslint-disable max-params */
  559. /**
  560. * Lets the underlying statistics module know where is given SSRC rendered by
  561. * providing renderer tag ID.
  562. * @param {TraceablePeerConnection} tpc the connection to which the stream
  563. * belongs to
  564. * @param {number} ssrc the SSRC of the stream
  565. * @param {boolean} isLocal
  566. * @param {string} userId
  567. * @param {string} usageLabel meaningful usage label of this stream like
  568. * 'microphone', 'camera' or 'screen'.
  569. * @param {string} containerId the id of media 'audio' or 'video' tag which
  570. * renders the stream.
  571. */
  572. Statistics.prototype.associateStreamWithVideoTag = function(
  573. tpc,
  574. ssrc,
  575. isLocal,
  576. userId,
  577. usageLabel,
  578. containerId) {
  579. const instance = this.callsStatsInstances.get(tpc.id);
  580. if (instance) {
  581. instance.associateStreamWithVideoTag(
  582. ssrc,
  583. isLocal,
  584. userId,
  585. usageLabel,
  586. containerId);
  587. }
  588. };
  589. /* eslint-enable max-params */
  590. /**
  591. * Notifies CallStats that getUserMedia failed.
  592. *
  593. * @param {Error} e error to send
  594. */
  595. Statistics.sendGetUserMediaFailed = function(e) {
  596. const error
  597. = e instanceof JitsiTrackError
  598. ? formatJitsiTrackErrorForCallStats(e) : e;
  599. const globalSet = Statistics._getAllCallStatsInstances();
  600. if (globalSet.size) {
  601. for (const cs of globalSet) {
  602. CallStats.sendGetUserMediaFailed(error, cs);
  603. }
  604. } else {
  605. CallStats.sendGetUserMediaFailed(error, null);
  606. }
  607. };
  608. /**
  609. * Notifies CallStats that peer connection failed to create offer.
  610. *
  611. * @param {Error} e error to send
  612. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  613. */
  614. Statistics.prototype.sendCreateOfferFailed = function(e, tpc) {
  615. const instance = this.callsStatsInstances.get(tpc.id);
  616. if (instance) {
  617. instance.sendCreateOfferFailed(e);
  618. }
  619. };
  620. /**
  621. * Notifies CallStats that peer connection failed to create answer.
  622. *
  623. * @param {Error} e error to send
  624. * @param {TraceablePeerConnection} tpc connection on which failure occured.
  625. */
  626. Statistics.prototype.sendCreateAnswerFailed = function(e, tpc) {
  627. const instance = this.callsStatsInstances.get(tpc.id);
  628. if (instance) {
  629. instance.sendCreateAnswerFailed(e);
  630. }
  631. };
  632. /**
  633. * Notifies CallStats that peer connection failed to set local description.
  634. *
  635. * @param {Error} e error to send
  636. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  637. */
  638. Statistics.prototype.sendSetLocalDescFailed = function(e, tpc) {
  639. const instance = this.callsStatsInstances.get(tpc.id);
  640. if (instance) {
  641. instance.sendSetLocalDescFailed(e);
  642. }
  643. };
  644. /**
  645. * Notifies CallStats that peer connection failed to set remote description.
  646. *
  647. * @param {Error} e error to send
  648. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  649. */
  650. Statistics.prototype.sendSetRemoteDescFailed = function(e, tpc) {
  651. const instance = this.callsStatsInstances.get(tpc.id);
  652. if (instance) {
  653. instance.sendSetRemoteDescFailed(e);
  654. }
  655. };
  656. /**
  657. * Notifies CallStats that peer connection failed to add ICE candidate.
  658. *
  659. * @param {Error} e error to send
  660. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  661. */
  662. Statistics.prototype.sendAddIceCandidateFailed = function(e, tpc) {
  663. const instance = this.callsStatsInstances.get(tpc.id);
  664. if (instance) {
  665. instance.sendAddIceCandidateFailed(e);
  666. }
  667. };
  668. /**
  669. * Adds to CallStats an application log.
  670. *
  671. * @param {String} m a log message to send or an {Error} object to be reported
  672. */
  673. Statistics.sendLog = function(m) {
  674. const globalSubSet = new Set();
  675. // FIXME we don't want to duplicate logs over P2P instance, but
  676. // here we should go over instances and call this method for each
  677. // unique conference ID rather than selecting the first one.
  678. // We don't have such use case though, so leaving as is for now.
  679. for (const stats of Statistics.instances) {
  680. if (stats.callStatsApplicationLogsDisabled) {
  681. return;
  682. }
  683. if (stats.callsStatsInstances.size) {
  684. globalSubSet.add(stats.callsStatsInstances.values().next().value);
  685. }
  686. }
  687. if (globalSubSet.size) {
  688. for (const csPerStats of globalSubSet) {
  689. CallStats.sendApplicationLog(m, csPerStats);
  690. }
  691. } else {
  692. CallStats.sendApplicationLog(m, null);
  693. }
  694. };
  695. /**
  696. * Sends the given feedback through CallStats.
  697. *
  698. * @param overall an integer between 1 and 5 indicating the user's rating.
  699. * @param comment the comment from the user.
  700. * @returns {Promise} Resolves when callstats feedback has been submitted
  701. * successfully.
  702. */
  703. Statistics.prototype.sendFeedback = function(overall, comment) {
  704. // Statistics.analytics.sendEvent is currently fire and forget, without
  705. // confirmation of successful send.
  706. Statistics.analytics.sendEvent(
  707. FEEDBACK,
  708. {
  709. rating: overall,
  710. comment
  711. });
  712. return CallStats.sendFeedback(this.options.confID, overall, comment);
  713. };
  714. Statistics.LOCAL_JID = require('../../service/statistics/constants').LOCAL_JID;
  715. /**
  716. * Reports global error to CallStats.
  717. *
  718. * @param {Error} error
  719. */
  720. Statistics.reportGlobalError = function(error) {
  721. if (error instanceof JitsiTrackError && error.gum) {
  722. Statistics.sendGetUserMediaFailed(error);
  723. } else {
  724. Statistics.sendLog(error);
  725. }
  726. };
  727. /**
  728. * Sends event to analytics and logs a message to the logger/console. Console
  729. * messages might also be logged to callstats automatically.
  730. *
  731. * @param {string | Object} event the event name, or an object which
  732. * represents the entire event.
  733. * @param {Object} properties properties to attach to the event (if an event
  734. * name as opposed to an event object is provided).
  735. */
  736. Statistics.sendAnalyticsAndLog = function(event, properties = {}) {
  737. if (!event) {
  738. logger.warn('No event or event name given.');
  739. return;
  740. }
  741. let eventToLog;
  742. // Also support an API with a single object as an event.
  743. if (typeof event === 'object') {
  744. eventToLog = event;
  745. } else {
  746. eventToLog = {
  747. name: event,
  748. properties
  749. };
  750. }
  751. logger.log(JSON.stringify(eventToLog));
  752. // We do this last, because it may modify the object which is passed.
  753. this.analytics.sendEvent(event, properties);
  754. };
  755. /**
  756. * Sends event to analytics.
  757. *
  758. * @param {string | Object} eventName the event name, or an object which
  759. * represents the entire event.
  760. * @param {Object} properties properties to attach to the event
  761. */
  762. Statistics.sendAnalytics = function(eventName, properties = {}) {
  763. this.analytics.sendEvent(eventName, properties);
  764. };