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

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