Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

JitsiConference.js 86KB

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