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

JitsiConference.js 143KB

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