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 141KB

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