Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

JitsiConference.js 138KB

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