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

JitsiConference.js 85KB

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