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

JitsiConference.js 82KB

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