modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

statistics.js 26KB

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