選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JitsiConference.js 140KB

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