modified lib-jitsi-meet dev repo
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

JitsiConference.js 139KB

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