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

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