Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JitsiConference.js 86KB

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