您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 146KB

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