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 16KB

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