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

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