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

JitsiConference.js 144KB

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