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

JitsiConference.js 142KB

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