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 74KB

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