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

JitsiConference.js 75KB

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