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

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