Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiConference.js 143KB

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