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 77KB

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