Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

statistics.js 23KB

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