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

JitsiConference.js 73KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373
  1. /* global __filename, Strophe, Promise */
  2. import ComponentsVersions from './modules/version/ComponentsVersions';
  3. import ConnectionQuality from './modules/connectivity/ConnectionQuality';
  4. import { getLogger } from 'jitsi-meet-logger';
  5. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  6. import EventEmitter from 'events';
  7. import * as JingleSessionState from './modules/xmpp/JingleSessionState';
  8. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  9. import JitsiConferenceEventManager from './JitsiConferenceEventManager';
  10. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  11. import JitsiDTMFManager from './modules/DTMF/JitsiDTMFManager';
  12. import JitsiParticipant from './JitsiParticipant';
  13. import JitsiTrackError from './JitsiTrackError';
  14. import * as JitsiTrackErrors from './JitsiTrackErrors';
  15. import * as JitsiTrackEvents from './JitsiTrackEvents';
  16. import * as MediaType from './service/RTC/MediaType';
  17. import ParticipantConnectionStatusHandler
  18. from './modules/connectivity/ParticipantConnectionStatus';
  19. import RTC from './modules/RTC/RTC';
  20. import RTCBrowserType from './modules/RTC/RTCBrowserType';
  21. import * as RTCEvents from './service/RTC/RTCEvents';
  22. import Statistics from './modules/statistics/statistics';
  23. import TalkMutedDetection from './modules/TalkMutedDetection';
  24. import Transcriber from './modules/transcription/transcriber';
  25. import VideoType from './service/RTC/VideoType';
  26. import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
  27. import * as XMPPEvents from './service/xmpp/XMPPEvents';
  28. import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
  29. const logger = getLogger(__filename);
  30. /**
  31. * Creates a JitsiConference object with the given name and properties.
  32. * Note: this constructor is not a part of the public API (objects should be
  33. * created using JitsiConnection.createConference).
  34. * @param options.config properties / settings related to the conference that
  35. * will be created.
  36. * @param options.name the name of the conference
  37. * @param options.connection the JitsiConnection object for this
  38. * JitsiConference.
  39. * @param {boolean} [options.config.enableP2P] when set to <tt>true</tt>
  40. * the peer to peer mode will be enabled. It means that when there are only 2
  41. * participants in the conference an attempt to make direct connection will be
  42. * made. If the connection succeeds the conference will stop sending data
  43. * through the JVB connection and will use the direct one instead.
  44. * @param {number} [options.config.backToP2PDelay=5] a delay given in seconds,
  45. * before the conference switches back to P2P, after the 3rd participant has
  46. * left the room.
  47. * @constructor
  48. *
  49. * FIXME Make all methods which are called from lib-internal classes
  50. * to non-public (use _). To name a few:
  51. * {@link JitsiConference.onLocalRoleChanged}
  52. * {@link JitsiConference.onUserRoleChanged}
  53. * {@link JitsiConference.onMemberLeft}
  54. * and so on...
  55. */
  56. function JitsiConference(options) {
  57. if (!options.name || options.name.toLowerCase() !== options.name) {
  58. const errmsg
  59. = 'Invalid conference name (no conference name passed or it '
  60. + 'contains invalid characters like capital letters)!';
  61. logger.error(errmsg);
  62. throw new Error(errmsg);
  63. }
  64. this.eventEmitter = new EventEmitter();
  65. this.options = options;
  66. this.eventManager = new JitsiConferenceEventManager(this);
  67. this._init(options);
  68. this.componentsVersions = new ComponentsVersions(this);
  69. this.participants = {};
  70. /**
  71. * Jingle session instance for the JVB connection.
  72. * @type {JingleSessionPC}
  73. */
  74. this.jvbJingleSession = null;
  75. this.lastDominantSpeaker = null;
  76. this.dtmfManager = null;
  77. this.somebodySupportsDTMF = false;
  78. this.authEnabled = false;
  79. this.startAudioMuted = false;
  80. this.startVideoMuted = false;
  81. this.startMutedPolicy = {
  82. audio: false,
  83. video: false
  84. };
  85. this.availableDevices = {
  86. audio: undefined,
  87. video: undefined
  88. };
  89. this.isMutedByFocus = false;
  90. // Flag indicates if the 'onCallEnded' method was ever called on this
  91. // instance. Used to log extra analytics event for debugging purpose.
  92. // We need to know if the potential issue happened before or after
  93. // the restart.
  94. this.wasStopped = false;
  95. /**
  96. * The object which monitors local and remote connection statistics (e.g.
  97. * sending bitrate) and calculates a number which represents the connection
  98. * quality.
  99. */
  100. this.connectionQuality
  101. = new ConnectionQuality(this, this.eventEmitter, options);
  102. /**
  103. * Indicates whether the connection is interrupted or not.
  104. */
  105. this.isJvbConnectionInterrupted = false;
  106. /**
  107. * The object which tracks active speaker times
  108. */
  109. this.speakerStatsCollector = new SpeakerStatsCollector(this);
  110. /* P2P related fields below: */
  111. /**
  112. * Stores reference to deferred start P2P task. It's created when 3rd
  113. * participant leaves the room in order to avoid ping pong effect (it
  114. * could be just a page reload).
  115. * @type {number|null}
  116. */
  117. this.deferredStartP2PTask = null;
  118. const delay = parseInt(options.config.backToP2PDelay, 10);
  119. /**
  120. * A delay given in seconds, before the conference switches back to P2P
  121. * after the 3rd participant has left.
  122. * @type {number}
  123. */
  124. this.backToP2PDelay = isNaN(delay) ? 5 : delay;
  125. logger.info(`backToP2PDelay: ${this.backToP2PDelay}`);
  126. /**
  127. * If set to <tt>true</tt> it means the P2P ICE is no longer connected.
  128. * When <tt>false</tt> it means that P2P ICE (media) connection is up
  129. * and running.
  130. * @type {boolean}
  131. */
  132. this.isP2PConnectionInterrupted = false;
  133. /**
  134. * Flag set to <tt>true</tt> when P2P session has been established
  135. * (ICE has been connected) and this conference is currently in the peer to
  136. * peer mode (P2P connection is the active one).
  137. * @type {boolean}
  138. */
  139. this.p2p = false;
  140. /**
  141. * A JingleSession for the direct peer to peer connection.
  142. * @type {JingleSessionPC}
  143. */
  144. this.p2pJingleSession = null;
  145. }
  146. // FIXME convert JitsiConference to ES6 - ASAP !
  147. JitsiConference.prototype.constructor = JitsiConference;
  148. /**
  149. * Initializes the conference object properties
  150. * @param options {object}
  151. * @param options.connection {JitsiConnection} overrides this.connection
  152. */
  153. JitsiConference.prototype._init = function(options = {}) {
  154. // Override connection and xmpp properties (Usefull if the connection
  155. // reloaded)
  156. if (options.connection) {
  157. this.connection = options.connection;
  158. this.xmpp = this.connection.xmpp;
  159. // Setup XMPP events only if we have new connection object.
  160. this.eventManager.setupXMPPListeners();
  161. }
  162. this.room = this.xmpp.createRoom(this.options.name, this.options.config);
  163. // Connection interrupted/restored listeners
  164. this._onIceConnectionInterrupted
  165. = this._onIceConnectionInterrupted.bind(this);
  166. this.room.addListener(
  167. XMPPEvents.CONNECTION_INTERRUPTED, this._onIceConnectionInterrupted);
  168. this._onIceConnectionRestored = this._onIceConnectionRestored.bind(this);
  169. this.room.addListener(
  170. XMPPEvents.CONNECTION_RESTORED, this._onIceConnectionRestored);
  171. this._onIceConnectionEstablished
  172. = this._onIceConnectionEstablished.bind(this);
  173. this.room.addListener(
  174. XMPPEvents.CONNECTION_ESTABLISHED, this._onIceConnectionEstablished);
  175. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  176. if (!this.rtc) {
  177. this.rtc = new RTC(this, options);
  178. this.eventManager.setupRTCListeners();
  179. }
  180. this.participantConnectionStatus
  181. = new ParticipantConnectionStatusHandler(
  182. this.rtc, this,
  183. options.config.peerDisconnectedThroughRtcTimeout);
  184. this.participantConnectionStatus.init();
  185. if (!this.statistics) {
  186. this.statistics = new Statistics(this.xmpp, {
  187. callStatsID: this.options.config.callStatsID,
  188. callStatsSecret: this.options.config.callStatsSecret,
  189. callStatsConfIDNamespace:
  190. this.options.config.callStatsConfIDNamespace
  191. || window.location.hostname,
  192. callStatsCustomScriptUrl:
  193. this.options.config.callStatsCustomScriptUrl,
  194. roomName: this.options.name
  195. });
  196. }
  197. this.eventManager.setupChatRoomListeners();
  198. // Always add listeners because on reload we are executing leave and the
  199. // listeners are removed from statistics module.
  200. this.eventManager.setupStatisticsListeners();
  201. if (this.options.config.enableTalkWhileMuted) {
  202. // eslint-disable-next-line no-new
  203. new TalkMutedDetection(
  204. this,
  205. () =>
  206. this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED));
  207. }
  208. };
  209. /**
  210. * Joins the conference.
  211. * @param password {string} the password
  212. */
  213. JitsiConference.prototype.join = function(password) {
  214. if (this.room) {
  215. this.room.join(password);
  216. }
  217. };
  218. /**
  219. * Check if joined to the conference.
  220. */
  221. JitsiConference.prototype.isJoined = function() {
  222. return this.room && this.room.joined;
  223. };
  224. /**
  225. * Leaves the conference.
  226. * @returns {Promise}
  227. */
  228. JitsiConference.prototype.leave = function() {
  229. if (this.participantConnectionStatus) {
  230. this.participantConnectionStatus.dispose();
  231. this.participantConnectionStatus = null;
  232. }
  233. this.getLocalTracks().forEach(track => this.onLocalTrackRemoved(track));
  234. this.rtc.closeAllDataChannels();
  235. if (this.statistics) {
  236. this.statistics.dispose();
  237. }
  238. // leave the conference
  239. if (this.room) {
  240. const room = this.room;
  241. // Unregister connection state listeners
  242. room.removeListener(
  243. XMPPEvents.CONNECTION_INTERRUPTED,
  244. this._onIceConnectionInterrupted);
  245. room.removeListener(
  246. XMPPEvents.CONNECTION_RESTORED,
  247. this._onIceConnectionRestored);
  248. room.removeListener(
  249. XMPPEvents.CONNECTION_ESTABLISHED,
  250. this._onIceConnectionEstablished);
  251. this.room = null;
  252. return room.leave().catch(() => {
  253. // remove all participants because currently the conference won't
  254. // be usable anyway. This is done on success automatically by the
  255. // ChatRoom instance.
  256. this.getParticipants().forEach(
  257. participant => this.onMemberLeft(participant.getJid()));
  258. // Close the JingleSession
  259. if (this.jvbJingleSession) {
  260. this.jvbJingleSession.close();
  261. this.jvbJingleSession = null;
  262. }
  263. });
  264. }
  265. // If this.room == null we are calling second time leave().
  266. return Promise.reject(
  267. new Error('The conference is has been already left'));
  268. };
  269. /**
  270. * Returns name of this conference.
  271. */
  272. JitsiConference.prototype.getName = function() {
  273. return this.options.name;
  274. };
  275. /**
  276. * Check if authentication is enabled for this conference.
  277. */
  278. JitsiConference.prototype.isAuthEnabled = function() {
  279. return this.authEnabled;
  280. };
  281. /**
  282. * Check if user is logged in.
  283. */
  284. JitsiConference.prototype.isLoggedIn = function() {
  285. return Boolean(this.authIdentity);
  286. };
  287. /**
  288. * Get authorized login.
  289. */
  290. JitsiConference.prototype.getAuthLogin = function() {
  291. return this.authIdentity;
  292. };
  293. /**
  294. * Check if external authentication is enabled for this conference.
  295. */
  296. JitsiConference.prototype.isExternalAuthEnabled = function() {
  297. return this.room && this.room.moderator.isExternalAuthEnabled();
  298. };
  299. /**
  300. * Get url for external authentication.
  301. * @param {boolean} [urlForPopup] if true then return url for login popup,
  302. * else url of login page.
  303. * @returns {Promise}
  304. */
  305. JitsiConference.prototype.getExternalAuthUrl = function(urlForPopup) {
  306. return new Promise((resolve, reject) => {
  307. if (!this.isExternalAuthEnabled()) {
  308. reject();
  309. return;
  310. }
  311. if (urlForPopup) {
  312. this.room.moderator.getPopupLoginUrl(resolve, reject);
  313. } else {
  314. this.room.moderator.getLoginUrl(resolve, reject);
  315. }
  316. });
  317. };
  318. /**
  319. * Returns the local tracks of the given media type, or all local tracks if no
  320. * specific type is given.
  321. * @param {MediaType} [mediaType] Optional media type (audio or video).
  322. */
  323. JitsiConference.prototype.getLocalTracks = function(mediaType) {
  324. let tracks = [];
  325. if (this.rtc) {
  326. tracks = this.rtc.getLocalTracks(mediaType);
  327. }
  328. return tracks;
  329. };
  330. /**
  331. * Obtains local audio track.
  332. * @return {JitsiLocalTrack|null}
  333. */
  334. JitsiConference.prototype.getLocalAudioTrack = function() {
  335. return this.rtc ? this.rtc.getLocalAudioTrack() : null;
  336. };
  337. /**
  338. * Obtains local video track.
  339. * @return {JitsiLocalTrack|null}
  340. */
  341. JitsiConference.prototype.getLocalVideoTrack = function() {
  342. return this.rtc ? this.rtc.getLocalVideoTrack() : null;
  343. };
  344. /**
  345. * Attaches a handler for events(For example - "participant joined".) in the
  346. * conference. All possible event are defined in JitsiConferenceEvents.
  347. * @param eventId the event ID.
  348. * @param handler handler for the event.
  349. *
  350. * Note: consider adding eventing functionality by extending an EventEmitter
  351. * impl, instead of rolling ourselves
  352. */
  353. JitsiConference.prototype.on = function(eventId, handler) {
  354. if (this.eventEmitter) {
  355. this.eventEmitter.on(eventId, handler);
  356. }
  357. };
  358. /**
  359. * Removes event listener
  360. * @param eventId the event ID.
  361. * @param [handler] optional, the specific handler to unbind
  362. *
  363. * Note: consider adding eventing functionality by extending an EventEmitter
  364. * impl, instead of rolling ourselves
  365. */
  366. JitsiConference.prototype.off = function(eventId, handler) {
  367. if (this.eventEmitter) {
  368. this.eventEmitter.removeListener(eventId, handler);
  369. }
  370. };
  371. // Common aliases for event emitter
  372. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  373. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  374. /**
  375. * Receives notifications from other participants about commands / custom events
  376. * (sent by sendCommand or sendCommandOnce methods).
  377. * @param command {String} the name of the command
  378. * @param handler {Function} handler for the command
  379. */
  380. JitsiConference.prototype.addCommandListener = function(command, handler) {
  381. if (this.room) {
  382. this.room.addPresenceListener(command, handler);
  383. }
  384. };
  385. /**
  386. * Removes command listener
  387. * @param command {String} the name of the command
  388. */
  389. JitsiConference.prototype.removeCommandListener = function(command) {
  390. if (this.room) {
  391. this.room.removePresenceListener(command);
  392. }
  393. };
  394. /**
  395. * Sends text message to the other participants in the conference
  396. * @param message the text message.
  397. */
  398. JitsiConference.prototype.sendTextMessage = function(message) {
  399. if (this.room) {
  400. this.room.sendMessage(message);
  401. }
  402. };
  403. /**
  404. * Send presence command.
  405. * @param name {String} the name of the command.
  406. * @param values {Object} with keys and values that will be sent.
  407. **/
  408. JitsiConference.prototype.sendCommand = function(name, values) {
  409. if (this.room) {
  410. this.room.addToPresence(name, values);
  411. this.room.sendPresence();
  412. }
  413. };
  414. /**
  415. * Send presence command one time.
  416. * @param name {String} the name of the command.
  417. * @param values {Object} with keys and values that will be sent.
  418. **/
  419. JitsiConference.prototype.sendCommandOnce = function(name, values) {
  420. this.sendCommand(name, values);
  421. this.removeCommand(name);
  422. };
  423. /**
  424. * Removes presence command.
  425. * @param name {String} the name of the command.
  426. **/
  427. JitsiConference.prototype.removeCommand = function(name) {
  428. if (this.room) {
  429. this.room.removeFromPresence(name);
  430. }
  431. };
  432. /**
  433. * Sets the display name for this conference.
  434. * @param name the display name to set
  435. */
  436. JitsiConference.prototype.setDisplayName = function(name) {
  437. if (this.room) {
  438. // remove previously set nickname
  439. this.room.removeFromPresence('nick');
  440. this.room.addToPresence('nick', {
  441. attributes: { xmlns: 'http://jabber.org/protocol/nick' },
  442. value: name
  443. });
  444. this.room.sendPresence();
  445. }
  446. };
  447. /**
  448. * Set new subject for this conference. (available only for moderator)
  449. * @param {string} subject new subject
  450. */
  451. JitsiConference.prototype.setSubject = function(subject) {
  452. if (this.room && this.isModerator()) {
  453. this.room.setSubject(subject);
  454. }
  455. };
  456. /**
  457. * Get a transcriber object for all current participants in this conference
  458. * @return {Transcriber} the transcriber object
  459. */
  460. JitsiConference.prototype.getTranscriber = function() {
  461. if (this.transcriber === undefined) {
  462. this.transcriber = new Transcriber();
  463. // add all existing local audio tracks to the transcriber
  464. const localAudioTracks = this.getLocalTracks(MediaType.AUDIO);
  465. for (const localAudio of localAudioTracks) {
  466. this.transcriber.addTrack(localAudio);
  467. }
  468. // and all remote audio tracks
  469. const remoteAudioTracks = this.rtc.getRemoteTracks(MediaType.AUDIO);
  470. for (const remoteTrack of remoteAudioTracks) {
  471. this.transcriber.addTrack(remoteTrack);
  472. }
  473. }
  474. return this.transcriber;
  475. };
  476. /**
  477. * Adds JitsiLocalTrack object to the conference.
  478. * @param track the JitsiLocalTrack object.
  479. * @returns {Promise<JitsiLocalTrack>}
  480. * @throws {Error} if the specified track is a video track and there is already
  481. * another video track in the conference.
  482. */
  483. JitsiConference.prototype.addTrack = function(track) {
  484. if (track.isVideoTrack()) {
  485. // Ensure there's exactly 1 local video track in the conference.
  486. const localVideoTrack = this.rtc.getLocalVideoTrack();
  487. if (localVideoTrack) {
  488. // Don't be excessively harsh and severe if the API client happens
  489. // to attempt to add the same local video track twice.
  490. if (track === localVideoTrack) {
  491. return Promise.resolve(track);
  492. }
  493. return Promise.reject(new Error(
  494. 'cannot add second video track to the conference'));
  495. }
  496. }
  497. return this.replaceTrack(null, track);
  498. };
  499. /**
  500. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  501. * @param audioLevel the audio level
  502. */
  503. JitsiConference.prototype._fireAudioLevelChangeEvent = function(audioLevel) {
  504. this.eventEmitter.emit(
  505. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  506. this.myUserId(), audioLevel);
  507. };
  508. /**
  509. * Fires TRACK_MUTE_CHANGED change conference event.
  510. * @param track the JitsiTrack object related to the event.
  511. */
  512. JitsiConference.prototype._fireMuteChangeEvent = function(track) {
  513. // check if track was muted by focus and now is unmuted by user
  514. if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
  515. this.isMutedByFocus = false;
  516. // unmute local user on server
  517. this.room.muteParticipant(this.room.myroomjid, false);
  518. }
  519. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  520. };
  521. /**
  522. * Clear JitsiLocalTrack properties and listeners.
  523. * @param track the JitsiLocalTrack object.
  524. */
  525. JitsiConference.prototype.onLocalTrackRemoved = function(track) {
  526. track._setConference(null);
  527. this.rtc.removeLocalTrack(track);
  528. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  529. track.muteHandler);
  530. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  531. track.audioLevelHandler);
  532. // send event for stopping screen sharing
  533. // FIXME: we assume we have only one screen sharing track
  534. // if we change this we need to fix this check
  535. if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP) {
  536. this.statistics.sendScreenSharingEvent(false);
  537. }
  538. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  539. };
  540. /**
  541. * Removes JitsiLocalTrack from the conference and performs
  542. * a new offer/answer cycle.
  543. * @param {JitsiLocalTrack} track
  544. * @returns {Promise}
  545. */
  546. JitsiConference.prototype.removeTrack = function(track) {
  547. return this.replaceTrack(track, null);
  548. };
  549. /**
  550. * Replaces oldTrack with newTrack and performs a single offer/answer
  551. * cycle after both operations are done. Either oldTrack or newTrack
  552. * can be null; replacing a valid 'oldTrack' with a null 'newTrack'
  553. * effectively just removes 'oldTrack'
  554. * @param {JitsiLocalTrack} oldTrack the current stream in use to be replaced
  555. * @param {JitsiLocalTrack} newTrack the new stream to use
  556. * @returns {Promise} resolves when the replacement is finished
  557. */
  558. JitsiConference.prototype.replaceTrack = function(oldTrack, newTrack) {
  559. // First do the removal of the oldTrack at the JitsiConference level
  560. if (oldTrack) {
  561. if (oldTrack.disposed) {
  562. return Promise.reject(
  563. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  564. }
  565. }
  566. if (newTrack) {
  567. if (newTrack.disposed) {
  568. return Promise.reject(
  569. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  570. }
  571. }
  572. // Now replace the stream at the lower levels
  573. return this._doReplaceTrack(oldTrack, newTrack)
  574. .then(() => {
  575. if (oldTrack) {
  576. this.onLocalTrackRemoved(oldTrack);
  577. }
  578. if (newTrack) {
  579. // Now handle the addition of the newTrack at the
  580. // JitsiConference level
  581. this._setupNewTrack(newTrack);
  582. }
  583. return Promise.resolve();
  584. }, error => Promise.reject(new Error(error)));
  585. };
  586. /**
  587. * Replaces the tracks at the lower level by going through the Jingle session
  588. * and WebRTC peer connection. The method will resolve immediately if there is
  589. * currently no JingleSession started.
  590. * @param {JitsiLocalTrack|null} oldTrack the track to be removed during
  591. * the process or <tt>null</t> if the method should act as "add track"
  592. * @param {JitsiLocalTrack|null} newTrack the new track to be added or
  593. * <tt>null</tt> if the method should act as "remove track"
  594. * @return {Promise} resolved when the process is done or rejected with a string
  595. * which describes the error.
  596. * @private
  597. */
  598. JitsiConference.prototype._doReplaceTrack = function(oldTrack, newTrack) {
  599. const replaceTrackPromises = [];
  600. if (this.jvbJingleSession) {
  601. replaceTrackPromises.push(
  602. this.jvbJingleSession.replaceTrack(oldTrack, newTrack));
  603. } else {
  604. logger.info('_doReplaceTrack - no JVB JingleSession');
  605. }
  606. if (this.p2pJingleSession) {
  607. replaceTrackPromises.push(
  608. this.p2pJingleSession.replaceTrack(oldTrack, newTrack));
  609. } else {
  610. logger.info('_doReplaceTrack - no P2P JingleSession');
  611. }
  612. return Promise.all(replaceTrackPromises);
  613. };
  614. /**
  615. * Operations related to creating a new track
  616. * @param {JitsiLocalTrack} newTrack the new track being created
  617. */
  618. JitsiConference.prototype._setupNewTrack = function(newTrack) {
  619. if (newTrack.isAudioTrack() || (newTrack.isVideoTrack()
  620. && newTrack.videoType !== VideoType.DESKTOP)) {
  621. // Report active device to statistics
  622. const devices = RTC.getCurrentlyAvailableMediaDevices();
  623. const device
  624. = devices.find(
  625. d =>
  626. d.kind === `${newTrack.getTrack().kind}input`
  627. && d.label === newTrack.getTrack().label);
  628. if (device) {
  629. Statistics.sendActiveDeviceListEvent(
  630. RTC.getEventDataForActiveDevice(device));
  631. }
  632. }
  633. if (newTrack.isVideoTrack()) {
  634. this.removeCommand('videoType');
  635. this.sendCommand('videoType', {
  636. value: newTrack.videoType,
  637. attributes: {
  638. xmlns: 'http://jitsi.org/jitmeet/video'
  639. }
  640. });
  641. }
  642. this.rtc.addLocalTrack(newTrack);
  643. // ensure that we're sharing proper "is muted" state
  644. if (newTrack.isAudioTrack()) {
  645. this.room.setAudioMute(newTrack.isMuted());
  646. } else {
  647. this.room.setVideoMute(newTrack.isMuted());
  648. }
  649. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  650. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  651. newTrack.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  652. newTrack.muteHandler);
  653. newTrack.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  654. newTrack.audioLevelHandler);
  655. newTrack._setConference(this);
  656. // send event for starting screen sharing
  657. // FIXME: we assume we have only one screen sharing track
  658. // if we change this we need to fix this check
  659. if (newTrack.isVideoTrack() && newTrack.videoType === VideoType.DESKTOP) {
  660. this.statistics.sendScreenSharingEvent(true);
  661. }
  662. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  663. };
  664. /**
  665. * Method called by the {@link JitsiLocalTrack} (a video one) in order to add
  666. * back the underlying WebRTC MediaStream to the PeerConnection (which has
  667. * removed on video mute).
  668. * @param {JitsiLocalTrack} track the local track that will be added as part of
  669. * the unmute operation.
  670. * @return {Promise} resolved when the process is done or rejected with a string
  671. * which describes the error.
  672. */
  673. JitsiConference.prototype._addLocalTrackAsUnmute = function(track) {
  674. const addAsUnmutePromises = [];
  675. if (this.jvbJingleSession) {
  676. addAsUnmutePromises.push(this.jvbJingleSession.addTrackAsUnmute(track));
  677. } else {
  678. logger.info(
  679. 'Add local MediaStream as unmute -'
  680. + ' no JVB Jingle session started yet');
  681. }
  682. if (this.p2pJingleSession) {
  683. addAsUnmutePromises.push(this.p2pJingleSession.addTrackAsUnmute(track));
  684. } else {
  685. logger.info(
  686. 'Add local MediaStream as unmute -'
  687. + ' no P2P Jingle session started yet');
  688. }
  689. return Promise.all(addAsUnmutePromises);
  690. };
  691. /**
  692. * Method called by the {@link JitsiLocalTrack} (a video one) in order to remove
  693. * the underlying WebRTC MediaStream from the PeerConnection. The purpose of
  694. * that is to stop sending any data and turn off the HW camera device.
  695. * @param {JitsiLocalTrack} track the local track that will be removed.
  696. * @return {Promise}
  697. */
  698. JitsiConference.prototype._removeLocalTrackAsMute = function(track) {
  699. const removeAsMutePromises = [];
  700. if (this.jvbJingleSession) {
  701. removeAsMutePromises.push(
  702. this.jvbJingleSession.removeTrackAsMute(track));
  703. } else {
  704. logger.info(
  705. 'Remove local MediaStream - no JVB JingleSession started yet');
  706. }
  707. if (this.p2pJingleSession) {
  708. removeAsMutePromises.push(
  709. this.p2pJingleSession.removeTrackAsMute(track));
  710. } else {
  711. logger.info(
  712. 'Remove local MediaStream - no P2P JingleSession started yet');
  713. }
  714. return Promise.all(removeAsMutePromises);
  715. };
  716. /**
  717. * Get role of the local user.
  718. * @returns {string} user role: 'moderator' or 'none'
  719. */
  720. JitsiConference.prototype.getRole = function() {
  721. return this.room.role;
  722. };
  723. /**
  724. * Check if local user is moderator.
  725. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  726. * we're no longer in the conference room then <tt>null</tt> is returned.
  727. */
  728. JitsiConference.prototype.isModerator = function() {
  729. return this.room ? this.room.isModerator() : null;
  730. };
  731. /**
  732. * Set password for the room.
  733. * @param {string} password new password for the room.
  734. * @returns {Promise}
  735. */
  736. JitsiConference.prototype.lock = function(password) {
  737. if (!this.isModerator()) {
  738. return Promise.reject();
  739. }
  740. return new Promise((resolve, reject) => {
  741. this.room.lockRoom(
  742. password || '',
  743. () => resolve(),
  744. err => reject(err),
  745. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  746. });
  747. };
  748. /**
  749. * Remove password from the room.
  750. * @returns {Promise}
  751. */
  752. JitsiConference.prototype.unlock = function() {
  753. return this.lock();
  754. };
  755. /**
  756. * Elects the participant with the given id to be the selected participant in
  757. * order to receive higher video quality (if simulcast is enabled).
  758. * Or cache it if channel is not created and send it once channel is available.
  759. * @param participantId the identifier of the participant
  760. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  761. */
  762. JitsiConference.prototype.selectParticipant = function(participantId) {
  763. this.rtc.selectEndpoint(participantId);
  764. };
  765. /**
  766. * Elects the participant with the given id to be the pinned participant in
  767. * order to always receive video for this participant (even when last n is
  768. * enabled).
  769. * @param participantId the identifier of the participant
  770. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  771. */
  772. JitsiConference.prototype.pinParticipant = function(participantId) {
  773. this.rtc.pinEndpoint(participantId);
  774. };
  775. /**
  776. * Selects a new value for "lastN". The requested amount of videos are going
  777. * to be delivered after the value is in effect. Set to -1 for unlimited or
  778. * all available videos.
  779. * @param lastN the new number of videos the user would like to receive.
  780. * @throws Error or RangeError if the given value is not a number or is smaller
  781. * than -1.
  782. */
  783. JitsiConference.prototype.setLastN = function(lastN) {
  784. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  785. throw new Error(`Invalid value for lastN: ${lastN}`);
  786. }
  787. const n = Number(lastN);
  788. if (n < -1) {
  789. throw new RangeError('lastN cannot be smaller than -1');
  790. }
  791. this.rtc.setLastN(n);
  792. };
  793. /**
  794. * Checks if the participant given by participantId is currently included in
  795. * the last N.
  796. * @param {string} participantId the identifier of the participant we would
  797. * like to check.
  798. * @return {boolean} true if the participant with id is in the last N set or
  799. * if there's no last N set, false otherwise.
  800. */
  801. JitsiConference.prototype.isInLastN = function(participantId) {
  802. return this.rtc.isInLastN(participantId);
  803. };
  804. /**
  805. * @return Array<JitsiParticipant> an array of all participants in this
  806. * conference.
  807. */
  808. JitsiConference.prototype.getParticipants = function() {
  809. return Object.keys(this.participants).map(function(key) {
  810. return this.participants[key];
  811. }, this);
  812. };
  813. /**
  814. * Returns the number of participants in the conference, including the local
  815. * participant.
  816. * @param countHidden {boolean} Whether or not to include hidden participants
  817. * in the count. Default: false.
  818. **/
  819. JitsiConference.prototype.getParticipantCount
  820. = function(countHidden = false) {
  821. let participants = this.getParticipants();
  822. if (!countHidden) {
  823. participants = participants.filter(p => !p.isHidden());
  824. }
  825. // Add one for the local participant.
  826. return participants.length + 1;
  827. };
  828. /**
  829. * @returns {JitsiParticipant} the participant in this conference with the
  830. * specified id (or undefined if there isn't one).
  831. * @param id the id of the participant.
  832. */
  833. JitsiConference.prototype.getParticipantById = function(id) {
  834. return this.participants[id];
  835. };
  836. /**
  837. * Kick participant from this conference.
  838. * @param {string} id id of the participant to kick
  839. */
  840. JitsiConference.prototype.kickParticipant = function(id) {
  841. const participant = this.getParticipantById(id);
  842. if (!participant) {
  843. return;
  844. }
  845. this.room.kick(participant.getJid());
  846. };
  847. /**
  848. * Mutes a participant.
  849. * @param {string} id The id of the participant to mute.
  850. */
  851. JitsiConference.prototype.muteParticipant = function(id) {
  852. const participant = this.getParticipantById(id);
  853. if (!participant) {
  854. return;
  855. }
  856. this.room.muteParticipant(participant.getJid(), true);
  857. };
  858. /* eslint-disable max-params */
  859. /**
  860. * Notifies this JitsiConference that a new member has joined its chat room.
  861. *
  862. * FIXME This should NOT be exposed!
  863. *
  864. * @param jid the jid of the participant in the MUC
  865. * @param nick the display name of the participant
  866. * @param role the role of the participant in the MUC
  867. * @param isHidden indicates if this is a hidden participant (system
  868. * participant for example a recorder).
  869. */
  870. JitsiConference.prototype.onMemberJoined = function(jid, nick, role, isHidden) {
  871. const id = Strophe.getResourceFromJid(jid);
  872. if (id === 'focus' || this.myUserId() === id) {
  873. return;
  874. }
  875. const participant = new JitsiParticipant(jid, this, nick, isHidden);
  876. participant._role = role;
  877. this.participants[id] = participant;
  878. this.eventEmitter.emit(
  879. JitsiConferenceEvents.USER_JOINED,
  880. id,
  881. participant);
  882. this.xmpp.caps.getFeatures(jid)
  883. .then(features => {
  884. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  885. this.updateDTMFSupport();
  886. },
  887. error => logger.error(`Failed to discover features of ${jid}`, error));
  888. this._maybeStartOrStopP2P();
  889. };
  890. /* eslint-enable max-params */
  891. JitsiConference.prototype.onMemberLeft = function(jid) {
  892. const id = Strophe.getResourceFromJid(jid);
  893. if (id === 'focus' || this.myUserId() === id) {
  894. return;
  895. }
  896. const participant = this.participants[id];
  897. delete this.participants[id];
  898. const removedTracks = this.rtc.removeRemoteTracks(id);
  899. removedTracks.forEach(
  900. track =>
  901. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track));
  902. // there can be no participant in case the member that left is focus
  903. if (participant) {
  904. this.eventEmitter.emit(
  905. JitsiConferenceEvents.USER_LEFT, id, participant);
  906. }
  907. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  908. };
  909. /**
  910. * Method called on local MUC role change.
  911. * @param {string} role the name of new user's role as defined by XMPP MUC.
  912. */
  913. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  914. // Emit role changed for local JID
  915. this.eventEmitter.emit(
  916. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  917. // Maybe start P2P
  918. this._maybeStartOrStopP2P();
  919. };
  920. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  921. const id = Strophe.getResourceFromJid(jid);
  922. const participant = this.getParticipantById(id);
  923. if (!participant) {
  924. return;
  925. }
  926. participant._role = role;
  927. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  928. };
  929. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  930. const id = Strophe.getResourceFromJid(jid);
  931. const participant = this.getParticipantById(id);
  932. if (!participant) {
  933. return;
  934. }
  935. if (participant._displayName === displayName) {
  936. return;
  937. }
  938. participant._displayName = displayName;
  939. this.eventEmitter.emit(
  940. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  941. id,
  942. displayName);
  943. };
  944. /**
  945. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  946. * the conference.
  947. *
  948. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  949. * JitsiConference
  950. */
  951. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  952. if (track.isP2P && !this.isP2PActive()) {
  953. logger.info(
  954. 'Trying to add remote P2P track, when not in P2P - IGNORED');
  955. return;
  956. } else if (!track.isP2P && this.isP2PActive()) {
  957. logger.info(
  958. 'Trying to add remote JVB track, when in P2P - IGNORED');
  959. return;
  960. }
  961. const id = track.getParticipantId();
  962. const participant = this.getParticipantById(id);
  963. if (!participant) {
  964. logger.error(`No participant found for id: ${id}`);
  965. return;
  966. }
  967. // Add track to JitsiParticipant.
  968. participant._tracks.push(track);
  969. if (this.transcriber) {
  970. this.transcriber.addTrack(track);
  971. }
  972. const emitter = this.eventEmitter;
  973. track.addEventListener(
  974. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  975. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  976. track.addEventListener(
  977. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  978. audioLevel => {
  979. emitter.emit(
  980. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  981. id,
  982. audioLevel);
  983. }
  984. );
  985. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  986. };
  987. /**
  988. * Callback called by the Jingle plugin when 'session-answer' is received.
  989. * @param {JingleSessionPC} session the Jingle session for which an answer was
  990. * received.
  991. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  992. */
  993. // eslint-disable-next-line no-unused-vars
  994. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  995. if (this.p2pJingleSession === session) {
  996. logger.info('P2P setAnswer');
  997. this.p2pJingleSession.setAnswer(answer);
  998. }
  999. };
  1000. /**
  1001. * Callback called by the Jingle plugin when 'transport-info' is received.
  1002. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1003. * received
  1004. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1005. * element
  1006. */
  1007. // eslint-disable-next-line no-unused-vars
  1008. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1009. if (this.p2pJingleSession === session) {
  1010. logger.info('P2P addIceCandidates');
  1011. this.p2pJingleSession.addIceCandidates(transportInfo);
  1012. }
  1013. };
  1014. /**
  1015. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1016. * the conference.
  1017. *
  1018. * @param {JitsiRemoteTrack} removedTrack
  1019. */
  1020. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1021. let consumed = false;
  1022. this.getParticipants().forEach(participant => {
  1023. const tracks = participant.getTracks();
  1024. for (let i = 0; i < tracks.length; i++) {
  1025. if (tracks[i] === removedTrack) {
  1026. // Since the tracks have been compared and are
  1027. // considered equal the result of splice can be ignored.
  1028. participant._tracks.splice(i, 1);
  1029. this.eventEmitter.emit(
  1030. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1031. if (this.transcriber) {
  1032. this.transcriber.removeTrack(removedTrack);
  1033. }
  1034. consumed = true;
  1035. break;
  1036. }
  1037. }
  1038. }, this);
  1039. if (!consumed) {
  1040. if ((this.isP2PActive() && !removedTrack.isP2P)
  1041. || (!this.isP2PActive() && removedTrack.isP2P)) {
  1042. // A remote track can be removed either as a result of
  1043. // 'source-remove' or the P2P logic which removes remote tracks
  1044. // explicitly when switching between JVB and P2P connections.
  1045. // The check above filters out the P2P logic case which should not
  1046. // result in an error (which just goes over all remote tracks).
  1047. return;
  1048. }
  1049. logger.error(
  1050. 'Failed to match remote track on remove'
  1051. + ' with any of the participants',
  1052. removedTrack.getStreamId(),
  1053. removedTrack.getParticipantId());
  1054. }
  1055. };
  1056. /**
  1057. * Handles incoming call event.
  1058. */
  1059. JitsiConference.prototype.onIncomingCall
  1060. = function(jingleSession, jingleOffer, now) {
  1061. // Handle incoming P2P call
  1062. if (jingleSession.isP2P) {
  1063. const role = this.room.getMemberRole(jingleSession.peerjid);
  1064. if (role !== 'moderator') {
  1065. // Reject incoming P2P call
  1066. this._rejectIncomingCallNonModerator(jingleSession);
  1067. } else if (!RTCBrowserType.isP2PSupported()) {
  1068. // Reject incoming P2P call (already in progress)
  1069. this._rejectIncomingCall(
  1070. jingleSession, {
  1071. reasonTag: 'unsupported-applications',
  1072. reasonMsg: 'P2P not supported',
  1073. errorMsg: 'This client does not support P2P connections'
  1074. });
  1075. } else if (this.p2pJingleSession) {
  1076. // Reject incoming P2P call (already in progress)
  1077. this._rejectIncomingCall(
  1078. jingleSession, {
  1079. reasonTag: 'busy',
  1080. reasonMsg: 'P2P already in progress',
  1081. errorMsg: 'Duplicated P2P "session-initiate"'
  1082. });
  1083. } else {
  1084. // Accept incoming P2P call
  1085. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1086. }
  1087. return;
  1088. } else if (!this.room.isFocus(jingleSession.peerjid)) {
  1089. this._rejectIncomingCall(jingleSession);
  1090. return;
  1091. }
  1092. // Accept incoming call
  1093. this.jvbJingleSession = jingleSession;
  1094. this.room.connectionTimes['session.initiate'] = now;
  1095. // Log "session.restart"
  1096. if (this.wasStopped) {
  1097. Statistics.sendEventToAll('session.restart');
  1098. }
  1099. // add info whether call is cross-region
  1100. let crossRegion = null;
  1101. if (window.jitsiRegionInfo) {
  1102. crossRegion = window.jitsiRegionInfo.CrossRegion;
  1103. }
  1104. Statistics.analytics.sendEvent(
  1105. 'session.initiate', {
  1106. value: now - this.room.connectionTimes['muc.joined'],
  1107. label: crossRegion
  1108. });
  1109. try {
  1110. jingleSession.initialize(false /* initiator */, this.room, this.rtc);
  1111. } catch (error) {
  1112. GlobalOnErrorHandler.callErrorHandler(error);
  1113. }
  1114. this.rtc.initializeDataChannels(jingleSession.peerconnection);
  1115. // Add local tracks to the session
  1116. try {
  1117. jingleSession.acceptOffer(
  1118. jingleOffer,
  1119. null /* success */,
  1120. error => {
  1121. GlobalOnErrorHandler.callErrorHandler(error);
  1122. logger.error(
  1123. 'Failed to accept incoming Jingle session', error);
  1124. },
  1125. this.getLocalTracks()
  1126. );
  1127. // Start callstats as soon as peerconnection is initialized,
  1128. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1129. // happen in case if user doesn't have or denied permission to
  1130. // both camera and microphone.
  1131. this.statistics.startCallStats(jingleSession);
  1132. this._startRemoteStats();
  1133. } catch (e) {
  1134. GlobalOnErrorHandler.callErrorHandler(e);
  1135. logger.error(e);
  1136. }
  1137. };
  1138. /**
  1139. * Rejects incoming Jingle call with 'security-error'. Method should be used to
  1140. * reject calls initiated by unauthorised entities.
  1141. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1142. * @private
  1143. */
  1144. JitsiConference.prototype._rejectIncomingCallNonModerator
  1145. = function(jingleSession) {
  1146. this._rejectIncomingCall(
  1147. jingleSession,
  1148. {
  1149. reasonTag: 'security-error',
  1150. reasonMsg: 'Only focus can start new sessions',
  1151. errorMsg: 'Rejecting session-initiate from non-focus and'
  1152. + `non-moderator user: ${jingleSession.peerjid}`
  1153. });
  1154. };
  1155. /**
  1156. * Rejects incoming Jingle call.
  1157. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1158. * @param {object} [options]
  1159. * @param {string} options.reasonTag the name of the reason element as defined
  1160. * by Jingle
  1161. * @param {string} options.reasonMsg the reason description which will
  1162. * be included in Jingle 'session-terminate' message.
  1163. * @param {string} options.errorMsg an error message to be logged on global
  1164. * error handler
  1165. * @private
  1166. */
  1167. JitsiConference.prototype._rejectIncomingCall
  1168. = function(jingleSession, options) {
  1169. if (options && options.errorMsg) {
  1170. GlobalOnErrorHandler.callErrorHandler(new Error(options.errorMsg));
  1171. }
  1172. // Terminate the jingle session with a reason
  1173. jingleSession.terminate(
  1174. options && options.reasonTag,
  1175. options && options.reasonMsg,
  1176. null /* success callback => we don't care */,
  1177. error => {
  1178. logger.warn(
  1179. 'An error occurred while trying to terminate'
  1180. + ' invalid Jingle session', error);
  1181. });
  1182. };
  1183. /**
  1184. * Method called to start remote stats for the current peer connection (if
  1185. * available).
  1186. * @private
  1187. */
  1188. JitsiConference.prototype._startRemoteStats = function() {
  1189. const activePeerConnection = this.getActivePeerConnection();
  1190. if (activePeerConnection) {
  1191. this.statistics.startRemoteStats(activePeerConnection);
  1192. }
  1193. };
  1194. /**
  1195. * Handles the call ended event.
  1196. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1197. * terminated.
  1198. * @param {String} reasonCondition the Jingle reason condition.
  1199. * @param {String|null} reasonText human readable reason text which may provide
  1200. * more details about why the call has been terminated.
  1201. */
  1202. JitsiConference.prototype.onCallEnded
  1203. = function(jingleSession, reasonCondition, reasonText) {
  1204. logger.info(
  1205. `Call ended: ${reasonCondition} - ${reasonText
  1206. } P2P ?${jingleSession.isP2P}`);
  1207. if (jingleSession === this.jvbJingleSession) {
  1208. this.wasStopped = true;
  1209. // Send session.terminate event
  1210. Statistics.sendEventToAll('session.terminate');
  1211. // Stop the stats
  1212. if (this.statistics) {
  1213. this.statistics.stopRemoteStats();
  1214. this.statistics.stopCallStats();
  1215. }
  1216. // Current JVB JingleSession is no longer valid, so set it to null
  1217. this.jvbJingleSession = null;
  1218. // Let the RTC service do any cleanups
  1219. this.rtc.onCallEnded();
  1220. } else if (jingleSession === this.p2pJingleSession) {
  1221. this._stopP2PSession();
  1222. } else {
  1223. logger.error(
  1224. 'Received onCallEnded for invalid session',
  1225. jingleSession.sid,
  1226. jingleSession.peerjid,
  1227. reasonCondition,
  1228. reasonText);
  1229. }
  1230. };
  1231. /**
  1232. * Handles the suspend detected event. Leaves the room and fires suspended.
  1233. * @param {JingleSessionPC} jingleSession
  1234. */
  1235. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  1236. if (!jingleSession.isP2P) {
  1237. this.leave();
  1238. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1239. }
  1240. };
  1241. JitsiConference.prototype.updateDTMFSupport = function() {
  1242. let somebodySupportsDTMF = false;
  1243. const participants = this.getParticipants();
  1244. // check if at least 1 participant supports DTMF
  1245. for (let i = 0; i < participants.length; i += 1) {
  1246. if (participants[i].supportsDTMF()) {
  1247. somebodySupportsDTMF = true;
  1248. break;
  1249. }
  1250. }
  1251. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1252. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1253. this.eventEmitter.emit(
  1254. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1255. somebodySupportsDTMF);
  1256. }
  1257. };
  1258. /**
  1259. * Allows to check if there is at least one user in the conference
  1260. * that supports DTMF.
  1261. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1262. */
  1263. JitsiConference.prototype.isDTMFSupported = function() {
  1264. return this.somebodySupportsDTMF;
  1265. };
  1266. /**
  1267. * Returns the local user's ID
  1268. * @return {string} local user's ID
  1269. */
  1270. JitsiConference.prototype.myUserId = function() {
  1271. return (
  1272. this.room
  1273. && this.room.myroomjid
  1274. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1275. : null);
  1276. };
  1277. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1278. if (!this.dtmfManager) {
  1279. const peerConnection = this.getActivePeerConnection();
  1280. if (!peerConnection) {
  1281. logger.warn('cannot sendTones: no peer connection');
  1282. return;
  1283. }
  1284. const localAudio = this.getLocalAudioTrack();
  1285. if (!localAudio) {
  1286. logger.warn('cannot sendTones: no local audio stream');
  1287. return;
  1288. }
  1289. this.dtmfManager = new JitsiDTMFManager(localAudio, peerConnection);
  1290. }
  1291. this.dtmfManager.sendTones(tones, duration, pause);
  1292. };
  1293. /**
  1294. * Returns true if recording is supported and false if not.
  1295. */
  1296. JitsiConference.prototype.isRecordingSupported = function() {
  1297. if (this.room) {
  1298. return this.room.isRecordingSupported();
  1299. }
  1300. return false;
  1301. };
  1302. /**
  1303. * Returns null if the recording is not supported, "on" if the recording started
  1304. * and "off" if the recording is not started.
  1305. */
  1306. JitsiConference.prototype.getRecordingState = function() {
  1307. return this.room ? this.room.getRecordingState() : undefined;
  1308. };
  1309. /**
  1310. * Returns the url of the recorded video.
  1311. */
  1312. JitsiConference.prototype.getRecordingURL = function() {
  1313. return this.room ? this.room.getRecordingURL() : null;
  1314. };
  1315. /**
  1316. * Starts/stops the recording
  1317. */
  1318. JitsiConference.prototype.toggleRecording = function(options) {
  1319. if (this.room) {
  1320. return this.room.toggleRecording(options, (status, error) => {
  1321. this.eventEmitter.emit(
  1322. JitsiConferenceEvents.RECORDER_STATE_CHANGED, status, error);
  1323. });
  1324. }
  1325. this.eventEmitter.emit(
  1326. JitsiConferenceEvents.RECORDER_STATE_CHANGED, 'error',
  1327. new Error('The conference is not created yet!'));
  1328. };
  1329. /**
  1330. * Returns true if the SIP calls are supported and false otherwise
  1331. */
  1332. JitsiConference.prototype.isSIPCallingSupported = function() {
  1333. if (this.room) {
  1334. return this.room.isSIPCallingSupported();
  1335. }
  1336. return false;
  1337. };
  1338. /**
  1339. * Dials a number.
  1340. * @param number the number
  1341. */
  1342. JitsiConference.prototype.dial = function(number) {
  1343. if (this.room) {
  1344. return this.room.dial(number);
  1345. }
  1346. return new Promise((resolve, reject) => {
  1347. reject(new Error('The conference is not created yet!'));
  1348. });
  1349. };
  1350. /**
  1351. * Hangup an existing call
  1352. */
  1353. JitsiConference.prototype.hangup = function() {
  1354. if (this.room) {
  1355. return this.room.hangup();
  1356. }
  1357. return new Promise((resolve, reject) => {
  1358. reject(new Error('The conference is not created yet!'));
  1359. });
  1360. };
  1361. /**
  1362. * Returns the phone number for joining the conference.
  1363. */
  1364. JitsiConference.prototype.getPhoneNumber = function() {
  1365. if (this.room) {
  1366. return this.room.getPhoneNumber();
  1367. }
  1368. return null;
  1369. };
  1370. /**
  1371. * Returns the pin for joining the conference with phone.
  1372. */
  1373. JitsiConference.prototype.getPhonePin = function() {
  1374. if (this.room) {
  1375. return this.room.getPhonePin();
  1376. }
  1377. return null;
  1378. };
  1379. /**
  1380. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  1381. * which connection is currently active.
  1382. *
  1383. * @return {TraceablePeerConnection|null} null if there isn't any active
  1384. * <tt>TraceablePeerConnection</tt> currently available.
  1385. * @protected
  1386. */
  1387. JitsiConference.prototype.getActivePeerConnection = function() {
  1388. if (this.isP2PActive()) {
  1389. return this.p2pJingleSession.peerconnection;
  1390. }
  1391. return this.jvbJingleSession ? this.jvbJingleSession.peerconnection : null;
  1392. };
  1393. /**
  1394. * Returns the connection state for the current room. Its ice connection state
  1395. * for its session.
  1396. * NOTE that "completed" ICE state which can appear on the P2P connection will
  1397. * be converted to "connected".
  1398. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  1399. * peer connection at this time.
  1400. */
  1401. JitsiConference.prototype.getConnectionState = function() {
  1402. const peerConnection = this.getActivePeerConnection();
  1403. return peerConnection ? peerConnection.getConnectionState() : null;
  1404. };
  1405. /**
  1406. * Make all new participants mute their audio/video on join.
  1407. * @param policy {Object} object with 2 boolean properties for video and audio:
  1408. * @param {boolean} audio if audio should be muted.
  1409. * @param {boolean} video if video should be muted.
  1410. */
  1411. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  1412. if (!this.isModerator()) {
  1413. return;
  1414. }
  1415. this.startMutedPolicy = policy;
  1416. this.room.removeFromPresence('startmuted');
  1417. this.room.addToPresence('startmuted', {
  1418. attributes: {
  1419. audio: policy.audio,
  1420. video: policy.video,
  1421. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  1422. }
  1423. });
  1424. this.room.sendPresence();
  1425. };
  1426. /**
  1427. * Returns current start muted policy
  1428. * @returns {Object} with 2 properties - audio and video.
  1429. */
  1430. JitsiConference.prototype.getStartMutedPolicy = function() {
  1431. return this.startMutedPolicy;
  1432. };
  1433. /**
  1434. * Check if audio is muted on join.
  1435. */
  1436. JitsiConference.prototype.isStartAudioMuted = function() {
  1437. return this.startAudioMuted;
  1438. };
  1439. /**
  1440. * Check if video is muted on join.
  1441. */
  1442. JitsiConference.prototype.isStartVideoMuted = function() {
  1443. return this.startVideoMuted;
  1444. };
  1445. /**
  1446. * Get object with internal logs.
  1447. */
  1448. JitsiConference.prototype.getLogs = function() {
  1449. const data = this.xmpp.getJingleLog();
  1450. const metadata = {};
  1451. metadata.time = new Date();
  1452. metadata.url = window.location.href;
  1453. metadata.ua = navigator.userAgent;
  1454. const log = this.xmpp.getXmppLog();
  1455. if (log) {
  1456. metadata.xmpp = log;
  1457. }
  1458. data.metadata = metadata;
  1459. return data;
  1460. };
  1461. /**
  1462. * Returns measured connectionTimes.
  1463. */
  1464. JitsiConference.prototype.getConnectionTimes = function() {
  1465. return this.room.connectionTimes;
  1466. };
  1467. /**
  1468. * Sets a property for the local participant.
  1469. */
  1470. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  1471. this.sendCommand(`jitsi_participant_${name}`, { value });
  1472. };
  1473. /**
  1474. * Sends the given feedback through CallStats if enabled.
  1475. *
  1476. * @param overallFeedback an integer between 1 and 5 indicating the
  1477. * user feedback
  1478. * @param detailedFeedback detailed feedback from the user. Not yet used
  1479. */
  1480. JitsiConference.prototype.sendFeedback
  1481. = function(overallFeedback, detailedFeedback) {
  1482. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  1483. };
  1484. /**
  1485. * Returns true if the callstats integration is enabled, otherwise returns
  1486. * false.
  1487. *
  1488. * @returns true if the callstats integration is enabled, otherwise returns
  1489. * false.
  1490. */
  1491. JitsiConference.prototype.isCallstatsEnabled = function() {
  1492. return this.statistics.isCallstatsEnabled();
  1493. };
  1494. /**
  1495. * Handles track attached to container (Calls associateStreamWithVideoTag method
  1496. * from statistics module)
  1497. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  1498. * @param container the container
  1499. */
  1500. JitsiConference.prototype._onTrackAttach = function(track, container) {
  1501. const isLocal = track.isLocal();
  1502. let ssrc = null;
  1503. if (isLocal) {
  1504. // FIXME currently we do CallStats only for JVB, but the same logic will
  1505. // need to happen for the P2P as well once the support is added.
  1506. // Local tracks have SSRC stored on per peer connection basis
  1507. const peerConnection
  1508. = this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  1509. if (peerConnection) {
  1510. ssrc = peerConnection.getLocalSSRC(track);
  1511. }
  1512. } else {
  1513. ssrc = track.getSSRC();
  1514. }
  1515. if (!container.id || !ssrc) {
  1516. return;
  1517. }
  1518. this.statistics.associateStreamWithVideoTag(
  1519. ssrc, isLocal, track.getUsageLabel(), container.id);
  1520. };
  1521. /**
  1522. * Logs an "application log" message.
  1523. * @param message {string} The message to log. Note that while this can be a
  1524. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  1525. * log valid JSON strings, with an "id" field used for distinguishing between
  1526. * message types. E.g.: {id: "recorder_status", status: "off"}
  1527. */
  1528. JitsiConference.prototype.sendApplicationLog = function(message) {
  1529. Statistics.sendLog(message);
  1530. };
  1531. /**
  1532. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1533. * focus.
  1534. * @param mucJid the full MUC address of the user to be checked.
  1535. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  1536. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  1537. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  1538. */
  1539. JitsiConference.prototype._isFocus = function(mucJid) {
  1540. return this.room ? this.room.isFocus(mucJid) : null;
  1541. };
  1542. /**
  1543. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  1544. */
  1545. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  1546. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  1547. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  1548. };
  1549. /**
  1550. * Sends a message via the data channel.
  1551. * @param to {string} the id of the endpoint that should receive the message.
  1552. * If "" the message will be sent to all participants.
  1553. * @param payload {object} the payload of the message.
  1554. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1555. */
  1556. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  1557. this.rtc.sendDataChannelMessage(to, payload);
  1558. };
  1559. /**
  1560. * Sends a broadcast message via the data channel.
  1561. * @param payload {object} the payload of the message.
  1562. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1563. */
  1564. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  1565. this.sendEndpointMessage('', payload);
  1566. };
  1567. JitsiConference.prototype.isConnectionInterrupted = function() {
  1568. return this.isP2PActive()
  1569. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  1570. };
  1571. /**
  1572. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  1573. * @param {JingleSessionPC} session
  1574. * @private
  1575. */
  1576. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  1577. if (session.isP2P) {
  1578. this.isP2PConnectionInterrupted = true;
  1579. } else {
  1580. this.isJvbConnectionInterrupted = true;
  1581. }
  1582. if (session.isP2P === this.isP2PActive()) {
  1583. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  1584. }
  1585. };
  1586. /**
  1587. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  1588. * @param {JingleSessionPC} session
  1589. * @private
  1590. */
  1591. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  1592. // We do nothing for the JVB connection, because it's up to the Jicofo to
  1593. // eventually come up with the new offer (at least for the time being).
  1594. if (session.isP2P) {
  1595. if (this.p2pJingleSession && this.p2pJingleSession.isInitiator) {
  1596. Statistics.sendEventToAll('p2p.ice_failed');
  1597. }
  1598. this._stopP2PSession('connectivity-error', 'ICE FAILED');
  1599. }
  1600. };
  1601. /**
  1602. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  1603. * @param {JingleSessionPC} session
  1604. * @private
  1605. */
  1606. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  1607. if (session.isP2P) {
  1608. this.isP2PConnectionInterrupted = false;
  1609. } else {
  1610. this.isJvbConnectionInterrupted = false;
  1611. }
  1612. if (session.isP2P === this.isP2PActive()) {
  1613. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  1614. }
  1615. };
  1616. /**
  1617. * Accept incoming P2P Jingle call.
  1618. * @param {JingleSessionPC} jingleSession the session instance
  1619. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  1620. * @private
  1621. */
  1622. JitsiConference.prototype._acceptP2PIncomingCall
  1623. = function(jingleSession, jingleOffer) {
  1624. jingleSession.setSSRCOwnerJid(this.room.myroomjid);
  1625. this.isP2PConnectionInterrupted = false;
  1626. // Accept the offer
  1627. this.p2pJingleSession = jingleSession;
  1628. this.p2pJingleSession.initialize(
  1629. false /* initiator */, this.room, this.rtc);
  1630. const localTracks = this.getLocalTracks();
  1631. this.p2pJingleSession.acceptOffer(
  1632. jingleOffer,
  1633. () => {
  1634. logger.debug('Got RESULT for P2P "session-accept"');
  1635. },
  1636. error => {
  1637. logger.error(
  1638. 'Failed to accept incoming P2P Jingle session', error);
  1639. },
  1640. localTracks);
  1641. };
  1642. /**
  1643. * Adds remote tracks to the conference associated with the JVB session.
  1644. * @private
  1645. */
  1646. JitsiConference.prototype._addRemoteJVBTracks = function() {
  1647. this._addRemoteTracks(
  1648. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  1649. };
  1650. /**
  1651. * Adds remote tracks to the conference associated with the P2P session.
  1652. * @private
  1653. */
  1654. JitsiConference.prototype._addRemoteP2PTracks = function() {
  1655. this._addRemoteTracks(
  1656. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  1657. };
  1658. /**
  1659. * Generates fake "remote track added" events for given Jingle session.
  1660. * @param {string} logName the session's nickname which will appear in log
  1661. * messages.
  1662. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  1663. * @private
  1664. */
  1665. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  1666. for (const track of remoteTracks) {
  1667. logger.info(`Adding remote ${logName} track: ${track}`);
  1668. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, track);
  1669. }
  1670. };
  1671. /**
  1672. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  1673. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  1674. * the P2P connection if the event comes from the P2P session.
  1675. * @param {JingleSessionPC} jingleSession the session instance.
  1676. * @private
  1677. */
  1678. JitsiConference.prototype._onIceConnectionEstablished
  1679. = function(jingleSession) {
  1680. // We don't care about the JVB case, there's nothing to be done
  1681. if (!jingleSession.isP2P) {
  1682. return;
  1683. } else if (this.p2pJingleSession !== jingleSession) {
  1684. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  1685. return;
  1686. }
  1687. // Update P2P status and emit events
  1688. this._setP2PStatus(true);
  1689. // Remove remote tracks
  1690. if (this.jvbJingleSession) {
  1691. this._removeRemoteJVBTracks();
  1692. } else {
  1693. logger.info('Not removing remote JVB tracks - no session yet');
  1694. }
  1695. // Add remote tracks
  1696. this._addRemoteP2PTracks();
  1697. // Stop media transfer over the JVB connection
  1698. if (this.jvbJingleSession) {
  1699. this._suspendMediaTransferForJvbConnection();
  1700. }
  1701. // Start remote stats
  1702. logger.info('Starting remote stats with p2p connection');
  1703. this._startRemoteStats();
  1704. // Log the P2P established event
  1705. if (this.p2pJingleSession.isInitiator) {
  1706. Statistics.sendEventToAll('p2p.established');
  1707. }
  1708. };
  1709. /**
  1710. * Clears the deferred start P2P task if it has been scheduled.
  1711. * @private
  1712. */
  1713. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  1714. if (this.deferredStartP2PTask) {
  1715. logger.info('Cleared deferred start P2P task');
  1716. clearTimeout(this.deferredStartP2PTask);
  1717. this.deferredStartP2PTask = null;
  1718. }
  1719. };
  1720. /**
  1721. * Removes from the conference remote tracks associated with the JVB
  1722. * connection.
  1723. * @private
  1724. */
  1725. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  1726. this._removeRemoteTracks(
  1727. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  1728. };
  1729. /**
  1730. * Removes from the conference remote tracks associated with the P2P
  1731. * connection.
  1732. * @private
  1733. */
  1734. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  1735. this._removeRemoteTracks(
  1736. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  1737. };
  1738. /**
  1739. * Generates fake "remote track removed" events for given Jingle session.
  1740. * @param {string} sessionNickname the session's nickname which will appear in
  1741. * log messages.
  1742. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  1743. * @private
  1744. */
  1745. JitsiConference.prototype._removeRemoteTracks
  1746. = function(sessionNickname, remoteTracks) {
  1747. for (const track of remoteTracks) {
  1748. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  1749. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, track);
  1750. }
  1751. };
  1752. /**
  1753. * Resumes media transfer over the JVB connection.
  1754. * @private
  1755. */
  1756. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  1757. logger.info('Resuming media transfer over the JVB connection...');
  1758. this.jvbJingleSession.setMediaTransferActive(true).then(
  1759. () => {
  1760. logger.info('Resumed media transfer over the JVB connection!');
  1761. },
  1762. error => {
  1763. logger.error(
  1764. 'Failed to resume media transfer over the JVB connection:',
  1765. error);
  1766. });
  1767. };
  1768. /**
  1769. * Sets new P2P status and updates some events/states hijacked from
  1770. * the <tt>JitsiConference</tt>.
  1771. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  1772. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  1773. * @private
  1774. */
  1775. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  1776. if (this.p2p === newStatus) {
  1777. logger.error(`Called _setP2PStatus with the same status: ${newStatus}`);
  1778. return;
  1779. }
  1780. this.p2p = newStatus;
  1781. if (newStatus) {
  1782. logger.info('Peer to peer connection established!');
  1783. } else {
  1784. logger.info('Peer to peer connection closed!');
  1785. }
  1786. // Clear dtmfManager, so that it can be recreated with new connection
  1787. this.dtmfManager = null;
  1788. // Update P2P status
  1789. this.eventEmitter.emit(
  1790. JitsiConferenceEvents.P2P_STATUS,
  1791. this,
  1792. this.p2p);
  1793. // Refresh connection interrupted/restored
  1794. this.eventEmitter.emit(
  1795. this.isConnectionInterrupted()
  1796. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  1797. : JitsiConferenceEvents.CONNECTION_RESTORED);
  1798. };
  1799. /**
  1800. * Starts new P2P session.
  1801. * @param {string} peerJid the JID of the remote participant
  1802. * @private
  1803. */
  1804. JitsiConference.prototype._startP2PSession = function(peerJid) {
  1805. this._maybeClearDeferredStartP2P();
  1806. if (this.p2pJingleSession) {
  1807. logger.error('P2P session already started!');
  1808. return;
  1809. }
  1810. this.isP2PConnectionInterrupted = false;
  1811. this.p2pJingleSession
  1812. = this.xmpp.connection.jingle.newP2PJingleSession(
  1813. this.room.myroomjid,
  1814. peerJid);
  1815. this.p2pJingleSession.setSSRCOwnerJid(this.room.myroomjid);
  1816. logger.info('Created new P2P JingleSession', this.room.myroomjid, peerJid);
  1817. this.p2pJingleSession.initialize(true /* initiator */, this.room, this.rtc);
  1818. // NOTE one may consider to start P2P with the local tracks detached,
  1819. // but no data will be sent until ICE succeeds anyway. And we switch
  1820. // immediately once the P2P ICE connects.
  1821. const localTracks = this.getLocalTracks();
  1822. this.p2pJingleSession.invite(localTracks);
  1823. };
  1824. /**
  1825. * Suspends media transfer over the JVB connection.
  1826. * @private
  1827. */
  1828. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  1829. logger.info('Suspending media transfer over the JVB connection...');
  1830. this.jvbJingleSession.setMediaTransferActive(false).then(
  1831. () => {
  1832. logger.info('Suspended media transfer over the JVB connection !');
  1833. },
  1834. error => {
  1835. logger.error(
  1836. 'Failed to suspend media transfer over the JVB connection:',
  1837. error);
  1838. });
  1839. };
  1840. /**
  1841. * Method when called will decide whether it's the time to start or stop
  1842. * the P2P session.
  1843. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  1844. * originates from the user left event.
  1845. * @private
  1846. */
  1847. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  1848. if (!this.options.config.enableP2P || !RTCBrowserType.isP2PSupported()) {
  1849. logger.info('Auto P2P disabled');
  1850. return;
  1851. }
  1852. const peers = this.getParticipants();
  1853. const peerCount = peers.length;
  1854. const isModerator = this.isModerator();
  1855. // FIXME 1 peer and it must *support* P2P switching
  1856. const shouldBeInP2P = peerCount === 1;
  1857. logger.debug(
  1858. `P2P? isModerator: ${isModerator
  1859. }, peerCount: ${peerCount} => ${shouldBeInP2P}`);
  1860. // Clear deferred "start P2P" task
  1861. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  1862. this._maybeClearDeferredStartP2P();
  1863. }
  1864. // Start peer to peer session
  1865. if (isModerator && !this.p2pJingleSession && shouldBeInP2P) {
  1866. const peer = peerCount && peers[0];
  1867. // Everyone is a moderator ?
  1868. if (isModerator && peer.getRole() === 'moderator') {
  1869. const myId = this.myUserId();
  1870. const peersId = peer.getId();
  1871. if (myId > peersId) {
  1872. logger.debug(
  1873. 'Everyone\'s a moderator - '
  1874. + 'the other peer should start P2P', myId, peersId);
  1875. return;
  1876. } else if (myId === peersId) {
  1877. logger.error('The same IDs ? ', myId, peersId);
  1878. return;
  1879. }
  1880. }
  1881. const jid = peer.getJid();
  1882. if (userLeftEvent) {
  1883. if (this.deferredStartP2PTask) {
  1884. logger.error('Deferred start P2P task\'s been set already!');
  1885. return;
  1886. }
  1887. logger.info(
  1888. `Will start P2P with: ${jid
  1889. } after ${this.backToP2PDelay} seconds...`);
  1890. this.deferredStartP2PTask = setTimeout(
  1891. this._startP2PSession.bind(this, jid),
  1892. this.backToP2PDelay * 1000);
  1893. } else {
  1894. logger.info(`Will start P2P with: ${jid}`);
  1895. this._startP2PSession(jid);
  1896. }
  1897. } else if (isModerator && this.p2pJingleSession && !shouldBeInP2P) {
  1898. logger.info(`Will stop P2P with: ${this.p2pJingleSession.peerjid}`);
  1899. // Log that there will be a switch back to the JVB connection
  1900. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  1901. Statistics.sendEventToAll('p2p.switch_to_jvb');
  1902. }
  1903. this._stopP2PSession();
  1904. }
  1905. };
  1906. /**
  1907. * Stops the current P2P session.
  1908. * @param {string} [reason="success"] one of the Jingle "reason" element
  1909. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  1910. * @param {string} [reasonDescription="Turing off P2P session"] text
  1911. * description that will be included in the session terminate message
  1912. * @private
  1913. */
  1914. JitsiConference.prototype._stopP2PSession
  1915. = function(reason, reasonDescription) {
  1916. if (!this.p2pJingleSession) {
  1917. logger.error('No P2P session to be stopped!');
  1918. return;
  1919. }
  1920. const wasP2PEstablished = this.isP2PActive();
  1921. // Swap remote tracks, but only if the P2P has been fully established
  1922. if (wasP2PEstablished) {
  1923. this._resumeMediaTransferForJvbConnection();
  1924. // Remove remote P2P tracks
  1925. this._removeRemoteP2PTracks();
  1926. }
  1927. // Stop P2P stats
  1928. logger.info('Stopping remote stats with P2P connection');
  1929. this.statistics.stopRemoteStats();
  1930. if (JingleSessionState.ENDED !== this.p2pJingleSession.state) {
  1931. this.p2pJingleSession.terminate(
  1932. reason ? reason : 'success',
  1933. reasonDescription
  1934. ? reasonDescription : 'Turing off P2P session',
  1935. () => {
  1936. logger.info('P2P session terminate RESULT');
  1937. },
  1938. error => {
  1939. logger.warn(
  1940. 'An error occurred while trying to terminate'
  1941. + ' P2P Jingle session', error);
  1942. });
  1943. }
  1944. this.p2pJingleSession = null;
  1945. // Update P2P status and other affected events/states
  1946. this._setP2PStatus(false);
  1947. if (wasP2PEstablished) {
  1948. // Add back remote JVB tracks
  1949. if (this.jvbJingleSession) {
  1950. this._addRemoteJVBTracks();
  1951. } else {
  1952. logger.info('Not adding remote JVB tracks - no session yet');
  1953. }
  1954. }
  1955. // Start remote stats
  1956. logger.info('Starting remote stats with JVB connection');
  1957. if (this.jvbJingleSession) {
  1958. this._startRemoteStats();
  1959. }
  1960. };
  1961. /**
  1962. * Checks whether or not the conference is currently in the peer to peer mode.
  1963. * Being in peer to peer mode means that the direct connection has been
  1964. * established and the P2P connection is being used for media transmission.
  1965. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  1966. */
  1967. JitsiConference.prototype.isP2PActive = function() {
  1968. return this.p2p;
  1969. };
  1970. /**
  1971. * Returns the current ICE state of the P2P connection.
  1972. * NOTE: method is used by the jitsi-meet-torture tests.
  1973. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  1974. * no P2P connection.
  1975. */
  1976. JitsiConference.prototype.getP2PConnectionState = function() {
  1977. if (this.isP2PActive()) {
  1978. return this.p2pJingleSession.peerconnection.getConnectionState();
  1979. }
  1980. return null;
  1981. };
  1982. /**
  1983. * Manually starts new P2P session (should be used only in the tests).
  1984. */
  1985. JitsiConference.prototype.startP2PSession = function() {
  1986. const peers = this.getParticipants();
  1987. // Start peer to peer session
  1988. if (peers.length === 1) {
  1989. const peerJid = peers[0].getJid();
  1990. this._startP2PSession(peerJid);
  1991. } else {
  1992. throw new Error(
  1993. 'There must be exactly 1 participant to start the P2P session !');
  1994. }
  1995. };
  1996. /**
  1997. * Manually stops the current P2P session (should be used only in the tests)
  1998. */
  1999. JitsiConference.prototype.stopP2PSession = function() {
  2000. this._stopP2PSession();
  2001. };
  2002. /**
  2003. * Get a summary of how long current participants have been the dominant speaker
  2004. * @returns {object}
  2005. */
  2006. JitsiConference.prototype.getSpeakerStats = function() {
  2007. return this.speakerStatsCollector.getStats();
  2008. };
  2009. /**
  2010. * Get video SIP GW handler, if missing will create one.
  2011. *
  2012. * @returns {VideoSIPGW} video SIP GW handler.
  2013. */
  2014. JitsiConference.prototype._getVideoSIPGWHandle = function() {
  2015. if (!this.videoSIPGWHandler) {
  2016. this.videoSIPGWHandler = new VideoSIPGW(this.room);
  2017. logger.info('Created VideoSIPGW');
  2018. }
  2019. return this.videoSIPGWHandler;
  2020. };
  2021. /**
  2022. * Checks whether video SIP GW service is available.
  2023. *
  2024. * @returns {boolean} whether video SIP GW service is available.
  2025. */
  2026. JitsiConference.prototype.isVideoSIPGWAvailable = function() {
  2027. return this._getVideoSIPGWHandle().isVideoSIPGWAvailable();
  2028. };
  2029. /**
  2030. * Creates a video SIP GW session and returns it if service is enabled. Before
  2031. * creating a session one need to check whether video SIP GW service is
  2032. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2033. * if there are available nodes to serve this request, after creating the
  2034. * session those nodes can be taken and the request about using the
  2035. * created session can fail.
  2036. *
  2037. * @param {string} sipAddress - The sip address to be used.
  2038. * @param {string} displayName - The display name to be used for this session.
  2039. * @returns {JitsiVideoSIPGWSession|null} Returns null if conference is not
  2040. * initialised and there is no room.
  2041. */
  2042. JitsiConference.prototype.createVideoSIPGWSession
  2043. = function(sipAddress, displayName) {
  2044. if (!this.room) {
  2045. return null;
  2046. }
  2047. return this._getVideoSIPGWHandle()
  2048. .createVideoSIPGWSession(sipAddress, displayName);
  2049. };
  2050. module.exports = JitsiConference;