您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 124KB

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