modified lib-jitsi-meet dev repo
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 73KB

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