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

JitsiConference.js 140KB

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