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

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