Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

CallStats.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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 = Settings.getCallStatsUserName();
  132. var location = window.location;
  133. // The confID is case sensitive!!!
  134. this.confID = location.hostname + "/" + options.roomName;
  135. this.callStatsID = options.callStatsID;
  136. this.callStatsSecret = options.callStatsSecret;
  137. CallStats.initializeInProgress = true;
  138. //userID is generated or given by the origin server
  139. callStats.initialize(this.callStatsID,
  140. this.callStatsSecret,
  141. this.userID,
  142. initCallback.bind(this));
  143. } catch (e) {
  144. // The callstats.io API failed to initialize (e.g. because its
  145. // download failed to succeed in general or on time). Further
  146. // attempts to utilize it cannot possibly succeed.
  147. GlobalOnErrorHandler.callErrorHandler(e);
  148. callStats = null;
  149. logger.error(e);
  150. }
  151. });
  152. // some errors/events may happen before CallStats init
  153. // in this case we accumulate them in this array
  154. // and send them to callstats on init
  155. CallStats.reportsQueue = [];
  156. /**
  157. * Whether the library was successfully initialized using its initialize method.
  158. * And whether we had successfully called addNewFabric.
  159. * @type {boolean}
  160. */
  161. CallStats.initialized = false;
  162. /**
  163. * Whether we are in progress of initializing.
  164. * @type {boolean}
  165. */
  166. CallStats.initializeInProgress = false;
  167. /**
  168. * Whether we tried to initialize and it failed.
  169. * @type {boolean}
  170. */
  171. CallStats.initializeFailed = false;
  172. /**
  173. * Shows weather sending feedback is enabled or not
  174. * @type {boolean}
  175. */
  176. CallStats.feedbackEnabled = false;
  177. /**
  178. * Checks whether we need to re-initialize callstats and starts the process.
  179. * @private
  180. */
  181. CallStats._checkInitialize = function () {
  182. if (CallStats.initialized || !CallStats.initializeFailed
  183. || !callStats || CallStats.initializeInProgress)
  184. return;
  185. // callstats object created, not initialized and it had previously failed,
  186. // and there is no init in progress, so lets try initialize it again
  187. CallStats.initializeInProgress = true;
  188. callStats.initialize(
  189. callStats.callStatsID,
  190. callStats.callStatsSecret,
  191. callStats.userID,
  192. initCallback.bind(callStats));
  193. };
  194. /**
  195. * Type of pending reports, can be event or an error.
  196. * @type {{ERROR: string, EVENT: string}}
  197. */
  198. var reportType = {
  199. ERROR: "error",
  200. EVENT: "event",
  201. MST_WITH_USERID: "mstWithUserID"
  202. };
  203. CallStats.prototype.pcCallback = _try_catch(function (err, msg) {
  204. if (!callStats) {
  205. return;
  206. }
  207. if (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. var callStatsId = 'focus';
  229. if (isLocal) {
  230. callStatsId = this.userID;
  231. }
  232. _try_catch(function() {
  233. logger.debug(
  234. "Calling callStats.associateMstWithUserID with:",
  235. this.peerconnection,
  236. callStatsId,
  237. this.confID,
  238. ssrc,
  239. usageLabel,
  240. containerId
  241. );
  242. if(CallStats.initialized) {
  243. callStats.associateMstWithUserID(
  244. this.peerconnection,
  245. callStatsId,
  246. this.confID,
  247. ssrc,
  248. usageLabel,
  249. containerId
  250. );
  251. }
  252. else {
  253. CallStats.reportsQueue.push({
  254. type: reportType.MST_WITH_USERID,
  255. data: {
  256. callStatsId: callStatsId,
  257. ssrc: ssrc,
  258. usageLabel: usageLabel,
  259. containerId: containerId
  260. }
  261. });
  262. CallStats._checkInitialize();
  263. }
  264. }).bind(this)();
  265. };
  266. /**
  267. * Notifies CallStats for mute events
  268. * @param mute {boolean} true for muted and false for not muted
  269. * @param type {String} "audio"/"video"
  270. * @param {CallStats} cs callstats instance related to the event
  271. */
  272. CallStats.sendMuteEvent = _try_catch(function (mute, type, cs) {
  273. var event = null;
  274. if (type === "video") {
  275. event = (mute? fabricEvent.videoPause : fabricEvent.videoResume);
  276. }
  277. else {
  278. event = (mute? fabricEvent.audioMute : fabricEvent.audioUnmute);
  279. }
  280. CallStats._reportEvent.call(cs, event);
  281. });
  282. /**
  283. * Notifies CallStats for screen sharing events
  284. * @param start {boolean} true for starting screen sharing and
  285. * false for not stopping
  286. * @param {CallStats} cs callstats instance related to the event
  287. */
  288. CallStats.sendScreenSharingEvent = _try_catch(function (start, cs) {
  289. CallStats._reportEvent.call(cs,
  290. start? fabricEvent.screenShareStart : fabricEvent.screenShareStop);
  291. });
  292. /**
  293. * Notifies CallStats that we are the new dominant speaker in the conference.
  294. * @param {CallStats} cs callstats instance related to the event
  295. */
  296. CallStats.sendDominantSpeakerEvent = _try_catch(function (cs) {
  297. CallStats._reportEvent.call(cs,
  298. fabricEvent.dominantSpeaker);
  299. });
  300. /**
  301. * Notifies CallStats about active device.
  302. * @param {{deviceList: {String:String}}} list of devices with their data
  303. * @param {CallStats} cs callstats instance related to the event
  304. */
  305. CallStats.sendActiveDeviceListEvent = _try_catch(function (devicesData, cs) {
  306. CallStats._reportEvent.call(cs, fabricEvent.activeDeviceList, devicesData);
  307. });
  308. /**
  309. * Reports an error to callstats.
  310. *
  311. * @param type the type of the error, which will be one of the wrtcFuncNames
  312. * @param e the error
  313. * @param pc the peerconnection
  314. * @param eventData additional data to pass to event
  315. * @private
  316. */
  317. CallStats._reportEvent = function (event, eventData) {
  318. if (CallStats.initialized) {
  319. callStats.sendFabricEvent(
  320. this.peerconnection, event, this.confID, eventData);
  321. } else {
  322. CallStats.reportsQueue.push({
  323. type: reportType.EVENT,
  324. data: {event: event, eventData: eventData}
  325. });
  326. CallStats._checkInitialize();
  327. }
  328. };
  329. /**
  330. * Notifies CallStats for connection setup errors
  331. */
  332. CallStats.prototype.sendTerminateEvent = _try_catch(function () {
  333. if(!CallStats.initialized) {
  334. return;
  335. }
  336. callStats.sendFabricEvent(this.peerconnection,
  337. callStats.fabricEvent.fabricTerminated, this.confID);
  338. });
  339. /**
  340. * Notifies CallStats that audio problems are detected.
  341. *
  342. * @param {Error} e error to send
  343. * @param {CallStats} cs callstats instance related to the error (optional)
  344. */
  345. CallStats.prototype.sendDetectedAudioProblem = _try_catch(function (e) {
  346. CallStats._reportError.call(this, wrtcFuncNames.applicationLog, e,
  347. this.peerconnection);
  348. });
  349. /**
  350. * Notifies CallStats for ice connection failed
  351. * @param {RTCPeerConnection} pc connection on which failure occured.
  352. * @param {CallStats} cs callstats instance related to the error (optional)
  353. */
  354. CallStats.prototype.sendIceConnectionFailedEvent = _try_catch(function (pc, cs){
  355. CallStats._reportError.call(
  356. cs, wrtcFuncNames.iceConnectionFailure, null, pc);
  357. });
  358. /**
  359. * Sends the given feedback through CallStats.
  360. *
  361. * @param overallFeedback an integer between 1 and 5 indicating the
  362. * user feedback
  363. * @param detailedFeedback detailed feedback from the user. Not yet used
  364. */
  365. CallStats.prototype.sendFeedback = _try_catch(
  366. function(overallFeedback, detailedFeedback) {
  367. if(!CallStats.feedbackEnabled) {
  368. return;
  369. }
  370. var feedbackString = '{"userID":"' + this.userID + '"' +
  371. ', "overall":' + overallFeedback +
  372. ', "comment": "' + detailedFeedback + '"}';
  373. var feedbackJSON = JSON.parse(feedbackString);
  374. callStats.sendUserFeedback(this.confID, feedbackJSON);
  375. });
  376. /**
  377. * Reports an error to callstats.
  378. *
  379. * @param type the type of the error, which will be one of the wrtcFuncNames
  380. * @param e the error
  381. * @param pc the peerconnection
  382. * @private
  383. */
  384. CallStats._reportError = function (type, e, pc) {
  385. if(!e) {
  386. logger.warn("No error is passed!");
  387. e = new Error("Unknown error");
  388. }
  389. if (CallStats.initialized) {
  390. callStats.reportError(pc, this.confID, type, e);
  391. } else {
  392. CallStats.reportsQueue.push({
  393. type: reportType.ERROR,
  394. data: { type: type, error: e, pc: pc}
  395. });
  396. CallStats._checkInitialize();
  397. }
  398. // else just ignore it
  399. };
  400. /**
  401. * Notifies CallStats that getUserMedia failed.
  402. *
  403. * @param {Error} e error to send
  404. * @param {CallStats} cs callstats instance related to the error (optional)
  405. */
  406. CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
  407. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  408. });
  409. /**
  410. * Notifies CallStats that peer connection failed to create offer.
  411. *
  412. * @param {Error} e error to send
  413. * @param {RTCPeerConnection} pc connection on which failure occured.
  414. * @param {CallStats} cs callstats instance related to the error (optional)
  415. */
  416. CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
  417. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  418. });
  419. /**
  420. * Notifies CallStats that peer connection failed to create answer.
  421. *
  422. * @param {Error} e error to send
  423. * @param {RTCPeerConnection} pc connection on which failure occured.
  424. * @param {CallStats} cs callstats instance related to the error (optional)
  425. */
  426. CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
  427. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  428. });
  429. /**
  430. * Notifies CallStats that peer connection failed to set local description.
  431. *
  432. * @param {Error} e error to send
  433. * @param {RTCPeerConnection} pc connection on which failure occured.
  434. * @param {CallStats} cs callstats instance related to the error (optional)
  435. */
  436. CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
  437. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  438. });
  439. /**
  440. * Notifies CallStats that peer connection failed to set remote description.
  441. *
  442. * @param {Error} e error to send
  443. * @param {RTCPeerConnection} pc connection on which failure occured.
  444. * @param {CallStats} cs callstats instance related to the error (optional)
  445. */
  446. CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
  447. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  448. });
  449. /**
  450. * Notifies CallStats that peer connection failed to add ICE candidate.
  451. *
  452. * @param {Error} e error to send
  453. * @param {RTCPeerConnection} pc connection on which failure occured.
  454. * @param {CallStats} cs callstats instance related to the error (optional)
  455. */
  456. CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
  457. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  458. });
  459. /**
  460. * Notifies CallStats that there is a log we want to report.
  461. *
  462. * @param {Error} e error to send or {String} message
  463. * @param {CallStats} cs callstats instance related to the error (optional)
  464. */
  465. CallStats.sendApplicationLog = _try_catch(function (e, cs) {
  466. CallStats._reportError
  467. .call(cs, wrtcFuncNames.applicationLog, e, null);
  468. });
  469. /**
  470. * Clears allocated resources.
  471. */
  472. CallStats.dispose = function () {
  473. // The next line is commented because we need to be able to send feedback
  474. // even after the conference has been destroyed.
  475. // callStats = null;
  476. CallStats.initialized = false;
  477. CallStats.initializeFailed = false;
  478. CallStats.initializeInProgress = false;
  479. };
  480. module.exports = CallStats;