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

JitsiConference.js 145KB

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