Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364
  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. if (newTrack.startMuted) {
  644. newTrack.mute();
  645. }
  646. // ensure that we're sharing proper "is muted" state
  647. if (newTrack.isAudioTrack()) {
  648. this.room.setAudioMute(newTrack.isMuted());
  649. } else {
  650. this.room.setVideoMute(newTrack.isMuted());
  651. }
  652. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  653. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  654. newTrack.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  655. newTrack.muteHandler);
  656. newTrack.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  657. newTrack.audioLevelHandler);
  658. newTrack._setConference(this);
  659. // send event for starting screen sharing
  660. // FIXME: we assume we have only one screen sharing track
  661. // if we change this we need to fix this check
  662. if (newTrack.isVideoTrack() && newTrack.videoType === VideoType.DESKTOP) {
  663. this.statistics.sendScreenSharingEvent(true);
  664. }
  665. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  666. };
  667. /**
  668. * Method called by the {@link JitsiLocalTrack} (a video one) in order to add
  669. * back the underlying WebRTC MediaStream to the PeerConnection (which has
  670. * removed on video mute).
  671. * @param {JitsiLocalTrack} track the local track that will be added as part of
  672. * the unmute operation.
  673. * @return {Promise} resolved when the process is done or rejected with a string
  674. * which describes the error.
  675. */
  676. JitsiConference.prototype._addLocalTrackAsUnmute = function(track) {
  677. const addAsUnmutePromises = [];
  678. if (this.jvbJingleSession) {
  679. addAsUnmutePromises.push(this.jvbJingleSession.addTrackAsUnmute(track));
  680. } else {
  681. logger.info(
  682. 'Add local MediaStream as unmute -'
  683. + ' no JVB Jingle session started yet');
  684. }
  685. if (this.p2pJingleSession) {
  686. addAsUnmutePromises.push(this.p2pJingleSession.addTrackAsUnmute(track));
  687. } else {
  688. logger.info(
  689. 'Add local MediaStream as unmute -'
  690. + ' no P2P Jingle session started yet');
  691. }
  692. return Promise.all(addAsUnmutePromises);
  693. };
  694. /**
  695. * Method called by the {@link JitsiLocalTrack} (a video one) in order to remove
  696. * the underlying WebRTC MediaStream from the PeerConnection. The purpose of
  697. * that is to stop sending any data and turn off the HW camera device.
  698. * @param {JitsiLocalTrack} track the local track that will be removed.
  699. * @return {Promise}
  700. */
  701. JitsiConference.prototype._removeLocalTrackAsMute = function(track) {
  702. const removeAsMutePromises = [];
  703. if (this.jvbJingleSession) {
  704. removeAsMutePromises.push(
  705. this.jvbJingleSession.removeTrackAsMute(track));
  706. } else {
  707. logger.info(
  708. 'Remove local MediaStream - no JVB JingleSession started yet');
  709. }
  710. if (this.p2pJingleSession) {
  711. removeAsMutePromises.push(
  712. this.p2pJingleSession.removeTrackAsMute(track));
  713. } else {
  714. logger.info(
  715. 'Remove local MediaStream - no P2P JingleSession started yet');
  716. }
  717. return Promise.all(removeAsMutePromises);
  718. };
  719. /**
  720. * Get role of the local user.
  721. * @returns {string} user role: 'moderator' or 'none'
  722. */
  723. JitsiConference.prototype.getRole = function() {
  724. return this.room.role;
  725. };
  726. /**
  727. * Check if local user is moderator.
  728. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  729. * we're no longer in the conference room then <tt>null</tt> is returned.
  730. */
  731. JitsiConference.prototype.isModerator = function() {
  732. return this.room ? this.room.isModerator() : null;
  733. };
  734. /**
  735. * Set password for the room.
  736. * @param {string} password new password for the room.
  737. * @returns {Promise}
  738. */
  739. JitsiConference.prototype.lock = function(password) {
  740. if (!this.isModerator()) {
  741. return Promise.reject();
  742. }
  743. return new Promise((resolve, reject) => {
  744. this.room.lockRoom(
  745. password || '',
  746. () => resolve(),
  747. err => reject(err),
  748. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  749. });
  750. };
  751. /**
  752. * Remove password from the room.
  753. * @returns {Promise}
  754. */
  755. JitsiConference.prototype.unlock = function() {
  756. return this.lock();
  757. };
  758. /**
  759. * Elects the participant with the given id to be the selected participant in
  760. * order to receive higher video quality (if simulcast is enabled).
  761. * Or cache it if channel is not created and send it once channel is available.
  762. * @param participantId the identifier of the participant
  763. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  764. */
  765. JitsiConference.prototype.selectParticipant = function(participantId) {
  766. this.rtc.selectEndpoint(participantId);
  767. };
  768. /**
  769. * Elects the participant with the given id to be the pinned participant in
  770. * order to always receive video for this participant (even when last n is
  771. * enabled).
  772. * @param participantId the identifier of the participant
  773. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  774. */
  775. JitsiConference.prototype.pinParticipant = function(participantId) {
  776. this.rtc.pinEndpoint(participantId);
  777. };
  778. /**
  779. * Selects a new value for "lastN". The requested amount of videos are going
  780. * to be delivered after the value is in effect. Set to -1 for unlimited or
  781. * all available videos.
  782. * @param lastN the new number of videos the user would like to receive.
  783. * @throws Error or RangeError if the given value is not a number or is smaller
  784. * than -1.
  785. */
  786. JitsiConference.prototype.setLastN = function(lastN) {
  787. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  788. throw new Error(`Invalid value for lastN: ${lastN}`);
  789. }
  790. const n = Number(lastN);
  791. if (n < -1) {
  792. throw new RangeError('lastN cannot be smaller than -1');
  793. }
  794. this.rtc.setLastN(n);
  795. };
  796. /**
  797. * Checks if the participant given by participantId is currently included in
  798. * the last N.
  799. * @param {string} participantId the identifier of the participant we would
  800. * like to check.
  801. * @return {boolean} true if the participant with id is in the last N set or
  802. * if there's no last N set, false otherwise.
  803. */
  804. JitsiConference.prototype.isInLastN = function(participantId) {
  805. return this.rtc.isInLastN(participantId);
  806. };
  807. /**
  808. * @return Array<JitsiParticipant> an array of all participants in this
  809. * conference.
  810. */
  811. JitsiConference.prototype.getParticipants = function() {
  812. return Object.keys(this.participants).map(function(key) {
  813. return this.participants[key];
  814. }, this);
  815. };
  816. /**
  817. * Returns the number of participants in the conference, including the local
  818. * participant.
  819. * @param countHidden {boolean} Whether or not to include hidden participants
  820. * in the count. Default: false.
  821. **/
  822. JitsiConference.prototype.getParticipantCount
  823. = function(countHidden = false) {
  824. let participants = this.getParticipants();
  825. if (!countHidden) {
  826. participants = participants.filter(p => !p.isHidden());
  827. }
  828. // Add one for the local participant.
  829. return participants.length + 1;
  830. };
  831. /**
  832. * @returns {JitsiParticipant} the participant in this conference with the
  833. * specified id (or undefined if there isn't one).
  834. * @param id the id of the participant.
  835. */
  836. JitsiConference.prototype.getParticipantById = function(id) {
  837. return this.participants[id];
  838. };
  839. /**
  840. * Kick participant from this conference.
  841. * @param {string} id id of the participant to kick
  842. */
  843. JitsiConference.prototype.kickParticipant = function(id) {
  844. const participant = this.getParticipantById(id);
  845. if (!participant) {
  846. return;
  847. }
  848. this.room.kick(participant.getJid());
  849. };
  850. /**
  851. * Mutes a participant.
  852. * @param {string} id The id of the participant to mute.
  853. */
  854. JitsiConference.prototype.muteParticipant = function(id) {
  855. const participant = this.getParticipantById(id);
  856. if (!participant) {
  857. return;
  858. }
  859. this.room.muteParticipant(participant.getJid(), true);
  860. };
  861. /* eslint-disable max-params */
  862. /**
  863. * Notifies this JitsiConference that a new member has joined its chat room.
  864. *
  865. * FIXME This should NOT be exposed!
  866. *
  867. * @param jid the jid of the participant in the MUC
  868. * @param nick the display name of the participant
  869. * @param role the role of the participant in the MUC
  870. * @param isHidden indicates if this is a hidden participant (system
  871. * participant for example a recorder).
  872. */
  873. JitsiConference.prototype.onMemberJoined = function(jid, nick, role, isHidden) {
  874. const id = Strophe.getResourceFromJid(jid);
  875. if (id === 'focus' || this.myUserId() === id) {
  876. return;
  877. }
  878. const participant = new JitsiParticipant(jid, this, nick, isHidden);
  879. participant._role = role;
  880. this.participants[id] = participant;
  881. this.eventEmitter.emit(
  882. JitsiConferenceEvents.USER_JOINED,
  883. id,
  884. participant);
  885. this.xmpp.caps.getFeatures(jid)
  886. .then(features => {
  887. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  888. this.updateDTMFSupport();
  889. },
  890. error => logger.error(`Failed to discover features of ${jid}`, error));
  891. this._maybeStartOrStopP2P();
  892. };
  893. /* eslint-enable max-params */
  894. JitsiConference.prototype.onMemberLeft = function(jid) {
  895. const id = Strophe.getResourceFromJid(jid);
  896. if (id === 'focus' || this.myUserId() === id) {
  897. return;
  898. }
  899. const participant = this.participants[id];
  900. delete this.participants[id];
  901. const removedTracks = this.rtc.removeRemoteTracks(id);
  902. removedTracks.forEach(
  903. track =>
  904. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track));
  905. // there can be no participant in case the member that left is focus
  906. if (participant) {
  907. this.eventEmitter.emit(
  908. JitsiConferenceEvents.USER_LEFT, id, participant);
  909. }
  910. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  911. };
  912. /**
  913. * Method called on local MUC role change.
  914. * @param {string} role the name of new user's role as defined by XMPP MUC.
  915. */
  916. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  917. // Emit role changed for local JID
  918. this.eventEmitter.emit(
  919. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  920. // Maybe start P2P
  921. this._maybeStartOrStopP2P();
  922. };
  923. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  924. const id = Strophe.getResourceFromJid(jid);
  925. const participant = this.getParticipantById(id);
  926. if (!participant) {
  927. return;
  928. }
  929. participant._role = role;
  930. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  931. };
  932. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  933. const id = Strophe.getResourceFromJid(jid);
  934. const participant = this.getParticipantById(id);
  935. if (!participant) {
  936. return;
  937. }
  938. if (participant._displayName === displayName) {
  939. return;
  940. }
  941. participant._displayName = displayName;
  942. this.eventEmitter.emit(
  943. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  944. id,
  945. displayName);
  946. };
  947. /**
  948. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  949. * the conference.
  950. *
  951. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  952. * JitsiConference
  953. */
  954. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  955. if (track.isP2P && !this.isP2PActive()) {
  956. logger.info(
  957. 'Trying to add remote P2P track, when not in P2P - IGNORED');
  958. return;
  959. } else if (!track.isP2P && this.isP2PActive()) {
  960. logger.info(
  961. 'Trying to add remote JVB track, when in P2P - IGNORED');
  962. return;
  963. }
  964. const id = track.getParticipantId();
  965. const participant = this.getParticipantById(id);
  966. if (!participant) {
  967. logger.error(`No participant found for id: ${id}`);
  968. return;
  969. }
  970. // Add track to JitsiParticipant.
  971. participant._tracks.push(track);
  972. if (this.transcriber) {
  973. this.transcriber.addTrack(track);
  974. }
  975. const emitter = this.eventEmitter;
  976. track.addEventListener(
  977. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  978. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  979. track.addEventListener(
  980. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  981. audioLevel => {
  982. emitter.emit(
  983. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  984. id,
  985. audioLevel);
  986. }
  987. );
  988. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  989. };
  990. /**
  991. * Callback called by the Jingle plugin when 'session-answer' is received.
  992. * @param {JingleSessionPC} session the Jingle session for which an answer was
  993. * received.
  994. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  995. */
  996. // eslint-disable-next-line no-unused-vars
  997. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  998. if (this.p2pJingleSession === session) {
  999. logger.info('P2P setAnswer');
  1000. this.p2pJingleSession.setAnswer(answer);
  1001. }
  1002. };
  1003. /**
  1004. * Callback called by the Jingle plugin when 'transport-info' is received.
  1005. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1006. * received
  1007. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1008. * element
  1009. */
  1010. // eslint-disable-next-line no-unused-vars
  1011. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1012. if (this.p2pJingleSession === session) {
  1013. logger.info('P2P addIceCandidates');
  1014. this.p2pJingleSession.addIceCandidates(transportInfo);
  1015. }
  1016. };
  1017. /**
  1018. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1019. * the conference.
  1020. *
  1021. * @param {JitsiRemoteTrack} removedTrack
  1022. */
  1023. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1024. let consumed = false;
  1025. this.getParticipants().forEach(participant => {
  1026. const tracks = participant.getTracks();
  1027. for (let i = 0; i < tracks.length; i++) {
  1028. if (tracks[i] === removedTrack) {
  1029. // Since the tracks have been compared and are
  1030. // considered equal the result of splice can be ignored.
  1031. participant._tracks.splice(i, 1);
  1032. this.eventEmitter.emit(
  1033. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1034. if (this.transcriber) {
  1035. this.transcriber.removeTrack(removedTrack);
  1036. }
  1037. consumed = true;
  1038. break;
  1039. }
  1040. }
  1041. }, this);
  1042. if (!consumed) {
  1043. if ((this.isP2PActive() && !removedTrack.isP2P)
  1044. || (!this.isP2PActive() && removedTrack.isP2P)) {
  1045. // A remote track can be removed either as a result of
  1046. // 'source-remove' or the P2P logic which removes remote tracks
  1047. // explicitly when switching between JVB and P2P connections.
  1048. // The check above filters out the P2P logic case which should not
  1049. // result in an error (which just goes over all remote tracks).
  1050. return;
  1051. }
  1052. logger.error(
  1053. 'Failed to match remote track on remove'
  1054. + ' with any of the participants',
  1055. removedTrack.getStreamId(),
  1056. removedTrack.getParticipantId());
  1057. }
  1058. };
  1059. /**
  1060. * Handles incoming call event.
  1061. */
  1062. JitsiConference.prototype.onIncomingCall
  1063. = function(jingleSession, jingleOffer, now) {
  1064. // Handle incoming P2P call
  1065. if (jingleSession.isP2P) {
  1066. const role = this.room.getMemberRole(jingleSession.peerjid);
  1067. if (role !== 'moderator') {
  1068. // Reject incoming P2P call
  1069. this._rejectIncomingCallNonModerator(jingleSession);
  1070. } else if (!RTCBrowserType.isP2PSupported()) {
  1071. // Reject incoming P2P call (already in progress)
  1072. this._rejectIncomingCall(
  1073. jingleSession, {
  1074. reasonTag: 'unsupported-applications',
  1075. reasonMsg: 'P2P not supported',
  1076. errorMsg: 'This client does not support P2P connections'
  1077. });
  1078. } else if (this.p2pJingleSession) {
  1079. // Reject incoming P2P call (already in progress)
  1080. this._rejectIncomingCall(
  1081. jingleSession, {
  1082. reasonTag: 'busy',
  1083. reasonMsg: 'P2P already in progress',
  1084. errorMsg: 'Duplicated P2P "session-initiate"'
  1085. });
  1086. } else {
  1087. // Accept incoming P2P call
  1088. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1089. }
  1090. return;
  1091. } else if (!this.room.isFocus(jingleSession.peerjid)) {
  1092. this._rejectIncomingCall(jingleSession);
  1093. return;
  1094. }
  1095. // Accept incoming call
  1096. this.jvbJingleSession = jingleSession;
  1097. this.room.connectionTimes['session.initiate'] = now;
  1098. // Log "session.restart"
  1099. if (this.wasStopped) {
  1100. Statistics.sendEventToAll('session.restart');
  1101. }
  1102. // add info whether call is cross-region
  1103. let crossRegion = null;
  1104. if (window.jitsiRegionInfo) {
  1105. crossRegion = window.jitsiRegionInfo.CrossRegion;
  1106. }
  1107. Statistics.analytics.sendEvent(
  1108. 'session.initiate', {
  1109. value: now - this.room.connectionTimes['muc.joined'],
  1110. label: crossRegion
  1111. });
  1112. try {
  1113. jingleSession.initialize(false /* initiator */, this.room, this.rtc);
  1114. } catch (error) {
  1115. GlobalOnErrorHandler.callErrorHandler(error);
  1116. }
  1117. this.rtc.initializeDataChannels(jingleSession.peerconnection);
  1118. // Add local tracks to the session
  1119. try {
  1120. jingleSession.acceptOffer(
  1121. jingleOffer,
  1122. null /* success */,
  1123. error => {
  1124. GlobalOnErrorHandler.callErrorHandler(error);
  1125. logger.error(
  1126. 'Failed to accept incoming Jingle session', error);
  1127. },
  1128. this.getLocalTracks()
  1129. );
  1130. // Start callstats as soon as peerconnection is initialized,
  1131. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1132. // happen in case if user doesn't have or denied permission to
  1133. // both camera and microphone.
  1134. this.statistics.startCallStats(jingleSession);
  1135. this._startRemoteStats();
  1136. } catch (e) {
  1137. GlobalOnErrorHandler.callErrorHandler(e);
  1138. logger.error(e);
  1139. }
  1140. };
  1141. /**
  1142. * Rejects incoming Jingle call with 'security-error'. Method should be used to
  1143. * reject calls initiated by unauthorised entities.
  1144. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1145. * @private
  1146. */
  1147. JitsiConference.prototype._rejectIncomingCallNonModerator
  1148. = function(jingleSession) {
  1149. this._rejectIncomingCall(
  1150. jingleSession,
  1151. {
  1152. reasonTag: 'security-error',
  1153. reasonMsg: 'Only focus can start new sessions',
  1154. errorMsg: 'Rejecting session-initiate from non-focus and'
  1155. + `non-moderator user: ${jingleSession.peerjid}`
  1156. });
  1157. };
  1158. /**
  1159. * Rejects incoming Jingle call.
  1160. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1161. * @param {object} [options]
  1162. * @param {string} options.reasonTag the name of the reason element as defined
  1163. * by Jingle
  1164. * @param {string} options.reasonMsg the reason description which will
  1165. * be included in Jingle 'session-terminate' message.
  1166. * @param {string} options.errorMsg an error message to be logged on global
  1167. * error handler
  1168. * @private
  1169. */
  1170. JitsiConference.prototype._rejectIncomingCall
  1171. = function(jingleSession, options) {
  1172. if (options && options.errorMsg) {
  1173. GlobalOnErrorHandler.callErrorHandler(new Error(options.errorMsg));
  1174. }
  1175. // Terminate the jingle session with a reason
  1176. jingleSession.terminate(
  1177. options && options.reasonTag,
  1178. options && options.reasonMsg,
  1179. null /* success callback => we don't care */,
  1180. error => {
  1181. logger.warn(
  1182. 'An error occurred while trying to terminate'
  1183. + ' invalid Jingle session', error);
  1184. });
  1185. };
  1186. /**
  1187. * Method called to start remote stats for the current peer connection (if
  1188. * available).
  1189. * @private
  1190. */
  1191. JitsiConference.prototype._startRemoteStats = function() {
  1192. const activePeerConnection = this.getActivePeerConnection();
  1193. if (activePeerConnection) {
  1194. this.statistics.startRemoteStats(activePeerConnection);
  1195. }
  1196. };
  1197. /**
  1198. * Handles the call ended event.
  1199. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1200. * terminated.
  1201. * @param {String} reasonCondition the Jingle reason condition.
  1202. * @param {String|null} reasonText human readable reason text which may provide
  1203. * more details about why the call has been terminated.
  1204. */
  1205. JitsiConference.prototype.onCallEnded
  1206. = function(jingleSession, reasonCondition, reasonText) {
  1207. logger.info(
  1208. `Call ended: ${reasonCondition} - ${reasonText
  1209. } P2P ?${jingleSession.isP2P}`);
  1210. if (jingleSession === this.jvbJingleSession) {
  1211. this.wasStopped = true;
  1212. // Send session.terminate event
  1213. Statistics.sendEventToAll('session.terminate');
  1214. // Stop the stats
  1215. if (this.statistics) {
  1216. this.statistics.stopRemoteStats();
  1217. this.statistics.stopCallStats();
  1218. }
  1219. // Current JVB JingleSession is no longer valid, so set it to null
  1220. this.jvbJingleSession = null;
  1221. // Let the RTC service do any cleanups
  1222. this.rtc.onCallEnded();
  1223. } else if (jingleSession === this.p2pJingleSession) {
  1224. this._stopP2PSession();
  1225. } else {
  1226. logger.error(
  1227. 'Received onCallEnded for invalid session',
  1228. jingleSession.sid,
  1229. jingleSession.peerjid,
  1230. reasonCondition,
  1231. reasonText);
  1232. }
  1233. };
  1234. /**
  1235. * Handles the suspend detected event. Leaves the room and fires suspended.
  1236. * @param {JingleSessionPC} jingleSession
  1237. */
  1238. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  1239. if (!jingleSession.isP2P) {
  1240. this.leave();
  1241. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1242. }
  1243. };
  1244. JitsiConference.prototype.updateDTMFSupport = function() {
  1245. let somebodySupportsDTMF = false;
  1246. const participants = this.getParticipants();
  1247. // check if at least 1 participant supports DTMF
  1248. for (let i = 0; i < participants.length; i += 1) {
  1249. if (participants[i].supportsDTMF()) {
  1250. somebodySupportsDTMF = true;
  1251. break;
  1252. }
  1253. }
  1254. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1255. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1256. this.eventEmitter.emit(
  1257. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1258. somebodySupportsDTMF);
  1259. }
  1260. };
  1261. /**
  1262. * Allows to check if there is at least one user in the conference
  1263. * that supports DTMF.
  1264. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1265. */
  1266. JitsiConference.prototype.isDTMFSupported = function() {
  1267. return this.somebodySupportsDTMF;
  1268. };
  1269. /**
  1270. * Returns the local user's ID
  1271. * @return {string} local user's ID
  1272. */
  1273. JitsiConference.prototype.myUserId = function() {
  1274. return (
  1275. this.room
  1276. && this.room.myroomjid
  1277. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1278. : null);
  1279. };
  1280. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1281. if (!this.dtmfManager) {
  1282. const peerConnection = this.getActivePeerConnection();
  1283. if (!peerConnection) {
  1284. logger.warn('cannot sendTones: no peer connection');
  1285. return;
  1286. }
  1287. const localAudio = this.getLocalAudioTrack();
  1288. if (!localAudio) {
  1289. logger.warn('cannot sendTones: no local audio stream');
  1290. return;
  1291. }
  1292. this.dtmfManager = new JitsiDTMFManager(localAudio, peerConnection);
  1293. }
  1294. this.dtmfManager.sendTones(tones, duration, pause);
  1295. };
  1296. /**
  1297. * Returns true if recording is supported and false if not.
  1298. */
  1299. JitsiConference.prototype.isRecordingSupported = function() {
  1300. if (this.room) {
  1301. return this.room.isRecordingSupported();
  1302. }
  1303. return false;
  1304. };
  1305. /**
  1306. * Returns null if the recording is not supported, "on" if the recording started
  1307. * and "off" if the recording is not started.
  1308. */
  1309. JitsiConference.prototype.getRecordingState = function() {
  1310. return this.room ? this.room.getRecordingState() : undefined;
  1311. };
  1312. /**
  1313. * Returns the url of the recorded video.
  1314. */
  1315. JitsiConference.prototype.getRecordingURL = function() {
  1316. return this.room ? this.room.getRecordingURL() : null;
  1317. };
  1318. /**
  1319. * Starts/stops the recording
  1320. */
  1321. JitsiConference.prototype.toggleRecording = function(options) {
  1322. if (this.room) {
  1323. return this.room.toggleRecording(options, (status, error) => {
  1324. this.eventEmitter.emit(
  1325. JitsiConferenceEvents.RECORDER_STATE_CHANGED, status, error);
  1326. });
  1327. }
  1328. this.eventEmitter.emit(
  1329. JitsiConferenceEvents.RECORDER_STATE_CHANGED, 'error',
  1330. new Error('The conference is not created yet!'));
  1331. };
  1332. /**
  1333. * Returns true if the SIP calls are supported and false otherwise
  1334. */
  1335. JitsiConference.prototype.isSIPCallingSupported = function() {
  1336. if (this.room) {
  1337. return this.room.isSIPCallingSupported();
  1338. }
  1339. return false;
  1340. };
  1341. /**
  1342. * Dials a number.
  1343. * @param number the number
  1344. */
  1345. JitsiConference.prototype.dial = function(number) {
  1346. if (this.room) {
  1347. return this.room.dial(number);
  1348. }
  1349. return new Promise((resolve, reject) => {
  1350. reject(new Error('The conference is not created yet!'));
  1351. });
  1352. };
  1353. /**
  1354. * Hangup an existing call
  1355. */
  1356. JitsiConference.prototype.hangup = function() {
  1357. if (this.room) {
  1358. return this.room.hangup();
  1359. }
  1360. return new Promise((resolve, reject) => {
  1361. reject(new Error('The conference is not created yet!'));
  1362. });
  1363. };
  1364. /**
  1365. * Returns the phone number for joining the conference.
  1366. */
  1367. JitsiConference.prototype.getPhoneNumber = function() {
  1368. if (this.room) {
  1369. return this.room.getPhoneNumber();
  1370. }
  1371. return null;
  1372. };
  1373. /**
  1374. * Returns the pin for joining the conference with phone.
  1375. */
  1376. JitsiConference.prototype.getPhonePin = function() {
  1377. if (this.room) {
  1378. return this.room.getPhonePin();
  1379. }
  1380. return null;
  1381. };
  1382. /**
  1383. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  1384. * which connection is currently active.
  1385. *
  1386. * @return {TraceablePeerConnection|null} null if there isn't any active
  1387. * <tt>TraceablePeerConnection</tt> currently available.
  1388. * @protected
  1389. */
  1390. JitsiConference.prototype.getActivePeerConnection = function() {
  1391. if (this.isP2PActive()) {
  1392. return this.p2pJingleSession.peerconnection;
  1393. }
  1394. return this.jvbJingleSession ? this.jvbJingleSession.peerconnection : null;
  1395. };
  1396. /**
  1397. * Returns the connection state for the current room. Its ice connection state
  1398. * for its session.
  1399. * NOTE that "completed" ICE state which can appear on the P2P connection will
  1400. * be converted to "connected".
  1401. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  1402. * peer connection at this time.
  1403. */
  1404. JitsiConference.prototype.getConnectionState = function() {
  1405. const peerConnection = this.getActivePeerConnection();
  1406. return peerConnection ? peerConnection.getConnectionState() : null;
  1407. };
  1408. /**
  1409. * Make all new participants mute their audio/video on join.
  1410. * @param policy {Object} object with 2 boolean properties for video and audio:
  1411. * @param {boolean} audio if audio should be muted.
  1412. * @param {boolean} video if video should be muted.
  1413. */
  1414. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  1415. if (!this.isModerator()) {
  1416. return;
  1417. }
  1418. this.startMutedPolicy = policy;
  1419. this.room.removeFromPresence('startmuted');
  1420. this.room.addToPresence('startmuted', {
  1421. attributes: {
  1422. audio: policy.audio,
  1423. video: policy.video,
  1424. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  1425. }
  1426. });
  1427. this.room.sendPresence();
  1428. };
  1429. /**
  1430. * Returns current start muted policy
  1431. * @returns {Object} with 2 properties - audio and video.
  1432. */
  1433. JitsiConference.prototype.getStartMutedPolicy = function() {
  1434. return this.startMutedPolicy;
  1435. };
  1436. /**
  1437. * Check if audio is muted on join.
  1438. */
  1439. JitsiConference.prototype.isStartAudioMuted = function() {
  1440. return this.startAudioMuted;
  1441. };
  1442. /**
  1443. * Check if video is muted on join.
  1444. */
  1445. JitsiConference.prototype.isStartVideoMuted = function() {
  1446. return this.startVideoMuted;
  1447. };
  1448. /**
  1449. * Get object with internal logs.
  1450. */
  1451. JitsiConference.prototype.getLogs = function() {
  1452. const data = this.xmpp.getJingleLog();
  1453. const metadata = {};
  1454. metadata.time = new Date();
  1455. metadata.url = window.location.href;
  1456. metadata.ua = navigator.userAgent;
  1457. const log = this.xmpp.getXmppLog();
  1458. if (log) {
  1459. metadata.xmpp = log;
  1460. }
  1461. data.metadata = metadata;
  1462. return data;
  1463. };
  1464. /**
  1465. * Returns measured connectionTimes.
  1466. */
  1467. JitsiConference.prototype.getConnectionTimes = function() {
  1468. return this.room.connectionTimes;
  1469. };
  1470. /**
  1471. * Sets a property for the local participant.
  1472. */
  1473. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  1474. this.sendCommand(`jitsi_participant_${name}`, { value });
  1475. };
  1476. /**
  1477. * Sends the given feedback through CallStats if enabled.
  1478. *
  1479. * @param overallFeedback an integer between 1 and 5 indicating the
  1480. * user feedback
  1481. * @param detailedFeedback detailed feedback from the user. Not yet used
  1482. */
  1483. JitsiConference.prototype.sendFeedback
  1484. = function(overallFeedback, detailedFeedback) {
  1485. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  1486. };
  1487. /**
  1488. * Returns true if the callstats integration is enabled, otherwise returns
  1489. * false.
  1490. *
  1491. * @returns true if the callstats integration is enabled, otherwise returns
  1492. * false.
  1493. */
  1494. JitsiConference.prototype.isCallstatsEnabled = function() {
  1495. return this.statistics.isCallstatsEnabled();
  1496. };
  1497. /**
  1498. * Handles track attached to container (Calls associateStreamWithVideoTag method
  1499. * from statistics module)
  1500. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  1501. * @param container the container
  1502. */
  1503. JitsiConference.prototype._onTrackAttach = function(track, container) {
  1504. const isLocal = track.isLocal();
  1505. let ssrc = null;
  1506. if (isLocal) {
  1507. // FIXME currently we do CallStats only for JVB, but the same logic will
  1508. // need to happen for the P2P as well once the support is added.
  1509. // Local tracks have SSRC stored on per peer connection basis
  1510. const peerConnection
  1511. = this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  1512. if (peerConnection) {
  1513. ssrc = peerConnection.getLocalSSRC(track);
  1514. }
  1515. } else {
  1516. ssrc = track.getSSRC();
  1517. }
  1518. if (!container.id || !ssrc) {
  1519. return;
  1520. }
  1521. this.statistics.associateStreamWithVideoTag(
  1522. ssrc, isLocal, track.getUsageLabel(), container.id);
  1523. };
  1524. /**
  1525. * Logs an "application log" message.
  1526. * @param message {string} The message to log. Note that while this can be a
  1527. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  1528. * log valid JSON strings, with an "id" field used for distinguishing between
  1529. * message types. E.g.: {id: "recorder_status", status: "off"}
  1530. */
  1531. JitsiConference.prototype.sendApplicationLog = function(message) {
  1532. Statistics.sendLog(message);
  1533. };
  1534. /**
  1535. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1536. * focus.
  1537. * @param mucJid the full MUC address of the user to be checked.
  1538. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  1539. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  1540. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  1541. */
  1542. JitsiConference.prototype._isFocus = function(mucJid) {
  1543. return this.room ? this.room.isFocus(mucJid) : null;
  1544. };
  1545. /**
  1546. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  1547. */
  1548. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  1549. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  1550. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  1551. };
  1552. /**
  1553. * Sends a message via the data channel.
  1554. * @param to {string} the id of the endpoint that should receive the message.
  1555. * If "" the message will be sent to all participants.
  1556. * @param payload {object} the payload of the message.
  1557. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1558. */
  1559. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  1560. this.rtc.sendDataChannelMessage(to, payload);
  1561. };
  1562. /**
  1563. * Sends a broadcast message via the data channel.
  1564. * @param payload {object} the payload of the message.
  1565. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1566. */
  1567. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  1568. this.sendEndpointMessage('', payload);
  1569. };
  1570. JitsiConference.prototype.isConnectionInterrupted = function() {
  1571. return this.isP2PActive()
  1572. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  1573. };
  1574. /**
  1575. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  1576. * @param {JingleSessionPC} session
  1577. * @private
  1578. */
  1579. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  1580. if (session.isP2P) {
  1581. this.isP2PConnectionInterrupted = true;
  1582. } else {
  1583. this.isJvbConnectionInterrupted = true;
  1584. }
  1585. if (session.isP2P === this.isP2PActive()) {
  1586. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  1587. }
  1588. };
  1589. /**
  1590. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  1591. * @param {JingleSessionPC} session
  1592. * @private
  1593. */
  1594. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  1595. // We do nothing for the JVB connection, because it's up to the Jicofo to
  1596. // eventually come up with the new offer (at least for the time being).
  1597. if (session.isP2P) {
  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. };
  1705. /**
  1706. * Clears the deferred start P2P task if it has been scheduled.
  1707. * @private
  1708. */
  1709. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  1710. if (this.deferredStartP2PTask) {
  1711. logger.info('Cleared deferred start P2P task');
  1712. clearTimeout(this.deferredStartP2PTask);
  1713. this.deferredStartP2PTask = null;
  1714. }
  1715. };
  1716. /**
  1717. * Removes from the conference remote tracks associated with the JVB
  1718. * connection.
  1719. * @private
  1720. */
  1721. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  1722. this._removeRemoteTracks(
  1723. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  1724. };
  1725. /**
  1726. * Removes from the conference remote tracks associated with the P2P
  1727. * connection.
  1728. * @private
  1729. */
  1730. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  1731. this._removeRemoteTracks(
  1732. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  1733. };
  1734. /**
  1735. * Generates fake "remote track removed" events for given Jingle session.
  1736. * @param {string} sessionNickname the session's nickname which will appear in
  1737. * log messages.
  1738. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  1739. * @private
  1740. */
  1741. JitsiConference.prototype._removeRemoteTracks
  1742. = function(sessionNickname, remoteTracks) {
  1743. for (const track of remoteTracks) {
  1744. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  1745. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, track);
  1746. }
  1747. };
  1748. /**
  1749. * Resumes media transfer over the JVB connection.
  1750. * @private
  1751. */
  1752. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  1753. logger.info('Resuming media transfer over the JVB connection...');
  1754. this.jvbJingleSession.setMediaTransferActive(true).then(
  1755. () => {
  1756. logger.info('Resumed media transfer over the JVB connection!');
  1757. },
  1758. error => {
  1759. logger.error(
  1760. 'Failed to resume media transfer over the JVB connection:',
  1761. error);
  1762. });
  1763. };
  1764. /**
  1765. * Sets new P2P status and updates some events/states hijacked from
  1766. * the <tt>JitsiConference</tt>.
  1767. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  1768. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  1769. * @private
  1770. */
  1771. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  1772. if (this.p2p === newStatus) {
  1773. logger.error(`Called _setP2PStatus with the same status: ${newStatus}`);
  1774. return;
  1775. }
  1776. this.p2p = newStatus;
  1777. if (newStatus) {
  1778. logger.info('Peer to peer connection established!');
  1779. } else {
  1780. logger.info('Peer to peer connection closed!');
  1781. }
  1782. // Clear dtmfManager, so that it can be recreated with new connection
  1783. this.dtmfManager = null;
  1784. // Update P2P status
  1785. this.eventEmitter.emit(
  1786. JitsiConferenceEvents.P2P_STATUS,
  1787. this,
  1788. this.p2p);
  1789. // Refresh connection interrupted/restored
  1790. this.eventEmitter.emit(
  1791. this.isConnectionInterrupted()
  1792. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  1793. : JitsiConferenceEvents.CONNECTION_RESTORED);
  1794. };
  1795. /**
  1796. * Starts new P2P session.
  1797. * @param {string} peerJid the JID of the remote participant
  1798. * @private
  1799. */
  1800. JitsiConference.prototype._startP2PSession = function(peerJid) {
  1801. this._maybeClearDeferredStartP2P();
  1802. if (this.p2pJingleSession) {
  1803. logger.error('P2P session already started!');
  1804. return;
  1805. }
  1806. this.isP2PConnectionInterrupted = false;
  1807. this.p2pJingleSession
  1808. = this.xmpp.connection.jingle.newP2PJingleSession(
  1809. this.room.myroomjid,
  1810. peerJid);
  1811. this.p2pJingleSession.setSSRCOwnerJid(this.room.myroomjid);
  1812. logger.info('Created new P2P JingleSession', this.room.myroomjid, peerJid);
  1813. this.p2pJingleSession.initialize(true /* initiator */, this.room, this.rtc);
  1814. // NOTE one may consider to start P2P with the local tracks detached,
  1815. // but no data will be sent until ICE succeeds anyway. And we switch
  1816. // immediately once the P2P ICE connects.
  1817. const localTracks = this.getLocalTracks();
  1818. this.p2pJingleSession.invite(localTracks);
  1819. };
  1820. /**
  1821. * Suspends media transfer over the JVB connection.
  1822. * @private
  1823. */
  1824. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  1825. logger.info('Suspending media transfer over the JVB connection...');
  1826. this.jvbJingleSession.setMediaTransferActive(false).then(
  1827. () => {
  1828. logger.info('Suspended media transfer over the JVB connection !');
  1829. },
  1830. error => {
  1831. logger.error(
  1832. 'Failed to suspend media transfer over the JVB connection:',
  1833. error);
  1834. });
  1835. };
  1836. /**
  1837. * Method when called will decide whether it's the time to start or stop
  1838. * the P2P session.
  1839. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  1840. * originates from the user left event.
  1841. * @private
  1842. */
  1843. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  1844. if (!this.options.config.enableP2P || !RTCBrowserType.isP2PSupported()) {
  1845. logger.info('Auto P2P disabled');
  1846. return;
  1847. }
  1848. const peers = this.getParticipants();
  1849. const peerCount = peers.length;
  1850. const isModerator = this.isModerator();
  1851. // FIXME 1 peer and it must *support* P2P switching
  1852. const shouldBeInP2P = peerCount === 1;
  1853. logger.debug(
  1854. `P2P? isModerator: ${isModerator
  1855. }, peerCount: ${peerCount} => ${shouldBeInP2P}`);
  1856. // Clear deferred "start P2P" task
  1857. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  1858. this._maybeClearDeferredStartP2P();
  1859. }
  1860. // Start peer to peer session
  1861. if (isModerator && !this.p2pJingleSession && shouldBeInP2P) {
  1862. const peer = peerCount && peers[0];
  1863. // Everyone is a moderator ?
  1864. if (isModerator && peer.getRole() === 'moderator') {
  1865. const myId = this.myUserId();
  1866. const peersId = peer.getId();
  1867. if (myId > peersId) {
  1868. logger.debug(
  1869. 'Everyone\'s a moderator - '
  1870. + 'the other peer should start P2P', myId, peersId);
  1871. return;
  1872. } else if (myId === peersId) {
  1873. logger.error('The same IDs ? ', myId, peersId);
  1874. return;
  1875. }
  1876. }
  1877. const jid = peer.getJid();
  1878. if (userLeftEvent) {
  1879. if (this.deferredStartP2PTask) {
  1880. logger.error('Deferred start P2P task\'s been set already!');
  1881. return;
  1882. }
  1883. logger.info(
  1884. `Will start P2P with: ${jid
  1885. } after ${this.backToP2PDelay} seconds...`);
  1886. this.deferredStartP2PTask = setTimeout(
  1887. this._startP2PSession.bind(this, jid),
  1888. this.backToP2PDelay * 1000);
  1889. } else {
  1890. logger.info(`Will start P2P with: ${jid}`);
  1891. this._startP2PSession(jid);
  1892. }
  1893. } else if (isModerator && this.p2pJingleSession && !shouldBeInP2P) {
  1894. logger.info(`Will stop P2P with: ${this.p2pJingleSession.peerjid}`);
  1895. this._stopP2PSession();
  1896. }
  1897. };
  1898. /**
  1899. * Stops the current P2P session.
  1900. * @param {string} [reason="success"] one of the Jingle "reason" element
  1901. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  1902. * @param {string} [reasonDescription="Turing off P2P session"] text
  1903. * description that will be included in the session terminate message
  1904. * @private
  1905. */
  1906. JitsiConference.prototype._stopP2PSession
  1907. = function(reason, reasonDescription) {
  1908. if (!this.p2pJingleSession) {
  1909. logger.error('No P2P session to be stopped!');
  1910. return;
  1911. }
  1912. const wasP2PEstablished = this.isP2PActive();
  1913. // Swap remote tracks, but only if the P2P has been fully established
  1914. if (wasP2PEstablished) {
  1915. this._resumeMediaTransferForJvbConnection();
  1916. // Remove remote P2P tracks
  1917. this._removeRemoteP2PTracks();
  1918. }
  1919. // Stop P2P stats
  1920. logger.info('Stopping remote stats with P2P connection');
  1921. this.statistics.stopRemoteStats();
  1922. if (JingleSessionState.ENDED !== this.p2pJingleSession.state) {
  1923. this.p2pJingleSession.terminate(
  1924. reason ? reason : 'success',
  1925. reasonDescription
  1926. ? reasonDescription : 'Turing off P2P session',
  1927. () => {
  1928. logger.info('P2P session terminate RESULT');
  1929. },
  1930. error => {
  1931. logger.warn(
  1932. 'An error occurred while trying to terminate'
  1933. + ' P2P Jingle session', error);
  1934. });
  1935. }
  1936. this.p2pJingleSession = null;
  1937. // Update P2P status and other affected events/states
  1938. this._setP2PStatus(false);
  1939. if (wasP2PEstablished) {
  1940. // Add back remote JVB tracks
  1941. if (this.jvbJingleSession) {
  1942. this._addRemoteJVBTracks();
  1943. } else {
  1944. logger.info('Not adding remote JVB tracks - no session yet');
  1945. }
  1946. }
  1947. // Start remote stats
  1948. logger.info('Starting remote stats with JVB connection');
  1949. if (this.jvbJingleSession) {
  1950. this._startRemoteStats();
  1951. }
  1952. };
  1953. /**
  1954. * Checks whether or not the conference is currently in the peer to peer mode.
  1955. * Being in peer to peer mode means that the direct connection has been
  1956. * established and the P2P connection is being used for media transmission.
  1957. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  1958. */
  1959. JitsiConference.prototype.isP2PActive = function() {
  1960. return this.p2p;
  1961. };
  1962. /**
  1963. * Returns the current ICE state of the P2P connection.
  1964. * NOTE: method is used by the jitsi-meet-torture tests.
  1965. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  1966. * no P2P connection.
  1967. */
  1968. JitsiConference.prototype.getP2PConnectionState = function() {
  1969. if (this.isP2PActive()) {
  1970. return this.p2pJingleSession.peerconnection.getConnectionState();
  1971. }
  1972. return null;
  1973. };
  1974. /**
  1975. * Manually starts new P2P session (should be used only in the tests).
  1976. */
  1977. JitsiConference.prototype.startP2PSession = function() {
  1978. const peers = this.getParticipants();
  1979. // Start peer to peer session
  1980. if (peers.length === 1) {
  1981. const peerJid = peers[0].getJid();
  1982. this._startP2PSession(peerJid);
  1983. } else {
  1984. throw new Error(
  1985. 'There must be exactly 1 participant to start the P2P session !');
  1986. }
  1987. };
  1988. /**
  1989. * Manually stops the current P2P session (should be used only in the tests)
  1990. */
  1991. JitsiConference.prototype.stopP2PSession = function() {
  1992. this._stopP2PSession();
  1993. };
  1994. /**
  1995. * Get a summary of how long current participants have been the dominant speaker
  1996. * @returns {object}
  1997. */
  1998. JitsiConference.prototype.getSpeakerStats = function() {
  1999. return this.speakerStatsCollector.getStats();
  2000. };
  2001. /**
  2002. * Get video SIP GW handler, if missing will create one.
  2003. *
  2004. * @returns {VideoSIPGW} video SIP GW handler.
  2005. */
  2006. JitsiConference.prototype._getVideoSIPGWHandle = function() {
  2007. if (!this.videoSIPGWHandler) {
  2008. this.videoSIPGWHandler = new VideoSIPGW(this.room);
  2009. logger.info('Created VideoSIPGW');
  2010. }
  2011. return this.videoSIPGWHandler;
  2012. };
  2013. /**
  2014. * Checks whether video SIP GW service is available.
  2015. *
  2016. * @returns {boolean} whether video SIP GW service is available.
  2017. */
  2018. JitsiConference.prototype.isVideoSIPGWAvailable = function() {
  2019. return this._getVideoSIPGWHandle().isVideoSIPGWAvailable();
  2020. };
  2021. /**
  2022. * Creates a video SIP GW session and returns it if service is enabled. Before
  2023. * creating a session one need to check whether video SIP GW service is
  2024. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2025. * if there are available nodes to serve this request, after creating the
  2026. * session those nodes can be taken and the request about using the
  2027. * created session can fail.
  2028. *
  2029. * @param {string} sipAddress - The sip address to be used.
  2030. * @param {string} displayName - The display name to be used for this session.
  2031. * @returns {JitsiVideoSIPGWSession|null} Returns null if conference is not
  2032. * initialised and there is no room.
  2033. */
  2034. JitsiConference.prototype.createVideoSIPGWSession
  2035. = function(sipAddress, displayName) {
  2036. if (!this.room) {
  2037. return null;
  2038. }
  2039. return this._getVideoSIPGWHandle()
  2040. .createVideoSIPGWSession(sipAddress, displayName);
  2041. };
  2042. module.exports = JitsiConference;