您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

statistics.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /* global require */
  2. var LocalStats = require("./LocalStatsCollector.js");
  3. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4. var RTPStats = require("./RTPStatsCollector.js");
  5. var EventEmitter = require("events");
  6. var StatisticsEvents = require("../../service/statistics/Events");
  7. var AnalyticsAdapter = require("./AnalyticsAdapter");
  8. var CallStats = require("./CallStats");
  9. var ScriptUtil = require('../util/ScriptUtil');
  10. import JitsiTrackError from "../../JitsiTrackError";
  11. /**
  12. * True if callstats API is loaded
  13. */
  14. var isCallstatsLoaded = false;
  15. // Since callstats.io is a third party, we cannot guarantee the quality of their
  16. // service. More specifically, their server may take noticeably long time to
  17. // respond. Consequently, it is in our best interest (in the sense that the
  18. // intergration of callstats.io is pretty important to us but not enough to
  19. // allow it to prevent people from joining a conference) to (1) start
  20. // downloading their API as soon as possible and (2) do the downloading
  21. // asynchronously.
  22. function loadCallStatsAPI(customScriptUrl) {
  23. if(!isCallstatsLoaded) {
  24. ScriptUtil.loadScript(
  25. customScriptUrl ? customScriptUrl :
  26. 'https://api.callstats.io/static/callstats.min.js',
  27. /* async */ true,
  28. /* prepend */ true);
  29. isCallstatsLoaded = true;
  30. }
  31. // FIXME At the time of this writing, we hope that the callstats.io API will
  32. // have loaded by the time we needed it (i.e. CallStats.init is invoked).
  33. }
  34. // Load the integration of a third-party analytics API such as Google Analytics.
  35. // Since we cannot guarantee the quality of the third-party service (e.g. their
  36. // server may take noticeably long time to respond), it is in our best interest
  37. // (in the sense that the intergration of the analytics API is important to us
  38. // but not enough to allow it to prevent people from joining a conference) to
  39. // download the API asynchronously. Additionally, Google Analytics will download
  40. // its implementation asynchronously anyway so it makes sense to append the
  41. // loading on our side rather than prepend it.
  42. function loadAnalytics(customScriptUrl) {
  43. // if we have a custom script url passed as parameter we don't want to
  44. // search it relatively near the library
  45. ScriptUtil.loadScript(
  46. customScriptUrl ? customScriptUrl : 'analytics.js',
  47. /* async */ true,
  48. /* prepend */ false,
  49. /* relativeURL */ customScriptUrl ? false : true,
  50. /* loadCallback */ function () {
  51. Statistics.analytics.loaded();
  52. },
  53. /* errorCallback */ function () {
  54. Statistics.analytics.dispose();
  55. });
  56. }
  57. /**
  58. * Log stats via the focus once every this many milliseconds.
  59. */
  60. var LOG_INTERVAL = 60000;
  61. /**
  62. * callstats strips any additional fields from Error except for "name", "stack",
  63. * "message" and "constraintName". So we need to bundle additional information
  64. * from JitsiTrackError into error passed to callstats to preserve valuable
  65. * information about error.
  66. * @param {JitsiTrackError} error
  67. */
  68. function formatJitsiTrackErrorForCallStats(error) {
  69. var err = new Error();
  70. // Just copy original stack from error
  71. err.stack = error.stack;
  72. // Combine name from error's name plus (possibly) name of original GUM error
  73. err.name = (error.name || "Unknown error") + (error.gum && error.gum.error
  74. && error.gum.error.name ? " - " + error.gum.error.name : "");
  75. // Put all constraints into this field. For constraint failed errors we will
  76. // still know which exactly constraint failed as it will be a part of
  77. // message.
  78. err.constraintName = error.gum && error.gum.constraints
  79. ? JSON.stringify(error.gum.constraints) : "";
  80. // Just copy error's message.
  81. err.message = error.message;
  82. return err;
  83. }
  84. /**
  85. * Init statistic options
  86. * @param options
  87. */
  88. Statistics.init = function (options) {
  89. Statistics.audioLevelsEnabled = !options.disableAudioLevels;
  90. if(typeof options.audioLevelsInterval === 'number') {
  91. Statistics.audioLevelsInterval = options.audioLevelsInterval;
  92. }
  93. Statistics.disableThirdPartyRequests = options.disableThirdPartyRequests;
  94. if (Statistics.disableThirdPartyRequests !== true)
  95. loadAnalytics(options.analyticsScriptUrl);
  96. else // if not enable make sure we dispose any event that goes in the queue
  97. Statistics.analytics.dispose();
  98. };
  99. function Statistics(xmpp, options) {
  100. this.rtpStats = null;
  101. this.eventEmitter = new EventEmitter();
  102. this.xmpp = xmpp;
  103. this.options = options || {};
  104. this.callStatsIntegrationEnabled
  105. = this.options.callStatsID && this.options.callStatsSecret
  106. // Even though AppID and AppSecret may be specified, the integration
  107. // of callstats.io may be disabled because of globally-disallowed
  108. // requests to any third parties.
  109. && (Statistics.disableThirdPartyRequests !== true);
  110. if(this.callStatsIntegrationEnabled)
  111. loadCallStatsAPI(this.options.callStatsCustomScriptUrl);
  112. this.callStats = null;
  113. // Flag indicates whether or not the CallStats have been started for this
  114. // Statistics instance
  115. this.callStatsStarted = false;
  116. /**
  117. * Send the stats already saved in rtpStats to be logged via the focus.
  118. */
  119. this.logStatsIntervalId = null;
  120. }
  121. Statistics.audioLevelsEnabled = false;
  122. Statistics.audioLevelsInterval = 200;
  123. Statistics.disableThirdPartyRequests = false;
  124. Statistics.analytics = AnalyticsAdapter;
  125. /**
  126. * Array of callstats instances. Used to call Statistics static methods and
  127. * send stats to all cs instances.
  128. */
  129. Statistics.callsStatsInstances = [];
  130. Statistics.prototype.startRemoteStats = function (peerconnection) {
  131. this.stopRemoteStats();
  132. try {
  133. this.rtpStats
  134. = new RTPStats(peerconnection,
  135. Statistics.audioLevelsInterval, 2000, this.eventEmitter);
  136. this.rtpStats.start(Statistics.audioLevelsEnabled);
  137. } catch (e) {
  138. this.rtpStats = null;
  139. logger.error('Failed to start collecting remote statistics: ' + e);
  140. }
  141. if (this.rtpStats) {
  142. this.logStatsIntervalId = setInterval(function () {
  143. var stats = this.rtpStats.getCollectedStats();
  144. if (this.xmpp.sendLogs(stats)) {
  145. this.rtpStats.clearCollectedStats();
  146. }
  147. }.bind(this), LOG_INTERVAL);
  148. }
  149. };
  150. Statistics.localStats = [];
  151. Statistics.startLocalStats = function (stream, callback) {
  152. if(!Statistics.audioLevelsEnabled)
  153. return;
  154. var localStats = new LocalStats(stream, Statistics.audioLevelsInterval,
  155. callback);
  156. this.localStats.push(localStats);
  157. localStats.start();
  158. };
  159. Statistics.prototype.addAudioLevelListener = function(listener) {
  160. if(!Statistics.audioLevelsEnabled)
  161. return;
  162. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  163. };
  164. Statistics.prototype.removeAudioLevelListener = function(listener) {
  165. if(!Statistics.audioLevelsEnabled)
  166. return;
  167. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  168. };
  169. /**
  170. * Adds listener for detected audio problems.
  171. * @param listener the listener.
  172. */
  173. Statistics.prototype.addAudioProblemListener = function (listener) {
  174. this.eventEmitter.on(StatisticsEvents.AUDIO_NOT_WORKING, listener);
  175. };
  176. Statistics.prototype.addConnectionStatsListener = function (listener) {
  177. this.eventEmitter.on(StatisticsEvents.CONNECTION_STATS, listener);
  178. };
  179. Statistics.prototype.removeConnectionStatsListener = function (listener) {
  180. this.eventEmitter.removeListener(StatisticsEvents.CONNECTION_STATS, listener);
  181. };
  182. Statistics.prototype.addByteSentStatsListener = function (listener) {
  183. this.eventEmitter.on(StatisticsEvents.BYTE_SENT_STATS, listener);
  184. };
  185. Statistics.prototype.removeByteSentStatsListener = function (listener) {
  186. this.eventEmitter.removeListener(StatisticsEvents.BYTE_SENT_STATS,
  187. listener);
  188. };
  189. Statistics.prototype.dispose = function () {
  190. this.stopRemoteStats();
  191. if(this.eventEmitter)
  192. this.eventEmitter.removeAllListeners();
  193. };
  194. Statistics.stopLocalStats = function (stream) {
  195. if(!Statistics.audioLevelsEnabled)
  196. return;
  197. for(var i = 0; i < Statistics.localStats.length; i++)
  198. if(Statistics.localStats[i].stream === stream){
  199. var localStats = Statistics.localStats.splice(i, 1);
  200. localStats[0].stop();
  201. break;
  202. }
  203. };
  204. Statistics.prototype.stopRemoteStats = function () {
  205. if (!this.rtpStats) {
  206. return;
  207. }
  208. this.rtpStats.stop();
  209. this.rtpStats = null;
  210. if (this.logStatsIntervalId) {
  211. clearInterval(this.logStatsIntervalId);
  212. this.logStatsIntervalId = null;
  213. }
  214. };
  215. //CALSTATS METHODS
  216. /**
  217. * Initializes the callstats.io API.
  218. * @param peerConnection {JingleSessionPC} the session object
  219. * @param Settings {Settings} the settings instance. Declared in
  220. * /modules/settings/Settings.js
  221. */
  222. Statistics.prototype.startCallStats = function (session, settings) {
  223. if(this.callStatsIntegrationEnabled && !this.callStatsStarted) {
  224. // Here we overwrite the previous instance, but it must be bound to
  225. // the new PeerConnection
  226. // FIXME CallStats does not show the participant after
  227. // stopCallStats/startCallStats, the issue is being investigated on both
  228. // our and CallStats side, but given how rare this situation should
  229. // be, we need to have this change merged. Without it "invalid pcHash"
  230. // error is reported(lib calls are made for the old PeerConnection).
  231. this.callstats = new CallStats(session, settings, this.options);
  232. Statistics.callsStatsInstances.push(this.callstats);
  233. this.callStatsStarted = true;
  234. }
  235. };
  236. /**
  237. * Removes the callstats.io instances.
  238. */
  239. Statistics.prototype.stopCallStats = function () {
  240. if(this.callStatsStarted) {
  241. var index = Statistics.callsStatsInstances.indexOf(this.callstats);
  242. if(index > -1)
  243. Statistics.callsStatsInstances.splice(index, 1);
  244. // The next line is commented because we need to be able to send
  245. // feedback even after the conference has been destroyed.
  246. // this.callstats = null;
  247. CallStats.dispose();
  248. this.callStatsStarted = false;
  249. }
  250. };
  251. /**
  252. * Returns true if the callstats integration is enabled, otherwise returns
  253. * false.
  254. *
  255. * @returns true if the callstats integration is enabled, otherwise returns
  256. * false.
  257. */
  258. Statistics.prototype.isCallstatsEnabled = function () {
  259. return this.callStatsIntegrationEnabled;
  260. };
  261. /**
  262. * Notifies CallStats for ice connection failed
  263. * @param {RTCPeerConnection} pc connection on which failure occured.
  264. */
  265. Statistics.prototype.sendIceConnectionFailedEvent = function (pc) {
  266. if(this.callstats)
  267. this.callstats.sendIceConnectionFailedEvent(pc, this.callstats);
  268. };
  269. /**
  270. * Notifies CallStats for mute events
  271. * @param mute {boolean} true for muted and false for not muted
  272. * @param type {String} "audio"/"video"
  273. */
  274. Statistics.prototype.sendMuteEvent = function (muted, type) {
  275. if(this.callstats)
  276. CallStats.sendMuteEvent(muted, type, this.callstats);
  277. };
  278. /**
  279. * Notifies CallStats for screen sharing events
  280. * @param start {boolean} true for starting screen sharing and
  281. * false for not stopping
  282. */
  283. Statistics.prototype.sendScreenSharingEvent = function (start) {
  284. if(this.callstats)
  285. CallStats.sendScreenSharingEvent(start, this.callstats);
  286. };
  287. /**
  288. * Notifies the statistics module that we are now the dominant speaker of the
  289. * conference.
  290. */
  291. Statistics.prototype.sendDominantSpeakerEvent = function () {
  292. if(this.callstats)
  293. CallStats.sendDominantSpeakerEvent(this.callstats);
  294. };
  295. /**
  296. * Notifies about active device.
  297. * @param {{deviceList: {String:String}}} devicesData - list of devices with
  298. * their data
  299. */
  300. Statistics.sendActiveDeviceListEvent = function (devicesData) {
  301. if (Statistics.callsStatsInstances.length) {
  302. Statistics.callsStatsInstances.forEach(function (cs) {
  303. CallStats.sendActiveDeviceListEvent(devicesData, cs);
  304. });
  305. } else {
  306. CallStats.sendActiveDeviceListEvent(devicesData, null);
  307. }
  308. };
  309. /**
  310. * Lets the underlying statistics module know where is given SSRC rendered by
  311. * providing renderer tag ID.
  312. * @param ssrc {number} the SSRC of the stream
  313. * @param isLocal {boolean} <tt>true<tt> if this stream is local or
  314. * <tt>false</tt> otherwise.
  315. * @param usageLabel {string} meaningful usage label of this stream like
  316. * 'microphone', 'camera' or 'screen'.
  317. * @param containerId {string} the id of media 'audio' or 'video' tag which
  318. * renders the stream.
  319. */
  320. Statistics.prototype.associateStreamWithVideoTag =
  321. function (ssrc, isLocal, usageLabel, containerId) {
  322. if(this.callstats) {
  323. this.callstats.associateStreamWithVideoTag(
  324. ssrc, isLocal, usageLabel, containerId);
  325. }
  326. };
  327. /**
  328. * Notifies CallStats that getUserMedia failed.
  329. *
  330. * @param {Error} e error to send
  331. */
  332. Statistics.sendGetUserMediaFailed = function (e) {
  333. if (Statistics.callsStatsInstances.length) {
  334. Statistics.callsStatsInstances.forEach(function (cs) {
  335. CallStats.sendGetUserMediaFailed(
  336. e instanceof JitsiTrackError
  337. ? formatJitsiTrackErrorForCallStats(e)
  338. : e,
  339. cs);
  340. });
  341. } else {
  342. CallStats.sendGetUserMediaFailed(
  343. e instanceof JitsiTrackError
  344. ? formatJitsiTrackErrorForCallStats(e)
  345. : e,
  346. null);
  347. }
  348. };
  349. /**
  350. * Notifies CallStats that peer connection failed to create offer.
  351. *
  352. * @param {Error} e error to send
  353. * @param {RTCPeerConnection} pc connection on which failure occured.
  354. */
  355. Statistics.prototype.sendCreateOfferFailed = function (e, pc) {
  356. if(this.callstats)
  357. CallStats.sendCreateOfferFailed(e, pc, this.callstats);
  358. };
  359. /**
  360. * Notifies CallStats that peer connection failed to create answer.
  361. *
  362. * @param {Error} e error to send
  363. * @param {RTCPeerConnection} pc connection on which failure occured.
  364. */
  365. Statistics.prototype.sendCreateAnswerFailed = function (e, pc) {
  366. if(this.callstats)
  367. CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
  368. };
  369. /**
  370. * Notifies CallStats that peer connection failed to set local description.
  371. *
  372. * @param {Error} e error to send
  373. * @param {RTCPeerConnection} pc connection on which failure occured.
  374. */
  375. Statistics.prototype.sendSetLocalDescFailed = function (e, pc) {
  376. if(this.callstats)
  377. CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
  378. };
  379. /**
  380. * Notifies CallStats that peer connection failed to set remote description.
  381. *
  382. * @param {Error} e error to send
  383. * @param {RTCPeerConnection} pc connection on which failure occured.
  384. */
  385. Statistics.prototype.sendSetRemoteDescFailed = function (e, pc) {
  386. if(this.callstats)
  387. CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
  388. };
  389. /**
  390. * Notifies CallStats that peer connection failed to add ICE candidate.
  391. *
  392. * @param {Error} e error to send
  393. * @param {RTCPeerConnection} pc connection on which failure occured.
  394. */
  395. Statistics.prototype.sendAddIceCandidateFailed = function (e, pc) {
  396. if(this.callstats)
  397. CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
  398. };
  399. /**
  400. * Notifies CallStats that audio problems are detected.
  401. *
  402. * @param {Error} e error to send
  403. */
  404. Statistics.prototype.sendDetectedAudioProblem = function (e) {
  405. if(this.callstats)
  406. this.callstats.sendDetectedAudioProblem(e);
  407. };
  408. /**
  409. * Adds to CallStats an application log.
  410. *
  411. * @param {String} a log message to send or an {Error} object to be reported
  412. */
  413. Statistics.sendLog = function (m) {
  414. if (Statistics.callsStatsInstances.length) {
  415. Statistics.callsStatsInstances.forEach(function (cs) {
  416. CallStats.sendApplicationLog(m, cs);
  417. });
  418. } else {
  419. CallStats.sendApplicationLog(m, null);
  420. }
  421. };
  422. /**
  423. * Sends the given feedback through CallStats.
  424. *
  425. * @param overall an integer between 1 and 5 indicating the user feedback
  426. * @param detailed detailed feedback from the user. Not yet used
  427. */
  428. Statistics.prototype.sendFeedback = function(overall, detailed) {
  429. if(this.callstats)
  430. this.callstats.sendFeedback(overall, detailed);
  431. Statistics.analytics.sendEvent('feedback.rating', overall);
  432. };
  433. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  434. /**
  435. * Reports global error to CallStats.
  436. *
  437. * @param {Error} error
  438. */
  439. Statistics.reportGlobalError = function (error) {
  440. if (error instanceof JitsiTrackError && error.gum) {
  441. Statistics.sendGetUserMediaFailed(error);
  442. } else {
  443. Statistics.sendLog(error);
  444. }
  445. };
  446. /**
  447. * Sends event to analytics and callstats.
  448. * @param eventName {string} the event name.
  449. * @param msg {String} optional event info/messages.
  450. */
  451. Statistics.sendEventToAll = function (eventName, msg) {
  452. this.analytics.sendEvent(eventName, null, msg);
  453. Statistics.sendLog({name: eventName, msg: msg ? msg : ""});
  454. };
  455. module.exports = Statistics;