modified lib-jitsi-meet dev repo
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 78KB

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