modified lib-jitsi-meet dev repo
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 86KB

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