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 139KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197
  1. import { getLogger } from '@jitsi/logger';
  2. import EventEmitter from 'events';
  3. import $ from 'jquery';
  4. import isEqual from 'lodash.isequal';
  5. import { Strophe } from 'strophe.js';
  6. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  7. import JitsiConferenceEventManager from './JitsiConferenceEventManager';
  8. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  9. import JitsiParticipant from './JitsiParticipant';
  10. import JitsiTrackError from './JitsiTrackError';
  11. import * as JitsiTrackErrors from './JitsiTrackErrors';
  12. import * as JitsiTrackEvents from './JitsiTrackEvents';
  13. import authenticateAndUpgradeRole from './authenticateAndUpgradeRole';
  14. import { CodecSelection } from './modules/RTC/CodecSelection';
  15. import RTC from './modules/RTC/RTC';
  16. import { SS_DEFAULT_FRAME_RATE } from './modules/RTC/ScreenObtainer';
  17. import browser from './modules/browser';
  18. import ConnectionQuality from './modules/connectivity/ConnectionQuality';
  19. import IceFailedHandling from './modules/connectivity/IceFailedHandling';
  20. import * as DetectionEvents from './modules/detection/DetectionEvents';
  21. import NoAudioSignalDetection from './modules/detection/NoAudioSignalDetection';
  22. import P2PDominantSpeakerDetection from './modules/detection/P2PDominantSpeakerDetection';
  23. import VADAudioAnalyser from './modules/detection/VADAudioAnalyser';
  24. import VADNoiseDetection from './modules/detection/VADNoiseDetection';
  25. import VADTalkMutedDetection from './modules/detection/VADTalkMutedDetection';
  26. import { E2EEncryption } from './modules/e2ee/E2EEncryption';
  27. import E2ePing from './modules/e2eping/e2eping';
  28. import Jvb121EventGenerator from './modules/event/Jvb121EventGenerator';
  29. import FeatureFlags from './modules/flags/FeatureFlags';
  30. import { LiteModeContext } from './modules/litemode/LiteModeContext';
  31. import ReceiveVideoController from './modules/qualitycontrol/ReceiveVideoController';
  32. import SendVideoController from './modules/qualitycontrol/SendVideoController';
  33. import RecordingManager from './modules/recording/RecordingManager';
  34. import Settings from './modules/settings/Settings';
  35. import AudioOutputProblemDetector from './modules/statistics/AudioOutputProblemDetector';
  36. import AvgRTPStatsReporter from './modules/statistics/AvgRTPStatsReporter';
  37. import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
  38. import Statistics from './modules/statistics/statistics';
  39. import Transcriber from './modules/transcription/transcriber';
  40. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  41. import RandomUtil from './modules/util/RandomUtil';
  42. import ComponentsVersions from './modules/version/ComponentsVersions';
  43. import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
  44. import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
  45. import SignalingLayerImpl from './modules/xmpp/SignalingLayerImpl';
  46. import {
  47. FEATURE_E2EE,
  48. FEATURE_JIGASI,
  49. JITSI_MEET_MUC_TYPE
  50. } from './modules/xmpp/xmpp';
  51. import BridgeVideoType from './service/RTC/BridgeVideoType';
  52. import CodecMimeType from './service/RTC/CodecMimeType';
  53. import { MediaType } from './service/RTC/MediaType';
  54. import RTCEvents from './service/RTC/RTCEvents';
  55. import { SignalingEvents } from './service/RTC/SignalingEvents';
  56. import { getMediaTypeFromSourceName, getSourceNameForJitsiTrack } from './service/RTC/SignalingLayer';
  57. import { VideoType } from './service/RTC/VideoType';
  58. import {
  59. ACTION_JINGLE_RESTART,
  60. ACTION_JINGLE_SI_RECEIVED,
  61. ACTION_JINGLE_SI_TIMEOUT,
  62. ACTION_JINGLE_TERMINATE,
  63. ACTION_P2P_DECLINED,
  64. ACTION_P2P_ESTABLISHED,
  65. ACTION_P2P_FAILED,
  66. ACTION_P2P_SWITCH_TO_JVB,
  67. ICE_ESTABLISHMENT_DURATION_DIFF,
  68. createConferenceEvent,
  69. createJingleEvent,
  70. createP2PEvent
  71. } from './service/statistics/AnalyticsEvents';
  72. import { XMPPEvents } from './service/xmpp/XMPPEvents';
  73. const logger = getLogger(__filename);
  74. /**
  75. * How long since Jicofo is supposed to send a session-initiate, before
  76. * {@link ACTION_JINGLE_SI_TIMEOUT} analytics event is sent (in ms).
  77. * @type {number}
  78. */
  79. const JINGLE_SI_TIMEOUT = 5000;
  80. /**
  81. * Checks if a given string is a valid video codec mime type.
  82. *
  83. * @param {string} codec the codec string that needs to be validated.
  84. * @returns {CodecMimeType|null} mime type if valid, null otherwise.
  85. * @private
  86. */
  87. function _getCodecMimeType(codec) {
  88. if (typeof codec === 'string') {
  89. return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
  90. }
  91. return null;
  92. }
  93. /**
  94. * Creates a JitsiConference object with the given name and properties.
  95. * Note: this constructor is not a part of the public API (objects should be
  96. * created using JitsiConnection.createConference).
  97. * @param options.config properties / settings related to the conference that
  98. * will be created.
  99. * @param options.name the name of the conference
  100. * @param options.connection the JitsiConnection object for this
  101. * JitsiConference.
  102. * @param {number} [options.config.avgRtpStatsN=15] how many samples are to be
  103. * collected by {@link AvgRTPStatsReporter}, before arithmetic mean is
  104. * calculated and submitted to the analytics module.
  105. * @param {boolean} [options.config.enableIceRestart=false] - enables the ICE
  106. * restart logic.
  107. * @param {boolean} [options.config.p2p.enabled] when set to <tt>true</tt>
  108. * the peer to peer mode will be enabled. It means that when there are only 2
  109. * participants in the conference an attempt to make direct connection will be
  110. * made. If the connection succeeds the conference will stop sending data
  111. * through the JVB connection and will use the direct one instead.
  112. * @param {number} [options.config.p2p.backToP2PDelay=5] a delay given in
  113. * seconds, before the conference switches back to P2P, after the 3rd
  114. * participant has left the room.
  115. * @param {number} [options.config.channelLastN=-1] The requested amount of
  116. * videos are going to be delivered after the value is in effect. Set to -1 for
  117. * unlimited or all available videos.
  118. * @param {number} [options.config.forceJVB121Ratio]
  119. * "Math.random() < forceJVB121Ratio" will determine whether a 2 people
  120. * conference should be moved to the JVB instead of P2P. The decision is made on
  121. * the responder side, after ICE succeeds on the P2P connection.
  122. * @constructor
  123. *
  124. * FIXME Make all methods which are called from lib-internal classes
  125. * to non-public (use _). To name a few:
  126. * {@link JitsiConference.onLocalRoleChanged}
  127. * {@link JitsiConference.onUserRoleChanged}
  128. * {@link JitsiConference.onMemberLeft}
  129. * and so on...
  130. */
  131. export default function JitsiConference(options) {
  132. if (!options.name || options.name.toLowerCase() !== options.name.toString()) {
  133. const errmsg
  134. = 'Invalid conference name (no conference name passed or it '
  135. + 'contains invalid characters like capital letters)!';
  136. logger.error(errmsg);
  137. throw new Error(errmsg);
  138. }
  139. this.connection = options.connection;
  140. this.xmpp = this.connection?.xmpp;
  141. if (this.xmpp.isRoomCreated(options.name, options.customDomain)) {
  142. const errmsg = 'A conference with the same name has already been created!';
  143. delete this.connection;
  144. delete this.xmpp;
  145. logger.error(errmsg);
  146. throw new Error(errmsg);
  147. }
  148. this.eventEmitter = new EventEmitter();
  149. this.options = options;
  150. this.eventManager = new JitsiConferenceEventManager(this);
  151. /**
  152. * List of all the participants in the conference.
  153. * @type {Map<string, JitsiParticipant>};
  154. */
  155. this.participants = new Map();
  156. /**
  157. * The signaling layer instance.
  158. * @type {SignalingLayerImpl}
  159. * @private
  160. */
  161. this._signalingLayer = new SignalingLayerImpl();
  162. this._init(options);
  163. this.componentsVersions = new ComponentsVersions(this);
  164. /**
  165. * Jingle session instance for the JVB connection.
  166. * @type {JingleSessionPC}
  167. */
  168. this.jvbJingleSession = null;
  169. this.lastDominantSpeaker = null;
  170. this.dtmfManager = null;
  171. this.somebodySupportsDTMF = false;
  172. this.authEnabled = false;
  173. this.startAudioMuted = false;
  174. this.startVideoMuted = false;
  175. this.startMutedPolicy = {
  176. audio: false,
  177. video: false
  178. };
  179. this.isMutedByFocus = false;
  180. // when muted by focus we receive the jid of the initiator of the mute
  181. this.mutedByFocusActor = null;
  182. this.isVideoMutedByFocus = false;
  183. // when video muted by focus we receive the jid of the initiator of the mute
  184. this.mutedVideoByFocusActor = null;
  185. // Flag indicates if the 'onCallEnded' method was ever called on this
  186. // instance. Used to log extra analytics event for debugging purpose.
  187. // We need to know if the potential issue happened before or after
  188. // the restart.
  189. this.wasStopped = false;
  190. // Conference properties, maintained by jicofo.
  191. this.properties = {};
  192. /**
  193. * The object which monitors local and remote connection statistics (e.g.
  194. * sending bitrate) and calculates a number which represents the connection
  195. * quality.
  196. */
  197. this.connectionQuality
  198. = new ConnectionQuality(this, this.eventEmitter, options);
  199. /**
  200. * Reports average RTP statistics to the analytics module.
  201. * @type {AvgRTPStatsReporter}
  202. */
  203. this.avgRtpStatsReporter
  204. = new AvgRTPStatsReporter(this, options.config.avgRtpStatsN || 15);
  205. /**
  206. * Detects issues with the audio of remote participants.
  207. * @type {AudioOutputProblemDetector}
  208. */
  209. if (!options.config.disableAudioLevels) {
  210. this._audioOutputProblemDetector = new AudioOutputProblemDetector(this);
  211. }
  212. /**
  213. * Indicates whether the connection is interrupted or not.
  214. */
  215. this.isJvbConnectionInterrupted = false;
  216. /**
  217. * The object which tracks active speaker times
  218. */
  219. this.speakerStatsCollector = new SpeakerStatsCollector(this);
  220. /* P2P related fields below: */
  221. /**
  222. * Stores reference to deferred start P2P task. It's created when 3rd
  223. * participant leaves the room in order to avoid ping pong effect (it
  224. * could be just a page reload).
  225. * @type {number|null}
  226. */
  227. this.deferredStartP2PTask = null;
  228. const delay
  229. = parseInt(options.config.p2p && options.config.p2p.backToP2PDelay, 10);
  230. /**
  231. * A delay given in seconds, before the conference switches back to P2P
  232. * after the 3rd participant has left.
  233. * @type {number}
  234. */
  235. this.backToP2PDelay = isNaN(delay) ? 5 : delay;
  236. logger.info(`backToP2PDelay: ${this.backToP2PDelay}`);
  237. /**
  238. * If set to <tt>true</tt> it means the P2P ICE is no longer connected.
  239. * When <tt>false</tt> it means that P2P ICE (media) connection is up
  240. * and running.
  241. * @type {boolean}
  242. */
  243. this.isP2PConnectionInterrupted = false;
  244. /**
  245. * Flag set to <tt>true</tt> when P2P session has been established
  246. * (ICE has been connected) and this conference is currently in the peer to
  247. * peer mode (P2P connection is the active one).
  248. * @type {boolean}
  249. */
  250. this.p2p = false;
  251. /**
  252. * A JingleSession for the direct peer to peer connection.
  253. * @type {JingleSessionPC}
  254. */
  255. this.p2pJingleSession = null;
  256. this.videoSIPGWHandler = new VideoSIPGW(this.room);
  257. this.recordingManager = new RecordingManager(this.room);
  258. /**
  259. * If the conference.joined event has been sent this will store the timestamp when it happened.
  260. *
  261. * @type {undefined|number}
  262. * @private
  263. */
  264. this._conferenceJoinAnalyticsEventSent = undefined;
  265. /**
  266. * End-to-End Encryption. Make it available if supported.
  267. */
  268. if (this.isE2EESupported()) {
  269. logger.info('End-to-End Encryption is supported');
  270. this._e2eEncryption = new E2EEncryption(this);
  271. }
  272. if (FeatureFlags.isRunInLiteModeEnabled()) {
  273. logger.info('Lite mode enabled');
  274. this._liteModeContext = new LiteModeContext(this);
  275. }
  276. /**
  277. * Flag set to <tt>true</tt> when Jicofo sends a presence message indicating that the max audio sender limit has
  278. * been reached for the call. Once this is set, unmuting audio will be disabled from the client until it gets reset
  279. * again by Jicofo.
  280. */
  281. this._audioSenderLimitReached = undefined;
  282. /**
  283. * Flag set to <tt>true</tt> when Jicofo sends a presence message indicating that the max video sender limit has
  284. * been reached for the call. Once this is set, unmuting video will be disabled from the client until it gets reset
  285. * again by Jicofo.
  286. */
  287. this._videoSenderLimitReached = undefined;
  288. }
  289. // FIXME convert JitsiConference to ES6 - ASAP !
  290. JitsiConference.prototype.constructor = JitsiConference;
  291. /**
  292. * Create a resource for the a jid. We use the room nickname (the resource part
  293. * of the occupant JID, see XEP-0045) as the endpoint ID in colibri. We require
  294. * endpoint IDs to be 8 hex digits because in some cases they get serialized
  295. * into a 32bit field.
  296. *
  297. * @param {string} jid - The id set onto the XMPP connection.
  298. * @param {boolean} isAuthenticatedUser - Whether or not the user has connected
  299. * to the XMPP service with a password.
  300. * @returns {string}
  301. * @static
  302. */
  303. JitsiConference.resourceCreator = function(jid, isAuthenticatedUser) {
  304. let mucNickname;
  305. if (isAuthenticatedUser) {
  306. // For authenticated users generate a random ID.
  307. mucNickname = RandomUtil.randomHexString(8).toLowerCase();
  308. } else {
  309. // We try to use the first part of the node (which for anonymous users
  310. // on prosody is a UUID) to match the previous behavior (and maybe make
  311. // debugging easier).
  312. mucNickname = Strophe.getNodeFromJid(jid)?.substr(0, 8)
  313. .toLowerCase();
  314. // But if this doesn't have the required format we just generate a new
  315. // random nickname.
  316. const re = /[0-9a-f]{8}/g;
  317. if (!mucNickname || !re.test(mucNickname)) {
  318. mucNickname = RandomUtil.randomHexString(8).toLowerCase();
  319. }
  320. }
  321. return mucNickname;
  322. };
  323. /**
  324. * Initializes the conference object properties
  325. * @param options {object}
  326. * @param options.connection {JitsiConnection} overrides this.connection
  327. */
  328. JitsiConference.prototype._init = function(options = {}) {
  329. this.eventManager.setupXMPPListeners();
  330. const { config } = this.options;
  331. // Get the codec preference settings from config.js.
  332. const codecSettings = {
  333. jvbDisabledCodec: _getCodecMimeType(config.videoQuality?.disabledCodec),
  334. p2pDisabledCodec: _getCodecMimeType(config.p2p?.disabledCodec),
  335. enforcePreferredCodec: config.videoQuality?.enforcePreferredCodec,
  336. jvbPreferredCodec: _getCodecMimeType(config.videoQuality?.preferredCodec),
  337. p2pPreferredCodec: _getCodecMimeType(config.p2p?.preferredCodec)
  338. };
  339. this.codecSelection = new CodecSelection(this, codecSettings);
  340. this._statsCurrentId = config.statisticsId ? config.statisticsId : Settings.callStatsUserName;
  341. this.room = this.xmpp.createRoom(
  342. this.options.name, {
  343. ...config,
  344. statsId: this._statsCurrentId
  345. },
  346. JitsiConference.resourceCreator
  347. );
  348. this._signalingLayer.setChatRoom(this.room);
  349. this._signalingLayer.on(
  350. SignalingEvents.SOURCE_UPDATED,
  351. (sourceName, endpointId, muted, videoType) => {
  352. const participant = this.participants.get(endpointId);
  353. const mediaType = getMediaTypeFromSourceName(sourceName);
  354. if (participant) {
  355. participant._setSources(mediaType, muted, sourceName, videoType);
  356. this.eventEmitter.emit(JitsiConferenceEvents.PARTICIPANT_SOURCE_UPDATED, participant);
  357. }
  358. });
  359. // Connection interrupted/restored listeners
  360. this._onIceConnectionInterrupted
  361. = this._onIceConnectionInterrupted.bind(this);
  362. this.room.addListener(
  363. XMPPEvents.CONNECTION_INTERRUPTED, this._onIceConnectionInterrupted);
  364. this._onIceConnectionRestored = this._onIceConnectionRestored.bind(this);
  365. this.room.addListener(
  366. XMPPEvents.CONNECTION_RESTORED, this._onIceConnectionRestored);
  367. this._onIceConnectionEstablished
  368. = this._onIceConnectionEstablished.bind(this);
  369. this.room.addListener(
  370. XMPPEvents.CONNECTION_ESTABLISHED, this._onIceConnectionEstablished);
  371. this._updateProperties = this._updateProperties.bind(this);
  372. this.room.addListener(XMPPEvents.CONFERENCE_PROPERTIES_CHANGED,
  373. this._updateProperties);
  374. this._sendConferenceJoinAnalyticsEvent = this._sendConferenceJoinAnalyticsEvent.bind(this);
  375. this.room.addListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
  376. this._removeLocalSourceOnReject = this._removeLocalSourceOnReject.bind(this);
  377. this._updateRoomPresence = this._updateRoomPresence.bind(this);
  378. this.room.addListener(XMPPEvents.SESSION_ACCEPT, this._updateRoomPresence);
  379. this.room.addListener(XMPPEvents.SOURCE_ADD, this._updateRoomPresence);
  380. this.room.addListener(XMPPEvents.SOURCE_ADD_ERROR, this._removeLocalSourceOnReject);
  381. this.room.addListener(XMPPEvents.SOURCE_REMOVE, this._updateRoomPresence);
  382. if (config.e2eping?.enabled) {
  383. this.e2eping = new E2ePing(
  384. this,
  385. config,
  386. (message, to) => {
  387. try {
  388. this.sendMessage(message, to, true /* sendThroughVideobridge */);
  389. } catch (error) {
  390. logger.warn('Failed to send E2E ping request or response.', error && error.msg);
  391. }
  392. });
  393. }
  394. if (!this.rtc) {
  395. this.rtc = new RTC(this, options);
  396. this.eventManager.setupRTCListeners();
  397. this._registerRtcListeners(this.rtc);
  398. }
  399. this.receiveVideoController = new ReceiveVideoController(this, this.rtc);
  400. this.sendVideoController = new SendVideoController(this, this.rtc);
  401. // Add the ability to enable callStats only on a percentage of users based on config.js settings.
  402. let enableCallStats = true;
  403. if (config.testing && config.testing.callStatsThreshold) {
  404. enableCallStats = (Math.random() * 100) <= config.testing.callStatsThreshold;
  405. }
  406. if (!this.statistics) {
  407. this.statistics = new Statistics(this.xmpp, {
  408. aliasName: this._statsCurrentId,
  409. userName: config.statisticsDisplayName ? config.statisticsDisplayName : this.myUserId(),
  410. confID: config.confID || `${this.connection.options.hosts.domain}/${this.options.name}`,
  411. siteID: config.siteID,
  412. customScriptUrl: config.callStatsCustomScriptUrl,
  413. callStatsID: config.callStatsID,
  414. callStatsSecret: config.callStatsSecret,
  415. callStatsApplicationLogsDisabled: config.callStatsApplicationLogsDisabled,
  416. enableCallStats,
  417. roomName: this.options.name,
  418. applicationName: config.applicationName,
  419. configParams: config.callStatsConfigParams
  420. });
  421. Statistics.analytics.addPermanentProperties({
  422. 'callstats_name': this._statsCurrentId
  423. });
  424. // Start performance observer for monitoring long tasks
  425. if (config.longTasksStatsInterval) {
  426. this.statistics.attachLongTasksStats(this);
  427. }
  428. }
  429. this.eventManager.setupChatRoomListeners();
  430. // Always add listeners because on reload we are executing leave and the
  431. // listeners are removed from statistics module.
  432. this.eventManager.setupStatisticsListeners();
  433. // Disable VAD processing on Safari since it causes audio input to
  434. // fail on some of the mobile devices.
  435. if (config.enableTalkWhileMuted && browser.supportsVADDetection()) {
  436. // If VAD processor factory method is provided uses VAD based detection, otherwise fallback to audio level
  437. // based detection.
  438. if (config.createVADProcessor) {
  439. logger.info('Using VAD detection for generating talk while muted events');
  440. if (!this._audioAnalyser) {
  441. this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
  442. }
  443. const vadTalkMutedDetection = new VADTalkMutedDetection();
  444. vadTalkMutedDetection.on(DetectionEvents.VAD_TALK_WHILE_MUTED, () =>
  445. this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED));
  446. this._audioAnalyser.addVADDetectionService(vadTalkMutedDetection);
  447. } else {
  448. logger.warn('No VAD Processor was provided. Talk while muted detection service was not initialized!');
  449. }
  450. }
  451. // Disable noisy mic detection on safari since it causes the audio input to
  452. // fail on Safari on iPadOS.
  453. if (config.enableNoisyMicDetection && browser.supportsVADDetection()) {
  454. if (config.createVADProcessor) {
  455. if (!this._audioAnalyser) {
  456. this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
  457. }
  458. const vadNoiseDetection = new VADNoiseDetection();
  459. vadNoiseDetection.on(DetectionEvents.VAD_NOISY_DEVICE, () =>
  460. this.eventEmitter.emit(JitsiConferenceEvents.NOISY_MIC));
  461. this._audioAnalyser.addVADDetectionService(vadNoiseDetection);
  462. } else {
  463. logger.warn('No VAD Processor was provided. Noisy microphone detection service was not initialized!');
  464. }
  465. }
  466. // Generates events based on no audio input detector.
  467. if (config.enableNoAudioDetection) {
  468. this._noAudioSignalDetection = new NoAudioSignalDetection(this);
  469. this._noAudioSignalDetection.on(DetectionEvents.NO_AUDIO_INPUT, () => {
  470. this.eventEmitter.emit(JitsiConferenceEvents.NO_AUDIO_INPUT);
  471. });
  472. this._noAudioSignalDetection.on(DetectionEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal => {
  473. this.eventEmitter.emit(JitsiConferenceEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal);
  474. });
  475. }
  476. if ('channelLastN' in config) {
  477. this.setLastN(config.channelLastN);
  478. }
  479. /**
  480. * Emits {@link JitsiConferenceEvents.JVB121_STATUS}.
  481. * @type {Jvb121EventGenerator}
  482. */
  483. this.jvb121Status = new Jvb121EventGenerator(this);
  484. // creates dominant speaker detection that works only in p2p mode
  485. this.p2pDominantSpeakerDetection = new P2PDominantSpeakerDetection(this);
  486. if (config && config.deploymentInfo && config.deploymentInfo.userRegion) {
  487. this.setLocalParticipantProperty(
  488. 'region', config.deploymentInfo.userRegion);
  489. }
  490. // Publish the codec type to presence.
  491. this.setLocalParticipantProperty('codecType', this.codecSelection.getPreferredCodec());
  492. // Set transcription language presence extension.
  493. // In case the language config is undefined or has the default value that the transcriber uses
  494. // (in our case Jigasi uses 'en-US'), don't set the participant property in order to avoid
  495. // needlessly polluting the presence stanza.
  496. if (config && config.transcriptionLanguage && config.transcriptionLanguage !== 'en-US') {
  497. this.setLocalParticipantProperty('transcription_language', config.transcriptionLanguage);
  498. }
  499. };
  500. /**
  501. * Joins the conference.
  502. * @param password {string} the password
  503. * @param replaceParticipant {boolean} whether the current join replaces
  504. * an existing participant with same jwt from the meeting.
  505. */
  506. JitsiConference.prototype.join = function(password, replaceParticipant = false) {
  507. if (this.room) {
  508. this.room.join(password, replaceParticipant).then(() => this._maybeSetSITimeout());
  509. }
  510. };
  511. /**
  512. * Authenticates and upgrades the role of the local participant/user.
  513. *
  514. * @returns {Object} A <tt>thenable</tt> which (1) settles when the process of
  515. * authenticating and upgrading the role of the local participant/user finishes
  516. * and (2) has a <tt>cancel</tt> method that allows the caller to interrupt the
  517. * process.
  518. */
  519. JitsiConference.prototype.authenticateAndUpgradeRole = function(options) {
  520. return authenticateAndUpgradeRole.call(this, {
  521. ...options,
  522. onCreateResource: JitsiConference.resourceCreator
  523. });
  524. };
  525. /**
  526. * Check if joined to the conference.
  527. */
  528. JitsiConference.prototype.isJoined = function() {
  529. return this.room && this.room.joined;
  530. };
  531. /**
  532. * Tells whether or not the P2P mode is enabled in the configuration.
  533. * @return {boolean}
  534. */
  535. JitsiConference.prototype.isP2PEnabled = function() {
  536. return Boolean(this.options.config.p2p && this.options.config.p2p.enabled)
  537. // FIXME: remove once we have a default config template. -saghul
  538. || typeof this.options.config.p2p === 'undefined';
  539. };
  540. /**
  541. * When in P2P test mode, the conference will not automatically switch to P2P
  542. * when there 2 participants.
  543. * @return {boolean}
  544. */
  545. JitsiConference.prototype.isP2PTestModeEnabled = function() {
  546. return Boolean(this.options.config.testing
  547. && this.options.config.testing.p2pTestMode);
  548. };
  549. /**
  550. * Leaves the conference.
  551. * @param reason {string|undefined} The reason for leaving the conference.
  552. * @returns {Promise}
  553. */
  554. JitsiConference.prototype.leave = async function(reason) {
  555. if (this.avgRtpStatsReporter) {
  556. this.avgRtpStatsReporter.dispose();
  557. this.avgRtpStatsReporter = null;
  558. }
  559. if (this._audioOutputProblemDetector) {
  560. this._audioOutputProblemDetector.dispose();
  561. this._audioOutputProblemDetector = null;
  562. }
  563. if (this.e2eping) {
  564. this.e2eping.stop();
  565. this.e2eping = null;
  566. }
  567. this.getLocalTracks().forEach(track => this.onLocalTrackRemoved(track));
  568. this.rtc.closeBridgeChannel();
  569. this._sendConferenceLeftAnalyticsEvent();
  570. if (this.statistics) {
  571. this.statistics.dispose();
  572. }
  573. this._delayedIceFailed && this._delayedIceFailed.cancel();
  574. this._maybeClearSITimeout();
  575. // Close both JVb and P2P JingleSessions
  576. if (this.jvbJingleSession) {
  577. this.jvbJingleSession.close();
  578. this.jvbJingleSession = null;
  579. }
  580. if (this.p2pJingleSession) {
  581. this.p2pJingleSession.close();
  582. this.p2pJingleSession = null;
  583. }
  584. // Leave the conference. If this.room == null we are calling second time leave().
  585. if (!this.room) {
  586. throw new Error('You have already left the conference');
  587. }
  588. const room = this.room;
  589. // Unregister connection state listeners
  590. room.removeListener(
  591. XMPPEvents.CONNECTION_INTERRUPTED,
  592. this._onIceConnectionInterrupted);
  593. room.removeListener(
  594. XMPPEvents.CONNECTION_RESTORED,
  595. this._onIceConnectionRestored);
  596. room.removeListener(
  597. XMPPEvents.CONNECTION_ESTABLISHED,
  598. this._onIceConnectionEstablished);
  599. room.removeListener(
  600. XMPPEvents.CONFERENCE_PROPERTIES_CHANGED,
  601. this._updateProperties);
  602. room.removeListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
  603. room.removeListener(XMPPEvents.SESSION_ACCEPT, this._updateRoomPresence);
  604. room.removeListener(XMPPEvents.SOURCE_ADD, this._updateRoomPresence);
  605. room.removeListener(XMPPEvents.SOURCE_ADD_ERROR, this._removeLocalSourceOnReject);
  606. room.removeListener(XMPPEvents.SOURCE_REMOVE, this._updateRoomPresence);
  607. this.eventManager.removeXMPPListeners();
  608. this._signalingLayer.setChatRoom(null);
  609. this.room = null;
  610. let leaveError;
  611. try {
  612. await room.leave(reason);
  613. } catch (err) {
  614. leaveError = err;
  615. // Remove all participants because currently the conference
  616. // won't be usable anyway. This is done on success automatically
  617. // by the ChatRoom instance.
  618. this.getParticipants().forEach(
  619. participant => this.onMemberLeft(participant.getJid()));
  620. }
  621. if (this.rtc) {
  622. this.rtc.destroy();
  623. }
  624. if (leaveError) {
  625. throw leaveError;
  626. }
  627. };
  628. /**
  629. * Returns <tt>true</tt> if end conference support is enabled in the backend.
  630. *
  631. * @returns {boolean} whether end conference is supported in the backend.
  632. */
  633. JitsiConference.prototype.isEndConferenceSupported = function() {
  634. return Boolean(this.room && this.room.xmpp.endConferenceComponentAddress);
  635. };
  636. /**
  637. * Ends the conference.
  638. */
  639. JitsiConference.prototype.end = function() {
  640. if (!this.isEndConferenceSupported()) {
  641. logger.warn('Cannot end conference: is not supported.');
  642. return;
  643. }
  644. if (!this.room) {
  645. throw new Error('You have already left the conference');
  646. }
  647. this.room.end();
  648. };
  649. /**
  650. * Returns the currently active media session if any.
  651. *
  652. * @returns {JingleSessionPC|undefined}
  653. */
  654. JitsiConference.prototype.getActiveMediaSession = function() {
  655. return this.isP2PActive() ? this.p2pJingleSession : this.jvbJingleSession;
  656. };
  657. /**
  658. * Returns an array containing all media sessions existing in this conference.
  659. *
  660. * @returns {Array<JingleSessionPC>}
  661. */
  662. JitsiConference.prototype.getMediaSessions = function() {
  663. const sessions = [];
  664. this.jvbJingleSession && sessions.push(this.jvbJingleSession);
  665. this.p2pJingleSession && sessions.push(this.p2pJingleSession);
  666. return sessions;
  667. };
  668. /**
  669. * Registers event listeners on the RTC instance.
  670. * @param {RTC} rtc - the RTC module instance used by this conference.
  671. * @private
  672. * @returns {void}
  673. */
  674. JitsiConference.prototype._registerRtcListeners = function(rtc) {
  675. rtc.addListener(RTCEvents.DATA_CHANNEL_OPEN, () => {
  676. for (const localTrack of this.rtc.localTracks) {
  677. localTrack.isVideoTrack() && this._sendBridgeVideoTypeMessage(localTrack);
  678. }
  679. });
  680. };
  681. /**
  682. * Sends the 'VideoTypeMessage' to the bridge on the bridge channel so that the bridge can make bitrate allocation
  683. * decisions based on the video type of the local source.
  684. *
  685. * @param {JitsiLocalTrack} localtrack - The track associated with the local source signaled to the bridge.
  686. * @returns {void}
  687. * @private
  688. */
  689. JitsiConference.prototype._sendBridgeVideoTypeMessage = function(localtrack) {
  690. let videoType = !localtrack || localtrack.isMuted() ? BridgeVideoType.NONE : localtrack.getVideoType();
  691. if (videoType === BridgeVideoType.DESKTOP && this._desktopSharingFrameRate > SS_DEFAULT_FRAME_RATE) {
  692. videoType = BridgeVideoType.DESKTOP_HIGH_FPS;
  693. }
  694. localtrack && this.rtc.sendSourceVideoType(localtrack.getSourceName(), videoType);
  695. };
  696. /**
  697. * Returns name of this conference.
  698. */
  699. JitsiConference.prototype.getName = function() {
  700. return this.options.name.toString();
  701. };
  702. /**
  703. * Returns the {@link JitsiConnection} used by this this conference.
  704. */
  705. JitsiConference.prototype.getConnection = function() {
  706. return this.connection;
  707. };
  708. /**
  709. * Check if authentication is enabled for this conference.
  710. */
  711. JitsiConference.prototype.isAuthEnabled = function() {
  712. return this.authEnabled;
  713. };
  714. /**
  715. * Check if user is logged in.
  716. */
  717. JitsiConference.prototype.isLoggedIn = function() {
  718. return Boolean(this.authIdentity);
  719. };
  720. /**
  721. * Get authorized login.
  722. */
  723. JitsiConference.prototype.getAuthLogin = function() {
  724. return this.authIdentity;
  725. };
  726. /**
  727. * Check if external authentication is enabled for this conference.
  728. */
  729. JitsiConference.prototype.isExternalAuthEnabled = function() {
  730. return this.room && this.room.moderator.isExternalAuthEnabled();
  731. };
  732. /**
  733. * Get url for external authentication.
  734. * @param {boolean} [urlForPopup] if true then return url for login popup,
  735. * else url of login page.
  736. * @returns {Promise}
  737. */
  738. JitsiConference.prototype.getExternalAuthUrl = function(urlForPopup) {
  739. return new Promise((resolve, reject) => {
  740. if (!this.isExternalAuthEnabled()) {
  741. reject();
  742. return;
  743. }
  744. if (urlForPopup) {
  745. this.room.moderator.getPopupLoginUrl(resolve, reject);
  746. } else {
  747. this.room.moderator.getLoginUrl(resolve, reject);
  748. }
  749. });
  750. };
  751. /**
  752. * Returns the local tracks of the given media type, or all local tracks if no
  753. * specific type is given.
  754. * @param {MediaType} [mediaType] Optional media type (audio or video).
  755. */
  756. JitsiConference.prototype.getLocalTracks = function(mediaType) {
  757. let tracks = [];
  758. if (this.rtc) {
  759. tracks = this.rtc.getLocalTracks(mediaType);
  760. }
  761. return tracks;
  762. };
  763. /**
  764. * Obtains local audio track.
  765. * @return {JitsiLocalTrack|null}
  766. */
  767. JitsiConference.prototype.getLocalAudioTrack = function() {
  768. return this.rtc ? this.rtc.getLocalAudioTrack() : null;
  769. };
  770. /**
  771. * Obtains local video track.
  772. * @return {JitsiLocalTrack|null}
  773. */
  774. JitsiConference.prototype.getLocalVideoTrack = function() {
  775. return this.rtc ? this.rtc.getLocalVideoTrack() : null;
  776. };
  777. /**
  778. * Returns all the local video tracks.
  779. * @returns {Array<JitsiLocalTrack>}
  780. */
  781. JitsiConference.prototype.getLocalVideoTracks = function() {
  782. return this.rtc ? this.rtc.getLocalVideoTracks() : null;
  783. };
  784. /**
  785. * Obtains the performance statistics.
  786. * @returns {Object|null}
  787. */
  788. JitsiConference.prototype.getPerformanceStats = function() {
  789. return {
  790. longTasksStats: this.statistics.getLongTasksStats()
  791. };
  792. };
  793. /**
  794. * Attaches a handler for events(For example - "participant joined".) in the
  795. * conference. All possible event are defined in JitsiConferenceEvents.
  796. * @param eventId the event ID.
  797. * @param handler handler for the event.
  798. *
  799. * Note: consider adding eventing functionality by extending an EventEmitter
  800. * impl, instead of rolling ourselves
  801. */
  802. JitsiConference.prototype.on = function(eventId, handler) {
  803. if (this.eventEmitter) {
  804. this.eventEmitter.on(eventId, handler);
  805. }
  806. };
  807. /**
  808. * Removes event listener
  809. * @param eventId the event ID.
  810. * @param [handler] optional, the specific handler to unbind
  811. *
  812. * Note: consider adding eventing functionality by extending an EventEmitter
  813. * impl, instead of rolling ourselves
  814. */
  815. JitsiConference.prototype.off = function(eventId, handler) {
  816. if (this.eventEmitter) {
  817. this.eventEmitter.removeListener(eventId, handler);
  818. }
  819. };
  820. // Common aliases for event emitter
  821. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  822. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  823. /**
  824. * Receives notifications from other participants about commands / custom events
  825. * (sent by sendCommand or sendCommandOnce methods).
  826. * @param command {String} the name of the command
  827. * @param handler {Function} handler for the command
  828. */
  829. JitsiConference.prototype.addCommandListener = function(command, handler) {
  830. if (this.room) {
  831. this.room.addPresenceListener(command, handler);
  832. }
  833. };
  834. /**
  835. * Removes command listener
  836. * @param command {String} the name of the command
  837. * @param handler {Function} handler to remove for the command
  838. */
  839. JitsiConference.prototype.removeCommandListener = function(command, handler) {
  840. if (this.room) {
  841. this.room.removePresenceListener(command, handler);
  842. }
  843. };
  844. /**
  845. * Sends text message to the other participants in the conference
  846. * @param message the text message.
  847. * @param elementName the element name to encapsulate the message.
  848. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  849. */
  850. JitsiConference.prototype.sendTextMessage = function(message, elementName = 'body') {
  851. if (this.room) {
  852. this.room.sendMessage(message, elementName);
  853. }
  854. };
  855. /**
  856. * Send private text message to another participant of the conference
  857. * @param id the id of the participant to send a private message.
  858. * @param message the text message.
  859. * @param elementName the element name to encapsulate the message.
  860. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  861. */
  862. JitsiConference.prototype.sendPrivateTextMessage = function(id, message, elementName = 'body') {
  863. if (this.room) {
  864. this.room.sendPrivateMessage(id, message, elementName);
  865. }
  866. };
  867. /**
  868. * Send presence command.
  869. * @param name {String} the name of the command.
  870. * @param values {Object} with keys and values that will be sent.
  871. **/
  872. JitsiConference.prototype.sendCommand = function(name, values) {
  873. if (this.room) {
  874. this.room.addOrReplaceInPresence(name, values) && this.room.sendPresence();
  875. } else {
  876. logger.warn('Not sending a command, room not initialized.');
  877. }
  878. };
  879. /**
  880. * Send presence command one time.
  881. * @param name {String} the name of the command.
  882. * @param values {Object} with keys and values that will be sent.
  883. **/
  884. JitsiConference.prototype.sendCommandOnce = function(name, values) {
  885. this.sendCommand(name, values);
  886. this.removeCommand(name);
  887. };
  888. /**
  889. * Removes presence command.
  890. * @param name {String} the name of the command.
  891. **/
  892. JitsiConference.prototype.removeCommand = function(name) {
  893. if (this.room) {
  894. this.room.removeFromPresence(name);
  895. }
  896. };
  897. /**
  898. * Sets the display name for this conference.
  899. * @param name the display name to set
  900. */
  901. JitsiConference.prototype.setDisplayName = function(name) {
  902. if (this.room) {
  903. const nickKey = 'nick';
  904. if (name) {
  905. this.room.addOrReplaceInPresence(nickKey, {
  906. attributes: { xmlns: 'http://jabber.org/protocol/nick' },
  907. value: name
  908. }) && this.room.sendPresence();
  909. } else if (this.room.getFromPresence(nickKey)) {
  910. this.room.removeFromPresence(nickKey);
  911. this.room.sendPresence();
  912. }
  913. }
  914. };
  915. /**
  916. * Set new subject for this conference. (available only for moderator)
  917. * @param {string} subject new subject
  918. */
  919. JitsiConference.prototype.setSubject = function(subject) {
  920. if (this.room && this.isModerator()) {
  921. this.room.setSubject(subject);
  922. } else {
  923. logger.warn(`Failed to set subject, ${this.room ? '' : 'not in a room, '}${
  924. this.isModerator() ? '' : 'participant is not a moderator'}`);
  925. }
  926. };
  927. /**
  928. * Get a transcriber object for all current participants in this conference
  929. * @return {Transcriber} the transcriber object
  930. */
  931. JitsiConference.prototype.getTranscriber = function() {
  932. if (this.transcriber === undefined) {
  933. this.transcriber = new Transcriber();
  934. // add all existing local audio tracks to the transcriber
  935. const localAudioTracks = this.getLocalTracks(MediaType.AUDIO);
  936. for (const localAudio of localAudioTracks) {
  937. this.transcriber.addTrack(localAudio);
  938. }
  939. // and all remote audio tracks
  940. const remoteAudioTracks = this.rtc.getRemoteTracks(MediaType.AUDIO);
  941. for (const remoteTrack of remoteAudioTracks) {
  942. this.transcriber.addTrack(remoteTrack);
  943. }
  944. }
  945. return this.transcriber;
  946. };
  947. /**
  948. * Returns the transcription status.
  949. *
  950. * @returns {String} "on" or "off".
  951. */
  952. JitsiConference.prototype.getTranscriptionStatus = function() {
  953. return this.room.transcriptionStatus;
  954. };
  955. /**
  956. * Adds JitsiLocalTrack object to the conference.
  957. * @param {JitsiLocalTrack} track the JitsiLocalTrack object.
  958. * @returns {Promise<JitsiLocalTrack>}
  959. * @throws {Error} if the specified track is a video track and there is already
  960. * another video track in the conference.
  961. */
  962. JitsiConference.prototype.addTrack = function(track) {
  963. const mediaType = track.getType();
  964. const localTracks = this.rtc.getLocalTracks(mediaType);
  965. // Ensure there's exactly 1 local track of each media type in the conference.
  966. if (localTracks.length > 0) {
  967. // Don't be excessively harsh and severe if the API client happens to attempt to add the same local track twice.
  968. if (track === localTracks[0]) {
  969. return Promise.resolve(track);
  970. }
  971. // Currently, only adding multiple video streams of different video types is supported.
  972. // TODO - remove this limitation once issues with jitsi-meet trying to add multiple camera streams is fixed.
  973. if (FeatureFlags.isMultiStreamSendSupportEnabled()
  974. && mediaType === MediaType.VIDEO
  975. && !localTracks.find(t => t.getVideoType() === track.getVideoType())) {
  976. const sourceName = getSourceNameForJitsiTrack(
  977. this.myUserId(),
  978. mediaType,
  979. this.getLocalTracks(mediaType)?.length);
  980. track.setSourceName(sourceName);
  981. const addTrackPromises = [];
  982. this.p2pJingleSession && addTrackPromises.push(this.p2pJingleSession.addTracks([ track ]));
  983. this.jvbJingleSession && addTrackPromises.push(this.jvbJingleSession.addTracks([ track ]));
  984. return Promise.all(addTrackPromises)
  985. .then(() => {
  986. this._setupNewTrack(track);
  987. this._sendBridgeVideoTypeMessage(track);
  988. this._updateRoomPresence(this.getActiveMediaSession());
  989. if (this.isMutedByFocus || this.isVideoMutedByFocus) {
  990. this._fireMuteChangeEvent(track);
  991. }
  992. });
  993. }
  994. return Promise.reject(new Error(`Cannot add second ${mediaType} track to the conference`));
  995. }
  996. return this.replaceTrack(null, track)
  997. .then(() => {
  998. // Presence needs to be sent here for desktop track since we need the presence to reach the remote peer
  999. // before signaling so that a fake participant tile is created for screenshare. Otherwise, presence will
  1000. // only be sent after a session-accept or source-add is ack'ed.
  1001. if (track.getVideoType() === VideoType.DESKTOP && FeatureFlags.isMultiStreamSendSupportEnabled()) {
  1002. this._updateRoomPresence(this.getActiveMediaSession());
  1003. }
  1004. });
  1005. };
  1006. /**
  1007. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event (for local tracks).
  1008. * @param {number} audioLevel the audio level
  1009. * @param {TraceablePeerConnection} [tpc]
  1010. */
  1011. JitsiConference.prototype._fireAudioLevelChangeEvent = function(audioLevel, tpc) {
  1012. const activeTpc = this.getActivePeerConnection();
  1013. // There will be no TraceablePeerConnection if audio levels do not come from
  1014. // a peerconnection. LocalStatsCollector.js measures audio levels using Web
  1015. // Audio Analyser API and emits local audio levels events through
  1016. // JitsiTrack.setAudioLevel, but does not provide TPC instance which is
  1017. // optional.
  1018. if (!tpc || activeTpc === tpc) {
  1019. this.eventEmitter.emit(
  1020. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1021. this.myUserId(), audioLevel);
  1022. }
  1023. };
  1024. /**
  1025. * Fires TRACK_MUTE_CHANGED change conference event.
  1026. * @param track the JitsiTrack object related to the event.
  1027. */
  1028. JitsiConference.prototype._fireMuteChangeEvent = function(track) {
  1029. // check if track was muted by focus and now is unmuted by user
  1030. if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
  1031. this.isMutedByFocus = false;
  1032. // unmute local user on server
  1033. this.room.muteParticipant(this.room.myroomjid, false, MediaType.AUDIO);
  1034. } else if (this.isVideoMutedByFocus && track.isVideoTrack() && !track.isMuted()) {
  1035. this.isVideoMutedByFocus = false;
  1036. // unmute local user on server
  1037. this.room.muteParticipant(this.room.myroomjid, false, MediaType.VIDEO);
  1038. }
  1039. let actorParticipant;
  1040. if (this.mutedByFocusActor && track.isAudioTrack()) {
  1041. const actorId = Strophe.getResourceFromJid(this.mutedByFocusActor);
  1042. actorParticipant = this.participants.get(actorId);
  1043. } else if (this.mutedVideoByFocusActor && track.isVideoTrack()) {
  1044. const actorId = Strophe.getResourceFromJid(this.mutedVideoByFocusActor);
  1045. actorParticipant = this.participants.get(actorId);
  1046. }
  1047. // Send the video type message to the bridge if the track is not removed/added to the pc as part of
  1048. // the mute/unmute operation.
  1049. // In React Native we mute the camera by setting track.enabled but that doesn't
  1050. // work for screen-share tracks, so do the remove-as-mute for those.
  1051. const doesVideoMuteByStreamRemove
  1052. = browser.isReactNative() ? track.videoType === VideoType.DESKTOP : browser.doesVideoMuteByStreamRemove();
  1053. if (track.isVideoTrack() && !doesVideoMuteByStreamRemove) {
  1054. this._sendBridgeVideoTypeMessage(track);
  1055. }
  1056. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track, actorParticipant);
  1057. };
  1058. /**
  1059. * Returns the list of local tracks that need to be added to the peerconnection on join.
  1060. * This takes the startAudioMuted/startVideoMuted flags into consideration since we do not
  1061. * want to add the tracks if the user joins the call audio/video muted. The tracks will be
  1062. * added when the user unmutes for the first time.
  1063. * @returns {Array<JitsiLocalTrack>} - list of local tracks that are unmuted.
  1064. */
  1065. JitsiConference.prototype._getInitialLocalTracks = function() {
  1066. // Always add the audio track on certain platforms:
  1067. // * Safari / WebKit: because of a known issue where audio playout doesn't happen
  1068. // if the user joins audio and video muted.
  1069. // * React Native: after iOS 15, if a user joins muted they won't be able to unmute.
  1070. return this.getLocalTracks()
  1071. .filter(track => {
  1072. const trackType = track.getType();
  1073. if (trackType === MediaType.AUDIO
  1074. && (!this.isStartAudioMuted() || browser.isWebKitBased() || browser.isReactNative())) {
  1075. return true;
  1076. } else if (trackType === MediaType.VIDEO && !this.isStartVideoMuted()) {
  1077. return true;
  1078. }
  1079. return false;
  1080. });
  1081. };
  1082. /**
  1083. * Clear JitsiLocalTrack properties and listeners.
  1084. * @param track the JitsiLocalTrack object.
  1085. */
  1086. JitsiConference.prototype.onLocalTrackRemoved = function(track) {
  1087. track.setConference(null);
  1088. this.rtc.removeLocalTrack(track);
  1089. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  1090. if (track.isAudioTrack()) {
  1091. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  1092. }
  1093. // send event for stopping screen sharing
  1094. // FIXME: we assume we have only one screen sharing track
  1095. // if we change this we need to fix this check
  1096. if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP) {
  1097. this.statistics.sendScreenSharingEvent(false);
  1098. }
  1099. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  1100. };
  1101. /**
  1102. * Removes JitsiLocalTrack from the conference and performs
  1103. * a new offer/answer cycle.
  1104. * @param {JitsiLocalTrack} track
  1105. * @returns {Promise}
  1106. */
  1107. JitsiConference.prototype.removeTrack = function(track) {
  1108. return this.replaceTrack(track, null);
  1109. };
  1110. /**
  1111. * Replaces oldTrack with newTrack and performs a single offer/answer
  1112. * cycle after both operations are done. Either oldTrack or newTrack
  1113. * can be null; replacing a valid 'oldTrack' with a null 'newTrack'
  1114. * effectively just removes 'oldTrack'
  1115. * @param {JitsiLocalTrack} oldTrack the current stream in use to be replaced
  1116. * @param {JitsiLocalTrack} newTrack the new stream to use
  1117. * @returns {Promise} resolves when the replacement is finished
  1118. */
  1119. JitsiConference.prototype.replaceTrack = function(oldTrack, newTrack) {
  1120. const oldVideoType = oldTrack?.getVideoType();
  1121. const mediaType = oldTrack?.getType() || newTrack?.getType();
  1122. const newVideoType = newTrack?.getVideoType();
  1123. if (FeatureFlags.isMultiStreamSendSupportEnabled() && oldTrack && newTrack && oldVideoType !== newVideoType) {
  1124. throw new Error(`Replacing a track of videoType=${oldVideoType} with a track of videoType=${newVideoType} is`
  1125. + ' not supported in this mode.');
  1126. }
  1127. if (newTrack) {
  1128. const sourceName = oldTrack
  1129. ? oldTrack.getSourceName()
  1130. : getSourceNameForJitsiTrack(
  1131. this.myUserId(),
  1132. mediaType,
  1133. this.getLocalTracks(mediaType)?.length);
  1134. newTrack.setSourceName(sourceName);
  1135. }
  1136. const oldTrackBelongsToConference = this === oldTrack?.conference;
  1137. if (oldTrackBelongsToConference && oldTrack.disposed) {
  1138. return Promise.reject(new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  1139. }
  1140. if (newTrack?.disposed) {
  1141. return Promise.reject(new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  1142. }
  1143. if (oldTrack && !oldTrackBelongsToConference) {
  1144. logger.warn(`JitsiConference.replaceTrack oldTrack (${oldTrack} does not belong to this conference`);
  1145. }
  1146. // Now replace the stream at the lower levels
  1147. return this._doReplaceTrack(oldTrackBelongsToConference ? oldTrack : null, newTrack)
  1148. .then(() => {
  1149. if (oldTrackBelongsToConference && !oldTrack.isMuted() && !newTrack) {
  1150. oldTrack._sendMuteStatus(true);
  1151. }
  1152. oldTrackBelongsToConference && this.onLocalTrackRemoved(oldTrack);
  1153. newTrack && this._setupNewTrack(newTrack);
  1154. // Send 'VideoTypeMessage' on the bridge channel when a video track is added/removed.
  1155. if ((oldTrackBelongsToConference && oldTrack?.isVideoTrack()) || newTrack?.isVideoTrack()) {
  1156. this._sendBridgeVideoTypeMessage(newTrack);
  1157. }
  1158. this._updateRoomPresence(this.getActiveMediaSession());
  1159. if (newTrack !== null && (this.isMutedByFocus || this.isVideoMutedByFocus)) {
  1160. this._fireMuteChangeEvent(newTrack);
  1161. }
  1162. return Promise.resolve();
  1163. })
  1164. .catch(error => {
  1165. logger.error(`replaceTrack failed: ${error?.stack}`);
  1166. return Promise.reject(error);
  1167. });
  1168. };
  1169. /**
  1170. * Replaces the tracks at the lower level by going through the Jingle session
  1171. * and WebRTC peer connection. The method will resolve immediately if there is
  1172. * currently no JingleSession started.
  1173. * @param {JitsiLocalTrack|null} oldTrack the track to be removed during
  1174. * the process or <tt>null</t> if the method should act as "add track"
  1175. * @param {JitsiLocalTrack|null} newTrack the new track to be added or
  1176. * <tt>null</tt> if the method should act as "remove track"
  1177. * @return {Promise} resolved when the process is done or rejected with a string
  1178. * which describes the error.
  1179. * @private
  1180. */
  1181. JitsiConference.prototype._doReplaceTrack = function(oldTrack, newTrack) {
  1182. const replaceTrackPromises = [];
  1183. if (this.jvbJingleSession) {
  1184. replaceTrackPromises.push(this.jvbJingleSession.replaceTrack(oldTrack, newTrack));
  1185. } else {
  1186. logger.info('_doReplaceTrack - no JVB JingleSession');
  1187. }
  1188. if (this.p2pJingleSession) {
  1189. replaceTrackPromises.push(this.p2pJingleSession.replaceTrack(oldTrack, newTrack));
  1190. } else {
  1191. logger.info('_doReplaceTrack - no P2P JingleSession');
  1192. }
  1193. return Promise.all(replaceTrackPromises);
  1194. };
  1195. /**
  1196. * Handler for when a source-add for a local source is rejected by Jicofo.
  1197. *
  1198. * @param {JingleSessionPC} jingleSession - The media session.
  1199. * @param {Error} error - The error message.
  1200. * @param {MediaType} mediaType - The media type of the track associated with the source that was rejected.
  1201. * @returns {void}
  1202. */
  1203. JitsiConference.prototype._removeLocalSourceOnReject = function(jingleSession, error, mediaType) {
  1204. if (!jingleSession) {
  1205. return;
  1206. }
  1207. logger.warn(`Source-add rejected on ${jingleSession}, reason="${error?.reason}", message="${error?.msg}"`);
  1208. const track = this.getLocalTracks(mediaType)[0];
  1209. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_UNMUTE_REJECTED, track);
  1210. };
  1211. /**
  1212. * Operations related to creating a new track
  1213. * @param {JitsiLocalTrack} newTrack the new track being created
  1214. */
  1215. JitsiConference.prototype._setupNewTrack = function(newTrack) {
  1216. const mediaType = newTrack.getType();
  1217. if (newTrack.isAudioTrack() || (newTrack.isVideoTrack() && newTrack.videoType !== VideoType.DESKTOP)) {
  1218. // Report active device to statistics
  1219. const devices = RTC.getCurrentlyAvailableMediaDevices();
  1220. const device = devices
  1221. .find(d => d.kind === `${newTrack.getTrack().kind}input` && d.label === newTrack.getTrack().label);
  1222. if (device) {
  1223. Statistics.sendActiveDeviceListEvent(RTC.getEventDataForActiveDevice(device));
  1224. }
  1225. }
  1226. // Create a source name for this track if it doesn't exist.
  1227. if (!newTrack.getSourceName()) {
  1228. const sourceName = getSourceNameForJitsiTrack(
  1229. this.myUserId(),
  1230. mediaType,
  1231. this.getLocalTracks(mediaType)?.length);
  1232. newTrack.setSourceName(sourceName);
  1233. }
  1234. this.rtc.addLocalTrack(newTrack);
  1235. newTrack.setConference(this);
  1236. // Add event handlers.
  1237. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  1238. newTrack.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, newTrack.muteHandler);
  1239. if (newTrack.isAudioTrack()) {
  1240. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  1241. newTrack.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, newTrack.audioLevelHandler);
  1242. }
  1243. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  1244. };
  1245. /**
  1246. * Sets the video type.
  1247. * @param track
  1248. * @return <tt>true</tt> if video type was changed in presence.
  1249. * @private
  1250. */
  1251. JitsiConference.prototype._setNewVideoType = function(track) {
  1252. let videoTypeChanged = false;
  1253. if (track) {
  1254. videoTypeChanged = this._signalingLayer.setTrackVideoType(track.getSourceName(), track.videoType);
  1255. }
  1256. return videoTypeChanged;
  1257. };
  1258. /**
  1259. * Sets mute status.
  1260. * @param mediaType
  1261. * @param localTrack
  1262. * @param isMuted
  1263. * @param <tt>true</tt> when presence was changed, <tt>false</tt> otherwise.
  1264. * @private
  1265. */
  1266. JitsiConference.prototype._setTrackMuteStatus = function(mediaType, localTrack, isMuted) {
  1267. let presenceChanged = false;
  1268. if (localTrack) {
  1269. presenceChanged = this._signalingLayer.setTrackMuteStatus(localTrack.getSourceName(), isMuted);
  1270. }
  1271. return presenceChanged;
  1272. };
  1273. /**
  1274. * Method called by the {@link JitsiLocalTrack} in order to add the underlying MediaStream to the RTCPeerConnection.
  1275. *
  1276. * @param {JitsiLocalTrack} track the local track that will be added to the pc.
  1277. * @return {Promise} resolved when the process is done or rejected with a string which describes the error.
  1278. */
  1279. JitsiConference.prototype._addLocalTrackToPc = function(track) {
  1280. const addPromises = [];
  1281. if (this.jvbJingleSession) {
  1282. addPromises.push(this.jvbJingleSession.addTrackToPc(track));
  1283. } else {
  1284. logger.debug('Add local MediaStream - no JVB Jingle session started yet');
  1285. }
  1286. if (this.p2pJingleSession) {
  1287. addPromises.push(this.p2pJingleSession.addTrackToPc(track));
  1288. } else {
  1289. logger.debug('Add local MediaStream - no P2P Jingle session started yet');
  1290. }
  1291. return Promise.allSettled(addPromises);
  1292. };
  1293. /**
  1294. * Method called by the {@link JitsiLocalTrack} in order to remove the underlying MediaStream from the
  1295. * RTCPeerConnection.
  1296. *
  1297. * @param {JitsiLocalTrack} track the local track that will be removed.
  1298. * @return {Promise} resolved when the process is done or rejected with a string which describes the error.
  1299. */
  1300. JitsiConference.prototype._removeLocalTrackFromPc = function(track) {
  1301. const removePromises = [];
  1302. if (this.jvbJingleSession) {
  1303. removePromises.push(this.jvbJingleSession.removeTrackFromPc(track));
  1304. } else {
  1305. logger.debug('Remove local MediaStream - no JVB JingleSession started yet');
  1306. }
  1307. if (this.p2pJingleSession) {
  1308. removePromises.push(this.p2pJingleSession.removeTrackFromPc(track));
  1309. } else {
  1310. logger.debug('Remove local MediaStream - no P2P JingleSession started yet');
  1311. }
  1312. return Promise.allSettled(removePromises);
  1313. };
  1314. /**
  1315. * Get role of the local user.
  1316. * @returns {string} user role: 'moderator' or 'none'
  1317. */
  1318. JitsiConference.prototype.getRole = function() {
  1319. return this.room.role;
  1320. };
  1321. /**
  1322. * Returns whether or not the current conference has been joined as a hidden
  1323. * user.
  1324. *
  1325. * @returns {boolean|null} True if hidden, false otherwise. Will return null if
  1326. * no connection is active.
  1327. */
  1328. JitsiConference.prototype.isHidden = function() {
  1329. if (!this.connection) {
  1330. return null;
  1331. }
  1332. return Strophe.getDomainFromJid(this.connection.getJid())
  1333. === this.options.config.hiddenDomain;
  1334. };
  1335. /**
  1336. * Check if local user is moderator.
  1337. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  1338. * we're no longer in the conference room then <tt>null</tt> is returned.
  1339. */
  1340. JitsiConference.prototype.isModerator = function() {
  1341. return this.room ? this.room.isModerator() : null;
  1342. };
  1343. /**
  1344. * Set password for the room.
  1345. * @param {string} password new password for the room.
  1346. * @returns {Promise}
  1347. */
  1348. JitsiConference.prototype.lock = function(password) {
  1349. if (!this.isModerator()) {
  1350. return Promise.reject(new Error('You are not moderator.'));
  1351. }
  1352. return new Promise((resolve, reject) => {
  1353. this.room.lockRoom(
  1354. password || '',
  1355. () => resolve(),
  1356. err => reject(err),
  1357. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  1358. });
  1359. };
  1360. /**
  1361. * Remove password from the room.
  1362. * @returns {Promise}
  1363. */
  1364. JitsiConference.prototype.unlock = function() {
  1365. return this.lock();
  1366. };
  1367. /**
  1368. * Obtains the current value for "lastN". See {@link setLastN} for more info.
  1369. * @returns {number}
  1370. */
  1371. JitsiConference.prototype.getLastN = function() {
  1372. return this.receiveVideoController.getLastN();
  1373. };
  1374. /**
  1375. * Obtains the forwarded sources list in this conference.
  1376. * @return {Array<string>|null}
  1377. */
  1378. JitsiConference.prototype.getForwardedSources = function() {
  1379. return this.rtc.getForwardedSources();
  1380. };
  1381. /**
  1382. * Selects a new value for "lastN". The requested amount of videos are going
  1383. * to be delivered after the value is in effect. Set to -1 for unlimited or
  1384. * all available videos.
  1385. * @param lastN the new number of videos the user would like to receive.
  1386. * @throws Error or RangeError if the given value is not a number or is smaller
  1387. * than -1.
  1388. */
  1389. JitsiConference.prototype.setLastN = function(lastN) {
  1390. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  1391. throw new Error(`Invalid value for lastN: ${lastN}`);
  1392. }
  1393. const n = Number(lastN);
  1394. if (n < -1) {
  1395. throw new RangeError('lastN cannot be smaller than -1');
  1396. }
  1397. this.receiveVideoController.setLastN(n);
  1398. // If the P2P session is not fully established yet, we wait until it gets established.
  1399. if (this.p2pJingleSession) {
  1400. const isVideoActive = n !== 0;
  1401. this.p2pJingleSession
  1402. .setP2pVideoTransferActive(isVideoActive)
  1403. .catch(error => {
  1404. logger.error(`Failed to adjust video transfer status (${isVideoActive})`, error);
  1405. });
  1406. }
  1407. };
  1408. /**
  1409. * @return Array<JitsiParticipant> an array of all participants in this conference.
  1410. */
  1411. JitsiConference.prototype.getParticipants = function() {
  1412. return Array.from(this.participants.values());
  1413. };
  1414. /**
  1415. * Returns the number of participants in the conference, including the local
  1416. * participant.
  1417. * @param countHidden {boolean} Whether or not to include hidden participants
  1418. * in the count. Default: false.
  1419. **/
  1420. JitsiConference.prototype.getParticipantCount = function(countHidden = false) {
  1421. let participants = this.getParticipants();
  1422. if (!countHidden) {
  1423. participants = participants.filter(p => !p.isHidden());
  1424. }
  1425. // Add one for the local participant.
  1426. return participants.length + 1;
  1427. };
  1428. /**
  1429. * @returns {JitsiParticipant} the participant in this conference with the
  1430. * specified id (or undefined if there isn't one).
  1431. * @param id the id of the participant.
  1432. */
  1433. JitsiConference.prototype.getParticipantById = function(id) {
  1434. return this.participants.get(id);
  1435. };
  1436. /**
  1437. * Grant owner rights to the participant.
  1438. * @param {string} id id of the participant to grant owner rights to.
  1439. */
  1440. JitsiConference.prototype.grantOwner = function(id) {
  1441. const participant = this.getParticipantById(id);
  1442. if (!participant) {
  1443. return;
  1444. }
  1445. this.room.setAffiliation(participant.getConnectionJid(), 'owner');
  1446. };
  1447. /**
  1448. * Revoke owner rights to the participant or local Participant as
  1449. * the user might want to refuse to be a moderator.
  1450. * @param {string} id id of the participant to revoke owner rights to.
  1451. */
  1452. JitsiConference.prototype.revokeOwner = function(id) {
  1453. const participant = this.getParticipantById(id);
  1454. const isMyself = this.myUserId() === id;
  1455. const role = this.isMembersOnly() ? 'member' : 'none';
  1456. if (isMyself) {
  1457. this.room.setAffiliation(this.connection.getJid(), role);
  1458. } else if (participant) {
  1459. this.room.setAffiliation(participant.getConnectionJid(), role);
  1460. }
  1461. };
  1462. /**
  1463. * Kick participant from this conference.
  1464. * @param {string} id id of the participant to kick
  1465. * @param {string} reason reason of the participant to kick
  1466. */
  1467. JitsiConference.prototype.kickParticipant = function(id, reason) {
  1468. const participant = this.getParticipantById(id);
  1469. if (!participant) {
  1470. return;
  1471. }
  1472. this.room.kick(participant.getJid(), reason);
  1473. };
  1474. /**
  1475. * Maybe clears the timeout which emits {@link ACTION_JINGLE_SI_TIMEOUT}
  1476. * analytics event.
  1477. * @private
  1478. */
  1479. JitsiConference.prototype._maybeClearSITimeout = function() {
  1480. if (this._sessionInitiateTimeout
  1481. && (this.jvbJingleSession || this.getParticipantCount() < 2)) {
  1482. window.clearTimeout(this._sessionInitiateTimeout);
  1483. this._sessionInitiateTimeout = null;
  1484. }
  1485. };
  1486. /**
  1487. * Sets a timeout which will emit {@link ACTION_JINGLE_SI_TIMEOUT} analytics
  1488. * event.
  1489. * @private
  1490. */
  1491. JitsiConference.prototype._maybeSetSITimeout = function() {
  1492. // Jicofo is supposed to invite if there are at least 2 participants
  1493. if (!this.jvbJingleSession
  1494. && this.getParticipantCount() >= 2
  1495. && !this._sessionInitiateTimeout) {
  1496. this._sessionInitiateTimeout = window.setTimeout(() => {
  1497. this._sessionInitiateTimeout = null;
  1498. Statistics.sendAnalytics(createJingleEvent(
  1499. ACTION_JINGLE_SI_TIMEOUT,
  1500. {
  1501. p2p: false,
  1502. value: JINGLE_SI_TIMEOUT
  1503. }));
  1504. }, JINGLE_SI_TIMEOUT);
  1505. }
  1506. };
  1507. /**
  1508. * Mutes a participant.
  1509. * @param {string} id The id of the participant to mute.
  1510. */
  1511. JitsiConference.prototype.muteParticipant = function(id, mediaType) {
  1512. const muteMediaType = mediaType ? mediaType : MediaType.AUDIO;
  1513. if (muteMediaType !== MediaType.AUDIO && muteMediaType !== MediaType.VIDEO) {
  1514. logger.error(`Unsupported media type: ${muteMediaType}`);
  1515. return;
  1516. }
  1517. const participant = this.getParticipantById(id);
  1518. if (!participant) {
  1519. return;
  1520. }
  1521. this.room.muteParticipant(participant.getJid(), true, muteMediaType);
  1522. };
  1523. /* eslint-disable max-params */
  1524. /**
  1525. * Notifies this JitsiConference that a new member has joined its chat room.
  1526. *
  1527. * FIXME This should NOT be exposed!
  1528. *
  1529. * @param jid the jid of the participant in the MUC
  1530. * @param nick the display name of the participant
  1531. * @param role the role of the participant in the MUC
  1532. * @param isHidden indicates if this is a hidden participant (system
  1533. * participant for example a recorder).
  1534. * @param statsID the participant statsID (optional)
  1535. * @param status the initial status if any
  1536. * @param identity the member identity, if any
  1537. * @param botType the member botType, if any
  1538. * @param fullJid the member full jid, if any
  1539. * @param features the member botType, if any
  1540. * @param isReplaceParticipant whether this join replaces a participant with
  1541. * the same jwt.
  1542. */
  1543. JitsiConference.prototype.onMemberJoined = function(
  1544. jid, nick, role, isHidden, statsID, status, identity, botType, fullJid, features, isReplaceParticipant) {
  1545. const id = Strophe.getResourceFromJid(jid);
  1546. if (id === 'focus' || this.myUserId() === id) {
  1547. return;
  1548. }
  1549. const participant = new JitsiParticipant(jid, this, nick, isHidden, statsID, status, identity);
  1550. participant.setConnectionJid(fullJid);
  1551. participant.setRole(role);
  1552. participant.setBotType(botType);
  1553. participant.setFeatures(features);
  1554. participant.setIsReplacing(isReplaceParticipant);
  1555. // Set remote tracks on the participant if source signaling was received before presence.
  1556. const remoteTracks = this.isP2PActive()
  1557. ? this.p2pJingleSession?.peerconnection.getRemoteTracks(id) ?? []
  1558. : this.jvbJingleSession?.peerconnection.getRemoteTracks(id) ?? [];
  1559. for (const track of remoteTracks) {
  1560. participant._tracks.push(track);
  1561. }
  1562. this.participants.set(id, participant);
  1563. this.eventEmitter.emit(
  1564. JitsiConferenceEvents.USER_JOINED,
  1565. id,
  1566. participant);
  1567. this._updateFeatures(participant);
  1568. // maybeStart only if we had finished joining as then we will have information for the number of participants
  1569. if (this.isJoined()) {
  1570. this._maybeStartOrStopP2P();
  1571. }
  1572. this._maybeSetSITimeout();
  1573. };
  1574. /* eslint-enable max-params */
  1575. /**
  1576. * Get notified when we joined the room.
  1577. *
  1578. * FIXME This should NOT be exposed!
  1579. *
  1580. * @private
  1581. */
  1582. JitsiConference.prototype._onMucJoined = function() {
  1583. this._maybeStartOrStopP2P();
  1584. };
  1585. /**
  1586. * Updates features for a participant.
  1587. * @param {JitsiParticipant} participant - The participant to query for features.
  1588. * @returns {void}
  1589. * @private
  1590. */
  1591. JitsiConference.prototype._updateFeatures = function(participant) {
  1592. participant.getFeatures()
  1593. .then(features => {
  1594. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  1595. this.updateDTMFSupport();
  1596. if (features.has(FEATURE_JIGASI)) {
  1597. participant.setProperty('features_jigasi', true);
  1598. }
  1599. if (features.has(FEATURE_E2EE)) {
  1600. participant.setProperty('features_e2ee', true);
  1601. }
  1602. })
  1603. .catch(() => false);
  1604. };
  1605. /**
  1606. * Get notified when member bot type had changed.
  1607. * @param jid the member jid
  1608. * @param botType the new botType value
  1609. * @private
  1610. */
  1611. JitsiConference.prototype._onMemberBotTypeChanged = function(jid, botType) {
  1612. // find the participant and mark it as non bot, as the real one will join
  1613. // in a moment
  1614. const peers = this.getParticipants();
  1615. const botParticipant = peers.find(p => p.getJid() === jid);
  1616. if (botParticipant) {
  1617. botParticipant.setBotType(botType);
  1618. const id = Strophe.getResourceFromJid(jid);
  1619. this.eventEmitter.emit(
  1620. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1621. id,
  1622. botType);
  1623. }
  1624. // if botType changed to undefined, botType was removed, in case of
  1625. // poltergeist mode this is the moment when the poltergeist had exited and
  1626. // the real participant had already replaced it.
  1627. // In this case we can check and try p2p
  1628. if (!botParticipant.getBotType()) {
  1629. this._maybeStartOrStopP2P();
  1630. }
  1631. };
  1632. JitsiConference.prototype.onMemberLeft = function(jid, reason) {
  1633. const id = Strophe.getResourceFromJid(jid);
  1634. if (id === 'focus' || this.myUserId() === id) {
  1635. return;
  1636. }
  1637. if (!FeatureFlags.isSsrcRewritingSupported()) {
  1638. const mediaSessions = this.getMediaSessions();
  1639. let tracksToBeRemoved = [];
  1640. for (const session of mediaSessions) {
  1641. const remoteTracks = session.peerconnection.getRemoteTracks(id);
  1642. remoteTracks && (tracksToBeRemoved = [ ...tracksToBeRemoved, ...remoteTracks ]);
  1643. // Update the SSRC owners list.
  1644. session._signalingLayer.updateSsrcOwnersOnLeave(id);
  1645. // Remove the ssrcs from the remote description and renegotiate.
  1646. session.removeRemoteStreamsOnLeave(id);
  1647. }
  1648. // Fire the event before renegotiation is done so that the thumbnails can be removed immediately.
  1649. tracksToBeRemoved.forEach(track => {
  1650. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  1651. });
  1652. }
  1653. const participant = this.participants.get(id);
  1654. if (participant) {
  1655. this.participants.delete(id);
  1656. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant, reason);
  1657. }
  1658. if (this.room !== null) { // Skip if we have left the room already.
  1659. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  1660. this._maybeClearSITimeout();
  1661. }
  1662. };
  1663. /* eslint-disable max-params */
  1664. /**
  1665. * Designates an event indicating that we were kicked from the XMPP MUC.
  1666. * @param {boolean} isSelfPresence - whether it is for local participant
  1667. * or another participant.
  1668. * @param {string} actorId - the id of the participant who was initiator
  1669. * of the kick.
  1670. * @param {string?} kickedParticipantId - when it is not a kick for local participant,
  1671. * this is the id of the participant which was kicked.
  1672. * @param {string} reason - reason of the participant to kick
  1673. * @param {boolean?} isReplaceParticipant - whether this is a server initiated kick in order
  1674. * to replace it with a participant with same jwt.
  1675. */
  1676. JitsiConference.prototype.onMemberKicked = function(
  1677. isSelfPresence,
  1678. actorId,
  1679. kickedParticipantId,
  1680. reason,
  1681. isReplaceParticipant) {
  1682. // This check which be true when we kick someone else. With the introduction of lobby
  1683. // the ChatRoom KICKED event is now also emitted for ourselves (the kicker) so we want to
  1684. // avoid emitting an event where `undefined` kicked someone.
  1685. if (actorId === this.myUserId()) {
  1686. return;
  1687. }
  1688. const actorParticipant = this.participants.get(actorId);
  1689. if (isSelfPresence) {
  1690. this.eventEmitter.emit(
  1691. JitsiConferenceEvents.KICKED, actorParticipant, reason, isReplaceParticipant);
  1692. this.leave();
  1693. return;
  1694. }
  1695. const kickedParticipant = this.participants.get(kickedParticipantId);
  1696. kickedParticipant.setIsReplaced(isReplaceParticipant);
  1697. this.eventEmitter.emit(
  1698. JitsiConferenceEvents.PARTICIPANT_KICKED, actorParticipant, kickedParticipant, reason);
  1699. };
  1700. /**
  1701. * Method called on local MUC role change.
  1702. * @param {string} role the name of new user's role as defined by XMPP MUC.
  1703. */
  1704. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  1705. // Emit role changed for local JID
  1706. this.eventEmitter.emit(
  1707. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  1708. };
  1709. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  1710. const id = Strophe.getResourceFromJid(jid);
  1711. const participant = this.getParticipantById(id);
  1712. if (!participant) {
  1713. return;
  1714. }
  1715. participant.setRole(role);
  1716. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  1717. };
  1718. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  1719. const id = Strophe.getResourceFromJid(jid);
  1720. const participant = this.getParticipantById(id);
  1721. if (!participant) {
  1722. return;
  1723. }
  1724. if (participant._displayName === displayName) {
  1725. return;
  1726. }
  1727. participant._displayName = displayName;
  1728. this.eventEmitter.emit(
  1729. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1730. id,
  1731. displayName);
  1732. };
  1733. /**
  1734. * Notifies this JitsiConference that a JitsiRemoteTrack was added to the conference.
  1735. *
  1736. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this JitsiConference.
  1737. */
  1738. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  1739. if (track.isP2P && !this.isP2PActive()) {
  1740. logger.info('Trying to add remote P2P track, when not in P2P - IGNORED');
  1741. return;
  1742. } else if (!track.isP2P && this.isP2PActive()) {
  1743. logger.info('Trying to add remote JVB track, when in P2P - IGNORED');
  1744. return;
  1745. }
  1746. const id = track.getParticipantId();
  1747. const participant = this.getParticipantById(id);
  1748. // Add track to JitsiParticipant.
  1749. if (participant) {
  1750. participant._tracks.push(track);
  1751. } else {
  1752. logger.info(`Source signaling received before presence for ${id}`);
  1753. }
  1754. if (this.transcriber) {
  1755. this.transcriber.addTrack(track);
  1756. }
  1757. const emitter = this.eventEmitter;
  1758. track.addEventListener(
  1759. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1760. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  1761. track.isAudioTrack() && track.addEventListener(
  1762. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1763. (audioLevel, tpc) => {
  1764. const activeTPC = this.getActivePeerConnection();
  1765. if (activeTPC === tpc) {
  1766. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  1767. }
  1768. }
  1769. );
  1770. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  1771. };
  1772. /**
  1773. * Callback called by the Jingle plugin when 'session-answer' is received.
  1774. * @param {JingleSessionPC} session the Jingle session for which an answer was
  1775. * received.
  1776. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  1777. */
  1778. // eslint-disable-next-line no-unused-vars
  1779. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  1780. if (this.p2pJingleSession === session) {
  1781. logger.info('P2P setAnswer');
  1782. this.p2pJingleSession.setAnswer(answer);
  1783. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_STARTED, this.p2pJingleSession);
  1784. }
  1785. };
  1786. /**
  1787. * Callback called by the Jingle plugin when 'transport-info' is received.
  1788. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1789. * received
  1790. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1791. * element
  1792. */
  1793. // eslint-disable-next-line no-unused-vars
  1794. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1795. if (this.p2pJingleSession === session) {
  1796. logger.info('P2P addIceCandidates');
  1797. this.p2pJingleSession.addIceCandidates(transportInfo);
  1798. }
  1799. };
  1800. /**
  1801. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1802. * the conference.
  1803. *
  1804. * @param {JitsiRemoteTrack} removedTrack
  1805. */
  1806. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1807. this.getParticipants().forEach(participant => {
  1808. const tracks = participant.getTracks();
  1809. for (let i = 0; i < tracks.length; i++) {
  1810. if (tracks[i] === removedTrack) {
  1811. // Since the tracks have been compared and are
  1812. // considered equal the result of splice can be ignored.
  1813. participant._tracks.splice(i, 1);
  1814. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1815. if (this.transcriber) {
  1816. this.transcriber.removeTrack(removedTrack);
  1817. }
  1818. break;
  1819. }
  1820. }
  1821. }, this);
  1822. };
  1823. /**
  1824. * Handles an incoming call event for the P2P jingle session.
  1825. */
  1826. JitsiConference.prototype._onIncomingCallP2P = function(jingleSession, jingleOffer) {
  1827. let rejectReason;
  1828. const usesUnifiedPlan = browser.supportsUnifiedPlan()
  1829. && (!browser.isChromiumBased() || (this.options.config.enableUnifiedOnChrome ?? true));
  1830. const contentName = jingleOffer.find('>content').attr('name');
  1831. const peerUsesUnifiedPlan = contentName === '0' || contentName === '1';
  1832. // Reject P2P between endpoints that are not running in the same mode w.r.t to SDPs (plan-b and unified plan).
  1833. if (usesUnifiedPlan !== peerUsesUnifiedPlan) {
  1834. rejectReason = {
  1835. reason: 'decline',
  1836. reasonDescription: 'P2P disabled',
  1837. errorMsg: 'P2P across two endpoints in different SDP modes is disabled'
  1838. };
  1839. } else if ((!this.isP2PEnabled() && !this.isP2PTestModeEnabled())
  1840. || browser.isFirefox()
  1841. || browser.isWebKitBased()) {
  1842. rejectReason = {
  1843. reason: 'decline',
  1844. reasonDescription: 'P2P disabled',
  1845. errorMsg: 'P2P mode disabled in the configuration or browser unsupported'
  1846. };
  1847. } else if (this.p2pJingleSession) {
  1848. // Reject incoming P2P call (already in progress)
  1849. rejectReason = {
  1850. reason: 'busy',
  1851. reasonDescription: 'P2P already in progress',
  1852. errorMsg: 'Duplicated P2P "session-initiate"'
  1853. };
  1854. } else if (!this._shouldBeInP2PMode()) {
  1855. rejectReason = {
  1856. reason: 'decline',
  1857. reasonDescription: 'P2P requirements not met',
  1858. errorMsg: 'Received P2P "session-initiate" when should not be in P2P mode'
  1859. };
  1860. Statistics.sendAnalytics(createJingleEvent(ACTION_P2P_DECLINED));
  1861. }
  1862. if (rejectReason) {
  1863. this._rejectIncomingCall(jingleSession, rejectReason);
  1864. } else {
  1865. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1866. }
  1867. };
  1868. /**
  1869. * Handles an incoming call event.
  1870. */
  1871. JitsiConference.prototype.onIncomingCall = function(jingleSession, jingleOffer, now) {
  1872. // Handle incoming P2P call
  1873. if (jingleSession.isP2P) {
  1874. this._onIncomingCallP2P(jingleSession, jingleOffer);
  1875. } else {
  1876. if (!this.isFocus(jingleSession.remoteJid)) {
  1877. const description = 'Rejecting session-initiate from non-focus.';
  1878. this._rejectIncomingCall(
  1879. jingleSession, {
  1880. reason: 'security-error',
  1881. reasonDescription: description,
  1882. errorMsg: description
  1883. });
  1884. return;
  1885. }
  1886. this._acceptJvbIncomingCall(jingleSession, jingleOffer, now);
  1887. }
  1888. };
  1889. /**
  1890. * Accepts an incoming call event for the JVB jingle session.
  1891. */
  1892. JitsiConference.prototype._acceptJvbIncomingCall = function(jingleSession, jingleOffer, now) {
  1893. // Accept incoming call
  1894. this.jvbJingleSession = jingleSession;
  1895. this.room.connectionTimes['session.initiate'] = now;
  1896. this._sendConferenceJoinAnalyticsEvent();
  1897. if (this.wasStopped) {
  1898. Statistics.sendAnalyticsAndLog(createJingleEvent(ACTION_JINGLE_RESTART, { p2p: false }));
  1899. }
  1900. const serverRegion
  1901. = $(jingleOffer)
  1902. .find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]')
  1903. .attr('region');
  1904. this.eventEmitter.emit(JitsiConferenceEvents.SERVER_REGION_CHANGED, serverRegion);
  1905. this._maybeClearSITimeout();
  1906. Statistics.sendAnalytics(createJingleEvent(
  1907. ACTION_JINGLE_SI_RECEIVED,
  1908. {
  1909. p2p: false,
  1910. value: now
  1911. }));
  1912. try {
  1913. jingleSession.initialize(
  1914. this.room,
  1915. this.rtc,
  1916. this._signalingLayer,
  1917. {
  1918. ...this.options.config,
  1919. enableInsertableStreams: this.isE2EEEnabled() || FeatureFlags.isRunInLiteModeEnabled()
  1920. });
  1921. } catch (error) {
  1922. GlobalOnErrorHandler.callErrorHandler(error);
  1923. logger.error(error);
  1924. return;
  1925. }
  1926. // Open a channel with the videobridge.
  1927. this._setBridgeChannel(jingleOffer, jingleSession.peerconnection);
  1928. const localTracks = this._getInitialLocalTracks();
  1929. try {
  1930. jingleSession.acceptOffer(
  1931. jingleOffer,
  1932. () => {
  1933. // If for any reason invite for the JVB session arrived after
  1934. // the P2P has been established already the media transfer needs
  1935. // to be turned off here.
  1936. if (this.isP2PActive() && this.jvbJingleSession) {
  1937. this._suspendMediaTransferForJvbConnection();
  1938. }
  1939. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_STARTED, jingleSession);
  1940. if (!this.isP2PActive()) {
  1941. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED, jingleSession);
  1942. }
  1943. },
  1944. error => {
  1945. GlobalOnErrorHandler.callErrorHandler(error);
  1946. logger.error('Failed to accept incoming Jingle session', error);
  1947. },
  1948. localTracks
  1949. );
  1950. // Enable or disable simulcast for plan-b screensharing based on the capture fps if it is set through the UI.
  1951. this._desktopSharingFrameRate
  1952. && jingleSession.peerconnection.setDesktopSharingFrameRate(this._desktopSharingFrameRate);
  1953. // Start callstats as soon as peerconnection is initialized,
  1954. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1955. // happen in case if user doesn't have or denied permission to
  1956. // both camera and microphone.
  1957. logger.info('Starting CallStats for JVB connection...');
  1958. this.statistics.startCallStats(
  1959. this.jvbJingleSession.peerconnection,
  1960. 'jitsi' /* Remote user ID for JVB is 'jitsi' */);
  1961. this.statistics.startRemoteStats(this.jvbJingleSession.peerconnection);
  1962. } catch (e) {
  1963. GlobalOnErrorHandler.callErrorHandler(e);
  1964. logger.error(e);
  1965. }
  1966. };
  1967. /**
  1968. * Sets the BridgeChannel.
  1969. *
  1970. * @param {jQuery} offerIq a jQuery selector pointing to the jingle element of
  1971. * the offer IQ which may carry the WebSocket URL for the 'websocket'
  1972. * BridgeChannel mode.
  1973. * @param {TraceablePeerConnection} pc the peer connection which will be used
  1974. * to listen for new WebRTC Data Channels (in the 'datachannel' mode).
  1975. */
  1976. JitsiConference.prototype._setBridgeChannel = function(offerIq, pc) {
  1977. const ignoreDomain = this.connection?.options?.bridgeChannel?.ignoreDomain;
  1978. const preferSctp = this.connection?.options?.bridgeChannel?.preferSctp ?? false;
  1979. const sctpOffered = $(offerIq).find('>content[name="data"]')
  1980. .first().length === 1;
  1981. let wsUrl = null;
  1982. logger.info(`SCTP: offered=${sctpOffered}, prefered=${preferSctp}`);
  1983. if (!(sctpOffered && preferSctp)) {
  1984. $(offerIq).find('>content>transport>web-socket')
  1985. .toArray()
  1986. .map(e => e.getAttribute('url'))
  1987. .forEach(url => {
  1988. if (!wsUrl && (!ignoreDomain || ignoreDomain !== new URL(url).hostname)) {
  1989. wsUrl = url;
  1990. logger.info(`Using colibri-ws url ${url}`);
  1991. } else if (!wsUrl) {
  1992. logger.info(`Ignoring colibri-ws url with domain ${ignoreDomain}`);
  1993. }
  1994. });
  1995. if (!wsUrl) {
  1996. const firstWsUrl = $(offerIq).find('>content>transport>web-socket')
  1997. .first();
  1998. if (firstWsUrl.length === 1) {
  1999. wsUrl = firstWsUrl[0].getAttribute('url');
  2000. logger.info(`Falling back to ${wsUrl}`);
  2001. }
  2002. }
  2003. }
  2004. if (wsUrl && !(sctpOffered && preferSctp)) {
  2005. // If the offer contains a websocket and we don't prefer SCTP use it.
  2006. this.rtc.initializeBridgeChannel(null, wsUrl);
  2007. } else if (sctpOffered) {
  2008. // Otherwise, fall back to an attempt to use SCTP.
  2009. this.rtc.initializeBridgeChannel(pc, null);
  2010. } else {
  2011. logger.warn('Neither SCTP nor a websocket is available. Will not initialize bridge channel.');
  2012. }
  2013. };
  2014. /**
  2015. * Rejects incoming Jingle call.
  2016. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  2017. * @param {object} [options]
  2018. * @param {string} options.reason the name of the reason element as defined
  2019. * by Jingle
  2020. * @param {string} options.reasonDescription the reason description which will
  2021. * be included in Jingle 'session-terminate' message.
  2022. * @param {string} options.errorMsg an error message to be logged on global
  2023. * error handler
  2024. * @private
  2025. */
  2026. JitsiConference.prototype._rejectIncomingCall = function(jingleSession, options) {
  2027. if (options?.errorMsg) {
  2028. logger.warn(options.errorMsg);
  2029. }
  2030. // Terminate the jingle session with a reason
  2031. jingleSession.terminate(
  2032. null /* success callback => we don't care */,
  2033. error => {
  2034. logger.warn(
  2035. 'An error occurred while trying to terminate'
  2036. + ' invalid Jingle session', error);
  2037. }, {
  2038. reason: options && options.reason,
  2039. reasonDescription: options && options.reasonDescription,
  2040. sendSessionTerminate: true
  2041. });
  2042. };
  2043. /**
  2044. * Handles the call ended event.
  2045. * XXX is this due to the remote side terminating the Jingle session?
  2046. *
  2047. * @param {JingleSessionPC} jingleSession the jingle session which has been
  2048. * terminated.
  2049. * @param {String} reasonCondition the Jingle reason condition.
  2050. * @param {String|null} reasonText human readable reason text which may provide
  2051. * more details about why the call has been terminated.
  2052. */
  2053. JitsiConference.prototype.onCallEnded = function(jingleSession, reasonCondition, reasonText) {
  2054. logger.info(
  2055. `Call ended: ${reasonCondition} - ${reasonText} P2P ?${
  2056. jingleSession.isP2P}`);
  2057. if (jingleSession === this.jvbJingleSession) {
  2058. this.wasStopped = true;
  2059. Statistics.sendAnalytics(
  2060. createJingleEvent(ACTION_JINGLE_TERMINATE, { p2p: false }));
  2061. // Stop the stats
  2062. if (this.statistics) {
  2063. this.statistics.stopRemoteStats(
  2064. this.jvbJingleSession.peerconnection);
  2065. logger.info('Stopping JVB CallStats');
  2066. this.statistics.stopCallStats(
  2067. this.jvbJingleSession.peerconnection);
  2068. }
  2069. // Current JVB JingleSession is no longer valid, so set it to null
  2070. this.jvbJingleSession = null;
  2071. // Let the RTC service do any cleanups
  2072. this.rtc.onCallEnded();
  2073. } else if (jingleSession === this.p2pJingleSession) {
  2074. const stopOptions = {};
  2075. // It's the responder who decides to enforce JVB mode, so that both
  2076. // initiator and responder are aware if it was intentional.
  2077. if (reasonCondition === 'decline' && reasonText === 'force JVB121') {
  2078. logger.info('In forced JVB 121 mode...');
  2079. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  2080. } else if (reasonCondition === 'connectivity-error'
  2081. && reasonText === 'ICE FAILED') {
  2082. // It can happen that the other peer detects ICE failed and
  2083. // terminates the session, before we get the event on our side.
  2084. // But we are able to parse the reason and mark it here.
  2085. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2086. } else if (reasonCondition === 'success' && reasonText === 'restart') {
  2087. // When we are restarting media sessions we don't want to switch the tracks
  2088. // to the JVB just yet.
  2089. stopOptions.requestRestart = true;
  2090. }
  2091. this._stopP2PSession(stopOptions);
  2092. } else {
  2093. logger.error(
  2094. 'Received onCallEnded for invalid session',
  2095. jingleSession.sid,
  2096. jingleSession.remoteJid,
  2097. reasonCondition,
  2098. reasonText);
  2099. }
  2100. };
  2101. /**
  2102. * Handles the suspend detected event. Leaves the room and fires suspended.
  2103. * @param {JingleSessionPC} jingleSession
  2104. */
  2105. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  2106. if (!jingleSession.isP2P) {
  2107. this.leave();
  2108. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  2109. }
  2110. };
  2111. JitsiConference.prototype.updateDTMFSupport = function() {
  2112. let somebodySupportsDTMF = false;
  2113. const participants = this.getParticipants();
  2114. // check if at least 1 participant supports DTMF
  2115. for (let i = 0; i < participants.length; i += 1) {
  2116. if (participants[i].supportsDTMF()) {
  2117. somebodySupportsDTMF = true;
  2118. break;
  2119. }
  2120. }
  2121. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  2122. this.somebodySupportsDTMF = somebodySupportsDTMF;
  2123. this.eventEmitter.emit(
  2124. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  2125. somebodySupportsDTMF);
  2126. }
  2127. };
  2128. /**
  2129. * Allows to check if there is at least one user in the conference
  2130. * that supports DTMF.
  2131. * @returns {boolean} true if somebody supports DTMF, false otherwise
  2132. */
  2133. JitsiConference.prototype.isDTMFSupported = function() {
  2134. return this.somebodySupportsDTMF;
  2135. };
  2136. /**
  2137. * Returns the local user's ID
  2138. * @return {string} local user's ID
  2139. */
  2140. JitsiConference.prototype.myUserId = function() {
  2141. return (
  2142. this.room && this.room.myroomjid
  2143. ? Strophe.getResourceFromJid(this.room.myroomjid)
  2144. : null);
  2145. };
  2146. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  2147. const peerConnection = this.getActivePeerConnection();
  2148. if (peerConnection) {
  2149. peerConnection.sendTones(tones, duration, pause);
  2150. } else {
  2151. logger.warn('cannot sendTones: no peer connection');
  2152. }
  2153. };
  2154. /**
  2155. * Starts recording the current conference.
  2156. *
  2157. * @param {Object} options - Configuration for the recording. See
  2158. * {@link Chatroom#startRecording} for more info.
  2159. * @returns {Promise} See {@link Chatroom#startRecording} for more info.
  2160. */
  2161. JitsiConference.prototype.startRecording = function(options) {
  2162. if (this.room) {
  2163. return this.recordingManager.startRecording(options);
  2164. }
  2165. return Promise.reject(new Error('The conference is not created yet!'));
  2166. };
  2167. /**
  2168. * Stop a recording session.
  2169. *
  2170. * @param {string} sessionID - The ID of the recording session that
  2171. * should be stopped.
  2172. * @returns {Promise} See {@link Chatroom#stopRecording} for more info.
  2173. */
  2174. JitsiConference.prototype.stopRecording = function(sessionID) {
  2175. if (this.room) {
  2176. return this.recordingManager.stopRecording(sessionID);
  2177. }
  2178. return Promise.reject(new Error('The conference is not created yet!'));
  2179. };
  2180. /**
  2181. * Returns true if the SIP calls are supported and false otherwise
  2182. */
  2183. JitsiConference.prototype.isSIPCallingSupported = function() {
  2184. return this.room?.moderator?.isSipGatewayEnabled() ?? false;
  2185. };
  2186. /**
  2187. * Dials a number.
  2188. * @param number the number
  2189. */
  2190. JitsiConference.prototype.dial = function(number) {
  2191. if (this.room) {
  2192. return this.room.dial(number);
  2193. }
  2194. return new Promise((resolve, reject) => {
  2195. reject(new Error('The conference is not created yet!'));
  2196. });
  2197. };
  2198. /**
  2199. * Hangup an existing call
  2200. */
  2201. JitsiConference.prototype.hangup = function() {
  2202. if (this.room) {
  2203. return this.room.hangup();
  2204. }
  2205. return new Promise((resolve, reject) => {
  2206. reject(new Error('The conference is not created yet!'));
  2207. });
  2208. };
  2209. /**
  2210. * Starts the transcription service.
  2211. */
  2212. JitsiConference.prototype.startTranscriber = function() {
  2213. return this.dial('jitsi_meet_transcribe');
  2214. };
  2215. /**
  2216. * Stops the transcription service.
  2217. */
  2218. JitsiConference.prototype.stopTranscriber = JitsiConference.prototype.hangup;
  2219. /**
  2220. * Returns the phone number for joining the conference.
  2221. */
  2222. JitsiConference.prototype.getPhoneNumber = function() {
  2223. if (this.room) {
  2224. return this.room.getPhoneNumber();
  2225. }
  2226. return null;
  2227. };
  2228. /**
  2229. * Returns the pin for joining the conference with phone.
  2230. */
  2231. JitsiConference.prototype.getPhonePin = function() {
  2232. if (this.room) {
  2233. return this.room.getPhonePin();
  2234. }
  2235. return null;
  2236. };
  2237. /**
  2238. * Returns the meeting unique ID if any.
  2239. *
  2240. * @returns {string|undefined}
  2241. */
  2242. JitsiConference.prototype.getMeetingUniqueId = function() {
  2243. if (this.room) {
  2244. return this.room.getMeetingId();
  2245. }
  2246. };
  2247. /**
  2248. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  2249. * which connection is currently active.
  2250. *
  2251. * @return {TraceablePeerConnection|null} null if there isn't any active
  2252. * <tt>TraceablePeerConnection</tt> currently available.
  2253. * @public (FIXME how to make package local ?)
  2254. */
  2255. JitsiConference.prototype.getActivePeerConnection = function() {
  2256. const session = this.isP2PActive() ? this.p2pJingleSession : this.jvbJingleSession;
  2257. return session ? session.peerconnection : null;
  2258. };
  2259. /**
  2260. * Returns the connection state for the current room. Its ice connection state
  2261. * for its session.
  2262. * NOTE that "completed" ICE state which can appear on the P2P connection will
  2263. * be converted to "connected".
  2264. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  2265. * peer connection at this time.
  2266. */
  2267. JitsiConference.prototype.getConnectionState = function() {
  2268. const peerConnection = this.getActivePeerConnection();
  2269. return peerConnection ? peerConnection.getConnectionState() : null;
  2270. };
  2271. /**
  2272. * Make all new participants mute their audio/video on join.
  2273. * @param policy {Object} object with 2 boolean properties for video and audio:
  2274. * @param {boolean} audio if audio should be muted.
  2275. * @param {boolean} video if video should be muted.
  2276. */
  2277. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  2278. if (!this.isModerator()) {
  2279. logger.warn(`Failed to set start muted policy, ${this.room ? '' : 'not in a room, '}${
  2280. this.isModerator() ? '' : 'participant is not a moderator'}`);
  2281. return;
  2282. }
  2283. this.startMutedPolicy = policy;
  2284. this.room.addOrReplaceInPresence('startmuted', {
  2285. attributes: {
  2286. audio: policy.audio,
  2287. video: policy.video,
  2288. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  2289. }
  2290. }) && this.room.sendPresence();
  2291. };
  2292. /**
  2293. * Returns current start muted policy
  2294. * @returns {Object} with 2 properties - audio and video.
  2295. */
  2296. JitsiConference.prototype.getStartMutedPolicy = function() {
  2297. return this.startMutedPolicy;
  2298. };
  2299. /**
  2300. * Check if audio is muted on join.
  2301. */
  2302. JitsiConference.prototype.isStartAudioMuted = function() {
  2303. return this.startAudioMuted;
  2304. };
  2305. /**
  2306. * Check if video is muted on join.
  2307. */
  2308. JitsiConference.prototype.isStartVideoMuted = function() {
  2309. return this.startVideoMuted;
  2310. };
  2311. /**
  2312. * Returns measured connectionTimes.
  2313. */
  2314. JitsiConference.prototype.getConnectionTimes = function() {
  2315. return this.room.connectionTimes;
  2316. };
  2317. /**
  2318. * Sets a property for the local participant.
  2319. */
  2320. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  2321. this.sendCommand(`jitsi_participant_${name}`, { value });
  2322. };
  2323. /**
  2324. * Removes a property for the local participant and sends the updated presence.
  2325. */
  2326. JitsiConference.prototype.removeLocalParticipantProperty = function(name) {
  2327. this.removeCommand(`jitsi_participant_${name}`);
  2328. this.room.sendPresence();
  2329. };
  2330. /**
  2331. * Gets a local participant property.
  2332. *
  2333. * @return value of the local participant property if the tagName exists in the
  2334. * list of properties, otherwise returns undefined.
  2335. */
  2336. JitsiConference.prototype.getLocalParticipantProperty = function(name) {
  2337. const property = this.room.presMap.nodes.find(prop =>
  2338. prop.tagName === `jitsi_participant_${name}`
  2339. );
  2340. return property ? property.value : undefined;
  2341. };
  2342. /**
  2343. * Sends the given feedback through CallStats if enabled.
  2344. *
  2345. * @param overallFeedback an integer between 1 and 5 indicating the
  2346. * user feedback
  2347. * @param detailedFeedback detailed feedback from the user. Not yet used
  2348. * @returns {Promise} Resolves if feedback is submitted successfully.
  2349. */
  2350. JitsiConference.prototype.sendFeedback = function(overallFeedback, detailedFeedback) {
  2351. return this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  2352. };
  2353. /**
  2354. * Returns true if the callstats integration is enabled, otherwise returns
  2355. * false.
  2356. *
  2357. * @returns true if the callstats integration is enabled, otherwise returns
  2358. * false.
  2359. */
  2360. JitsiConference.prototype.isCallstatsEnabled = function() {
  2361. return this.statistics.isCallstatsEnabled();
  2362. };
  2363. /**
  2364. * Finds the SSRC of a given track
  2365. *
  2366. * @param track
  2367. * @returns {number|undefined} the SSRC of the specificed track, otherwise undefined.
  2368. */
  2369. JitsiConference.prototype.getSsrcByTrack = function(track) {
  2370. return track.isLocal() ? this.getActivePeerConnection()?.getLocalSSRC(track) : track.getSSRC();
  2371. };
  2372. /**
  2373. * Handles track attached to container (Calls associateStreamWithVideoTag method
  2374. * from statistics module)
  2375. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  2376. * @param container the container
  2377. */
  2378. JitsiConference.prototype._onTrackAttach = function(track, container) {
  2379. const isLocal = track.isLocal();
  2380. let ssrc = null;
  2381. const isP2P = track.isP2P;
  2382. const remoteUserId = isP2P ? track.getParticipantId() : 'jitsi';
  2383. const peerConnection
  2384. = isP2P
  2385. ? this.p2pJingleSession && this.p2pJingleSession.peerconnection
  2386. : this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  2387. if (isLocal) {
  2388. // Local tracks have SSRC stored on per peer connection basis.
  2389. if (peerConnection) {
  2390. ssrc = peerConnection.getLocalSSRC(track);
  2391. }
  2392. } else {
  2393. ssrc = track.getSSRC();
  2394. }
  2395. if (!container.id || !ssrc || !peerConnection) {
  2396. return;
  2397. }
  2398. this.statistics.associateStreamWithVideoTag(
  2399. peerConnection,
  2400. ssrc,
  2401. isLocal,
  2402. remoteUserId,
  2403. track.getUsageLabel(),
  2404. container.id);
  2405. };
  2406. /**
  2407. * Logs an "application log" message.
  2408. * @param message {string} The message to log. Note that while this can be a
  2409. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  2410. * log valid JSON strings, with an "id" field used for distinguishing between
  2411. * message types. E.g.: {id: "recorder_status", status: "off"}
  2412. */
  2413. JitsiConference.prototype.sendApplicationLog = function(message) {
  2414. Statistics.sendLog(message);
  2415. };
  2416. /**
  2417. * Checks if the user identified by given <tt>mucJid</tt> is the conference focus.
  2418. * @param mucJid the full MUC address of the user to be checked.
  2419. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  2420. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  2421. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  2422. */
  2423. JitsiConference.prototype.isFocus = function(mucJid) {
  2424. return this.room ? this.room.isFocus(mucJid) : null;
  2425. };
  2426. /**
  2427. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  2428. */
  2429. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  2430. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  2431. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  2432. };
  2433. /**
  2434. * Sends a message via the data channel.
  2435. * @param to {string} the id of the endpoint that should receive the message.
  2436. * If "" the message will be sent to all participants.
  2437. * @param payload {object} the payload of the message.
  2438. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2439. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2440. */
  2441. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  2442. this.rtc.sendChannelMessage(to, payload);
  2443. };
  2444. /**
  2445. * Sends local stats via the bridge channel which then forwards to other endpoints selectively.
  2446. * @param {Object} payload The payload of the message.
  2447. * @throws NetworkError/InvalidStateError/Error if the operation fails or if there is no data channel created.
  2448. */
  2449. JitsiConference.prototype.sendEndpointStatsMessage = function(payload) {
  2450. this.rtc.sendEndpointStatsMessage(payload);
  2451. };
  2452. /**
  2453. * Sends a broadcast message via the data channel.
  2454. * @param payload {object} the payload of the message.
  2455. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2456. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2457. */
  2458. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  2459. this.sendEndpointMessage('', payload);
  2460. };
  2461. /**
  2462. * Sends a message to a given endpoint (if 'to' is a non-empty string), or
  2463. * broadcasts it to all endpoints in the conference.
  2464. * @param {string} to The ID of the endpoint/participant which is to receive
  2465. * the message, or '' to broadcast the message to all endpoints in the
  2466. * conference.
  2467. * @param {string|object} message the message to send. If this is of type
  2468. * 'string' it will be sent as a chat message. If it is of type 'object', it
  2469. * will be encapsulated in a format recognized by jitsi-meet and converted to
  2470. * JSON before being sent.
  2471. * @param {boolean} sendThroughVideobridge Whether to send the message through
  2472. * jitsi-videobridge (via the COLIBRI data channel or web socket), or through
  2473. * the XMPP MUC. Currently only objects can be sent through jitsi-videobridge.
  2474. */
  2475. JitsiConference.prototype.sendMessage = function(message, to = '', sendThroughVideobridge = false) {
  2476. const messageType = typeof message;
  2477. // Through videobridge we support only objects. Through XMPP we support
  2478. // objects (encapsulated in a specific JSON format) and strings (i.e.
  2479. // regular chat messages).
  2480. if (messageType !== 'object'
  2481. && (sendThroughVideobridge || messageType !== 'string')) {
  2482. logger.error(`Can not send a message of type ${messageType}`);
  2483. return;
  2484. }
  2485. if (sendThroughVideobridge) {
  2486. this.sendEndpointMessage(to, message);
  2487. } else {
  2488. let messageToSend = message;
  2489. // Name of packet extension of message stanza to send the required
  2490. // message in.
  2491. let elementName = 'body';
  2492. if (messageType === 'object') {
  2493. elementName = 'json-message';
  2494. // Mark as valid JSON message if not already
  2495. if (!messageToSend.hasOwnProperty(JITSI_MEET_MUC_TYPE)) {
  2496. messageToSend[JITSI_MEET_MUC_TYPE] = '';
  2497. }
  2498. try {
  2499. messageToSend = JSON.stringify(messageToSend);
  2500. } catch (e) {
  2501. logger.error('Can not send a message, stringify failed: ', e);
  2502. return;
  2503. }
  2504. }
  2505. if (to) {
  2506. this.sendPrivateTextMessage(to, messageToSend, elementName);
  2507. } else {
  2508. // Broadcast
  2509. this.sendTextMessage(messageToSend, elementName);
  2510. }
  2511. }
  2512. };
  2513. JitsiConference.prototype.isConnectionInterrupted = function() {
  2514. return this.isP2PActive()
  2515. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  2516. };
  2517. /**
  2518. * Handles {@link XMPPEvents.CONNECTION_RESTARTED} event. This happens when the bridge goes down
  2519. * and Jicofo moves conferences away to a different bridge.
  2520. * @param {JingleSessionPC} session
  2521. * @private
  2522. */
  2523. JitsiConference.prototype._onConferenceRestarted = function(session) {
  2524. if (!session.isP2P && this.options.config.enableForcedReload) {
  2525. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONFERENCE_RESTARTED);
  2526. }
  2527. };
  2528. /**
  2529. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  2530. * @param {JingleSessionPC} session
  2531. * @private
  2532. */
  2533. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  2534. if (session.isP2P) {
  2535. this.isP2PConnectionInterrupted = true;
  2536. } else {
  2537. this.isJvbConnectionInterrupted = true;
  2538. }
  2539. if (session.isP2P === this.isP2PActive()) {
  2540. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  2541. }
  2542. };
  2543. /**
  2544. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  2545. * @param {JingleSessionPC} session
  2546. * @private
  2547. */
  2548. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  2549. // We do nothing for the JVB connection, because it's up to the Jicofo to
  2550. // eventually come up with the new offer (at least for the time being).
  2551. if (session.isP2P) {
  2552. // Add p2pFailed property to analytics to distinguish, between "good"
  2553. // and "bad" connection
  2554. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2555. if (this.p2pJingleSession) {
  2556. Statistics.sendAnalyticsAndLog(
  2557. createP2PEvent(
  2558. ACTION_P2P_FAILED,
  2559. {
  2560. initiator: this.p2pJingleSession.isInitiator
  2561. }));
  2562. }
  2563. this._stopP2PSession({
  2564. reason: 'connectivity-error',
  2565. reasonDescription: 'ICE FAILED'
  2566. });
  2567. } else if (session && this.jvbJingleSession === session) {
  2568. this._delayedIceFailed = new IceFailedHandling(this);
  2569. this._delayedIceFailed.start(session);
  2570. }
  2571. };
  2572. /**
  2573. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  2574. * @param {JingleSessionPC} session
  2575. * @private
  2576. */
  2577. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  2578. if (session.isP2P) {
  2579. this.isP2PConnectionInterrupted = false;
  2580. } else {
  2581. this.isJvbConnectionInterrupted = false;
  2582. this._delayedIceFailed && this._delayedIceFailed.cancel();
  2583. }
  2584. if (session.isP2P === this.isP2PActive()) {
  2585. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  2586. }
  2587. };
  2588. /**
  2589. * Accept incoming P2P Jingle call.
  2590. * @param {JingleSessionPC} jingleSession the session instance
  2591. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  2592. * @private
  2593. */
  2594. JitsiConference.prototype._acceptP2PIncomingCall = function(jingleSession, jingleOffer) {
  2595. this.isP2PConnectionInterrupted = false;
  2596. // Accept the offer
  2597. this.p2pJingleSession = jingleSession;
  2598. this._sendConferenceJoinAnalyticsEvent();
  2599. this.p2pJingleSession.initialize(
  2600. this.room,
  2601. this.rtc,
  2602. this._signalingLayer,
  2603. {
  2604. ...this.options.config,
  2605. enableInsertableStreams: this.isE2EEEnabled() || FeatureFlags.isRunInLiteModeEnabled()
  2606. });
  2607. logger.info('Starting CallStats for P2P connection...');
  2608. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2609. const participant = this.participants.get(remoteID);
  2610. if (participant) {
  2611. remoteID = participant.getStatsID() || remoteID;
  2612. }
  2613. this.statistics.startCallStats(
  2614. this.p2pJingleSession.peerconnection,
  2615. remoteID);
  2616. const localTracks = this.getLocalTracks();
  2617. this.p2pJingleSession.acceptOffer(
  2618. jingleOffer,
  2619. () => {
  2620. logger.debug('Got RESULT for P2P "session-accept"');
  2621. this.eventEmitter.emit(
  2622. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  2623. jingleSession);
  2624. },
  2625. error => {
  2626. logger.error(
  2627. 'Failed to accept incoming P2P Jingle session', error);
  2628. },
  2629. localTracks);
  2630. };
  2631. /**
  2632. * Adds remote tracks to the conference associated with the JVB session.
  2633. * @private
  2634. */
  2635. JitsiConference.prototype._addRemoteJVBTracks = function() {
  2636. this._addRemoteTracks('JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2637. };
  2638. /**
  2639. * Adds remote tracks to the conference associated with the P2P session.
  2640. * @private
  2641. */
  2642. JitsiConference.prototype._addRemoteP2PTracks = function() {
  2643. this._addRemoteTracks('P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2644. };
  2645. /**
  2646. * Generates fake "remote track added" events for given Jingle session.
  2647. * @param {string} logName the session's nickname which will appear in log
  2648. * messages.
  2649. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  2650. * @private
  2651. */
  2652. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  2653. for (const track of remoteTracks) {
  2654. logger.info(`Adding remote ${logName} track: ${track}`);
  2655. this.onRemoteTrackAdded(track);
  2656. }
  2657. };
  2658. /**
  2659. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  2660. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  2661. * the P2P connection if the event comes from the P2P session.
  2662. * @param {JingleSessionPC} jingleSession the session instance.
  2663. * @private
  2664. */
  2665. JitsiConference.prototype._onIceConnectionEstablished = function(jingleSession) {
  2666. if (this.p2pJingleSession !== null) {
  2667. // store the establishment time of the p2p session as a field of the
  2668. // JitsiConference because the p2pJingleSession might get disposed (thus
  2669. // the value is lost).
  2670. this.p2pEstablishmentDuration
  2671. = this.p2pJingleSession.establishmentDuration;
  2672. }
  2673. if (this.jvbJingleSession !== null) {
  2674. this.jvbEstablishmentDuration
  2675. = this.jvbJingleSession.establishmentDuration;
  2676. }
  2677. let done = false;
  2678. const forceJVB121Ratio = this.options.config.forceJVB121Ratio;
  2679. // We don't care about the JVB case, there's nothing to be done
  2680. if (!jingleSession.isP2P) {
  2681. done = true;
  2682. } else if (this.p2pJingleSession !== jingleSession) {
  2683. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  2684. done = true;
  2685. } else if (!jingleSession.isInitiator
  2686. && typeof forceJVB121Ratio === 'number'
  2687. && Math.random() < forceJVB121Ratio) {
  2688. logger.info(`Forcing JVB 121 mode (ratio=${forceJVB121Ratio})...`);
  2689. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  2690. this._stopP2PSession({
  2691. reason: 'decline',
  2692. reasonDescription: 'force JVB121'
  2693. });
  2694. done = true;
  2695. }
  2696. if (!isNaN(this.p2pEstablishmentDuration)
  2697. && !isNaN(this.jvbEstablishmentDuration)) {
  2698. const establishmentDurationDiff
  2699. = this.p2pEstablishmentDuration - this.jvbEstablishmentDuration;
  2700. Statistics.sendAnalytics(
  2701. ICE_ESTABLISHMENT_DURATION_DIFF,
  2702. { value: establishmentDurationDiff });
  2703. }
  2704. if (jingleSession.isP2P === this.isP2PActive()) {
  2705. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_ESTABLISHED);
  2706. }
  2707. if (done) {
  2708. return;
  2709. }
  2710. // Update P2P status and emit events
  2711. this._setP2PStatus(true);
  2712. // Remove remote tracks
  2713. if (this.jvbJingleSession) {
  2714. this._removeRemoteJVBTracks();
  2715. } else {
  2716. logger.info('Not removing remote JVB tracks - no session yet');
  2717. }
  2718. this._addRemoteP2PTracks();
  2719. // Stop media transfer over the JVB connection
  2720. if (this.jvbJingleSession) {
  2721. this._suspendMediaTransferForJvbConnection();
  2722. }
  2723. logger.info('Starting remote stats with p2p connection');
  2724. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  2725. Statistics.sendAnalyticsAndLog(
  2726. createP2PEvent(
  2727. ACTION_P2P_ESTABLISHED,
  2728. {
  2729. initiator: this.p2pJingleSession.isInitiator
  2730. }));
  2731. };
  2732. /**
  2733. * Called when the chat room reads a new list of properties from jicofo's
  2734. * presence. The properties may have changed, but they don't have to.
  2735. *
  2736. * @param {Object} properties - The properties keyed by the property name
  2737. * ('key').
  2738. * @private
  2739. */
  2740. JitsiConference.prototype._updateProperties = function(properties = {}) {
  2741. const changed = !isEqual(properties, this.properties);
  2742. this.properties = properties;
  2743. if (changed) {
  2744. this.eventEmitter.emit(JitsiConferenceEvents.PROPERTIES_CHANGED, this.properties);
  2745. const audioLimitReached = this.properties['audio-limit-reached'] === 'true';
  2746. const videoLimitReached = this.properties['video-limit-reached'] === 'true';
  2747. if (this._audioSenderLimitReached !== audioLimitReached) {
  2748. this._audioSenderLimitReached = audioLimitReached;
  2749. this.eventEmitter.emit(JitsiConferenceEvents.AUDIO_UNMUTE_PERMISSIONS_CHANGED, audioLimitReached);
  2750. logger.info(`Audio unmute permissions set by Jicofo to ${audioLimitReached}`);
  2751. }
  2752. if (this._videoSenderLimitReached !== videoLimitReached) {
  2753. this._videoSenderLimitReached = videoLimitReached;
  2754. this.eventEmitter.emit(JitsiConferenceEvents.VIDEO_UNMUTE_PERMISSIONS_CHANGED, videoLimitReached);
  2755. logger.info(`Video unmute permissions set by Jicofo to ${videoLimitReached}`);
  2756. }
  2757. // Some of the properties need to be added to analytics events.
  2758. const analyticsKeys = [
  2759. // The number of jitsi-videobridge instances currently used for the
  2760. // conference.
  2761. 'bridge-count'
  2762. ];
  2763. analyticsKeys.forEach(key => {
  2764. if (properties[key] !== undefined) {
  2765. Statistics.analytics.addPermanentProperties({
  2766. [key.replace('-', '_')]: properties[key]
  2767. });
  2768. }
  2769. });
  2770. }
  2771. };
  2772. /**
  2773. * Gets a conference property with a given key.
  2774. *
  2775. * @param {string} key - The key.
  2776. * @returns {*} The value
  2777. */
  2778. JitsiConference.prototype.getProperty = function(key) {
  2779. return this.properties[key];
  2780. };
  2781. /**
  2782. * Clears the deferred start P2P task if it has been scheduled.
  2783. * @private
  2784. */
  2785. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  2786. if (this.deferredStartP2PTask) {
  2787. logger.info('Cleared deferred start P2P task');
  2788. clearTimeout(this.deferredStartP2PTask);
  2789. this.deferredStartP2PTask = null;
  2790. }
  2791. };
  2792. /**
  2793. * Removes from the conference remote tracks associated with the JVB
  2794. * connection.
  2795. * @private
  2796. */
  2797. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  2798. this._removeRemoteTracks(
  2799. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2800. };
  2801. /**
  2802. * Removes from the conference remote tracks associated with the P2P
  2803. * connection.
  2804. * @private
  2805. */
  2806. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  2807. this._removeRemoteTracks(
  2808. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2809. };
  2810. /**
  2811. * Generates fake "remote track removed" events for given Jingle session.
  2812. * @param {string} sessionNickname the session's nickname which will appear in
  2813. * log messages.
  2814. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  2815. * @private
  2816. */
  2817. JitsiConference.prototype._removeRemoteTracks = function(sessionNickname, remoteTracks) {
  2818. for (const track of remoteTracks) {
  2819. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  2820. this.onRemoteTrackRemoved(track);
  2821. }
  2822. };
  2823. /**
  2824. * Resumes media transfer over the JVB connection.
  2825. * @private
  2826. */
  2827. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  2828. logger.info('Resuming media transfer over the JVB connection...');
  2829. this.jvbJingleSession.setMediaTransferActive(true)
  2830. .then(() => {
  2831. logger.info('Resumed media transfer over the JVB connection!');
  2832. })
  2833. .catch(error => {
  2834. logger.error('Failed to resume media transfer over the JVB connection:', error);
  2835. });
  2836. };
  2837. /**
  2838. * Sets new P2P status and updates some events/states hijacked from
  2839. * the <tt>JitsiConference</tt>.
  2840. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  2841. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  2842. * @private
  2843. */
  2844. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  2845. if (this.p2p === newStatus) {
  2846. logger.debug(`Called _setP2PStatus with the same status: ${newStatus}`);
  2847. return;
  2848. }
  2849. this.p2p = newStatus;
  2850. if (newStatus) {
  2851. logger.info('Peer to peer connection established!');
  2852. // When we end up in a valid P2P session need to reset the properties
  2853. // in case they have persisted, after session with another peer.
  2854. Statistics.analytics.addPermanentProperties({
  2855. p2pFailed: false,
  2856. forceJvb121: false
  2857. });
  2858. // Sync up video transfer active in case p2pJingleSession not existed
  2859. // when the lastN value was being adjusted.
  2860. const isVideoActive = this.getLastN() !== 0;
  2861. this.p2pJingleSession.setP2pVideoTransferActive(isVideoActive)
  2862. .catch(error => {
  2863. logger.error(`Failed to sync up P2P video transfer status (${isVideoActive}), ${error}`);
  2864. });
  2865. } else {
  2866. logger.info('Peer to peer connection closed!');
  2867. }
  2868. // Put the JVB connection on hold/resume
  2869. if (this.jvbJingleSession) {
  2870. this.statistics.sendConnectionResumeOrHoldEvent(
  2871. this.jvbJingleSession.peerconnection, !newStatus);
  2872. }
  2873. // Clear dtmfManager, so that it can be recreated with new connection
  2874. this.dtmfManager = null;
  2875. // Update P2P status
  2876. this.eventEmitter.emit(
  2877. JitsiConferenceEvents.P2P_STATUS,
  2878. this,
  2879. this.p2p);
  2880. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED, this.getActiveMediaSession());
  2881. // Refresh connection interrupted/restored
  2882. this.eventEmitter.emit(
  2883. this.isConnectionInterrupted()
  2884. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  2885. : JitsiConferenceEvents.CONNECTION_RESTORED);
  2886. };
  2887. /**
  2888. * Starts new P2P session.
  2889. * @param {string} remoteJid the JID of the remote participant
  2890. * @private
  2891. */
  2892. JitsiConference.prototype._startP2PSession = function(remoteJid) {
  2893. this._maybeClearDeferredStartP2P();
  2894. if (this.p2pJingleSession) {
  2895. logger.error('P2P session already started!');
  2896. return;
  2897. }
  2898. this.isP2PConnectionInterrupted = false;
  2899. this.p2pJingleSession
  2900. = this.xmpp.connection.jingle.newP2PJingleSession(
  2901. this.room.myroomjid,
  2902. remoteJid);
  2903. logger.info(
  2904. 'Created new P2P JingleSession', this.room.myroomjid, remoteJid);
  2905. this._sendConferenceJoinAnalyticsEvent();
  2906. this.p2pJingleSession.initialize(
  2907. this.room,
  2908. this.rtc,
  2909. this._signalingLayer,
  2910. {
  2911. ...this.options.config,
  2912. enableInsertableStreams: this.isE2EEEnabled() || FeatureFlags.isRunInLiteModeEnabled()
  2913. });
  2914. logger.info('Starting CallStats for P2P connection...');
  2915. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2916. const participant = this.participants.get(remoteID);
  2917. if (participant) {
  2918. remoteID = participant.getStatsID() || remoteID;
  2919. }
  2920. this.statistics.startCallStats(
  2921. this.p2pJingleSession.peerconnection,
  2922. remoteID);
  2923. const localTracks = this.getLocalTracks();
  2924. this.p2pJingleSession.invite(localTracks);
  2925. };
  2926. /**
  2927. * Suspends media transfer over the JVB connection.
  2928. * @private
  2929. */
  2930. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  2931. logger.info('Suspending media transfer over the JVB connection...');
  2932. this.jvbJingleSession.setMediaTransferActive(false)
  2933. .then(() => {
  2934. logger.info('Suspended media transfer over the JVB connection !');
  2935. })
  2936. .catch(error => {
  2937. logger.error('Failed to suspend media transfer over the JVB connection:', error);
  2938. });
  2939. };
  2940. /**
  2941. * Method when called will decide whether it's the time to start or stop
  2942. * the P2P session.
  2943. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  2944. * originates from the user left event.
  2945. * @private
  2946. */
  2947. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  2948. if (!this.isP2PEnabled()
  2949. || this.isP2PTestModeEnabled()
  2950. || browser.isFirefox()
  2951. || browser.isWebKitBased()
  2952. || this.isE2EEEnabled()) {
  2953. logger.info('Auto P2P disabled');
  2954. return;
  2955. }
  2956. const peers = this.getParticipants();
  2957. const peerCount = peers.length;
  2958. // FIXME 1 peer and it must *support* P2P switching
  2959. const shouldBeInP2P = this._shouldBeInP2PMode();
  2960. // Clear deferred "start P2P" task
  2961. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  2962. this._maybeClearDeferredStartP2P();
  2963. }
  2964. // Start peer to peer session
  2965. if (!this.p2pJingleSession && shouldBeInP2P) {
  2966. const peer = peerCount && peers[0];
  2967. const myId = this.myUserId();
  2968. const peersId = peer.getId();
  2969. if (myId > peersId) {
  2970. logger.debug(
  2971. 'I\'m the bigger peersId - '
  2972. + 'the other peer should start P2P', myId, peersId);
  2973. return;
  2974. } else if (myId === peersId) {
  2975. logger.error('The same IDs ? ', myId, peersId);
  2976. return;
  2977. }
  2978. const jid = peer.getJid();
  2979. if (userLeftEvent) {
  2980. if (this.deferredStartP2PTask) {
  2981. logger.error('Deferred start P2P task\'s been set already!');
  2982. return;
  2983. }
  2984. logger.info(
  2985. `Will start P2P with: ${jid} after ${
  2986. this.backToP2PDelay} seconds...`);
  2987. this.deferredStartP2PTask = setTimeout(
  2988. this._startP2PSession.bind(this, jid),
  2989. this.backToP2PDelay * 1000);
  2990. } else {
  2991. logger.info(`Will start P2P with: ${jid}`);
  2992. this._startP2PSession(jid);
  2993. }
  2994. } else if (this.p2pJingleSession && !shouldBeInP2P) {
  2995. logger.info(`Will stop P2P with: ${this.p2pJingleSession.remoteJid}`);
  2996. // Log that there will be a switch back to the JVB connection
  2997. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  2998. Statistics.sendAnalyticsAndLog(
  2999. createP2PEvent(ACTION_P2P_SWITCH_TO_JVB));
  3000. }
  3001. this._stopP2PSession();
  3002. }
  3003. };
  3004. /**
  3005. * Tells whether or not this conference should be currently in the P2P mode.
  3006. *
  3007. * @private
  3008. * @returns {boolean}
  3009. */
  3010. JitsiConference.prototype._shouldBeInP2PMode = function() {
  3011. const peers = this.getParticipants();
  3012. const peerCount = peers.length;
  3013. const hasBotPeer = peers.find(p => p.getBotType() === 'poltergeist' || p.hasFeature(FEATURE_JIGASI)) !== undefined;
  3014. const shouldBeInP2P = peerCount === 1 && !hasBotPeer;
  3015. logger.debug(`P2P? peerCount: ${peerCount}, hasBotPeer: ${hasBotPeer} => ${shouldBeInP2P}`);
  3016. return shouldBeInP2P;
  3017. };
  3018. /**
  3019. * Stops the current P2P session.
  3020. * @param {Object} options - Options for stopping P2P.
  3021. * @param {string} options.reason - One of the Jingle "reason" element
  3022. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  3023. * @param {string} options.reasonDescription - Text
  3024. * description that will be included in the session terminate message
  3025. * @param {boolean} requestRestart - Whether this is due to a session restart, in which case
  3026. * media will not be resumed on the JVB.
  3027. * @private
  3028. */
  3029. JitsiConference.prototype._stopP2PSession = function(options = {}) {
  3030. const {
  3031. reason = 'success',
  3032. reasonDescription = 'Turning off P2P session',
  3033. requestRestart = false
  3034. } = options;
  3035. if (!this.p2pJingleSession) {
  3036. logger.error('No P2P session to be stopped!');
  3037. return;
  3038. }
  3039. const wasP2PEstablished = this.isP2PActive();
  3040. // Swap remote tracks, but only if the P2P has been fully established
  3041. if (wasP2PEstablished) {
  3042. if (this.jvbJingleSession && !requestRestart) {
  3043. this._resumeMediaTransferForJvbConnection();
  3044. }
  3045. // Remove remote P2P tracks
  3046. this._removeRemoteP2PTracks();
  3047. }
  3048. // Stop P2P stats
  3049. logger.info('Stopping remote stats for P2P connection');
  3050. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  3051. logger.info('Stopping CallStats for P2P connection');
  3052. this.statistics.stopCallStats(this.p2pJingleSession.peerconnection);
  3053. this.p2pJingleSession.terminate(
  3054. () => {
  3055. logger.info('P2P session terminate RESULT');
  3056. },
  3057. error => {
  3058. // Because both initiator and responder are simultaneously
  3059. // terminating their JingleSessions in case of the 'to JVB switch'
  3060. // when 3rd participant joins, both will dispose their sessions and
  3061. // reply with 'item-not-found' (see strophe.jingle.js). We don't
  3062. // want to log this as an error since it's expected behaviour.
  3063. //
  3064. // We want them both to terminate, because in case of initiator's
  3065. // crash the responder would stay in P2P mode until ICE fails which
  3066. // could take up to 20 seconds.
  3067. //
  3068. // NOTE: whilst this is an error callback, 'success' as a reason is
  3069. // considered as graceful session terminate
  3070. // where both initiator and responder terminate their sessions
  3071. // simultaneously.
  3072. if (reason !== 'success') {
  3073. logger.error('An error occurred while trying to terminate P2P Jingle session', error);
  3074. }
  3075. }, {
  3076. reason,
  3077. reasonDescription,
  3078. sendSessionTerminate: this.room
  3079. && this.getParticipantById(
  3080. Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid))
  3081. });
  3082. this.p2pJingleSession = null;
  3083. // Update P2P status and other affected events/states
  3084. this._setP2PStatus(false);
  3085. if (wasP2PEstablished) {
  3086. // Add back remote JVB tracks
  3087. if (this.jvbJingleSession && !requestRestart) {
  3088. this._addRemoteJVBTracks();
  3089. } else {
  3090. logger.info('Not adding remote JVB tracks - no session yet');
  3091. }
  3092. }
  3093. };
  3094. /**
  3095. * Updates room presence if needed and send the packet in case of a modification.
  3096. * @param {JingleSessionPC} jingleSession the session firing the event, contains the peer connection which
  3097. * tracks we will check.
  3098. * @param {Object|null} ctx a context object we can distinguish multiple calls of the same pass of updating tracks.
  3099. */
  3100. JitsiConference.prototype._updateRoomPresence = function(jingleSession, ctx) {
  3101. if (!jingleSession) {
  3102. return;
  3103. }
  3104. // skips sending presence twice for the same pass of updating ssrcs
  3105. if (ctx) {
  3106. if (ctx.skip) {
  3107. return;
  3108. }
  3109. ctx.skip = true;
  3110. }
  3111. let presenceChanged = false;
  3112. let muteStatusChanged, videoTypeChanged;
  3113. const localTracks = jingleSession.peerconnection.getLocalTracks();
  3114. // Set presence for all the available local tracks.
  3115. for (const track of localTracks) {
  3116. muteStatusChanged = this._setTrackMuteStatus(track.getType(), track, track.isMuted());
  3117. if (track.getType() === MediaType.VIDEO) {
  3118. videoTypeChanged = this._setNewVideoType(track);
  3119. }
  3120. presenceChanged = presenceChanged || muteStatusChanged || videoTypeChanged;
  3121. }
  3122. presenceChanged && this.room.sendPresence();
  3123. };
  3124. /**
  3125. * Checks whether or not the conference is currently in the peer to peer mode.
  3126. * Being in peer to peer mode means that the direct connection has been
  3127. * established and the P2P connection is being used for media transmission.
  3128. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  3129. */
  3130. JitsiConference.prototype.isP2PActive = function() {
  3131. return this.p2p;
  3132. };
  3133. /**
  3134. * Returns the current ICE state of the P2P connection.
  3135. * NOTE: method is used by the jitsi-meet-torture tests.
  3136. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  3137. * no P2P connection.
  3138. */
  3139. JitsiConference.prototype.getP2PConnectionState = function() {
  3140. if (this.isP2PActive()) {
  3141. return this.p2pJingleSession.peerconnection.getConnectionState();
  3142. }
  3143. return null;
  3144. };
  3145. /**
  3146. * Configures the peerconnection so that a given framre rate can be achieved for desktop share.
  3147. *
  3148. * @param {number} maxFps The capture framerate to be used for desktop tracks.
  3149. * @returns {boolean} true if the operation is successful, false otherwise.
  3150. */
  3151. JitsiConference.prototype.setDesktopSharingFrameRate = function(maxFps) {
  3152. if (typeof maxFps !== 'number' || isNaN(maxFps)) {
  3153. logger.error(`Invalid value ${maxFps} specified for desktop capture frame rate`);
  3154. return false;
  3155. }
  3156. this._desktopSharingFrameRate = maxFps;
  3157. // Enable or disable simulcast for plan-b screensharing based on the capture fps.
  3158. this.jvbJingleSession && this.jvbJingleSession.peerconnection.setDesktopSharingFrameRate(maxFps);
  3159. // Set the capture rate for desktop sharing.
  3160. this.rtc.setDesktopSharingFrameRate(maxFps);
  3161. return true;
  3162. };
  3163. /**
  3164. * Manually starts new P2P session (should be used only in the tests).
  3165. */
  3166. JitsiConference.prototype.startP2PSession = function() {
  3167. const peers = this.getParticipants();
  3168. // Start peer to peer session
  3169. if (peers.length === 1) {
  3170. const peerJid = peers[0].getJid();
  3171. this._startP2PSession(peerJid);
  3172. } else {
  3173. throw new Error(
  3174. 'There must be exactly 1 participant to start the P2P session !');
  3175. }
  3176. };
  3177. /**
  3178. * Manually stops the current P2P session (should be used only in the tests).
  3179. */
  3180. JitsiConference.prototype.stopP2PSession = function(options) {
  3181. this._stopP2PSession(options);
  3182. };
  3183. /**
  3184. * Get a summary of how long current participants have been the dominant speaker
  3185. * @returns {object}
  3186. */
  3187. JitsiConference.prototype.getSpeakerStats = function() {
  3188. return this.speakerStatsCollector.getStats();
  3189. };
  3190. /**
  3191. * Sends a face landmarks object to the xmpp server.
  3192. * @param {Object} payload
  3193. */
  3194. JitsiConference.prototype.sendFaceLandmarks = function(payload) {
  3195. if (payload.faceExpression) {
  3196. this.xmpp.sendFaceLandmarksEvent(this.room.roomjid, payload);
  3197. }
  3198. };
  3199. /**
  3200. * Sets the constraints for the video that is requested from the bridge.
  3201. *
  3202. * @param {Object} videoConstraints The constraints which are specified in the
  3203. * following format. The message updates the fields that are present and leaves the
  3204. * rest unchanged on the bridge. Therefore, any field that is not applicable anymore
  3205. * should be cleared by passing an empty object or list (whatever is applicable).
  3206. * {
  3207. * 'lastN': 20,
  3208. * 'selectedEndpoints': ['A', 'B', 'C'],
  3209. * 'onStageEndpoints': ['A'],
  3210. * 'defaultConstraints': { 'maxHeight': 180 },
  3211. * 'constraints': {
  3212. * 'A': { 'maxHeight': 720 }
  3213. * }
  3214. * }
  3215. */
  3216. JitsiConference.prototype.setReceiverConstraints = function(videoConstraints) {
  3217. this.receiveVideoController.setReceiverConstraints(videoConstraints);
  3218. };
  3219. /**
  3220. * Sets the maximum video size the local participant should receive from remote
  3221. * participants.
  3222. *
  3223. * @param {number} maxFrameHeight - the maximum frame height, in pixels,
  3224. * this receiver is willing to receive.
  3225. * @returns {void}
  3226. */
  3227. JitsiConference.prototype.setReceiverVideoConstraint = function(maxFrameHeight) {
  3228. this.receiveVideoController.setPreferredReceiveMaxFrameHeight(maxFrameHeight);
  3229. };
  3230. /**
  3231. * Sets the maximum video size the local participant should send to remote
  3232. * participants.
  3233. * @param {number} maxFrameHeight - The user preferred max frame height.
  3234. * @returns {Promise} promise that will be resolved when the operation is
  3235. * successful and rejected otherwise.
  3236. */
  3237. JitsiConference.prototype.setSenderVideoConstraint = function(maxFrameHeight) {
  3238. return this.sendVideoController.setPreferredSendMaxFrameHeight(maxFrameHeight);
  3239. };
  3240. /**
  3241. * Creates a video SIP GW session and returns it if service is enabled. Before
  3242. * creating a session one need to check whether video SIP GW service is
  3243. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  3244. * if there are available nodes to serve this request, after creating the
  3245. * session those nodes can be taken and the request about using the
  3246. * created session can fail.
  3247. *
  3248. * @param {string} sipAddress - The sip address to be used.
  3249. * @param {string} displayName - The display name to be used for this session.
  3250. * @returns {JitsiVideoSIPGWSession|Error} Returns null if conference is not
  3251. * initialised and there is no room.
  3252. */
  3253. JitsiConference.prototype.createVideoSIPGWSession = function(sipAddress, displayName) {
  3254. if (!this.room) {
  3255. return new Error(VideoSIPGWConstants.ERROR_NO_CONNECTION);
  3256. }
  3257. return this.videoSIPGWHandler
  3258. .createVideoSIPGWSession(sipAddress, displayName);
  3259. };
  3260. /**
  3261. * Sends a conference.join analytics event.
  3262. *
  3263. * @returns {void}
  3264. */
  3265. JitsiConference.prototype._sendConferenceJoinAnalyticsEvent = function() {
  3266. const meetingId = this.getMeetingUniqueId();
  3267. if (this._conferenceJoinAnalyticsEventSent || !meetingId || this.getActivePeerConnection() === null) {
  3268. return;
  3269. }
  3270. Statistics.sendAnalytics(createConferenceEvent('joined', {
  3271. meetingId,
  3272. participantId: `${meetingId}.${this._statsCurrentId}`
  3273. }));
  3274. this._conferenceJoinAnalyticsEventSent = Date.now();
  3275. };
  3276. /**
  3277. * Sends conference.left analytics event.
  3278. * @private
  3279. */
  3280. JitsiConference.prototype._sendConferenceLeftAnalyticsEvent = function() {
  3281. const meetingId = this.getMeetingUniqueId();
  3282. if (!meetingId || !this._conferenceJoinAnalyticsEventSent) {
  3283. return;
  3284. }
  3285. Statistics.sendAnalytics(createConferenceEvent('left', {
  3286. meetingId,
  3287. participantId: `${meetingId}.${this._statsCurrentId}`,
  3288. stats: {
  3289. duration: Math.floor((Date.now() - this._conferenceJoinAnalyticsEventSent) / 1000),
  3290. perf: this.getPerformanceStats()
  3291. }
  3292. }));
  3293. };
  3294. /**
  3295. * Restarts all active media sessions.
  3296. *
  3297. * @returns {void}
  3298. */
  3299. JitsiConference.prototype._restartMediaSessions = function() {
  3300. if (this.p2pJingleSession) {
  3301. this._stopP2PSession({
  3302. reasonDescription: 'restart',
  3303. requestRestart: true
  3304. });
  3305. }
  3306. if (this.jvbJingleSession) {
  3307. this.jvbJingleSession.terminate(
  3308. null /* success callback => we don't care */,
  3309. error => {
  3310. logger.warn('An error occurred while trying to terminate the JVB session', error);
  3311. }, {
  3312. reason: 'success',
  3313. reasonDescription: 'restart required',
  3314. requestRestart: true,
  3315. sendSessionTerminate: true
  3316. });
  3317. }
  3318. this._maybeStartOrStopP2P(false);
  3319. };
  3320. /**
  3321. * Returns whether End-To-End encryption is enabled.
  3322. *
  3323. * @returns {boolean}
  3324. */
  3325. JitsiConference.prototype.isE2EEEnabled = function() {
  3326. return Boolean(this._e2eEncryption && this._e2eEncryption.isEnabled());
  3327. };
  3328. /**
  3329. * Returns whether End-To-End encryption is supported. Note that not all participants
  3330. * in the conference may support it.
  3331. *
  3332. * @returns {boolean}
  3333. */
  3334. JitsiConference.prototype.isE2EESupported = function() {
  3335. return E2EEncryption.isSupported(this.options.config);
  3336. };
  3337. /**
  3338. * Enables / disables End-to-End encryption.
  3339. *
  3340. * @param {boolean} enabled whether to enable E2EE or not.
  3341. * @returns {void}
  3342. */
  3343. JitsiConference.prototype.toggleE2EE = function(enabled) {
  3344. if (!this.isE2EESupported()) {
  3345. logger.warn('Cannot enable / disable E2EE: platform is not supported.');
  3346. return;
  3347. }
  3348. this._e2eEncryption.setEnabled(enabled);
  3349. };
  3350. /**
  3351. * Sets the key and index for End-to-End encryption.
  3352. *
  3353. * @param {CryptoKey} [keyInfo.encryptionKey] - encryption key.
  3354. * @param {Number} [keyInfo.index] - the index of the encryption key.
  3355. * @returns {void}
  3356. */
  3357. JitsiConference.prototype.setMediaEncryptionKey = function(keyInfo) {
  3358. this._e2eEncryption.setEncryptionKey(keyInfo);
  3359. };
  3360. /**
  3361. * Starts the participant verification process.
  3362. *
  3363. * @param {string} participantId The participant which will be marked as verified.
  3364. * @returns {void}
  3365. */
  3366. JitsiConference.prototype.startVerification = function(participantId) {
  3367. const participant = this.getParticipantById(participantId);
  3368. if (!participant) {
  3369. return;
  3370. }
  3371. this._e2eEncryption.startVerification(participant);
  3372. };
  3373. /**
  3374. * Marks the given participant as verified. After this is done, MAC verification will
  3375. * be performed and an event will be emitted with the result.
  3376. *
  3377. * @param {string} participantId The participant which will be marked as verified.
  3378. * @param {boolean} isVerified - whether the verification was succesfull.
  3379. * @returns {void}
  3380. */
  3381. JitsiConference.prototype.markParticipantVerified = function(participantId, isVerified) {
  3382. const participant = this.getParticipantById(participantId);
  3383. if (!participant) {
  3384. return;
  3385. }
  3386. this._e2eEncryption.markParticipantVerified(participant, isVerified);
  3387. };
  3388. /**
  3389. * Returns <tt>true</tt> if lobby support is enabled in the backend.
  3390. *
  3391. * @returns {boolean} whether lobby is supported in the backend.
  3392. */
  3393. JitsiConference.prototype.isLobbySupported = function() {
  3394. return Boolean(this.room && this.room.getLobby().isSupported());
  3395. };
  3396. /**
  3397. * Returns <tt>true</tt> if the room has members only enabled.
  3398. *
  3399. * @returns {boolean} whether conference room is members only.
  3400. */
  3401. JitsiConference.prototype.isMembersOnly = function() {
  3402. return Boolean(this.room && this.room.membersOnlyEnabled);
  3403. };
  3404. /**
  3405. * Enables lobby by moderators
  3406. *
  3407. * @returns {Promise} resolves when lobby room is joined or rejects with the error.
  3408. */
  3409. JitsiConference.prototype.enableLobby = function() {
  3410. if (this.room && this.isModerator()) {
  3411. return this.room.getLobby().enable();
  3412. }
  3413. return Promise.reject(
  3414. new Error('The conference not started or user is not moderator'));
  3415. };
  3416. /**
  3417. * Disabled lobby by moderators
  3418. *
  3419. * @returns {void}
  3420. */
  3421. JitsiConference.prototype.disableLobby = function() {
  3422. if (this.room && this.isModerator()) {
  3423. this.room.getLobby().disable();
  3424. } else {
  3425. logger.warn(`Failed to disable lobby, ${this.room ? '' : 'not in a room, '}${
  3426. this.isModerator() ? '' : 'participant is not a moderator'}`);
  3427. }
  3428. };
  3429. /**
  3430. * Joins the lobby room with display name and optional email or with a shared password to skip waiting.
  3431. *
  3432. * @param {string} displayName Display name should be set to show it to moderators.
  3433. * @param {string} email Optional email is used to present avatar to the moderator.
  3434. * @returns {Promise<never>}
  3435. */
  3436. JitsiConference.prototype.joinLobby = function(displayName, email) {
  3437. if (this.room) {
  3438. return this.room.getLobby().join(displayName, email);
  3439. }
  3440. return Promise.reject(new Error('The conference not started'));
  3441. };
  3442. /**
  3443. * Gets the local id for a participant in a lobby room.
  3444. * Returns undefined when current participant is not in the lobby room.
  3445. * This is used for lobby room private chat messages.
  3446. *
  3447. * @returns {string}
  3448. */
  3449. JitsiConference.prototype.myLobbyUserId = function() {
  3450. if (this.room) {
  3451. return this.room.getLobby().getLocalId();
  3452. }
  3453. };
  3454. /**
  3455. * Sends a message to a lobby room.
  3456. * When id is specified it sends a private message.
  3457. * Otherwise it sends the message to all moderators.
  3458. * @param {message} Object The message to send
  3459. * @param {string} id The participant id.
  3460. *
  3461. * @returns {void}
  3462. */
  3463. JitsiConference.prototype.sendLobbyMessage = function(message, id) {
  3464. if (this.room) {
  3465. if (id) {
  3466. return this.room.getLobby().sendPrivateMessage(id, message);
  3467. }
  3468. return this.room.getLobby().sendMessage(message);
  3469. }
  3470. };
  3471. /**
  3472. * Adds a message listener to the lobby room
  3473. * @param {Function} listener The listener function,
  3474. * called when a new message is received in the lobby room.
  3475. *
  3476. * @returns {Function} Handler returned to be able to remove it later.
  3477. */
  3478. JitsiConference.prototype.addLobbyMessageListener = function(listener) {
  3479. if (this.room) {
  3480. return this.room.getLobby().addMessageListener(listener);
  3481. }
  3482. };
  3483. /**
  3484. * Removes a message handler from the lobby room
  3485. * @param {Function} handler The handler function to remove.
  3486. *
  3487. * @returns {void}
  3488. */
  3489. JitsiConference.prototype.removeLobbyMessageHandler = function(handler) {
  3490. if (this.room) {
  3491. return this.room.getLobby().removeMessageHandler(handler);
  3492. }
  3493. };
  3494. /**
  3495. * Denies an occupant in the lobby room access to the conference.
  3496. * @param {string} id The participant id.
  3497. */
  3498. JitsiConference.prototype.lobbyDenyAccess = function(id) {
  3499. if (this.room) {
  3500. this.room.getLobby().denyAccess(id);
  3501. }
  3502. };
  3503. /**
  3504. * Approves the request to join the conference to a participant waiting in the lobby.
  3505. *
  3506. * @param {string} id The participant id.
  3507. */
  3508. JitsiConference.prototype.lobbyApproveAccess = function(id) {
  3509. if (this.room) {
  3510. this.room.getLobby().approveAccess(id);
  3511. }
  3512. };
  3513. /**
  3514. * Returns <tt>true</tt> if AV Moderation support is enabled in the backend.
  3515. *
  3516. * @returns {boolean} whether AV Moderation is supported in the backend.
  3517. */
  3518. JitsiConference.prototype.isAVModerationSupported = function() {
  3519. return Boolean(this.room && this.room.getAVModeration().isSupported());
  3520. };
  3521. /**
  3522. * Enables AV Moderation.
  3523. * @param {MediaType} mediaType "audio" or "video"
  3524. */
  3525. JitsiConference.prototype.enableAVModeration = function(mediaType) {
  3526. if (this.room && this.isModerator()
  3527. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3528. this.room.getAVModeration().enable(true, mediaType);
  3529. } else {
  3530. logger.warn(`Failed to enable AV moderation, ${this.room ? '' : 'not in a room, '}${
  3531. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3532. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3533. }
  3534. };
  3535. /**
  3536. * Disables AV Moderation.
  3537. * @param {MediaType} mediaType "audio" or "video"
  3538. */
  3539. JitsiConference.prototype.disableAVModeration = function(mediaType) {
  3540. if (this.room && this.isModerator()
  3541. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3542. this.room.getAVModeration().enable(false, mediaType);
  3543. } else {
  3544. logger.warn(`Failed to disable AV moderation, ${this.room ? '' : 'not in a room, '}${
  3545. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3546. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3547. }
  3548. };
  3549. /**
  3550. * Approve participant access to certain media, allows unmuting audio or video.
  3551. *
  3552. * @param {MediaType} mediaType "audio" or "video"
  3553. * @param id the id of the participant.
  3554. */
  3555. JitsiConference.prototype.avModerationApprove = function(mediaType, id) {
  3556. if (this.room && this.isModerator()
  3557. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3558. const participant = this.getParticipantById(id);
  3559. if (!participant) {
  3560. return;
  3561. }
  3562. this.room.getAVModeration().approve(mediaType, participant.getJid());
  3563. } else {
  3564. logger.warn(`AV moderation approve skipped , ${this.room ? '' : 'not in a room, '}${
  3565. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3566. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3567. }
  3568. };
  3569. /**
  3570. * Reject participant access to certain media, blocks unmuting audio or video.
  3571. *
  3572. * @param {MediaType} mediaType "audio" or "video"
  3573. * @param id the id of the participant.
  3574. */
  3575. JitsiConference.prototype.avModerationReject = function(mediaType, id) {
  3576. if (this.room && this.isModerator()
  3577. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3578. const participant = this.getParticipantById(id);
  3579. if (!participant) {
  3580. return;
  3581. }
  3582. this.room.getAVModeration().reject(mediaType, participant.getJid());
  3583. } else {
  3584. logger.warn(`AV moderation reject skipped , ${this.room ? '' : 'not in a room, '}${
  3585. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3586. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3587. }
  3588. };
  3589. /**
  3590. * Returns the breakout rooms manager object.
  3591. *
  3592. * @returns {Object} the breakout rooms manager.
  3593. */
  3594. JitsiConference.prototype.getBreakoutRooms = function() {
  3595. return this.room?.getBreakoutRooms();
  3596. };
  3597. /**
  3598. * Returns the metadata handler object.
  3599. *
  3600. * @returns {Object} the room metadata handler.
  3601. */
  3602. JitsiConference.prototype.getMetadataHandler = function() {
  3603. return this.room?.getMetadataHandler();
  3604. };