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

JitsiConference.js 86KB

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