Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JitsiConference.js 74KB

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