Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JitsiConference.js 137KB

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