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

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