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

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