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

statistics.js 16KB

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