Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiConference.js 155KB

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