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

JitsiConference.js 86KB

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