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

JitsiConference.js 141KB

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