您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 86KB

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