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