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

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