您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 140KB

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