Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

JitsiConference.js 140KB

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