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

JitsiConference.js 89KB

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