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

JitsiConference.js 85KB

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