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

JitsiConference.js 72KB

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