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

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