You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiConference.js 139KB

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