Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

JitsiConference.js 140KB

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