You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiConference.js 140KB

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