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

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