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

JitsiConference.js 120KB

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