您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 81KB

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