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

statistics.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. // Flag indicates whether or not the CallStats have been started for this
  113. // Statistics instance
  114. this.callStatsStarted = false;
  115. /**
  116. * Send the stats already saved in rtpStats to be logged via the focus.
  117. */
  118. this.logStatsIntervalId = null;
  119. }
  120. Statistics.audioLevelsEnabled = false;
  121. Statistics.audioLevelsInterval = 200;
  122. Statistics.disableThirdPartyRequests = false;
  123. Statistics.analytics = AnalyticsAdapter;
  124. /**
  125. * Array of callstats instances. Used to call Statistics static methods and
  126. * send stats to all cs instances.
  127. */
  128. Statistics.callsStatsInstances = [];
  129. Statistics.prototype.startRemoteStats = function (peerconnection) {
  130. this.stopRemoteStats();
  131. try {
  132. this.rtpStats
  133. = new RTPStats(peerconnection,
  134. Statistics.audioLevelsInterval, 2000, this.eventEmitter);
  135. this.rtpStats.start(Statistics.audioLevelsEnabled);
  136. } catch (e) {
  137. this.rtpStats = null;
  138. logger.error('Failed to start collecting remote statistics: ' + e);
  139. }
  140. if (this.rtpStats) {
  141. this.logStatsIntervalId = setInterval(function () {
  142. var stats = this.rtpStats.getCollectedStats();
  143. if (this.xmpp.sendLogs(stats)) {
  144. this.rtpStats.clearCollectedStats();
  145. }
  146. }.bind(this), LOG_INTERVAL);
  147. }
  148. };
  149. Statistics.localStats = [];
  150. Statistics.startLocalStats = function (stream, callback) {
  151. if(!Statistics.audioLevelsEnabled)
  152. return;
  153. var localStats = new LocalStats(stream, Statistics.audioLevelsInterval,
  154. callback);
  155. this.localStats.push(localStats);
  156. localStats.start();
  157. };
  158. Statistics.prototype.addAudioLevelListener = function(listener) {
  159. if(!Statistics.audioLevelsEnabled)
  160. return;
  161. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  162. };
  163. Statistics.prototype.removeAudioLevelListener = function(listener) {
  164. if(!Statistics.audioLevelsEnabled)
  165. return;
  166. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  167. };
  168. /**
  169. * Adds listener for detected audio problems.
  170. * @param listener the listener.
  171. */
  172. Statistics.prototype.addAudioProblemListener = function (listener) {
  173. this.eventEmitter.on(StatisticsEvents.AUDIO_NOT_WORKING, listener);
  174. };
  175. Statistics.prototype.addConnectionStatsListener = function (listener) {
  176. this.eventEmitter.on(StatisticsEvents.CONNECTION_STATS, listener);
  177. };
  178. Statistics.prototype.removeConnectionStatsListener = function (listener) {
  179. this.eventEmitter.removeListener(StatisticsEvents.CONNECTION_STATS, listener);
  180. };
  181. Statistics.prototype.addByteSentStatsListener = function (listener) {
  182. this.eventEmitter.on(StatisticsEvents.BYTE_SENT_STATS, listener);
  183. };
  184. Statistics.prototype.removeByteSentStatsListener = function (listener) {
  185. this.eventEmitter.removeListener(StatisticsEvents.BYTE_SENT_STATS,
  186. listener);
  187. };
  188. Statistics.prototype.dispose = function () {
  189. this.stopRemoteStats();
  190. if(this.eventEmitter)
  191. this.eventEmitter.removeAllListeners();
  192. };
  193. Statistics.stopLocalStats = function (stream) {
  194. if(!Statistics.audioLevelsEnabled)
  195. return;
  196. for(var i = 0; i < Statistics.localStats.length; i++)
  197. if(Statistics.localStats[i].stream === stream){
  198. var localStats = Statistics.localStats.splice(i, 1);
  199. localStats[0].stop();
  200. break;
  201. }
  202. };
  203. Statistics.prototype.stopRemoteStats = function () {
  204. if (!this.rtpStats) {
  205. return;
  206. }
  207. this.rtpStats.stop();
  208. this.rtpStats = null;
  209. if (this.logStatsIntervalId) {
  210. clearInterval(this.logStatsIntervalId);
  211. this.logStatsIntervalId = null;
  212. }
  213. };
  214. //CALSTATS METHODS
  215. /**
  216. * Initializes the callstats.io API.
  217. * @param peerConnection {JingleSessionPC} the session object
  218. * @param Settings {Settings} the settings instance. Declared in
  219. * /modules/settings/Settings.js
  220. */
  221. Statistics.prototype.startCallStats = function (session, settings) {
  222. if(this.callStatsIntegrationEnabled && !this.callStatsStarted) {
  223. // Here we overwrite the previous instance, but it must be bound to
  224. // the new PeerConnection
  225. // FIXME CallStats does not show the participant after
  226. // stopCallStats/startCallStats, the issue is being investigated on both
  227. // our and CallStats side, but given how rare this situation should
  228. // be, we need to have this change merged. Without it "invalid pcHash"
  229. // error is reported(lib calls are made for the old PeerConnection).
  230. this.callstats = new CallStats(session, settings, this.options);
  231. Statistics.callsStatsInstances.push(this.callstats);
  232. this.callStatsStarted = true;
  233. }
  234. };
  235. /**
  236. * Removes the callstats.io instances.
  237. */
  238. Statistics.prototype.stopCallStats = function () {
  239. if(this.callStatsStarted) {
  240. var index = Statistics.callsStatsInstances.indexOf(this.callstats);
  241. if(index > -1)
  242. Statistics.callsStatsInstances.splice(index, 1);
  243. // The next line is commented because we need to be able to send
  244. // feedback even after the conference has been destroyed.
  245. // this.callstats = null;
  246. CallStats.dispose();
  247. this.callStatsStarted = false;
  248. }
  249. };
  250. /**
  251. * Returns true if the callstats integration is enabled, otherwise returns
  252. * false.
  253. *
  254. * @returns true if the callstats integration is enabled, otherwise returns
  255. * false.
  256. */
  257. Statistics.prototype.isCallstatsEnabled = function () {
  258. return this.callStatsIntegrationEnabled;
  259. };
  260. /**
  261. * Notifies CallStats for ice connection failed
  262. * @param {RTCPeerConnection} pc connection on which failure occured.
  263. */
  264. Statistics.prototype.sendIceConnectionFailedEvent = function (pc) {
  265. if(this.callstats)
  266. this.callstats.sendIceConnectionFailedEvent(pc, this.callstats);
  267. };
  268. /**
  269. * Notifies CallStats for mute events
  270. * @param mute {boolean} true for muted and false for not muted
  271. * @param type {String} "audio"/"video"
  272. */
  273. Statistics.prototype.sendMuteEvent = function (muted, type) {
  274. if(this.callstats)
  275. CallStats.sendMuteEvent(muted, type, this.callstats);
  276. };
  277. /**
  278. * Notifies CallStats for screen sharing events
  279. * @param start {boolean} true for starting screen sharing and
  280. * false for not stopping
  281. */
  282. Statistics.prototype.sendScreenSharingEvent = function (start) {
  283. if(this.callstats)
  284. CallStats.sendScreenSharingEvent(start, this.callstats);
  285. };
  286. /**
  287. * Notifies the statistics module that we are now the dominant speaker of the
  288. * conference.
  289. */
  290. Statistics.prototype.sendDominantSpeakerEvent = function () {
  291. if(this.callstats)
  292. CallStats.sendDominantSpeakerEvent(this.callstats);
  293. };
  294. /**
  295. * Notifies about active device.
  296. * @param {{deviceList: {String:String}}} devicesData - list of devices with
  297. * their data
  298. */
  299. Statistics.sendActiveDeviceListEvent = function (devicesData) {
  300. if (Statistics.callsStatsInstances.length) {
  301. Statistics.callsStatsInstances.forEach(function (cs) {
  302. CallStats.sendActiveDeviceListEvent(devicesData, cs);
  303. });
  304. } else {
  305. CallStats.sendActiveDeviceListEvent(devicesData, null);
  306. }
  307. };
  308. /**
  309. * Lets the underlying statistics module know where is given SSRC rendered by
  310. * providing renderer tag ID.
  311. * @param ssrc {number} the SSRC of the stream
  312. * @param isLocal {boolean} <tt>true<tt> if this stream is local or
  313. * <tt>false</tt> otherwise.
  314. * @param usageLabel {string} meaningful usage label of this stream like
  315. * 'microphone', 'camera' or 'screen'.
  316. * @param containerId {string} the id of media 'audio' or 'video' tag which
  317. * renders the stream.
  318. */
  319. Statistics.prototype.associateStreamWithVideoTag =
  320. function (ssrc, isLocal, usageLabel, containerId) {
  321. if(this.callstats) {
  322. this.callstats.associateStreamWithVideoTag(
  323. ssrc, isLocal, usageLabel, containerId);
  324. }
  325. };
  326. /**
  327. * Notifies CallStats that getUserMedia failed.
  328. *
  329. * @param {Error} e error to send
  330. */
  331. Statistics.sendGetUserMediaFailed = function (e) {
  332. if (Statistics.callsStatsInstances.length) {
  333. Statistics.callsStatsInstances.forEach(function (cs) {
  334. CallStats.sendGetUserMediaFailed(
  335. e instanceof JitsiTrackError
  336. ? formatJitsiTrackErrorForCallStats(e)
  337. : e,
  338. cs);
  339. });
  340. } else {
  341. CallStats.sendGetUserMediaFailed(
  342. e instanceof JitsiTrackError
  343. ? formatJitsiTrackErrorForCallStats(e)
  344. : e,
  345. null);
  346. }
  347. };
  348. /**
  349. * Notifies CallStats that peer connection failed to create offer.
  350. *
  351. * @param {Error} e error to send
  352. * @param {RTCPeerConnection} pc connection on which failure occured.
  353. */
  354. Statistics.prototype.sendCreateOfferFailed = function (e, pc) {
  355. if(this.callstats)
  356. CallStats.sendCreateOfferFailed(e, pc, this.callstats);
  357. };
  358. /**
  359. * Notifies CallStats that peer connection failed to create answer.
  360. *
  361. * @param {Error} e error to send
  362. * @param {RTCPeerConnection} pc connection on which failure occured.
  363. */
  364. Statistics.prototype.sendCreateAnswerFailed = function (e, pc) {
  365. if(this.callstats)
  366. CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
  367. };
  368. /**
  369. * Notifies CallStats that peer connection failed to set local description.
  370. *
  371. * @param {Error} e error to send
  372. * @param {RTCPeerConnection} pc connection on which failure occured.
  373. */
  374. Statistics.prototype.sendSetLocalDescFailed = function (e, pc) {
  375. if(this.callstats)
  376. CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
  377. };
  378. /**
  379. * Notifies CallStats that peer connection failed to set remote description.
  380. *
  381. * @param {Error} e error to send
  382. * @param {RTCPeerConnection} pc connection on which failure occured.
  383. */
  384. Statistics.prototype.sendSetRemoteDescFailed = function (e, pc) {
  385. if(this.callstats)
  386. CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
  387. };
  388. /**
  389. * Notifies CallStats that peer connection failed to add ICE candidate.
  390. *
  391. * @param {Error} e error to send
  392. * @param {RTCPeerConnection} pc connection on which failure occured.
  393. */
  394. Statistics.prototype.sendAddIceCandidateFailed = function (e, pc) {
  395. if(this.callstats)
  396. CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
  397. };
  398. /**
  399. * Notifies CallStats that audio problems are detected.
  400. *
  401. * @param {Error} e error to send
  402. */
  403. Statistics.prototype.sendDetectedAudioProblem = function (e) {
  404. if(this.callstats)
  405. this.callstats.sendDetectedAudioProblem(e);
  406. };
  407. /**
  408. * Adds to CallStats an application log.
  409. *
  410. * @param {String} a log message to send or an {Error} object to be reported
  411. */
  412. Statistics.sendLog = function (m) {
  413. if (Statistics.callsStatsInstances.length) {
  414. Statistics.callsStatsInstances.forEach(function (cs) {
  415. CallStats.sendApplicationLog(m, cs);
  416. });
  417. } else {
  418. CallStats.sendApplicationLog(m, null);
  419. }
  420. };
  421. /**
  422. * Sends the given feedback through CallStats.
  423. *
  424. * @param overall an integer between 1 and 5 indicating the user feedback
  425. * @param detailed detailed feedback from the user. Not yet used
  426. */
  427. Statistics.prototype.sendFeedback = function(overall, detailed) {
  428. if(this.callstats)
  429. this.callstats.sendFeedback(overall, detailed);
  430. };
  431. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  432. /**
  433. * Reports global error to CallStats.
  434. *
  435. * @param {Error} error
  436. */
  437. Statistics.reportGlobalError = function (error) {
  438. if (error instanceof JitsiTrackError && error.gum) {
  439. Statistics.sendGetUserMediaFailed(error);
  440. } else {
  441. Statistics.sendLog(error);
  442. }
  443. };
  444. /**
  445. * Sends event to analytics and callstats.
  446. * @param eventName {string} the event name.
  447. * @param msg {String} optional event info/messages.
  448. */
  449. Statistics.sendEventToAll = function (eventName, msg) {
  450. this.analytics.sendEvent(eventName, null, msg);
  451. Statistics.sendLog({name: eventName, msg: msg ? msg : ""});
  452. };
  453. module.exports = Statistics;