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

CallStats.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. console.log("callstats fabric not initilized", ret.message);
  62. return;
  63. }
  64. CallStats.initializeFailed = false;
  65. CallStats.initialized = true;
  66. // notify callstats about failures if there were any
  67. if (CallStats.reportsQueue.length) {
  68. CallStats.reportsQueue.forEach(function (report) {
  69. if (report.type === reportType.ERROR) {
  70. var error = report.data;
  71. CallStats._reportError.call(this, error.type, error.error,
  72. error.pc);
  73. }
  74. // if we have and event to report and we failed to add fabric
  75. // this event will not be reported anyway, returning an error
  76. else if (report.type === reportType.EVENT
  77. && fabricInitialized) {
  78. var eventData = report.data;
  79. callStats.sendFabricEvent(
  80. this.peerconnection,
  81. eventData.event,
  82. this.confID,
  83. eventData.eventData);
  84. } else if (report.type === reportType.MST_WITH_USERID) {
  85. var data = report.data;
  86. callStats.associateMstWithUserID(
  87. this.peerconnection,
  88. data.callStatsId,
  89. this.confID,
  90. data.ssrc,
  91. data.usageLabel,
  92. data.containerId
  93. );
  94. }
  95. }, this);
  96. CallStats.reportsQueue.length = 0;
  97. }
  98. }
  99. /**
  100. * Returns a function which invokes f in a try/catch block, logs any exception
  101. * to the console, and then swallows it.
  102. *
  103. * @param f the function to invoke in a try/catch block
  104. * @return a function which invokes f in a try/catch block, logs any exception
  105. * to the console, and then swallows it
  106. */
  107. function _try_catch (f) {
  108. return function () {
  109. try {
  110. f.apply(this, arguments);
  111. } catch (e) {
  112. GlobalOnErrorHandler.callErrorHandler(e);
  113. logger.error(e);
  114. }
  115. };
  116. }
  117. /**
  118. * Creates new CallStats instance that handles all callstats API calls.
  119. * @param peerConnection {JingleSessionPC} the session object
  120. * @param Settings {Settings} the settings instance. Declared in
  121. * /modules/settings/Settings.js
  122. * @param options {object} credentials for callstats.
  123. */
  124. var CallStats = _try_catch(function(jingleSession, Settings, options) {
  125. try{
  126. //check weather that should work with more than 1 peerconnection
  127. if(!callStats) {
  128. callStats = new callstats($, io, jsSHA);
  129. } else {
  130. return;
  131. }
  132. this.session = jingleSession;
  133. this.peerconnection = jingleSession.peerconnection.peerconnection;
  134. this.userID = Settings.getCallStatsUserName();
  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. * Checks whether we need to re-initialize callstats and starts the process.
  177. * @private
  178. */
  179. CallStats._checkInitialize = function () {
  180. if (CallStats.initialized || !CallStats.initializeFailed
  181. || !callStats || CallStats.initializeInProgress)
  182. return;
  183. // callstats object created, not initialized and it had previously failed,
  184. // and there is no init in progress, so lets try initialize it again
  185. CallStats.initializeInProgress = true;
  186. callStats.initialize(
  187. callStats.callStatsID,
  188. callStats.callStatsSecret,
  189. callStats.userID,
  190. initCallback.bind(callStats));
  191. };
  192. /**
  193. * Type of pending reports, can be event or an error.
  194. * @type {{ERROR: string, EVENT: string}}
  195. */
  196. var reportType = {
  197. ERROR: "error",
  198. EVENT: "event",
  199. MST_WITH_USERID: "mstWithUserID"
  200. };
  201. CallStats.prototype.pcCallback = _try_catch(function (err, msg) {
  202. if (!callStats) {
  203. return;
  204. }
  205. logger.log("Monitoring status: "+ err + " msg: " + msg);
  206. });
  207. /**
  208. * Lets CallStats module know where is given SSRC rendered by providing renderer
  209. * tag ID.
  210. * If the lib is not initialized yet queue the call for later, when its ready.
  211. * @param ssrc {number} the SSRC of the stream
  212. * @param isLocal {boolean} <tt>true<tt> if this stream is local or
  213. * <tt>false</tt> otherwise.
  214. * @param usageLabel {string} meaningful usage label of this stream like
  215. * 'microphone', 'camera' or 'screen'.
  216. * @param containerId {string} the id of media 'audio' or 'video' tag which
  217. * renders the stream.
  218. */
  219. CallStats.prototype.associateStreamWithVideoTag =
  220. function (ssrc, isLocal, usageLabel, containerId) {
  221. if(!callStats) {
  222. return;
  223. }
  224. // 'focus' is default remote user ID for now
  225. var callStatsId = 'focus';
  226. if (isLocal) {
  227. callStatsId = this.userID;
  228. }
  229. _try_catch(function() {
  230. logger.debug(
  231. "Calling callStats.associateMstWithUserID with:",
  232. this.peerconnection,
  233. callStatsId,
  234. this.confID,
  235. ssrc,
  236. usageLabel,
  237. containerId
  238. );
  239. if(CallStats.initialized) {
  240. callStats.associateMstWithUserID(
  241. this.peerconnection,
  242. callStatsId,
  243. this.confID,
  244. ssrc,
  245. usageLabel,
  246. containerId
  247. );
  248. }
  249. else {
  250. CallStats.reportsQueue.push({
  251. type: reportType.MST_WITH_USERID,
  252. data: {
  253. callStatsId: callStatsId,
  254. ssrc: ssrc,
  255. usageLabel: usageLabel,
  256. containerId: containerId
  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 = _try_catch(function (mute, type, cs) {
  270. var event = null;
  271. if (type === "video") {
  272. event = (mute? fabricEvent.videoPause : fabricEvent.videoResume);
  273. }
  274. else {
  275. event = (mute? fabricEvent.audioMute : fabricEvent.audioUnmute);
  276. }
  277. CallStats._reportEvent.call(cs, event);
  278. });
  279. /**
  280. * Notifies CallStats for screen sharing events
  281. * @param start {boolean} true for starting screen sharing and
  282. * false for not stopping
  283. * @param {CallStats} cs callstats instance related to the event
  284. */
  285. CallStats.sendScreenSharingEvent = _try_catch(function (start, cs) {
  286. CallStats._reportEvent.call(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 = _try_catch(function (cs) {
  294. CallStats._reportEvent.call(cs,
  295. fabricEvent.dominantSpeaker);
  296. });
  297. /**
  298. * Notifies CallStats about active device.
  299. * @param {{deviceList: {String:String}}} list of devices with their data
  300. * @param {CallStats} cs callstats instance related to the event
  301. */
  302. CallStats.sendActiveDeviceListEvent = _try_catch(function (devicesData, cs) {
  303. CallStats._reportEvent.call(cs, fabricEvent.activeDeviceList, devicesData);
  304. });
  305. /**
  306. * Reports an error to callstats.
  307. *
  308. * @param type the type of the error, which will be one of the wrtcFuncNames
  309. * @param e the error
  310. * @param pc the peerconnection
  311. * @param eventData additional data to pass to event
  312. * @private
  313. */
  314. CallStats._reportEvent = function (event, eventData) {
  315. if (CallStats.initialized) {
  316. callStats.sendFabricEvent(
  317. this.peerconnection, event, this.confID, eventData);
  318. } else {
  319. CallStats.reportsQueue.push({
  320. type: reportType.EVENT,
  321. data: {event: event, eventData: eventData}
  322. });
  323. CallStats._checkInitialize();
  324. }
  325. };
  326. /**
  327. * Notifies CallStats for connection setup errors
  328. */
  329. CallStats.prototype.sendTerminateEvent = _try_catch(function () {
  330. if(!CallStats.initialized) {
  331. return;
  332. }
  333. callStats.sendFabricEvent(this.peerconnection,
  334. callStats.fabricEvent.fabricTerminated, this.confID);
  335. });
  336. /**
  337. * Notifies CallStats that audio problems are detected.
  338. *
  339. * @param {Error} e error to send
  340. * @param {CallStats} cs callstats instance related to the error (optional)
  341. */
  342. CallStats.prototype.sendDetectedAudioProblem = _try_catch(function (e) {
  343. CallStats._reportError.call(this, wrtcFuncNames.applicationLog, e,
  344. this.peerconnection);
  345. });
  346. /**
  347. * Notifies CallStats for ice connection failed
  348. * @param {RTCPeerConnection} pc connection on which failure occured.
  349. * @param {CallStats} cs callstats instance related to the error (optional)
  350. */
  351. CallStats.prototype.sendIceConnectionFailedEvent = _try_catch(function (pc, cs){
  352. CallStats._reportError.call(
  353. cs, wrtcFuncNames.iceConnectionFailure, null, pc);
  354. });
  355. /**
  356. * Sends the given feedback through CallStats.
  357. *
  358. * @param overallFeedback an integer between 1 and 5 indicating the
  359. * user feedback
  360. * @param detailedFeedback detailed feedback from the user. Not yet used
  361. */
  362. CallStats.prototype.sendFeedback = _try_catch(
  363. function(overallFeedback, detailedFeedback) {
  364. if(!CallStats.initialized) {
  365. return;
  366. }
  367. var feedbackString = '{"userID":"' + this.userID + '"' +
  368. ', "overall":' + overallFeedback +
  369. ', "comment": "' + detailedFeedback + '"}';
  370. var feedbackJSON = JSON.parse(feedbackString);
  371. callStats.sendUserFeedback(this.confID, feedbackJSON);
  372. });
  373. /**
  374. * Reports an error to callstats.
  375. *
  376. * @param type the type of the error, which will be one of the wrtcFuncNames
  377. * @param e the error
  378. * @param pc the peerconnection
  379. * @private
  380. */
  381. CallStats._reportError = function (type, e, pc) {
  382. if(!e) {
  383. logger.warn("No error is passed!");
  384. e = new Error("Unknown error");
  385. }
  386. if (CallStats.initialized) {
  387. callStats.reportError(pc, this.confID, type, e);
  388. } else {
  389. CallStats.reportsQueue.push({
  390. type: reportType.ERROR,
  391. data: { type: type, error: e, pc: pc}
  392. });
  393. CallStats._checkInitialize();
  394. }
  395. // else just ignore it
  396. };
  397. /**
  398. * Notifies CallStats that getUserMedia failed.
  399. *
  400. * @param {Error} e error to send
  401. * @param {CallStats} cs callstats instance related to the error (optional)
  402. */
  403. CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
  404. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  405. });
  406. /**
  407. * Notifies CallStats that peer connection failed to create offer.
  408. *
  409. * @param {Error} e error to send
  410. * @param {RTCPeerConnection} pc connection on which failure occured.
  411. * @param {CallStats} cs callstats instance related to the error (optional)
  412. */
  413. CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
  414. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  415. });
  416. /**
  417. * Notifies CallStats that peer connection failed to create answer.
  418. *
  419. * @param {Error} e error to send
  420. * @param {RTCPeerConnection} pc connection on which failure occured.
  421. * @param {CallStats} cs callstats instance related to the error (optional)
  422. */
  423. CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
  424. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  425. });
  426. /**
  427. * Notifies CallStats that peer connection failed to set local description.
  428. *
  429. * @param {Error} e error to send
  430. * @param {RTCPeerConnection} pc connection on which failure occured.
  431. * @param {CallStats} cs callstats instance related to the error (optional)
  432. */
  433. CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
  434. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  435. });
  436. /**
  437. * Notifies CallStats that peer connection failed to set remote description.
  438. *
  439. * @param {Error} e error to send
  440. * @param {RTCPeerConnection} pc connection on which failure occured.
  441. * @param {CallStats} cs callstats instance related to the error (optional)
  442. */
  443. CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
  444. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  445. });
  446. /**
  447. * Notifies CallStats that peer connection failed to add ICE candidate.
  448. *
  449. * @param {Error} e error to send
  450. * @param {RTCPeerConnection} pc connection on which failure occured.
  451. * @param {CallStats} cs callstats instance related to the error (optional)
  452. */
  453. CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
  454. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  455. });
  456. /**
  457. * Notifies CallStats that there is a log we want to report.
  458. *
  459. * @param {Error} e error to send or {String} message
  460. * @param {CallStats} cs callstats instance related to the error (optional)
  461. */
  462. CallStats.sendApplicationLog = _try_catch(function (e, cs) {
  463. CallStats._reportError
  464. .call(cs, wrtcFuncNames.applicationLog, e, null);
  465. });
  466. /**
  467. * Clears allocated resources.
  468. */
  469. CallStats.dispose = function () {
  470. callStats = null;
  471. CallStats.initialized = false;
  472. CallStats.initializeFailed = false;
  473. CallStats.initializeInProgress = false;
  474. };
  475. module.exports = CallStats;