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

JitsiConference.js 85KB

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