選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

CallStats.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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 _try_catch(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 = _try_catch(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 = _try_catch(function(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. _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. 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 = _try_catch(function(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 = _try_catch(function(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 = _try_catch(function(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 = _try_catch(function(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, eventData}
  321. });
  322. CallStats._checkInitialize();
  323. }
  324. };
  325. /**
  326. * Notifies CallStats for connection setup errors
  327. */
  328. CallStats.prototype.sendTerminateEvent = _try_catch(function() {
  329. if(!CallStats.initialized) {
  330. return;
  331. }
  332. callStats.sendFabricEvent(this.peerconnection,
  333. callStats.fabricEvent.fabricTerminated, this.confID);
  334. });
  335. /**
  336. * Notifies CallStats for ice connection failed
  337. * @param {RTCPeerConnection} pc connection on which failure occured.
  338. * @param {CallStats} cs callstats instance related to the error (optional)
  339. */
  340. CallStats.prototype.sendIceConnectionFailedEvent = _try_catch(function(pc, cs) {
  341. CallStats._reportError.call(
  342. cs, wrtcFuncNames.iceConnectionFailure, null, pc);
  343. });
  344. /**
  345. * Sends the given feedback through CallStats.
  346. *
  347. * @param overallFeedback an integer between 1 and 5 indicating the
  348. * user feedback
  349. * @param detailedFeedback detailed feedback from the user. Not yet used
  350. */
  351. CallStats.prototype.sendFeedback = _try_catch(
  352. function(overallFeedback, detailedFeedback) {
  353. if(!CallStats.feedbackEnabled) {
  354. return;
  355. }
  356. callStats.sendUserFeedback(this.confID, {
  357. userID: this.userID,
  358. overall: overallFeedback,
  359. comment: detailedFeedback
  360. });
  361. });
  362. /**
  363. * Reports an error to callstats.
  364. *
  365. * @param type the type of the error, which will be one of the wrtcFuncNames
  366. * @param e the error
  367. * @param pc the peerconnection
  368. * @private
  369. */
  370. CallStats._reportError = function(type, e, pc) {
  371. if(!e) {
  372. logger.warn('No error is passed!');
  373. e = new Error('Unknown error');
  374. }
  375. if (CallStats.initialized) {
  376. callStats.reportError(pc, this.confID, type, e);
  377. } else {
  378. CallStats.reportsQueue.push({
  379. type: reportType.ERROR,
  380. data: { type, error: e, pc}
  381. });
  382. CallStats._checkInitialize();
  383. }
  384. // else just ignore it
  385. };
  386. /**
  387. * Notifies CallStats that getUserMedia failed.
  388. *
  389. * @param {Error} e error to send
  390. * @param {CallStats} cs callstats instance related to the error (optional)
  391. */
  392. CallStats.sendGetUserMediaFailed = _try_catch(function(e, cs) {
  393. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  394. });
  395. /**
  396. * Notifies CallStats that peer connection failed to create offer.
  397. *
  398. * @param {Error} e error to send
  399. * @param {RTCPeerConnection} pc connection on which failure occured.
  400. * @param {CallStats} cs callstats instance related to the error (optional)
  401. */
  402. CallStats.sendCreateOfferFailed = _try_catch(function(e, pc, cs) {
  403. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  404. });
  405. /**
  406. * Notifies CallStats that peer connection failed to create answer.
  407. *
  408. * @param {Error} e error to send
  409. * @param {RTCPeerConnection} pc connection on which failure occured.
  410. * @param {CallStats} cs callstats instance related to the error (optional)
  411. */
  412. CallStats.sendCreateAnswerFailed = _try_catch(function(e, pc, cs) {
  413. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  414. });
  415. /**
  416. * Notifies CallStats that peer connection failed to set local description.
  417. *
  418. * @param {Error} e error to send
  419. * @param {RTCPeerConnection} pc connection on which failure occured.
  420. * @param {CallStats} cs callstats instance related to the error (optional)
  421. */
  422. CallStats.sendSetLocalDescFailed = _try_catch(function(e, pc, cs) {
  423. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  424. });
  425. /**
  426. * Notifies CallStats that peer connection failed to set remote description.
  427. *
  428. * @param {Error} e error to send
  429. * @param {RTCPeerConnection} pc connection on which failure occured.
  430. * @param {CallStats} cs callstats instance related to the error (optional)
  431. */
  432. CallStats.sendSetRemoteDescFailed = _try_catch(function(e, pc, cs) {
  433. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  434. });
  435. /**
  436. * Notifies CallStats that peer connection failed to add ICE candidate.
  437. *
  438. * @param {Error} e error to send
  439. * @param {RTCPeerConnection} pc connection on which failure occured.
  440. * @param {CallStats} cs callstats instance related to the error (optional)
  441. */
  442. CallStats.sendAddIceCandidateFailed = _try_catch(function(e, pc, cs) {
  443. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  444. });
  445. /**
  446. * Notifies CallStats that there is a log we want to report.
  447. *
  448. * @param {Error} e error to send or {String} message
  449. * @param {CallStats} cs callstats instance related to the error (optional)
  450. */
  451. CallStats.sendApplicationLog = _try_catch(function(e, cs) {
  452. CallStats._reportError.call(cs, wrtcFuncNames.applicationLog, e, null);
  453. });
  454. /**
  455. * Clears allocated resources.
  456. */
  457. CallStats.dispose = function() {
  458. // The next line is commented because we need to be able to send feedback
  459. // even after the conference has been destroyed.
  460. // callStats = null;
  461. CallStats.initialized = false;
  462. CallStats.initializeFailed = false;
  463. CallStats.initializeInProgress = false;
  464. };
  465. module.exports = CallStats;