Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JitsiConference.js 145KB

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