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

JitsiConference.js 145KB

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