Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

CallStats.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. userName : Settings.getCallStatsUserName(),
  133. aliasName : Strophe.getResourceFromJid(jingleSession.room.myroomjid)
  134. };
  135. var 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
  148. // download failed to succeed in general or on time). Further
  149. // attempts to utilize 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) {
  208. return;
  209. }
  210. if (err !== 'success')
  211. logger.error("Monitoring status: "+ err + " msg: " + msg);
  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. // 'focus' is default remote user ID for now
  231. var callStatsId = 'focus';
  232. if (isLocal) {
  233. callStatsId = this.userID;
  234. }
  235. _try_catch(function() {
  236. logger.debug(
  237. "Calling callStats.associateMstWithUserID with:",
  238. this.peerconnection,
  239. callStatsId,
  240. this.confID,
  241. ssrc,
  242. usageLabel,
  243. containerId
  244. );
  245. if(CallStats.initialized) {
  246. callStats.associateMstWithUserID(
  247. this.peerconnection,
  248. callStatsId,
  249. this.confID,
  250. ssrc,
  251. usageLabel,
  252. containerId
  253. );
  254. }
  255. else {
  256. CallStats.reportsQueue.push({
  257. type: reportType.MST_WITH_USERID,
  258. data: {
  259. callStatsId: callStatsId,
  260. ssrc: ssrc,
  261. usageLabel: usageLabel,
  262. containerId: containerId
  263. }
  264. });
  265. CallStats._checkInitialize();
  266. }
  267. }).bind(this)();
  268. };
  269. /**
  270. * Notifies CallStats for mute events
  271. * @param mute {boolean} true for muted and false for not muted
  272. * @param type {String} "audio"/"video"
  273. * @param {CallStats} cs callstats instance related to the event
  274. */
  275. CallStats.sendMuteEvent = _try_catch(function (mute, type, cs) {
  276. var event = null;
  277. if (type === "video") {
  278. event = (mute? fabricEvent.videoPause : fabricEvent.videoResume);
  279. }
  280. else {
  281. event = (mute? fabricEvent.audioMute : fabricEvent.audioUnmute);
  282. }
  283. CallStats._reportEvent.call(cs, event);
  284. });
  285. /**
  286. * Notifies CallStats for screen sharing events
  287. * @param start {boolean} true for starting screen sharing and
  288. * false for not stopping
  289. * @param {CallStats} cs callstats instance related to the event
  290. */
  291. CallStats.sendScreenSharingEvent = _try_catch(function (start, cs) {
  292. CallStats._reportEvent.call(cs,
  293. start? fabricEvent.screenShareStart : fabricEvent.screenShareStop);
  294. });
  295. /**
  296. * Notifies CallStats that we are the new dominant speaker in the conference.
  297. * @param {CallStats} cs callstats instance related to the event
  298. */
  299. CallStats.sendDominantSpeakerEvent = _try_catch(function (cs) {
  300. CallStats._reportEvent.call(cs,
  301. fabricEvent.dominantSpeaker);
  302. });
  303. /**
  304. * Notifies CallStats about active device.
  305. * @param {{deviceList: {String:String}}} list of devices with their data
  306. * @param {CallStats} cs callstats instance related to the event
  307. */
  308. CallStats.sendActiveDeviceListEvent = _try_catch(function (devicesData, cs) {
  309. CallStats._reportEvent.call(cs, fabricEvent.activeDeviceList, devicesData);
  310. });
  311. /**
  312. * Reports an error to callstats.
  313. *
  314. * @param type the type of the error, which will be one of the wrtcFuncNames
  315. * @param e the error
  316. * @param pc the peerconnection
  317. * @param eventData additional data to pass to event
  318. * @private
  319. */
  320. CallStats._reportEvent = function (event, eventData) {
  321. if (CallStats.initialized) {
  322. callStats.sendFabricEvent(
  323. this.peerconnection, event, this.confID, eventData);
  324. } else {
  325. CallStats.reportsQueue.push({
  326. type: reportType.EVENT,
  327. data: {event: event, eventData: eventData}
  328. });
  329. CallStats._checkInitialize();
  330. }
  331. };
  332. /**
  333. * Notifies CallStats for connection setup errors
  334. */
  335. CallStats.prototype.sendTerminateEvent = _try_catch(function () {
  336. if(!CallStats.initialized) {
  337. return;
  338. }
  339. callStats.sendFabricEvent(this.peerconnection,
  340. callStats.fabricEvent.fabricTerminated, this.confID);
  341. });
  342. /**
  343. * Notifies CallStats that audio problems are detected.
  344. *
  345. * @param {Error} e error to send
  346. * @param {CallStats} cs callstats instance related to the error (optional)
  347. */
  348. CallStats.prototype.sendDetectedAudioProblem = _try_catch(function (e) {
  349. CallStats._reportError.call(this, wrtcFuncNames.applicationLog, e,
  350. this.peerconnection);
  351. });
  352. /**
  353. * Notifies CallStats for ice connection failed
  354. * @param {RTCPeerConnection} pc connection on which failure occured.
  355. * @param {CallStats} cs callstats instance related to the error (optional)
  356. */
  357. CallStats.prototype.sendIceConnectionFailedEvent = _try_catch(function (pc, cs){
  358. CallStats._reportError.call(
  359. cs, wrtcFuncNames.iceConnectionFailure, null, pc);
  360. });
  361. /**
  362. * Sends the given feedback through CallStats.
  363. *
  364. * @param overallFeedback an integer between 1 and 5 indicating the
  365. * user feedback
  366. * @param detailedFeedback detailed feedback from the user. Not yet used
  367. */
  368. CallStats.prototype.sendFeedback = _try_catch(
  369. function(overallFeedback, detailedFeedback) {
  370. if(!CallStats.feedbackEnabled) {
  371. return;
  372. }
  373. var feedbackString = '{"userID":"' + this.userID + '"' +
  374. ', "overall":' + overallFeedback +
  375. ', "comment": "' + detailedFeedback + '"}';
  376. var feedbackJSON = JSON.parse(feedbackString);
  377. callStats.sendUserFeedback(this.confID, feedbackJSON);
  378. });
  379. /**
  380. * Reports an error to callstats.
  381. *
  382. * @param type the type of the error, which will be one of the wrtcFuncNames
  383. * @param e the error
  384. * @param pc the peerconnection
  385. * @private
  386. */
  387. CallStats._reportError = function (type, e, pc) {
  388. if(!e) {
  389. logger.warn("No error is passed!");
  390. e = new Error("Unknown error");
  391. }
  392. if (CallStats.initialized) {
  393. callStats.reportError(pc, this.confID, type, e);
  394. } else {
  395. CallStats.reportsQueue.push({
  396. type: reportType.ERROR,
  397. data: { type: type, error: e, pc: pc}
  398. });
  399. CallStats._checkInitialize();
  400. }
  401. // else just ignore it
  402. };
  403. /**
  404. * Notifies CallStats that getUserMedia failed.
  405. *
  406. * @param {Error} e error to send
  407. * @param {CallStats} cs callstats instance related to the error (optional)
  408. */
  409. CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
  410. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  411. });
  412. /**
  413. * Notifies CallStats that peer connection failed to create offer.
  414. *
  415. * @param {Error} e error to send
  416. * @param {RTCPeerConnection} pc connection on which failure occured.
  417. * @param {CallStats} cs callstats instance related to the error (optional)
  418. */
  419. CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
  420. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  421. });
  422. /**
  423. * Notifies CallStats that peer connection failed to create answer.
  424. *
  425. * @param {Error} e error to send
  426. * @param {RTCPeerConnection} pc connection on which failure occured.
  427. * @param {CallStats} cs callstats instance related to the error (optional)
  428. */
  429. CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
  430. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  431. });
  432. /**
  433. * Notifies CallStats that peer connection failed to set local description.
  434. *
  435. * @param {Error} e error to send
  436. * @param {RTCPeerConnection} pc connection on which failure occured.
  437. * @param {CallStats} cs callstats instance related to the error (optional)
  438. */
  439. CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
  440. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  441. });
  442. /**
  443. * Notifies CallStats that peer connection failed to set remote description.
  444. *
  445. * @param {Error} e error to send
  446. * @param {RTCPeerConnection} pc connection on which failure occured.
  447. * @param {CallStats} cs callstats instance related to the error (optional)
  448. */
  449. CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
  450. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  451. });
  452. /**
  453. * Notifies CallStats that peer connection failed to add ICE candidate.
  454. *
  455. * @param {Error} e error to send
  456. * @param {RTCPeerConnection} pc connection on which failure occured.
  457. * @param {CallStats} cs callstats instance related to the error (optional)
  458. */
  459. CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
  460. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  461. });
  462. /**
  463. * Notifies CallStats that there is a log we want to report.
  464. *
  465. * @param {Error} e error to send or {String} message
  466. * @param {CallStats} cs callstats instance related to the error (optional)
  467. */
  468. CallStats.sendApplicationLog = _try_catch(function (e, cs) {
  469. CallStats._reportError
  470. .call(cs, wrtcFuncNames.applicationLog, e, null);
  471. });
  472. /**
  473. * Clears allocated resources.
  474. */
  475. CallStats.dispose = function () {
  476. // The next line is commented because we need to be able to send feedback
  477. // even after the conference has been destroyed.
  478. // callStats = null;
  479. CallStats.initialized = false;
  480. CallStats.initializeFailed = false;
  481. CallStats.initializeInProgress = false;
  482. };
  483. module.exports = CallStats;