modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiConference.js 123KB

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