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

JitsiConference.js 86KB

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