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 126KB

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