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

JitsiConference.js 139KB

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