選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JitsiConference.js 73KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360
  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 ParticipantConnectionStatusHandler
  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 ParticipantConnectionStatusHandler(
  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. // ensure that we're sharing proper "is muted" state
  644. if (newTrack.isAudioTrack()) {
  645. this.room.setAudioMute(newTrack.isMuted());
  646. } else {
  647. this.room.setVideoMute(newTrack.isMuted());
  648. }
  649. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  650. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  651. newTrack.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  652. newTrack.muteHandler);
  653. newTrack.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  654. newTrack.audioLevelHandler);
  655. newTrack._setConference(this);
  656. // send event for starting screen sharing
  657. // FIXME: we assume we have only one screen sharing track
  658. // if we change this we need to fix this check
  659. if (newTrack.isVideoTrack() && newTrack.videoType === VideoType.DESKTOP) {
  660. this.statistics.sendScreenSharingEvent(true);
  661. }
  662. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  663. };
  664. /**
  665. * Method called by the {@link JitsiLocalTrack} (a video one) in order to add
  666. * back the underlying WebRTC MediaStream to the PeerConnection (which has
  667. * removed on video mute).
  668. * @param {JitsiLocalTrack} track the local track that will be added as part of
  669. * the unmute operation.
  670. * @return {Promise} resolved when the process is done or rejected with a string
  671. * which describes the error.
  672. */
  673. JitsiConference.prototype._addLocalTrackAsUnmute = function(track) {
  674. const addAsUnmutePromises = [];
  675. if (this.jvbJingleSession) {
  676. addAsUnmutePromises.push(this.jvbJingleSession.addTrackAsUnmute(track));
  677. } else {
  678. logger.info(
  679. 'Add local MediaStream as unmute -'
  680. + ' no JVB Jingle session started yet');
  681. }
  682. if (this.p2pJingleSession) {
  683. addAsUnmutePromises.push(this.p2pJingleSession.addTrackAsUnmute(track));
  684. } else {
  685. logger.info(
  686. 'Add local MediaStream as unmute -'
  687. + ' no P2P Jingle session started yet');
  688. }
  689. return Promise.all(addAsUnmutePromises);
  690. };
  691. /**
  692. * Method called by the {@link JitsiLocalTrack} (a video one) in order to remove
  693. * the underlying WebRTC MediaStream from the PeerConnection. The purpose of
  694. * that is to stop sending any data and turn off the HW camera device.
  695. * @param {JitsiLocalTrack} track the local track that will be removed.
  696. * @return {Promise}
  697. */
  698. JitsiConference.prototype._removeLocalTrackAsMute = function(track) {
  699. const removeAsMutePromises = [];
  700. if (this.jvbJingleSession) {
  701. removeAsMutePromises.push(
  702. this.jvbJingleSession.removeTrackAsMute(track));
  703. } else {
  704. logger.info(
  705. 'Remove local MediaStream - no JVB JingleSession started yet');
  706. }
  707. if (this.p2pJingleSession) {
  708. removeAsMutePromises.push(
  709. this.p2pJingleSession.removeTrackAsMute(track));
  710. } else {
  711. logger.info(
  712. 'Remove local MediaStream - no P2P JingleSession started yet');
  713. }
  714. return Promise.all(removeAsMutePromises);
  715. };
  716. /**
  717. * Get role of the local user.
  718. * @returns {string} user role: 'moderator' or 'none'
  719. */
  720. JitsiConference.prototype.getRole = function() {
  721. return this.room.role;
  722. };
  723. /**
  724. * Check if local user is moderator.
  725. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  726. * we're no longer in the conference room then <tt>null</tt> is returned.
  727. */
  728. JitsiConference.prototype.isModerator = function() {
  729. return this.room ? this.room.isModerator() : null;
  730. };
  731. /**
  732. * Set password for the room.
  733. * @param {string} password new password for the room.
  734. * @returns {Promise}
  735. */
  736. JitsiConference.prototype.lock = function(password) {
  737. if (!this.isModerator()) {
  738. return Promise.reject();
  739. }
  740. return new Promise((resolve, reject) => {
  741. this.room.lockRoom(
  742. password || '',
  743. () => resolve(),
  744. err => reject(err),
  745. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  746. });
  747. };
  748. /**
  749. * Remove password from the room.
  750. * @returns {Promise}
  751. */
  752. JitsiConference.prototype.unlock = function() {
  753. return this.lock();
  754. };
  755. /**
  756. * Elects the participant with the given id to be the selected participant in
  757. * order to receive higher video quality (if simulcast is enabled).
  758. * Or cache it if channel is not created and send it once channel is available.
  759. * @param participantId the identifier of the participant
  760. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  761. */
  762. JitsiConference.prototype.selectParticipant = function(participantId) {
  763. this.rtc.selectEndpoint(participantId);
  764. };
  765. /**
  766. * Elects the participant with the given id to be the pinned participant in
  767. * order to always receive video for this participant (even when last n is
  768. * enabled).
  769. * @param participantId the identifier of the participant
  770. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  771. */
  772. JitsiConference.prototype.pinParticipant = function(participantId) {
  773. this.rtc.pinEndpoint(participantId);
  774. };
  775. /**
  776. * Selects a new value for "lastN". The requested amount of videos are going
  777. * to be delivered after the value is in effect. Set to -1 for unlimited or
  778. * all available videos.
  779. * @param lastN the new number of videos the user would like to receive.
  780. * @throws Error or RangeError if the given value is not a number or is smaller
  781. * than -1.
  782. */
  783. JitsiConference.prototype.setLastN = function(lastN) {
  784. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  785. throw new Error(`Invalid value for lastN: ${lastN}`);
  786. }
  787. const n = Number(lastN);
  788. if (n < -1) {
  789. throw new RangeError('lastN cannot be smaller than -1');
  790. }
  791. this.rtc.setLastN(n);
  792. };
  793. /**
  794. * Checks if the participant given by participantId is currently included in
  795. * the last N.
  796. * @param {string} participantId the identifier of the participant we would
  797. * like to check.
  798. * @return {boolean} true if the participant with id is in the last N set or
  799. * if there's no last N set, false otherwise.
  800. */
  801. JitsiConference.prototype.isInLastN = function(participantId) {
  802. return this.rtc.isInLastN(participantId);
  803. };
  804. /**
  805. * @return Array<JitsiParticipant> an array of all participants in this
  806. * conference.
  807. */
  808. JitsiConference.prototype.getParticipants = function() {
  809. return Object.keys(this.participants).map(function(key) {
  810. return this.participants[key];
  811. }, this);
  812. };
  813. /**
  814. * Returns the number of participants in the conference, including the local
  815. * participant.
  816. * @param countHidden {boolean} Whether or not to include hidden participants
  817. * in the count. Default: false.
  818. **/
  819. JitsiConference.prototype.getParticipantCount
  820. = function(countHidden = false) {
  821. let participants = this.getParticipants();
  822. if (!countHidden) {
  823. participants = participants.filter(p => !p.isHidden());
  824. }
  825. // Add one for the local participant.
  826. return participants.length + 1;
  827. };
  828. /**
  829. * @returns {JitsiParticipant} the participant in this conference with the
  830. * specified id (or undefined if there isn't one).
  831. * @param id the id of the participant.
  832. */
  833. JitsiConference.prototype.getParticipantById = function(id) {
  834. return this.participants[id];
  835. };
  836. /**
  837. * Kick participant from this conference.
  838. * @param {string} id id of the participant to kick
  839. */
  840. JitsiConference.prototype.kickParticipant = function(id) {
  841. const participant = this.getParticipantById(id);
  842. if (!participant) {
  843. return;
  844. }
  845. this.room.kick(participant.getJid());
  846. };
  847. /**
  848. * Mutes a participant.
  849. * @param {string} id The id of the participant to mute.
  850. */
  851. JitsiConference.prototype.muteParticipant = function(id) {
  852. const participant = this.getParticipantById(id);
  853. if (!participant) {
  854. return;
  855. }
  856. this.room.muteParticipant(participant.getJid(), true);
  857. };
  858. /* eslint-disable max-params */
  859. /**
  860. * Notifies this JitsiConference that a new member has joined its chat room.
  861. *
  862. * FIXME This should NOT be exposed!
  863. *
  864. * @param jid the jid of the participant in the MUC
  865. * @param nick the display name of the participant
  866. * @param role the role of the participant in the MUC
  867. * @param isHidden indicates if this is a hidden participant (system
  868. * participant for example a recorder).
  869. */
  870. JitsiConference.prototype.onMemberJoined = function(jid, nick, role, isHidden) {
  871. const id = Strophe.getResourceFromJid(jid);
  872. if (id === 'focus' || this.myUserId() === id) {
  873. return;
  874. }
  875. const participant = new JitsiParticipant(jid, this, nick, isHidden);
  876. participant._role = role;
  877. this.participants[id] = participant;
  878. this.eventEmitter.emit(
  879. JitsiConferenceEvents.USER_JOINED,
  880. id,
  881. participant);
  882. this.xmpp.caps.getFeatures(jid)
  883. .then(features => {
  884. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  885. this.updateDTMFSupport();
  886. },
  887. error => logger.error(`Failed to discover features of ${jid}`, error));
  888. this._maybeStartOrStopP2P();
  889. };
  890. /* eslint-enable max-params */
  891. JitsiConference.prototype.onMemberLeft = function(jid) {
  892. const id = Strophe.getResourceFromJid(jid);
  893. if (id === 'focus' || this.myUserId() === id) {
  894. return;
  895. }
  896. const participant = this.participants[id];
  897. delete this.participants[id];
  898. const removedTracks = this.rtc.removeRemoteTracks(id);
  899. removedTracks.forEach(
  900. track =>
  901. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track));
  902. // there can be no participant in case the member that left is focus
  903. if (participant) {
  904. this.eventEmitter.emit(
  905. JitsiConferenceEvents.USER_LEFT, id, participant);
  906. }
  907. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  908. };
  909. /**
  910. * Method called on local MUC role change.
  911. * @param {string} role the name of new user's role as defined by XMPP MUC.
  912. */
  913. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  914. // Emit role changed for local JID
  915. this.eventEmitter.emit(
  916. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  917. // Maybe start P2P
  918. this._maybeStartOrStopP2P();
  919. };
  920. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  921. const id = Strophe.getResourceFromJid(jid);
  922. const participant = this.getParticipantById(id);
  923. if (!participant) {
  924. return;
  925. }
  926. participant._role = role;
  927. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  928. };
  929. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  930. const id = Strophe.getResourceFromJid(jid);
  931. const participant = this.getParticipantById(id);
  932. if (!participant) {
  933. return;
  934. }
  935. if (participant._displayName === displayName) {
  936. return;
  937. }
  938. participant._displayName = displayName;
  939. this.eventEmitter.emit(
  940. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  941. id,
  942. displayName);
  943. };
  944. /**
  945. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  946. * the conference.
  947. *
  948. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  949. * JitsiConference
  950. */
  951. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  952. if (track.isP2P && !this.isP2PActive()) {
  953. logger.info(
  954. 'Trying to add remote P2P track, when not in P2P - IGNORED');
  955. return;
  956. } else if (!track.isP2P && this.isP2PActive()) {
  957. logger.info(
  958. 'Trying to add remote JVB track, when in P2P - IGNORED');
  959. return;
  960. }
  961. const id = track.getParticipantId();
  962. const participant = this.getParticipantById(id);
  963. if (!participant) {
  964. logger.error(`No participant found for id: ${id}`);
  965. return;
  966. }
  967. // Add track to JitsiParticipant.
  968. participant._tracks.push(track);
  969. if (this.transcriber) {
  970. this.transcriber.addTrack(track);
  971. }
  972. const emitter = this.eventEmitter;
  973. track.addEventListener(
  974. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  975. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  976. track.addEventListener(
  977. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  978. audioLevel => {
  979. emitter.emit(
  980. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  981. id,
  982. audioLevel);
  983. }
  984. );
  985. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  986. };
  987. /**
  988. * Callback called by the Jingle plugin when 'session-answer' is received.
  989. * @param {JingleSessionPC} session the Jingle session for which an answer was
  990. * received.
  991. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  992. */
  993. // eslint-disable-next-line no-unused-vars
  994. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  995. if (this.p2pJingleSession === session) {
  996. logger.info('P2P setAnswer');
  997. this.p2pJingleSession.setAnswer(answer);
  998. }
  999. };
  1000. /**
  1001. * Callback called by the Jingle plugin when 'transport-info' is received.
  1002. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1003. * received
  1004. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1005. * element
  1006. */
  1007. // eslint-disable-next-line no-unused-vars
  1008. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1009. if (this.p2pJingleSession === session) {
  1010. logger.info('P2P addIceCandidates');
  1011. this.p2pJingleSession.addIceCandidates(transportInfo);
  1012. }
  1013. };
  1014. /**
  1015. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1016. * the conference.
  1017. *
  1018. * @param {JitsiRemoteTrack} removedTrack
  1019. */
  1020. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1021. let consumed = false;
  1022. this.getParticipants().forEach(participant => {
  1023. const tracks = participant.getTracks();
  1024. for (let i = 0; i < tracks.length; i++) {
  1025. if (tracks[i] === removedTrack) {
  1026. // Since the tracks have been compared and are
  1027. // considered equal the result of splice can be ignored.
  1028. participant._tracks.splice(i, 1);
  1029. this.eventEmitter.emit(
  1030. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1031. if (this.transcriber) {
  1032. this.transcriber.removeTrack(removedTrack);
  1033. }
  1034. consumed = true;
  1035. break;
  1036. }
  1037. }
  1038. }, this);
  1039. if (!consumed) {
  1040. if ((this.isP2PActive() && !removedTrack.isP2P)
  1041. || (!this.isP2PActive() && removedTrack.isP2P)) {
  1042. // A remote track can be removed either as a result of
  1043. // 'source-remove' or the P2P logic which removes remote tracks
  1044. // explicitly when switching between JVB and P2P connections.
  1045. // The check above filters out the P2P logic case which should not
  1046. // result in an error (which just goes over all remote tracks).
  1047. return;
  1048. }
  1049. logger.error(
  1050. 'Failed to match remote track on remove'
  1051. + ' with any of the participants',
  1052. removedTrack.getStreamId(),
  1053. removedTrack.getParticipantId());
  1054. }
  1055. };
  1056. /**
  1057. * Handles incoming call event.
  1058. */
  1059. JitsiConference.prototype.onIncomingCall
  1060. = function(jingleSession, jingleOffer, now) {
  1061. // Handle incoming P2P call
  1062. if (jingleSession.isP2P) {
  1063. const role = this.room.getMemberRole(jingleSession.peerjid);
  1064. if (role !== 'moderator') {
  1065. // Reject incoming P2P call
  1066. this._rejectIncomingCallNonModerator(jingleSession);
  1067. } else if (!RTCBrowserType.isP2PSupported()) {
  1068. // Reject incoming P2P call (already in progress)
  1069. this._rejectIncomingCall(
  1070. jingleSession, {
  1071. reasonTag: 'unsupported-applications',
  1072. reasonMsg: 'P2P not supported',
  1073. errorMsg: 'This client does not support P2P connections'
  1074. });
  1075. } else if (this.p2pJingleSession) {
  1076. // Reject incoming P2P call (already in progress)
  1077. this._rejectIncomingCall(
  1078. jingleSession, {
  1079. reasonTag: 'busy',
  1080. reasonMsg: 'P2P already in progress',
  1081. errorMsg: 'Duplicated P2P "session-initiate"'
  1082. });
  1083. } else {
  1084. // Accept incoming P2P call
  1085. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1086. }
  1087. return;
  1088. } else if (!this.room.isFocus(jingleSession.peerjid)) {
  1089. this._rejectIncomingCall(jingleSession);
  1090. return;
  1091. }
  1092. // Accept incoming call
  1093. this.jvbJingleSession = jingleSession;
  1094. this.room.connectionTimes['session.initiate'] = now;
  1095. // Log "session.restart"
  1096. if (this.wasStopped) {
  1097. Statistics.sendEventToAll('session.restart');
  1098. }
  1099. // add info whether call is cross-region
  1100. let crossRegion = null;
  1101. if (window.jitsiRegionInfo) {
  1102. crossRegion = window.jitsiRegionInfo.CrossRegion;
  1103. }
  1104. Statistics.analytics.sendEvent(
  1105. 'session.initiate', {
  1106. value: now - this.room.connectionTimes['muc.joined'],
  1107. label: crossRegion
  1108. });
  1109. try {
  1110. jingleSession.initialize(false /* initiator */, this.room, this.rtc);
  1111. } catch (error) {
  1112. GlobalOnErrorHandler.callErrorHandler(error);
  1113. }
  1114. this.rtc.initializeDataChannels(jingleSession.peerconnection);
  1115. // Add local tracks to the session
  1116. try {
  1117. jingleSession.acceptOffer(
  1118. jingleOffer,
  1119. null /* success */,
  1120. error => {
  1121. GlobalOnErrorHandler.callErrorHandler(error);
  1122. logger.error(
  1123. 'Failed to accept incoming Jingle session', error);
  1124. },
  1125. this.getLocalTracks()
  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. } catch (e) {
  1134. GlobalOnErrorHandler.callErrorHandler(e);
  1135. logger.error(e);
  1136. }
  1137. };
  1138. /**
  1139. * Rejects incoming Jingle call with 'security-error'. Method should be used to
  1140. * reject calls initiated by unauthorised entities.
  1141. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1142. * @private
  1143. */
  1144. JitsiConference.prototype._rejectIncomingCallNonModerator
  1145. = function(jingleSession) {
  1146. this._rejectIncomingCall(
  1147. jingleSession,
  1148. {
  1149. reasonTag: 'security-error',
  1150. reasonMsg: 'Only focus can start new sessions',
  1151. errorMsg: 'Rejecting session-initiate from non-focus and'
  1152. + `non-moderator user: ${jingleSession.peerjid}`
  1153. });
  1154. };
  1155. /**
  1156. * Rejects incoming Jingle call.
  1157. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1158. * @param {object} [options]
  1159. * @param {string} options.reasonTag the name of the reason element as defined
  1160. * by Jingle
  1161. * @param {string} options.reasonMsg the reason description which will
  1162. * be included in Jingle 'session-terminate' message.
  1163. * @param {string} options.errorMsg an error message to be logged on global
  1164. * error handler
  1165. * @private
  1166. */
  1167. JitsiConference.prototype._rejectIncomingCall
  1168. = function(jingleSession, options) {
  1169. if (options && options.errorMsg) {
  1170. GlobalOnErrorHandler.callErrorHandler(new Error(options.errorMsg));
  1171. }
  1172. // Terminate the jingle session with a reason
  1173. jingleSession.terminate(
  1174. options && options.reasonTag,
  1175. options && options.reasonMsg,
  1176. null /* success callback => we don't care */,
  1177. error => {
  1178. logger.warn(
  1179. 'An error occurred while trying to terminate'
  1180. + ' invalid Jingle session', error);
  1181. });
  1182. };
  1183. /**
  1184. * Method called to start remote stats for the current peer connection (if
  1185. * available).
  1186. * @private
  1187. */
  1188. JitsiConference.prototype._startRemoteStats = function() {
  1189. const activePeerConnection = this.getActivePeerConnection();
  1190. if (activePeerConnection) {
  1191. this.statistics.startRemoteStats(activePeerConnection);
  1192. }
  1193. };
  1194. /**
  1195. * Handles the call ended event.
  1196. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1197. * terminated.
  1198. * @param {String} reasonCondition the Jingle reason condition.
  1199. * @param {String|null} reasonText human readable reason text which may provide
  1200. * more details about why the call has been terminated.
  1201. */
  1202. JitsiConference.prototype.onCallEnded
  1203. = function(jingleSession, reasonCondition, reasonText) {
  1204. logger.info(
  1205. `Call ended: ${reasonCondition} - ${reasonText
  1206. } P2P ?${jingleSession.isP2P}`);
  1207. if (jingleSession === this.jvbJingleSession) {
  1208. this.wasStopped = true;
  1209. // Send session.terminate event
  1210. Statistics.sendEventToAll('session.terminate');
  1211. // Stop the stats
  1212. if (this.statistics) {
  1213. this.statistics.stopRemoteStats();
  1214. this.statistics.stopCallStats();
  1215. }
  1216. // Current JVB JingleSession is no longer valid, so set it to null
  1217. this.jvbJingleSession = null;
  1218. // Let the RTC service do any cleanups
  1219. this.rtc.onCallEnded();
  1220. } else if (jingleSession === this.p2pJingleSession) {
  1221. this._stopP2PSession();
  1222. } else {
  1223. logger.error(
  1224. 'Received onCallEnded for invalid session',
  1225. jingleSession.sid,
  1226. jingleSession.peerjid,
  1227. reasonCondition,
  1228. reasonText);
  1229. }
  1230. };
  1231. /**
  1232. * Handles the suspend detected event. Leaves the room and fires suspended.
  1233. * @param {JingleSessionPC} jingleSession
  1234. */
  1235. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  1236. if (!jingleSession.isP2P) {
  1237. this.leave();
  1238. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1239. }
  1240. };
  1241. JitsiConference.prototype.updateDTMFSupport = function() {
  1242. let somebodySupportsDTMF = false;
  1243. const participants = this.getParticipants();
  1244. // check if at least 1 participant supports DTMF
  1245. for (let i = 0; i < participants.length; i += 1) {
  1246. if (participants[i].supportsDTMF()) {
  1247. somebodySupportsDTMF = true;
  1248. break;
  1249. }
  1250. }
  1251. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1252. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1253. this.eventEmitter.emit(
  1254. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1255. somebodySupportsDTMF);
  1256. }
  1257. };
  1258. /**
  1259. * Allows to check if there is at least one user in the conference
  1260. * that supports DTMF.
  1261. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1262. */
  1263. JitsiConference.prototype.isDTMFSupported = function() {
  1264. return this.somebodySupportsDTMF;
  1265. };
  1266. /**
  1267. * Returns the local user's ID
  1268. * @return {string} local user's ID
  1269. */
  1270. JitsiConference.prototype.myUserId = function() {
  1271. return (
  1272. this.room
  1273. && this.room.myroomjid
  1274. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1275. : null);
  1276. };
  1277. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1278. if (!this.dtmfManager) {
  1279. const peerConnection = this.getActivePeerConnection();
  1280. if (!peerConnection) {
  1281. logger.warn('cannot sendTones: no peer connection');
  1282. return;
  1283. }
  1284. const localAudio = this.getLocalAudioTrack();
  1285. if (!localAudio) {
  1286. logger.warn('cannot sendTones: no local audio stream');
  1287. return;
  1288. }
  1289. this.dtmfManager = new JitsiDTMFManager(localAudio, peerConnection);
  1290. }
  1291. this.dtmfManager.sendTones(tones, duration, pause);
  1292. };
  1293. /**
  1294. * Returns true if recording is supported and false if not.
  1295. */
  1296. JitsiConference.prototype.isRecordingSupported = function() {
  1297. if (this.room) {
  1298. return this.room.isRecordingSupported();
  1299. }
  1300. return false;
  1301. };
  1302. /**
  1303. * Returns null if the recording is not supported, "on" if the recording started
  1304. * and "off" if the recording is not started.
  1305. */
  1306. JitsiConference.prototype.getRecordingState = function() {
  1307. return this.room ? this.room.getRecordingState() : undefined;
  1308. };
  1309. /**
  1310. * Returns the url of the recorded video.
  1311. */
  1312. JitsiConference.prototype.getRecordingURL = function() {
  1313. return this.room ? this.room.getRecordingURL() : null;
  1314. };
  1315. /**
  1316. * Starts/stops the recording
  1317. */
  1318. JitsiConference.prototype.toggleRecording = function(options) {
  1319. if (this.room) {
  1320. return this.room.toggleRecording(options, (status, error) => {
  1321. this.eventEmitter.emit(
  1322. JitsiConferenceEvents.RECORDER_STATE_CHANGED, status, error);
  1323. });
  1324. }
  1325. this.eventEmitter.emit(
  1326. JitsiConferenceEvents.RECORDER_STATE_CHANGED, 'error',
  1327. new Error('The conference is not created yet!'));
  1328. };
  1329. /**
  1330. * Returns true if the SIP calls are supported and false otherwise
  1331. */
  1332. JitsiConference.prototype.isSIPCallingSupported = function() {
  1333. if (this.room) {
  1334. return this.room.isSIPCallingSupported();
  1335. }
  1336. return false;
  1337. };
  1338. /**
  1339. * Dials a number.
  1340. * @param number the number
  1341. */
  1342. JitsiConference.prototype.dial = function(number) {
  1343. if (this.room) {
  1344. return this.room.dial(number);
  1345. }
  1346. return new Promise((resolve, reject) => {
  1347. reject(new Error('The conference is not created yet!'));
  1348. });
  1349. };
  1350. /**
  1351. * Hangup an existing call
  1352. */
  1353. JitsiConference.prototype.hangup = function() {
  1354. if (this.room) {
  1355. return this.room.hangup();
  1356. }
  1357. return new Promise((resolve, reject) => {
  1358. reject(new Error('The conference is not created yet!'));
  1359. });
  1360. };
  1361. /**
  1362. * Returns the phone number for joining the conference.
  1363. */
  1364. JitsiConference.prototype.getPhoneNumber = function() {
  1365. if (this.room) {
  1366. return this.room.getPhoneNumber();
  1367. }
  1368. return null;
  1369. };
  1370. /**
  1371. * Returns the pin for joining the conference with phone.
  1372. */
  1373. JitsiConference.prototype.getPhonePin = function() {
  1374. if (this.room) {
  1375. return this.room.getPhonePin();
  1376. }
  1377. return null;
  1378. };
  1379. /**
  1380. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  1381. * which connection is currently active.
  1382. *
  1383. * @return {TraceablePeerConnection|null} null if there isn't any active
  1384. * <tt>TraceablePeerConnection</tt> currently available.
  1385. * @protected
  1386. */
  1387. JitsiConference.prototype.getActivePeerConnection = function() {
  1388. if (this.isP2PActive()) {
  1389. return this.p2pJingleSession.peerconnection;
  1390. }
  1391. return this.jvbJingleSession ? this.jvbJingleSession.peerconnection : null;
  1392. };
  1393. /**
  1394. * Returns the connection state for the current room. Its ice connection state
  1395. * for its session.
  1396. * NOTE that "completed" ICE state which can appear on the P2P connection will
  1397. * be converted to "connected".
  1398. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  1399. * peer connection at this time.
  1400. */
  1401. JitsiConference.prototype.getConnectionState = function() {
  1402. const peerConnection = this.getActivePeerConnection();
  1403. return peerConnection ? peerConnection.getConnectionState() : null;
  1404. };
  1405. /**
  1406. * Make all new participants mute their audio/video on join.
  1407. * @param policy {Object} object with 2 boolean properties for video and audio:
  1408. * @param {boolean} audio if audio should be muted.
  1409. * @param {boolean} video if video should be muted.
  1410. */
  1411. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  1412. if (!this.isModerator()) {
  1413. return;
  1414. }
  1415. this.startMutedPolicy = policy;
  1416. this.room.removeFromPresence('startmuted');
  1417. this.room.addToPresence('startmuted', {
  1418. attributes: {
  1419. audio: policy.audio,
  1420. video: policy.video,
  1421. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  1422. }
  1423. });
  1424. this.room.sendPresence();
  1425. };
  1426. /**
  1427. * Returns current start muted policy
  1428. * @returns {Object} with 2 properties - audio and video.
  1429. */
  1430. JitsiConference.prototype.getStartMutedPolicy = function() {
  1431. return this.startMutedPolicy;
  1432. };
  1433. /**
  1434. * Check if audio is muted on join.
  1435. */
  1436. JitsiConference.prototype.isStartAudioMuted = function() {
  1437. return this.startAudioMuted;
  1438. };
  1439. /**
  1440. * Check if video is muted on join.
  1441. */
  1442. JitsiConference.prototype.isStartVideoMuted = function() {
  1443. return this.startVideoMuted;
  1444. };
  1445. /**
  1446. * Get object with internal logs.
  1447. */
  1448. JitsiConference.prototype.getLogs = function() {
  1449. const data = this.xmpp.getJingleLog();
  1450. const metadata = {};
  1451. metadata.time = new Date();
  1452. metadata.url = window.location.href;
  1453. metadata.ua = navigator.userAgent;
  1454. const log = this.xmpp.getXmppLog();
  1455. if (log) {
  1456. metadata.xmpp = log;
  1457. }
  1458. data.metadata = metadata;
  1459. return data;
  1460. };
  1461. /**
  1462. * Returns measured connectionTimes.
  1463. */
  1464. JitsiConference.prototype.getConnectionTimes = function() {
  1465. return this.room.connectionTimes;
  1466. };
  1467. /**
  1468. * Sets a property for the local participant.
  1469. */
  1470. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  1471. this.sendCommand(`jitsi_participant_${name}`, { value });
  1472. };
  1473. /**
  1474. * Sends the given feedback through CallStats if enabled.
  1475. *
  1476. * @param overallFeedback an integer between 1 and 5 indicating the
  1477. * user feedback
  1478. * @param detailedFeedback detailed feedback from the user. Not yet used
  1479. */
  1480. JitsiConference.prototype.sendFeedback
  1481. = function(overallFeedback, detailedFeedback) {
  1482. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  1483. };
  1484. /**
  1485. * Returns true if the callstats integration is enabled, otherwise returns
  1486. * false.
  1487. *
  1488. * @returns true if the callstats integration is enabled, otherwise returns
  1489. * false.
  1490. */
  1491. JitsiConference.prototype.isCallstatsEnabled = function() {
  1492. return this.statistics.isCallstatsEnabled();
  1493. };
  1494. /**
  1495. * Handles track attached to container (Calls associateStreamWithVideoTag method
  1496. * from statistics module)
  1497. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  1498. * @param container the container
  1499. */
  1500. JitsiConference.prototype._onTrackAttach = function(track, container) {
  1501. const isLocal = track.isLocal();
  1502. let ssrc = null;
  1503. if (isLocal) {
  1504. // FIXME currently we do CallStats only for JVB, but the same logic will
  1505. // need to happen for the P2P as well once the support is added.
  1506. // Local tracks have SSRC stored on per peer connection basis
  1507. const peerConnection
  1508. = this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  1509. if (peerConnection) {
  1510. ssrc = peerConnection.getLocalSSRC(track);
  1511. }
  1512. } else {
  1513. ssrc = track.getSSRC();
  1514. }
  1515. if (!container.id || !ssrc) {
  1516. return;
  1517. }
  1518. this.statistics.associateStreamWithVideoTag(
  1519. ssrc, isLocal, track.getUsageLabel(), container.id);
  1520. };
  1521. /**
  1522. * Logs an "application log" message.
  1523. * @param message {string} The message to log. Note that while this can be a
  1524. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  1525. * log valid JSON strings, with an "id" field used for distinguishing between
  1526. * message types. E.g.: {id: "recorder_status", status: "off"}
  1527. */
  1528. JitsiConference.prototype.sendApplicationLog = function(message) {
  1529. Statistics.sendLog(message);
  1530. };
  1531. /**
  1532. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1533. * focus.
  1534. * @param mucJid the full MUC address of the user to be checked.
  1535. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  1536. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  1537. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  1538. */
  1539. JitsiConference.prototype._isFocus = function(mucJid) {
  1540. return this.room ? this.room.isFocus(mucJid) : null;
  1541. };
  1542. /**
  1543. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  1544. */
  1545. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  1546. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  1547. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  1548. };
  1549. /**
  1550. * Sends a message via the data channel.
  1551. * @param to {string} the id of the endpoint that should receive the message.
  1552. * If "" the message will be sent to all participants.
  1553. * @param payload {object} the payload of the message.
  1554. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1555. */
  1556. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  1557. this.rtc.sendDataChannelMessage(to, payload);
  1558. };
  1559. /**
  1560. * Sends a broadcast message via the data channel.
  1561. * @param payload {object} the payload of the message.
  1562. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1563. */
  1564. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  1565. this.sendEndpointMessage('', payload);
  1566. };
  1567. JitsiConference.prototype.isConnectionInterrupted = function() {
  1568. return this.isP2PActive()
  1569. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  1570. };
  1571. /**
  1572. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  1573. * @param {JingleSessionPC} session
  1574. * @private
  1575. */
  1576. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  1577. if (session.isP2P) {
  1578. this.isP2PConnectionInterrupted = true;
  1579. } else {
  1580. this.isJvbConnectionInterrupted = true;
  1581. }
  1582. if (session.isP2P === this.isP2PActive()) {
  1583. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  1584. }
  1585. };
  1586. /**
  1587. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  1588. * @param {JingleSessionPC} session
  1589. * @private
  1590. */
  1591. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  1592. // We do nothing for the JVB connection, because it's up to the Jicofo to
  1593. // eventually come up with the new offer (at least for the time being).
  1594. if (session.isP2P) {
  1595. this._stopP2PSession('connectivity-error', 'ICE FAILED');
  1596. }
  1597. };
  1598. /**
  1599. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  1600. * @param {JingleSessionPC} session
  1601. * @private
  1602. */
  1603. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  1604. if (session.isP2P) {
  1605. this.isP2PConnectionInterrupted = false;
  1606. } else {
  1607. this.isJvbConnectionInterrupted = false;
  1608. }
  1609. if (session.isP2P === this.isP2PActive()) {
  1610. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  1611. }
  1612. };
  1613. /**
  1614. * Accept incoming P2P Jingle call.
  1615. * @param {JingleSessionPC} jingleSession the session instance
  1616. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  1617. * @private
  1618. */
  1619. JitsiConference.prototype._acceptP2PIncomingCall
  1620. = function(jingleSession, jingleOffer) {
  1621. jingleSession.setSSRCOwnerJid(this.room.myroomjid);
  1622. this.isP2PConnectionInterrupted = false;
  1623. // Accept the offer
  1624. this.p2pJingleSession = jingleSession;
  1625. this.p2pJingleSession.initialize(
  1626. false /* initiator */, this.room, this.rtc);
  1627. const localTracks = this.getLocalTracks();
  1628. this.p2pJingleSession.acceptOffer(
  1629. jingleOffer,
  1630. () => {
  1631. logger.debug('Got RESULT for P2P "session-accept"');
  1632. },
  1633. error => {
  1634. logger.error(
  1635. 'Failed to accept incoming P2P Jingle session', error);
  1636. },
  1637. localTracks);
  1638. };
  1639. /**
  1640. * Adds remote tracks to the conference associated with the JVB session.
  1641. * @private
  1642. */
  1643. JitsiConference.prototype._addRemoteJVBTracks = function() {
  1644. this._addRemoteTracks(
  1645. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  1646. };
  1647. /**
  1648. * Adds remote tracks to the conference associated with the P2P session.
  1649. * @private
  1650. */
  1651. JitsiConference.prototype._addRemoteP2PTracks = function() {
  1652. this._addRemoteTracks(
  1653. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  1654. };
  1655. /**
  1656. * Generates fake "remote track added" events for given Jingle session.
  1657. * @param {string} logName the session's nickname which will appear in log
  1658. * messages.
  1659. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  1660. * @private
  1661. */
  1662. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  1663. for (const track of remoteTracks) {
  1664. logger.info(`Adding remote ${logName} track: ${track}`);
  1665. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, track);
  1666. }
  1667. };
  1668. /**
  1669. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  1670. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  1671. * the P2P connection if the event comes from the P2P session.
  1672. * @param {JingleSessionPC} jingleSession the session instance.
  1673. * @private
  1674. */
  1675. JitsiConference.prototype._onIceConnectionEstablished
  1676. = function(jingleSession) {
  1677. // We don't care about the JVB case, there's nothing to be done
  1678. if (!jingleSession.isP2P) {
  1679. return;
  1680. } else if (this.p2pJingleSession !== jingleSession) {
  1681. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  1682. return;
  1683. }
  1684. // Update P2P status and emit events
  1685. this._setP2PStatus(true);
  1686. // Remove remote tracks
  1687. if (this.jvbJingleSession) {
  1688. this._removeRemoteJVBTracks();
  1689. } else {
  1690. logger.info('Not removing remote JVB tracks - no session yet');
  1691. }
  1692. // Add remote tracks
  1693. this._addRemoteP2PTracks();
  1694. // Stop media transfer over the JVB connection
  1695. if (this.jvbJingleSession) {
  1696. this._suspendMediaTransferForJvbConnection();
  1697. }
  1698. // Start remote stats
  1699. logger.info('Starting remote stats with p2p connection');
  1700. this._startRemoteStats();
  1701. };
  1702. /**
  1703. * Clears the deferred start P2P task if it has been scheduled.
  1704. * @private
  1705. */
  1706. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  1707. if (this.deferredStartP2PTask) {
  1708. logger.info('Cleared deferred start P2P task');
  1709. clearTimeout(this.deferredStartP2PTask);
  1710. this.deferredStartP2PTask = null;
  1711. }
  1712. };
  1713. /**
  1714. * Removes from the conference remote tracks associated with the JVB
  1715. * connection.
  1716. * @private
  1717. */
  1718. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  1719. this._removeRemoteTracks(
  1720. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  1721. };
  1722. /**
  1723. * Removes from the conference remote tracks associated with the P2P
  1724. * connection.
  1725. * @private
  1726. */
  1727. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  1728. this._removeRemoteTracks(
  1729. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  1730. };
  1731. /**
  1732. * Generates fake "remote track removed" events for given Jingle session.
  1733. * @param {string} sessionNickname the session's nickname which will appear in
  1734. * log messages.
  1735. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  1736. * @private
  1737. */
  1738. JitsiConference.prototype._removeRemoteTracks
  1739. = function(sessionNickname, remoteTracks) {
  1740. for (const track of remoteTracks) {
  1741. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  1742. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, track);
  1743. }
  1744. };
  1745. /**
  1746. * Resumes media transfer over the JVB connection.
  1747. * @private
  1748. */
  1749. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  1750. logger.info('Resuming media transfer over the JVB connection...');
  1751. this.jvbJingleSession.setMediaTransferActive(true).then(
  1752. () => {
  1753. logger.info('Resumed media transfer over the JVB connection!');
  1754. },
  1755. error => {
  1756. logger.error(
  1757. 'Failed to resume media transfer over the JVB connection:',
  1758. error);
  1759. });
  1760. };
  1761. /**
  1762. * Sets new P2P status and updates some events/states hijacked from
  1763. * the <tt>JitsiConference</tt>.
  1764. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  1765. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  1766. * @private
  1767. */
  1768. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  1769. if (this.p2p === newStatus) {
  1770. logger.error(`Called _setP2PStatus with the same status: ${newStatus}`);
  1771. return;
  1772. }
  1773. this.p2p = newStatus;
  1774. if (newStatus) {
  1775. logger.info('Peer to peer connection established!');
  1776. } else {
  1777. logger.info('Peer to peer connection closed!');
  1778. }
  1779. // Clear dtmfManager, so that it can be recreated with new connection
  1780. this.dtmfManager = null;
  1781. // Update P2P status
  1782. this.eventEmitter.emit(
  1783. JitsiConferenceEvents.P2P_STATUS,
  1784. this,
  1785. this.p2p);
  1786. // Refresh connection interrupted/restored
  1787. this.eventEmitter.emit(
  1788. this.isConnectionInterrupted()
  1789. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  1790. : JitsiConferenceEvents.CONNECTION_RESTORED);
  1791. };
  1792. /**
  1793. * Starts new P2P session.
  1794. * @param {string} peerJid the JID of the remote participant
  1795. * @private
  1796. */
  1797. JitsiConference.prototype._startP2PSession = function(peerJid) {
  1798. this._maybeClearDeferredStartP2P();
  1799. if (this.p2pJingleSession) {
  1800. logger.error('P2P session already started!');
  1801. return;
  1802. }
  1803. this.isP2PConnectionInterrupted = false;
  1804. this.p2pJingleSession
  1805. = this.xmpp.connection.jingle.newP2PJingleSession(
  1806. this.room.myroomjid,
  1807. peerJid);
  1808. this.p2pJingleSession.setSSRCOwnerJid(this.room.myroomjid);
  1809. logger.info('Created new P2P JingleSession', this.room.myroomjid, peerJid);
  1810. this.p2pJingleSession.initialize(true /* initiator */, this.room, this.rtc);
  1811. // NOTE one may consider to start P2P with the local tracks detached,
  1812. // but no data will be sent until ICE succeeds anyway. And we switch
  1813. // immediately once the P2P ICE connects.
  1814. const localTracks = this.getLocalTracks();
  1815. this.p2pJingleSession.invite(localTracks);
  1816. };
  1817. /**
  1818. * Suspends media transfer over the JVB connection.
  1819. * @private
  1820. */
  1821. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  1822. logger.info('Suspending media transfer over the JVB connection...');
  1823. this.jvbJingleSession.setMediaTransferActive(false).then(
  1824. () => {
  1825. logger.info('Suspended media transfer over the JVB connection !');
  1826. },
  1827. error => {
  1828. logger.error(
  1829. 'Failed to suspend media transfer over the JVB connection:',
  1830. error);
  1831. });
  1832. };
  1833. /**
  1834. * Method when called will decide whether it's the time to start or stop
  1835. * the P2P session.
  1836. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  1837. * originates from the user left event.
  1838. * @private
  1839. */
  1840. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  1841. if (!this.options.config.enableP2P || !RTCBrowserType.isP2PSupported()) {
  1842. logger.info('Auto P2P disabled');
  1843. return;
  1844. }
  1845. const peers = this.getParticipants();
  1846. const peerCount = peers.length;
  1847. const isModerator = this.isModerator();
  1848. // FIXME 1 peer and it must *support* P2P switching
  1849. const shouldBeInP2P = peerCount === 1;
  1850. logger.debug(
  1851. `P2P? isModerator: ${isModerator
  1852. }, peerCount: ${peerCount} => ${shouldBeInP2P}`);
  1853. // Clear deferred "start P2P" task
  1854. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  1855. this._maybeClearDeferredStartP2P();
  1856. }
  1857. // Start peer to peer session
  1858. if (isModerator && !this.p2pJingleSession && shouldBeInP2P) {
  1859. const peer = peerCount && peers[0];
  1860. // Everyone is a moderator ?
  1861. if (isModerator && peer.getRole() === 'moderator') {
  1862. const myId = this.myUserId();
  1863. const peersId = peer.getId();
  1864. if (myId > peersId) {
  1865. logger.debug(
  1866. 'Everyone\'s a moderator - '
  1867. + 'the other peer should start P2P', myId, peersId);
  1868. return;
  1869. } else if (myId === peersId) {
  1870. logger.error('The same IDs ? ', myId, peersId);
  1871. return;
  1872. }
  1873. }
  1874. const jid = peer.getJid();
  1875. if (userLeftEvent) {
  1876. if (this.deferredStartP2PTask) {
  1877. logger.error('Deferred start P2P task\'s been set already!');
  1878. return;
  1879. }
  1880. logger.info(
  1881. `Will start P2P with: ${jid
  1882. } after ${this.backToP2PDelay} seconds...`);
  1883. this.deferredStartP2PTask = setTimeout(
  1884. this._startP2PSession.bind(this, jid),
  1885. this.backToP2PDelay * 1000);
  1886. } else {
  1887. logger.info(`Will start P2P with: ${jid}`);
  1888. this._startP2PSession(jid);
  1889. }
  1890. } else if (isModerator && this.p2pJingleSession && !shouldBeInP2P) {
  1891. logger.info(`Will stop P2P with: ${this.p2pJingleSession.peerjid}`);
  1892. this._stopP2PSession();
  1893. }
  1894. };
  1895. /**
  1896. * Stops the current P2P session.
  1897. * @param {string} [reason="success"] one of the Jingle "reason" element
  1898. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  1899. * @param {string} [reasonDescription="Turing off P2P session"] text
  1900. * description that will be included in the session terminate message
  1901. * @private
  1902. */
  1903. JitsiConference.prototype._stopP2PSession
  1904. = function(reason, reasonDescription) {
  1905. if (!this.p2pJingleSession) {
  1906. logger.error('No P2P session to be stopped!');
  1907. return;
  1908. }
  1909. const wasP2PEstablished = this.isP2PActive();
  1910. // Swap remote tracks, but only if the P2P has been fully established
  1911. if (wasP2PEstablished) {
  1912. this._resumeMediaTransferForJvbConnection();
  1913. // Remove remote P2P tracks
  1914. this._removeRemoteP2PTracks();
  1915. }
  1916. // Stop P2P stats
  1917. logger.info('Stopping remote stats with P2P connection');
  1918. this.statistics.stopRemoteStats();
  1919. if (JingleSessionState.ENDED !== this.p2pJingleSession.state) {
  1920. this.p2pJingleSession.terminate(
  1921. reason ? reason : 'success',
  1922. reasonDescription
  1923. ? reasonDescription : 'Turing off P2P session',
  1924. () => {
  1925. logger.info('P2P session terminate RESULT');
  1926. },
  1927. error => {
  1928. logger.warn(
  1929. 'An error occurred while trying to terminate'
  1930. + ' P2P Jingle session', error);
  1931. });
  1932. }
  1933. this.p2pJingleSession = null;
  1934. // Update P2P status and other affected events/states
  1935. this._setP2PStatus(false);
  1936. if (wasP2PEstablished) {
  1937. // Add back remote JVB tracks
  1938. if (this.jvbJingleSession) {
  1939. this._addRemoteJVBTracks();
  1940. } else {
  1941. logger.info('Not adding remote JVB tracks - no session yet');
  1942. }
  1943. }
  1944. // Start remote stats
  1945. logger.info('Starting remote stats with JVB connection');
  1946. if (this.jvbJingleSession) {
  1947. this._startRemoteStats();
  1948. }
  1949. };
  1950. /**
  1951. * Checks whether or not the conference is currently in the peer to peer mode.
  1952. * Being in peer to peer mode means that the direct connection has been
  1953. * established and the P2P connection is being used for media transmission.
  1954. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  1955. */
  1956. JitsiConference.prototype.isP2PActive = function() {
  1957. return this.p2p;
  1958. };
  1959. /**
  1960. * Returns the current ICE state of the P2P connection.
  1961. * NOTE: method is used by the jitsi-meet-torture tests.
  1962. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  1963. * no P2P connection.
  1964. */
  1965. JitsiConference.prototype.getP2PConnectionState = function() {
  1966. if (this.isP2PActive()) {
  1967. return this.p2pJingleSession.peerconnection.getConnectionState();
  1968. }
  1969. return null;
  1970. };
  1971. /**
  1972. * Manually starts new P2P session (should be used only in the tests).
  1973. */
  1974. JitsiConference.prototype.startP2PSession = function() {
  1975. const peers = this.getParticipants();
  1976. // Start peer to peer session
  1977. if (peers.length === 1) {
  1978. const peerJid = peers[0].getJid();
  1979. this._startP2PSession(peerJid);
  1980. } else {
  1981. throw new Error(
  1982. 'There must be exactly 1 participant to start the P2P session !');
  1983. }
  1984. };
  1985. /**
  1986. * Manually stops the current P2P session (should be used only in the tests)
  1987. */
  1988. JitsiConference.prototype.stopP2PSession = function() {
  1989. this._stopP2PSession();
  1990. };
  1991. /**
  1992. * Get a summary of how long current participants have been the dominant speaker
  1993. * @returns {object}
  1994. */
  1995. JitsiConference.prototype.getSpeakerStats = function() {
  1996. return this.speakerStatsCollector.getStats();
  1997. };
  1998. /**
  1999. * Get video SIP GW handler, if missing will create one.
  2000. *
  2001. * @returns {VideoSIPGW} video SIP GW handler.
  2002. */
  2003. JitsiConference.prototype._getVideoSIPGWHandle = function() {
  2004. if (!this.videoSIPGWHandler) {
  2005. this.videoSIPGWHandler = new VideoSIPGW(this.room);
  2006. logger.info('Created VideoSIPGW');
  2007. }
  2008. return this.videoSIPGWHandler;
  2009. };
  2010. /**
  2011. * Checks whether video SIP GW service is available.
  2012. *
  2013. * @returns {boolean} whether video SIP GW service is available.
  2014. */
  2015. JitsiConference.prototype.isVideoSIPGWAvailable = function() {
  2016. return this._getVideoSIPGWHandle().isVideoSIPGWAvailable();
  2017. };
  2018. /**
  2019. * Creates a video SIP GW session and returns it if service is enabled. Before
  2020. * creating a session one need to check whether video SIP GW service is
  2021. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2022. * if there are available nodes to serve this request, after creating the
  2023. * session those nodes can be taken and the request about using the
  2024. * created session can fail.
  2025. *
  2026. * @param {string} sipAddress - The sip address to be used.
  2027. * @param {string} displayName - The display name to be used for this session.
  2028. * @returns {JitsiVideoSIPGWSession|null} Returns null if conference is not
  2029. * initialised and there is no room.
  2030. */
  2031. JitsiConference.prototype.createVideoSIPGWSession
  2032. = function(sipAddress, displayName) {
  2033. if (!this.room) {
  2034. return null;
  2035. }
  2036. return this._getVideoSIPGWHandle()
  2037. .createVideoSIPGWSession(sipAddress, displayName);
  2038. };
  2039. module.exports = JitsiConference;