Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JitsiConference.js 84KB

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