您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 86KB

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