You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiConference.js 81KB

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