You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CallStats.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. /* global $, Strophe, callstats */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  4. var jsSHA = require('jssha');
  5. var io = require('socket.io-client');
  6. /**
  7. * We define enumeration of wrtcFuncNames as we need them before
  8. * callstats is initialized to queue events.
  9. * @const
  10. * @see http://www.callstats.io/api/#enumeration-of-wrtcfuncnames
  11. */
  12. var wrtcFuncNames = {
  13. createOffer: "createOffer",
  14. createAnswer: "createAnswer",
  15. setLocalDescription: "setLocalDescription",
  16. setRemoteDescription: "setRemoteDescription",
  17. addIceCandidate: "addIceCandidate",
  18. getUserMedia: "getUserMedia",
  19. iceConnectionFailure: "iceConnectionFailure",
  20. signalingError: "signalingError",
  21. applicationLog: "applicationLog"
  22. };
  23. /**
  24. * We define enumeration of fabricEvent as we need them before
  25. * callstats is initialized to queue events.
  26. * @const
  27. * @see http://www.callstats.io/api/#enumeration-of-fabricevent
  28. */
  29. var fabricEvent = {
  30. fabricHold:"fabricHold",
  31. fabricResume:"fabricResume",
  32. audioMute:"audioMute",
  33. audioUnmute:"audioUnmute",
  34. videoPause:"videoPause",
  35. videoResume:"videoResume",
  36. fabricUsageEvent:"fabricUsageEvent",
  37. fabricStats:"fabricStats",
  38. fabricTerminated:"fabricTerminated",
  39. screenShareStart:"screenShareStart",
  40. screenShareStop:"screenShareStop",
  41. dominantSpeaker:"dominantSpeaker",
  42. activeDeviceList:"activeDeviceList"
  43. };
  44. var callStats = null;
  45. /**
  46. * The user id to report to callstats as destination.
  47. * @type {string}
  48. */
  49. const DEFAULT_REMOTE_USER = "jitsi";
  50. function initCallback (err, msg) {
  51. logger.log("CallStats Status: err=" + err + " msg=" + msg);
  52. CallStats.initializeInProgress = false;
  53. // there is no lib, nothing to report to
  54. if (err !== 'success') {
  55. CallStats.initializeFailed = true;
  56. return;
  57. }
  58. var ret = callStats.addNewFabric(this.peerconnection,
  59. DEFAULT_REMOTE_USER,
  60. callStats.fabricUsage.multiplex,
  61. this.confID,
  62. this.pcCallback.bind(this));
  63. var fabricInitialized = (ret.status === 'success');
  64. if(!fabricInitialized) {
  65. CallStats.initializeFailed = true;
  66. logger.log("callstats fabric not initilized", ret.message);
  67. return;
  68. }
  69. CallStats.initializeFailed = false;
  70. CallStats.initialized = true;
  71. CallStats.feedbackEnabled = true;
  72. // notify callstats about failures if there were any
  73. if (CallStats.reportsQueue.length) {
  74. CallStats.reportsQueue.forEach(function (report) {
  75. if (report.type === reportType.ERROR) {
  76. var error = report.data;
  77. CallStats._reportError.call(this, error.type, error.error,
  78. error.pc);
  79. }
  80. // if we have and event to report and we failed to add fabric
  81. // this event will not be reported anyway, returning an error
  82. else if (report.type === reportType.EVENT
  83. && fabricInitialized) {
  84. var eventData = report.data;
  85. callStats.sendFabricEvent(
  86. this.peerconnection,
  87. eventData.event,
  88. this.confID,
  89. eventData.eventData);
  90. } else if (report.type === reportType.MST_WITH_USERID) {
  91. var data = report.data;
  92. callStats.associateMstWithUserID(
  93. this.peerconnection,
  94. data.callStatsId,
  95. this.confID,
  96. data.ssrc,
  97. data.usageLabel,
  98. data.containerId
  99. );
  100. }
  101. }, this);
  102. CallStats.reportsQueue.length = 0;
  103. }
  104. }
  105. /**
  106. * Returns a function which invokes f in a try/catch block, logs any exception
  107. * to the console, and then swallows it.
  108. *
  109. * @param f the function to invoke in a try/catch block
  110. * @return a function which invokes f in a try/catch block, logs any exception
  111. * to the console, and then swallows it
  112. */
  113. function _try_catch (f) {
  114. return function () {
  115. try {
  116. f.apply(this, arguments);
  117. } catch (e) {
  118. GlobalOnErrorHandler.callErrorHandler(e);
  119. logger.error(e);
  120. }
  121. };
  122. }
  123. /**
  124. * Creates new CallStats instance that handles all callstats API calls.
  125. * @param peerConnection {JingleSessionPC} the session object
  126. * @param Settings {Settings} the settings instance. Declared in
  127. * /modules/settings/Settings.js
  128. * @param options {object} credentials for callstats.
  129. */
  130. var CallStats = _try_catch(function(jingleSession, Settings, options) {
  131. try{
  132. CallStats.feedbackEnabled = false;
  133. callStats = new callstats($, io, jsSHA); // eslint-disable-line new-cap
  134. this.peerconnection = jingleSession.peerconnection.peerconnection;
  135. this.userID = {
  136. aliasName: Strophe.getResourceFromJid(jingleSession.room.myroomjid),
  137. userName: Settings.getCallStatsUserName()
  138. };
  139. const location = window.location;
  140. // The confID is case sensitive!!!
  141. this.confID = location.hostname + "/" + options.roomName;
  142. this.callStatsID = options.callStatsID;
  143. this.callStatsSecret = options.callStatsSecret;
  144. CallStats.initializeInProgress = true;
  145. //userID is generated or given by the origin server
  146. callStats.initialize(this.callStatsID,
  147. this.callStatsSecret,
  148. this.userID,
  149. initCallback.bind(this));
  150. } catch (e) {
  151. // The callstats.io API failed to initialize (e.g. because its download
  152. // did not succeed in general or on time). Further attempts to utilize
  153. // it cannot possibly succeed.
  154. GlobalOnErrorHandler.callErrorHandler(e);
  155. callStats = null;
  156. logger.error(e);
  157. }
  158. });
  159. // some errors/events may happen before CallStats init
  160. // in this case we accumulate them in this array
  161. // and send them to callstats on init
  162. CallStats.reportsQueue = [];
  163. /**
  164. * Whether the library was successfully initialized using its initialize method.
  165. * And whether we had successfully called addNewFabric.
  166. * @type {boolean}
  167. */
  168. CallStats.initialized = false;
  169. /**
  170. * Whether we are in progress of initializing.
  171. * @type {boolean}
  172. */
  173. CallStats.initializeInProgress = false;
  174. /**
  175. * Whether we tried to initialize and it failed.
  176. * @type {boolean}
  177. */
  178. CallStats.initializeFailed = false;
  179. /**
  180. * Shows weather sending feedback is enabled or not
  181. * @type {boolean}
  182. */
  183. CallStats.feedbackEnabled = false;
  184. /**
  185. * Checks whether we need to re-initialize callstats and starts the process.
  186. * @private
  187. */
  188. CallStats._checkInitialize = function () {
  189. if (CallStats.initialized || !CallStats.initializeFailed
  190. || !callStats || CallStats.initializeInProgress)
  191. return;
  192. // callstats object created, not initialized and it had previously failed,
  193. // and there is no init in progress, so lets try initialize it again
  194. CallStats.initializeInProgress = true;
  195. callStats.initialize(
  196. callStats.callStatsID,
  197. callStats.callStatsSecret,
  198. callStats.userID,
  199. initCallback.bind(callStats));
  200. };
  201. /**
  202. * Type of pending reports, can be event or an error.
  203. * @type {{ERROR: string, EVENT: string}}
  204. */
  205. var reportType = {
  206. ERROR: "error",
  207. EVENT: "event",
  208. MST_WITH_USERID: "mstWithUserID"
  209. };
  210. CallStats.prototype.pcCallback = _try_catch(function (err, msg) {
  211. if (callStats && err !== 'success')
  212. logger.error("Monitoring status: "+ err + " msg: " + msg);
  213. });
  214. /**
  215. * Lets CallStats module know where is given SSRC rendered by providing renderer
  216. * tag ID.
  217. * If the lib is not initialized yet queue the call for later, when its ready.
  218. * @param ssrc {number} the SSRC of the stream
  219. * @param isLocal {boolean} <tt>true<tt> if this stream is local or
  220. * <tt>false</tt> otherwise.
  221. * @param usageLabel {string} meaningful usage label of this stream like
  222. * 'microphone', 'camera' or 'screen'.
  223. * @param containerId {string} the id of media 'audio' or 'video' tag which
  224. * renders the stream.
  225. */
  226. CallStats.prototype.associateStreamWithVideoTag =
  227. function (ssrc, isLocal, usageLabel, containerId) {
  228. if(!callStats) {
  229. return;
  230. }
  231. // 'focus' is default remote user ID for now
  232. const callStatsId = isLocal ? this.userID : 'focus';
  233. _try_catch(function() {
  234. logger.debug(
  235. "Calling callStats.associateMstWithUserID with:",
  236. this.peerconnection,
  237. callStatsId,
  238. this.confID,
  239. ssrc,
  240. usageLabel,
  241. containerId);
  242. if(CallStats.initialized) {
  243. callStats.associateMstWithUserID(
  244. this.peerconnection,
  245. callStatsId,
  246. this.confID,
  247. ssrc,
  248. usageLabel,
  249. containerId);
  250. }
  251. else {
  252. CallStats.reportsQueue.push({
  253. type: reportType.MST_WITH_USERID,
  254. data: {
  255. callStatsId,
  256. containerId,
  257. ssrc,
  258. usageLabel
  259. }
  260. });
  261. CallStats._checkInitialize();
  262. }
  263. }).bind(this)();
  264. };
  265. /**
  266. * Notifies CallStats for mute events
  267. * @param mute {boolean} true for muted and false for not muted
  268. * @param type {String} "audio"/"video"
  269. * @param {CallStats} cs callstats instance related to the event
  270. */
  271. CallStats.sendMuteEvent = _try_catch(function (mute, type, cs) {
  272. let event;
  273. if (type === "video") {
  274. event = mute ? fabricEvent.videoPause : fabricEvent.videoResume;
  275. } else {
  276. event = mute ? fabricEvent.audioMute : fabricEvent.audioUnmute;
  277. }
  278. CallStats._reportEvent.call(cs, event);
  279. });
  280. /**
  281. * Notifies CallStats for screen sharing events
  282. * @param start {boolean} true for starting screen sharing and
  283. * false for not stopping
  284. * @param {CallStats} cs callstats instance related to the event
  285. */
  286. CallStats.sendScreenSharingEvent = _try_catch(function (start, cs) {
  287. CallStats._reportEvent.call(
  288. cs,
  289. start ? fabricEvent.screenShareStart : fabricEvent.screenShareStop);
  290. });
  291. /**
  292. * Notifies CallStats that we are the new dominant speaker in the conference.
  293. * @param {CallStats} cs callstats instance related to the event
  294. */
  295. CallStats.sendDominantSpeakerEvent = _try_catch(function (cs) {
  296. CallStats._reportEvent.call(cs, fabricEvent.dominantSpeaker);
  297. });
  298. /**
  299. * Notifies CallStats about active device.
  300. * @param {{deviceList: {String:String}}} list of devices with their data
  301. * @param {CallStats} cs callstats instance related to the event
  302. */
  303. CallStats.sendActiveDeviceListEvent = _try_catch(function (devicesData, cs) {
  304. CallStats._reportEvent.call(cs, fabricEvent.activeDeviceList, devicesData);
  305. });
  306. /**
  307. * Reports an error to callstats.
  308. *
  309. * @param type the type of the error, which will be one of the wrtcFuncNames
  310. * @param e the error
  311. * @param pc the peerconnection
  312. * @param eventData additional data to pass to event
  313. * @private
  314. */
  315. CallStats._reportEvent = function (event, eventData) {
  316. if (CallStats.initialized) {
  317. callStats.sendFabricEvent(
  318. this.peerconnection, event, this.confID, eventData);
  319. } else {
  320. CallStats.reportsQueue.push({
  321. type: reportType.EVENT,
  322. data: {event: event, eventData: eventData}
  323. });
  324. CallStats._checkInitialize();
  325. }
  326. };
  327. /**
  328. * Notifies CallStats for connection setup errors
  329. */
  330. CallStats.prototype.sendTerminateEvent = _try_catch(function () {
  331. if(!CallStats.initialized) {
  332. return;
  333. }
  334. callStats.sendFabricEvent(this.peerconnection,
  335. callStats.fabricEvent.fabricTerminated, this.confID);
  336. });
  337. /**
  338. * Notifies CallStats that audio problems are detected.
  339. *
  340. * @param {Error} e error to send
  341. * @param {CallStats} cs callstats instance related to the error (optional)
  342. */
  343. CallStats.prototype.sendDetectedAudioProblem = _try_catch(function (e) {
  344. CallStats._reportError.call(this, wrtcFuncNames.applicationLog, e,
  345. this.peerconnection);
  346. });
  347. /**
  348. * Notifies CallStats for ice connection failed
  349. * @param {RTCPeerConnection} pc connection on which failure occured.
  350. * @param {CallStats} cs callstats instance related to the error (optional)
  351. */
  352. CallStats.prototype.sendIceConnectionFailedEvent = _try_catch(function (pc, cs){
  353. CallStats._reportError.call(
  354. cs, wrtcFuncNames.iceConnectionFailure, null, pc);
  355. });
  356. /**
  357. * Sends the given feedback through CallStats.
  358. *
  359. * @param overallFeedback an integer between 1 and 5 indicating the
  360. * user feedback
  361. * @param detailedFeedback detailed feedback from the user. Not yet used
  362. */
  363. CallStats.prototype.sendFeedback = _try_catch(
  364. function(overallFeedback, detailedFeedback) {
  365. if(!CallStats.feedbackEnabled) {
  366. return;
  367. }
  368. var feedbackString = '{"userID":"' + this.userID + '"' +
  369. ', "overall":' + overallFeedback +
  370. ', "comment": "' + detailedFeedback + '"}';
  371. var feedbackJSON = JSON.parse(feedbackString);
  372. callStats.sendUserFeedback(this.confID, feedbackJSON);
  373. });
  374. /**
  375. * Reports an error to callstats.
  376. *
  377. * @param type the type of the error, which will be one of the wrtcFuncNames
  378. * @param e the error
  379. * @param pc the peerconnection
  380. * @private
  381. */
  382. CallStats._reportError = function (type, e, pc) {
  383. if(!e) {
  384. logger.warn("No error is passed!");
  385. e = new Error("Unknown error");
  386. }
  387. if (CallStats.initialized) {
  388. callStats.reportError(pc, this.confID, type, e);
  389. } else {
  390. CallStats.reportsQueue.push({
  391. type: reportType.ERROR,
  392. data: { type: type, error: e, pc: pc}
  393. });
  394. CallStats._checkInitialize();
  395. }
  396. // else just ignore it
  397. };
  398. /**
  399. * Notifies CallStats that getUserMedia failed.
  400. *
  401. * @param {Error} e error to send
  402. * @param {CallStats} cs callstats instance related to the error (optional)
  403. */
  404. CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
  405. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  406. });
  407. /**
  408. * Notifies CallStats that peer connection failed to create offer.
  409. *
  410. * @param {Error} e error to send
  411. * @param {RTCPeerConnection} pc connection on which failure occured.
  412. * @param {CallStats} cs callstats instance related to the error (optional)
  413. */
  414. CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
  415. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  416. });
  417. /**
  418. * Notifies CallStats that peer connection failed to create answer.
  419. *
  420. * @param {Error} e error to send
  421. * @param {RTCPeerConnection} pc connection on which failure occured.
  422. * @param {CallStats} cs callstats instance related to the error (optional)
  423. */
  424. CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
  425. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  426. });
  427. /**
  428. * Notifies CallStats that peer connection failed to set local description.
  429. *
  430. * @param {Error} e error to send
  431. * @param {RTCPeerConnection} pc connection on which failure occured.
  432. * @param {CallStats} cs callstats instance related to the error (optional)
  433. */
  434. CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
  435. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  436. });
  437. /**
  438. * Notifies CallStats that peer connection failed to set remote description.
  439. *
  440. * @param {Error} e error to send
  441. * @param {RTCPeerConnection} pc connection on which failure occured.
  442. * @param {CallStats} cs callstats instance related to the error (optional)
  443. */
  444. CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
  445. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  446. });
  447. /**
  448. * Notifies CallStats that peer connection failed to add ICE candidate.
  449. *
  450. * @param {Error} e error to send
  451. * @param {RTCPeerConnection} pc connection on which failure occured.
  452. * @param {CallStats} cs callstats instance related to the error (optional)
  453. */
  454. CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
  455. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  456. });
  457. /**
  458. * Notifies CallStats that there is a log we want to report.
  459. *
  460. * @param {Error} e error to send or {String} message
  461. * @param {CallStats} cs callstats instance related to the error (optional)
  462. */
  463. CallStats.sendApplicationLog = _try_catch(function (e, cs) {
  464. CallStats._reportError.call(cs, wrtcFuncNames.applicationLog, e, null);
  465. });
  466. /**
  467. * Clears allocated resources.
  468. */
  469. CallStats.dispose = function () {
  470. // The next line is commented because we need to be able to send feedback
  471. // even after the conference has been destroyed.
  472. // callStats = null;
  473. CallStats.initialized = false;
  474. CallStats.initializeFailed = false;
  475. CallStats.initializeInProgress = false;
  476. };
  477. module.exports = CallStats;