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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663
  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.isWebKitBased()) {
  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.isWebKitBased()) {
  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. const displayName = (this.room.getFromPresence('nick') || {}).value;
  739. this.room.sendMessage(message, elementName, displayName);
  740. }
  741. };
  742. /**
  743. * Send private text message to another participant of the conference
  744. * @param id the id of the participant to send a private message.
  745. * @param message the text message.
  746. * @param elementName the element name to encapsulate the message.
  747. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  748. */
  749. JitsiConference.prototype.sendPrivateTextMessage = function(
  750. id, message, elementName = 'body') {
  751. if (this.room) {
  752. this.room.sendPrivateMessage(id, message, elementName);
  753. }
  754. };
  755. /**
  756. * Send presence command.
  757. * @param name {String} the name of the command.
  758. * @param values {Object} with keys and values that will be sent.
  759. **/
  760. JitsiConference.prototype.sendCommand = function(name, values) {
  761. if (this.room) {
  762. this.room.addOrReplaceInPresence(name, values) && this.room.sendPresence();
  763. } else {
  764. logger.warn('Not sending a command, room not initialized.');
  765. }
  766. };
  767. /**
  768. * Send presence command one time.
  769. * @param name {String} the name of the command.
  770. * @param values {Object} with keys and values that will be sent.
  771. **/
  772. JitsiConference.prototype.sendCommandOnce = function(name, values) {
  773. this.sendCommand(name, values);
  774. this.removeCommand(name);
  775. };
  776. /**
  777. * Removes presence command.
  778. * @param name {String} the name of the command.
  779. **/
  780. JitsiConference.prototype.removeCommand = function(name) {
  781. if (this.room) {
  782. this.room.removeFromPresence(name);
  783. }
  784. };
  785. /**
  786. * Sets the display name for this conference.
  787. * @param name the display name to set
  788. */
  789. JitsiConference.prototype.setDisplayName = function(name) {
  790. if (this.room) {
  791. this.room.addOrReplaceInPresence('nick', {
  792. attributes: { xmlns: 'http://jabber.org/protocol/nick' },
  793. value: name
  794. }) && this.room.sendPresence();
  795. }
  796. };
  797. /**
  798. * Set new subject for this conference. (available only for moderator)
  799. * @param {string} subject new subject
  800. */
  801. JitsiConference.prototype.setSubject = function(subject) {
  802. if (this.room && this.isModerator()) {
  803. this.room.setSubject(subject);
  804. }
  805. };
  806. /**
  807. * Get a transcriber object for all current participants in this conference
  808. * @return {Transcriber} the transcriber object
  809. */
  810. JitsiConference.prototype.getTranscriber = function() {
  811. if (this.transcriber === undefined) {
  812. this.transcriber = new Transcriber();
  813. // add all existing local audio tracks to the transcriber
  814. const localAudioTracks = this.getLocalTracks(MediaType.AUDIO);
  815. for (const localAudio of localAudioTracks) {
  816. this.transcriber.addTrack(localAudio);
  817. }
  818. // and all remote audio tracks
  819. const remoteAudioTracks = this.rtc.getRemoteTracks(MediaType.AUDIO);
  820. for (const remoteTrack of remoteAudioTracks) {
  821. this.transcriber.addTrack(remoteTrack);
  822. }
  823. }
  824. return this.transcriber;
  825. };
  826. /**
  827. * Returns the transcription status.
  828. *
  829. * @returns {String} "on" or "off".
  830. */
  831. JitsiConference.prototype.getTranscriptionStatus = function() {
  832. return this.room.transcriptionStatus;
  833. };
  834. /**
  835. * Adds JitsiLocalTrack object to the conference.
  836. * @param {JitsiLocalTrack} track the JitsiLocalTrack object.
  837. * @returns {Promise<JitsiLocalTrack>}
  838. * @throws {Error} if the specified track is a video track and there is already
  839. * another video track in the conference.
  840. */
  841. JitsiConference.prototype.addTrack = function(track) {
  842. const mediaType = track.getType();
  843. const localTracks = this.rtc.getLocalTracks(mediaType);
  844. // Ensure there's exactly 1 local track of each media type in the conference.
  845. if (localTracks.length > 0) {
  846. // Don't be excessively harsh and severe if the API client happens to attempt to add the same local track twice.
  847. if (track === localTracks[0]) {
  848. return Promise.resolve(track);
  849. }
  850. return Promise.reject(new Error(`Cannot add second ${mediaType} track to the conference`));
  851. }
  852. return this.replaceTrack(null, track);
  853. };
  854. /**
  855. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event (for local tracks).
  856. * @param {number} audioLevel the audio level
  857. * @param {TraceablePeerConnection} [tpc]
  858. */
  859. JitsiConference.prototype._fireAudioLevelChangeEvent = function(
  860. audioLevel,
  861. tpc) {
  862. const activeTpc = this.getActivePeerConnection();
  863. // There will be no TraceablePeerConnection if audio levels do not come from
  864. // a peerconnection. LocalStatsCollector.js measures audio levels using Web
  865. // Audio Analyser API and emits local audio levels events through
  866. // JitsiTrack.setAudioLevel, but does not provide TPC instance which is
  867. // optional.
  868. if (!tpc || activeTpc === tpc) {
  869. this.eventEmitter.emit(
  870. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  871. this.myUserId(), audioLevel);
  872. }
  873. };
  874. /**
  875. * Fires TRACK_MUTE_CHANGED change conference event.
  876. * @param track the JitsiTrack object related to the event.
  877. */
  878. JitsiConference.prototype._fireMuteChangeEvent = function(track) {
  879. // check if track was muted by focus and now is unmuted by user
  880. if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
  881. this.isMutedByFocus = false;
  882. // unmute local user on server
  883. this.room.muteParticipant(this.room.myroomjid, false, MediaType.AUDIO);
  884. } else if (this.isVideoMutedByFocus && track.isVideoTrack() && !track.isMuted()) {
  885. this.isVideoMutedByFocus = false;
  886. // unmute local user on server
  887. this.room.muteParticipant(this.room.myroomjid, false, MediaType.VIDEO);
  888. }
  889. let actorParticipant;
  890. if (this.mutedByFocusActor && track.isAudioTrack()) {
  891. const actorId = Strophe.getResourceFromJid(this.mutedByFocusActor);
  892. actorParticipant = this.participants[actorId];
  893. } else if (this.mutedVideoByFocusActor && track.isVideoTrack()) {
  894. const actorId = Strophe.getResourceFromJid(this.mutedVideoByFocusActor);
  895. actorParticipant = this.participants[actorId];
  896. }
  897. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track, actorParticipant);
  898. };
  899. /**
  900. * Returns the list of local tracks that need to be added to the peerconnection on join.
  901. * This takes the startAudioMuted/startVideoMuted flags into consideration since we do not
  902. * want to add the tracks if the user joins the call audio/video muted. The tracks will be
  903. * added when the user unmutes for the first time.
  904. * @returns {Array<JitsiLocalTrack>} - list of local tracks that are unmuted.
  905. */
  906. JitsiConference.prototype._getInitialLocalTracks = function() {
  907. return this.getLocalTracks()
  908. .filter(track => (track.getType() === MediaType.AUDIO && !this.isStartAudioMuted())
  909. || (track.getType() === MediaType.VIDEO && !this.isStartVideoMuted()));
  910. };
  911. /**
  912. * Clear JitsiLocalTrack properties and listeners.
  913. * @param track the JitsiLocalTrack object.
  914. */
  915. JitsiConference.prototype.onLocalTrackRemoved = function(track) {
  916. track._setConference(null);
  917. this.rtc.removeLocalTrack(track);
  918. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  919. track.muteHandler);
  920. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  921. track.audioLevelHandler);
  922. // send event for stopping screen sharing
  923. // FIXME: we assume we have only one screen sharing track
  924. // if we change this we need to fix this check
  925. if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP) {
  926. this.statistics.sendScreenSharingEvent(false);
  927. }
  928. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  929. };
  930. /**
  931. * Removes JitsiLocalTrack from the conference and performs
  932. * a new offer/answer cycle.
  933. * @param {JitsiLocalTrack} track
  934. * @returns {Promise}
  935. */
  936. JitsiConference.prototype.removeTrack = function(track) {
  937. return this.replaceTrack(track, null);
  938. };
  939. /**
  940. * Replaces oldTrack with newTrack and performs a single offer/answer
  941. * cycle after both operations are done. Either oldTrack or newTrack
  942. * can be null; replacing a valid 'oldTrack' with a null 'newTrack'
  943. * effectively just removes 'oldTrack'
  944. * @param {JitsiLocalTrack} oldTrack the current stream in use to be replaced
  945. * @param {JitsiLocalTrack} newTrack the new stream to use
  946. * @returns {Promise} resolves when the replacement is finished
  947. */
  948. JitsiConference.prototype.replaceTrack = function(oldTrack, newTrack) {
  949. // First do the removal of the oldTrack at the JitsiConference level
  950. if (oldTrack) {
  951. if (oldTrack.disposed) {
  952. return Promise.reject(
  953. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  954. }
  955. }
  956. if (newTrack) {
  957. if (newTrack.disposed) {
  958. return Promise.reject(
  959. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  960. }
  961. }
  962. // Now replace the stream at the lower levels
  963. return this._doReplaceTrack(oldTrack, newTrack)
  964. .then(() => {
  965. if (oldTrack) {
  966. this.onLocalTrackRemoved(oldTrack);
  967. }
  968. if (newTrack) {
  969. // Now handle the addition of the newTrack at the
  970. // JitsiConference level
  971. this._setupNewTrack(newTrack);
  972. }
  973. return Promise.resolve();
  974. })
  975. .catch(error => Promise.reject(new Error(error)));
  976. };
  977. /**
  978. * Replaces the tracks at the lower level by going through the Jingle session
  979. * and WebRTC peer connection. The method will resolve immediately if there is
  980. * currently no JingleSession started.
  981. * @param {JitsiLocalTrack|null} oldTrack the track to be removed during
  982. * the process or <tt>null</t> if the method should act as "add track"
  983. * @param {JitsiLocalTrack|null} newTrack the new track to be added or
  984. * <tt>null</tt> if the method should act as "remove track"
  985. * @return {Promise} resolved when the process is done or rejected with a string
  986. * which describes the error.
  987. * @private
  988. */
  989. JitsiConference.prototype._doReplaceTrack = function(oldTrack, newTrack) {
  990. const replaceTrackPromises = [];
  991. if (this.jvbJingleSession) {
  992. replaceTrackPromises.push(
  993. this.jvbJingleSession.replaceTrack(oldTrack, newTrack));
  994. } else {
  995. logger.info('_doReplaceTrack - no JVB JingleSession');
  996. }
  997. if (this.p2pJingleSession) {
  998. replaceTrackPromises.push(
  999. this.p2pJingleSession.replaceTrack(oldTrack, newTrack));
  1000. } else {
  1001. logger.info('_doReplaceTrack - no P2P JingleSession');
  1002. }
  1003. return Promise.all(replaceTrackPromises);
  1004. };
  1005. /**
  1006. * Operations related to creating a new track
  1007. * @param {JitsiLocalTrack} newTrack the new track being created
  1008. */
  1009. JitsiConference.prototype._setupNewTrack = function(newTrack) {
  1010. if (newTrack.isAudioTrack() || (newTrack.isVideoTrack()
  1011. && newTrack.videoType !== VideoType.DESKTOP)) {
  1012. // Report active device to statistics
  1013. const devices = RTC.getCurrentlyAvailableMediaDevices();
  1014. const device
  1015. = devices.find(
  1016. d =>
  1017. d.kind === `${newTrack.getTrack().kind}input`
  1018. && d.label === newTrack.getTrack().label);
  1019. if (device) {
  1020. Statistics.sendActiveDeviceListEvent(
  1021. RTC.getEventDataForActiveDevice(device));
  1022. }
  1023. }
  1024. if (newTrack.isVideoTrack()) {
  1025. this.sendCommand('videoType', {
  1026. value: newTrack.videoType,
  1027. attributes: {
  1028. xmlns: 'http://jitsi.org/jitmeet/video'
  1029. }
  1030. });
  1031. }
  1032. this.rtc.addLocalTrack(newTrack);
  1033. // ensure that we're sharing proper "is muted" state
  1034. if (newTrack.isAudioTrack()) {
  1035. this.room.setAudioMute(newTrack.isMuted());
  1036. } else {
  1037. this.room.setVideoMute(newTrack.isMuted());
  1038. }
  1039. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  1040. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  1041. newTrack.addEventListener(
  1042. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1043. newTrack.muteHandler);
  1044. newTrack.addEventListener(
  1045. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1046. newTrack.audioLevelHandler);
  1047. newTrack._setConference(this);
  1048. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  1049. };
  1050. /**
  1051. * Method called by the {@link JitsiLocalTrack} (a video one) in order to add
  1052. * back the underlying WebRTC MediaStream to the PeerConnection (which has
  1053. * removed on video mute).
  1054. * @param {JitsiLocalTrack} track the local track that will be added as part of
  1055. * the unmute operation.
  1056. * @return {Promise} resolved when the process is done or rejected with a string
  1057. * which describes the error.
  1058. */
  1059. JitsiConference.prototype._addLocalTrackAsUnmute = function(track) {
  1060. const addAsUnmutePromises = [];
  1061. if (this.jvbJingleSession) {
  1062. addAsUnmutePromises.push(this.jvbJingleSession.addTrackAsUnmute(track));
  1063. } else {
  1064. logger.info(
  1065. 'Add local MediaStream as unmute -'
  1066. + ' no JVB Jingle session started yet');
  1067. }
  1068. if (this.p2pJingleSession) {
  1069. addAsUnmutePromises.push(this.p2pJingleSession.addTrackAsUnmute(track));
  1070. } else {
  1071. logger.info(
  1072. 'Add local MediaStream as unmute -'
  1073. + ' no P2P Jingle session started yet');
  1074. }
  1075. return Promise.all(addAsUnmutePromises);
  1076. };
  1077. /**
  1078. * Method called by the {@link JitsiLocalTrack} (a video one) in order to remove
  1079. * the underlying WebRTC MediaStream from the PeerConnection. The purpose of
  1080. * that is to stop sending any data and turn off the HW camera device.
  1081. * @param {JitsiLocalTrack} track the local track that will be removed.
  1082. * @return {Promise}
  1083. */
  1084. JitsiConference.prototype._removeLocalTrackAsMute = function(track) {
  1085. const removeAsMutePromises = [];
  1086. if (this.jvbJingleSession) {
  1087. removeAsMutePromises.push(
  1088. this.jvbJingleSession.removeTrackAsMute(track));
  1089. } else {
  1090. logger.info(
  1091. 'Remove local MediaStream - no JVB JingleSession started yet');
  1092. }
  1093. if (this.p2pJingleSession) {
  1094. removeAsMutePromises.push(
  1095. this.p2pJingleSession.removeTrackAsMute(track));
  1096. } else {
  1097. logger.info(
  1098. 'Remove local MediaStream - no P2P JingleSession started yet');
  1099. }
  1100. return Promise.all(removeAsMutePromises);
  1101. };
  1102. /**
  1103. * Get role of the local user.
  1104. * @returns {string} user role: 'moderator' or 'none'
  1105. */
  1106. JitsiConference.prototype.getRole = function() {
  1107. return this.room.role;
  1108. };
  1109. /**
  1110. * Returns whether or not the current conference has been joined as a hidden
  1111. * user.
  1112. *
  1113. * @returns {boolean|null} True if hidden, false otherwise. Will return null if
  1114. * no connection is active.
  1115. */
  1116. JitsiConference.prototype.isHidden = function() {
  1117. if (!this.connection) {
  1118. return null;
  1119. }
  1120. return Strophe.getDomainFromJid(this.connection.getJid())
  1121. === this.options.config.hiddenDomain;
  1122. };
  1123. /**
  1124. * Check if local user is moderator.
  1125. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  1126. * we're no longer in the conference room then <tt>null</tt> is returned.
  1127. */
  1128. JitsiConference.prototype.isModerator = function() {
  1129. return this.room ? this.room.isModerator() : null;
  1130. };
  1131. /**
  1132. * Set password for the room.
  1133. * @param {string} password new password for the room.
  1134. * @returns {Promise}
  1135. */
  1136. JitsiConference.prototype.lock = function(password) {
  1137. if (!this.isModerator()) {
  1138. return Promise.reject(new Error('You are not moderator.'));
  1139. }
  1140. return new Promise((resolve, reject) => {
  1141. this.room.lockRoom(
  1142. password || '',
  1143. () => resolve(),
  1144. err => reject(err),
  1145. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  1146. });
  1147. };
  1148. /**
  1149. * Remove password from the room.
  1150. * @returns {Promise}
  1151. */
  1152. JitsiConference.prototype.unlock = function() {
  1153. return this.lock();
  1154. };
  1155. /**
  1156. * Elects the participant with the given id to be the selected participant in
  1157. * order to receive higher video quality (if simulcast is enabled).
  1158. * Or cache it if channel is not created and send it once channel is available.
  1159. * @param participantId the identifier of the participant
  1160. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1161. * @returns {void}
  1162. */
  1163. JitsiConference.prototype.selectParticipant = function(participantId) {
  1164. this.selectParticipants([ participantId ]);
  1165. };
  1166. /*
  1167. * Elects participants with given ids to be the selected participants in order
  1168. * to receive higher video quality (if simulcast is enabled). The argument
  1169. * should be an array of participant id strings or an empty array; an error will
  1170. * be thrown if a non-array is passed in. The error is thrown as a layer of
  1171. * protection against passing an invalid argument, as the error will happen in
  1172. * the bridge and may not be visible in the client.
  1173. *
  1174. * @param {Array<strings>} participantIds - An array of identifiers for
  1175. * participants.
  1176. * @returns {void}
  1177. */
  1178. JitsiConference.prototype.selectParticipants = function(participantIds) {
  1179. if (!Array.isArray(participantIds)) {
  1180. throw new Error('Invalid argument; participantIds must be an array.');
  1181. }
  1182. this.receiveVideoController.selectEndpoints(participantIds);
  1183. };
  1184. /**
  1185. * Obtains the current value for "lastN". See {@link setLastN} for more info.
  1186. * @returns {number}
  1187. */
  1188. JitsiConference.prototype.getLastN = function() {
  1189. return this.receiveVideoController.getLastN();
  1190. };
  1191. /**
  1192. * Selects a new value for "lastN". The requested amount of videos are going
  1193. * to be delivered after the value is in effect. Set to -1 for unlimited or
  1194. * all available videos.
  1195. * @param lastN the new number of videos the user would like to receive.
  1196. * @throws Error or RangeError if the given value is not a number or is smaller
  1197. * than -1.
  1198. */
  1199. JitsiConference.prototype.setLastN = function(lastN) {
  1200. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  1201. throw new Error(`Invalid value for lastN: ${lastN}`);
  1202. }
  1203. const n = Number(lastN);
  1204. if (n < -1) {
  1205. throw new RangeError('lastN cannot be smaller than -1');
  1206. }
  1207. this.receiveVideoController.setLastN(n);
  1208. // If the P2P session is not fully established yet, we wait until it gets
  1209. // established.
  1210. if (this.p2pJingleSession) {
  1211. const isVideoActive = n !== 0;
  1212. this.p2pJingleSession
  1213. .setMediaTransferActive(true, isVideoActive)
  1214. .catch(error => {
  1215. logger.error(
  1216. `Failed to adjust video transfer status (${isVideoActive})`,
  1217. error);
  1218. });
  1219. }
  1220. };
  1221. /**
  1222. * Checks if the participant given by participantId is currently included in
  1223. * the last N.
  1224. * @param {string} participantId the identifier of the participant we would
  1225. * like to check.
  1226. * @return {boolean} true if the participant with id is in the last N set or
  1227. * if there's no last N set, false otherwise.
  1228. * @deprecated this method should never be used to figure out the UI, but
  1229. * {@link ParticipantConnectionStatus} should be used instead.
  1230. */
  1231. JitsiConference.prototype.isInLastN = function(participantId) {
  1232. return this.rtc.isInLastN(participantId);
  1233. };
  1234. /**
  1235. * @return Array<JitsiParticipant> an array of all participants in this
  1236. * conference.
  1237. */
  1238. JitsiConference.prototype.getParticipants = function() {
  1239. return Object.values(this.participants);
  1240. };
  1241. /**
  1242. * Returns the number of participants in the conference, including the local
  1243. * participant.
  1244. * @param countHidden {boolean} Whether or not to include hidden participants
  1245. * in the count. Default: false.
  1246. **/
  1247. JitsiConference.prototype.getParticipantCount
  1248. = function(countHidden = false) {
  1249. let participants = this.getParticipants();
  1250. if (!countHidden) {
  1251. participants = participants.filter(p => !p.isHidden());
  1252. }
  1253. // Add one for the local participant.
  1254. return participants.length + 1;
  1255. };
  1256. /**
  1257. * @returns {JitsiParticipant} the participant in this conference with the
  1258. * specified id (or undefined if there isn't one).
  1259. * @param id the id of the participant.
  1260. */
  1261. JitsiConference.prototype.getParticipantById = function(id) {
  1262. return this.participants[id];
  1263. };
  1264. /**
  1265. * Grant owner rights to the participant.
  1266. * @param {string} id id of the participant to grant owner rights to.
  1267. */
  1268. JitsiConference.prototype.grantOwner = function(id) {
  1269. const participant = this.getParticipantById(id);
  1270. if (!participant) {
  1271. return;
  1272. }
  1273. this.room.setAffiliation(participant.getJid(), 'owner');
  1274. };
  1275. /**
  1276. * Revoke owner rights to the participant or local Participant as
  1277. * the user might want to refuse to be a moderator.
  1278. * @param {string} id id of the participant to revoke owner rights to.
  1279. */
  1280. JitsiConference.prototype.revokeOwner = function(id) {
  1281. const participant = this.getParticipantById(id);
  1282. const isMyself = this.myUserId() === id;
  1283. const role = this.isMembersOnly() ? 'member' : 'none';
  1284. if (isMyself) {
  1285. this.room.setAffiliation(this.room.myroomjid, role);
  1286. } else if (participant) {
  1287. this.room.setAffiliation(participant.getJid(), role);
  1288. }
  1289. };
  1290. /**
  1291. * Kick participant from this conference.
  1292. * @param {string} id id of the participant to kick
  1293. * @param {string} reason reason of the participant to kick
  1294. */
  1295. JitsiConference.prototype.kickParticipant = function(id, reason) {
  1296. const participant = this.getParticipantById(id);
  1297. if (!participant) {
  1298. return;
  1299. }
  1300. this.room.kick(participant.getJid(), reason);
  1301. };
  1302. /**
  1303. * Maybe clears the timeout which emits {@link ACTION_JINGLE_SI_TIMEOUT}
  1304. * analytics event.
  1305. * @private
  1306. */
  1307. JitsiConference.prototype._maybeClearSITimeout = function() {
  1308. if (this._sessionInitiateTimeout
  1309. && (this.jvbJingleSession || this.getParticipantCount() < 2)) {
  1310. window.clearTimeout(this._sessionInitiateTimeout);
  1311. this._sessionInitiateTimeout = null;
  1312. }
  1313. };
  1314. /**
  1315. * Sets a timeout which will emit {@link ACTION_JINGLE_SI_TIMEOUT} analytics
  1316. * event.
  1317. * @private
  1318. */
  1319. JitsiConference.prototype._maybeSetSITimeout = function() {
  1320. // Jicofo is supposed to invite if there are at least 2 participants
  1321. if (!this.jvbJingleSession
  1322. && this.getParticipantCount() >= 2
  1323. && !this._sessionInitiateTimeout) {
  1324. this._sessionInitiateTimeout = window.setTimeout(() => {
  1325. this._sessionInitiateTimeout = null;
  1326. Statistics.sendAnalytics(createJingleEvent(
  1327. ACTION_JINGLE_SI_TIMEOUT,
  1328. {
  1329. p2p: false,
  1330. value: JINGLE_SI_TIMEOUT
  1331. }));
  1332. }, JINGLE_SI_TIMEOUT);
  1333. }
  1334. };
  1335. /**
  1336. * Mutes a participant.
  1337. * @param {string} id The id of the participant to mute.
  1338. */
  1339. JitsiConference.prototype.muteParticipant = function(id, mediaType) {
  1340. const muteMediaType = mediaType ? mediaType : MediaType.AUDIO;
  1341. if (muteMediaType !== MediaType.AUDIO && muteMediaType !== MediaType.VIDEO) {
  1342. logger.error(`Unsupported media type: ${muteMediaType}`);
  1343. return;
  1344. }
  1345. const participant = this.getParticipantById(id);
  1346. if (!participant) {
  1347. return;
  1348. }
  1349. this.room.muteParticipant(participant.getJid(), true, muteMediaType);
  1350. };
  1351. /* eslint-disable max-params */
  1352. /**
  1353. * Notifies this JitsiConference that a new member has joined its chat room.
  1354. *
  1355. * FIXME This should NOT be exposed!
  1356. *
  1357. * @param jid the jid of the participant in the MUC
  1358. * @param nick the display name of the participant
  1359. * @param role the role of the participant in the MUC
  1360. * @param isHidden indicates if this is a hidden participant (system
  1361. * participant for example a recorder).
  1362. * @param statsID the participant statsID (optional)
  1363. * @param status the initial status if any
  1364. * @param identity the member identity, if any
  1365. * @param botType the member botType, if any
  1366. * @param fullJid the member full jid, if any
  1367. * @param features the member botType, if any
  1368. */
  1369. JitsiConference.prototype.onMemberJoined = function(
  1370. jid, nick, role, isHidden, statsID, status, identity, botType, fullJid, features) {
  1371. const id = Strophe.getResourceFromJid(jid);
  1372. if (id === 'focus' || this.myUserId() === id) {
  1373. return;
  1374. }
  1375. const participant
  1376. = new JitsiParticipant(jid, this, nick, isHidden, statsID, status, identity);
  1377. participant.setRole(role);
  1378. participant.setBotType(botType);
  1379. participant.setFeatures(features);
  1380. this.participants[id] = participant;
  1381. this.eventEmitter.emit(
  1382. JitsiConferenceEvents.USER_JOINED,
  1383. id,
  1384. participant);
  1385. this._updateFeatures(participant);
  1386. // maybeStart only if we had finished joining as then we will have information for the number of participants
  1387. if (this.isJoined()) {
  1388. this._maybeStartOrStopP2P();
  1389. }
  1390. this._maybeSetSITimeout();
  1391. };
  1392. /* eslint-enable max-params */
  1393. /**
  1394. * Get notified when we joined the room.
  1395. *
  1396. * FIXME This should NOT be exposed!
  1397. *
  1398. * @private
  1399. */
  1400. JitsiConference.prototype._onMucJoined = function() {
  1401. this._maybeStartOrStopP2P();
  1402. };
  1403. /**
  1404. * Updates features for a participant.
  1405. * @param {JitsiParticipant} participant - The participant to query for features.
  1406. * @returns {void}
  1407. * @private
  1408. */
  1409. JitsiConference.prototype._updateFeatures = function(participant) {
  1410. participant.getFeatures()
  1411. .then(features => {
  1412. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  1413. this.updateDTMFSupport();
  1414. if (features.has(FEATURE_JIGASI)) {
  1415. participant.setProperty('features_jigasi', true);
  1416. }
  1417. if (features.has(FEATURE_E2EE)) {
  1418. participant.setProperty('features_e2ee', true);
  1419. }
  1420. })
  1421. .catch(() => false);
  1422. };
  1423. /**
  1424. * Get notified when member bot type had changed.
  1425. * @param jid the member jid
  1426. * @param botType the new botType value
  1427. * @private
  1428. */
  1429. JitsiConference.prototype._onMemberBotTypeChanged = function(jid, botType) {
  1430. // find the participant and mark it as non bot, as the real one will join
  1431. // in a moment
  1432. const peers = this.getParticipants();
  1433. const botParticipant = peers.find(p => p.getJid() === jid);
  1434. if (botParticipant) {
  1435. botParticipant.setBotType(botType);
  1436. const id = Strophe.getResourceFromJid(jid);
  1437. this.eventEmitter.emit(
  1438. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1439. id,
  1440. botType);
  1441. }
  1442. // if botType changed to undefined, botType was removed, in case of
  1443. // poltergeist mode this is the moment when the poltergeist had exited and
  1444. // the real participant had already replaced it.
  1445. // In this case we can check and try p2p
  1446. if (!botParticipant.getBotType()) {
  1447. this._maybeStartOrStopP2P();
  1448. }
  1449. };
  1450. JitsiConference.prototype.onMemberLeft = function(jid) {
  1451. const id = Strophe.getResourceFromJid(jid);
  1452. if (id === 'focus' || this.myUserId() === id) {
  1453. return;
  1454. }
  1455. const participant = this.participants[id];
  1456. delete this.participants[id];
  1457. // Remove the ssrcs from the remote description.
  1458. const mediaSessions = this._getMediaSessions();
  1459. const removePromises = [];
  1460. for (const session of mediaSessions) {
  1461. removePromises.push(session.removeRemoteStreamsOnLeave(id));
  1462. }
  1463. Promise.allSettled(removePromises)
  1464. .then(results => {
  1465. let removedTracks = [];
  1466. results.map(result => result.value).forEach(value => {
  1467. if (value) {
  1468. removedTracks = removedTracks.concat(value);
  1469. }
  1470. });
  1471. removedTracks.forEach(track => {
  1472. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  1473. });
  1474. // There can be no participant in case the member that left is focus.
  1475. if (participant) {
  1476. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  1477. }
  1478. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  1479. this._maybeClearSITimeout();
  1480. });
  1481. };
  1482. /**
  1483. * Designates an event indicating that we were kicked from the XMPP MUC.
  1484. * @param {boolean} isSelfPresence - whether it is for local participant
  1485. * or another participant.
  1486. * @param {string} actorId - the id of the participant who was initiator
  1487. * of the kick.
  1488. * @param {string?} kickedParticipantId - when it is not a kick for local participant,
  1489. * this is the id of the participant which was kicked.
  1490. * @param {string} reason - reason of the participant to kick
  1491. */
  1492. JitsiConference.prototype.onMemberKicked = function(isSelfPresence, actorId, kickedParticipantId, reason) {
  1493. // This check which be true when we kick someone else. With the introduction of lobby
  1494. // the ChatRoom KICKED event is now also emitted for ourselves (the kicker) so we want to
  1495. // avoid emitting an event where `undefined` kicked someone.
  1496. if (actorId === this.myUserId()) {
  1497. return;
  1498. }
  1499. const actorParticipant = this.participants[actorId];
  1500. if (isSelfPresence) {
  1501. this.eventEmitter.emit(
  1502. JitsiConferenceEvents.KICKED, actorParticipant, reason);
  1503. this.leave();
  1504. return;
  1505. }
  1506. const kickedParticipant = this.participants[kickedParticipantId];
  1507. this.eventEmitter.emit(
  1508. JitsiConferenceEvents.PARTICIPANT_KICKED, actorParticipant, kickedParticipant, reason);
  1509. };
  1510. /**
  1511. * Method called on local MUC role change.
  1512. * @param {string} role the name of new user's role as defined by XMPP MUC.
  1513. */
  1514. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  1515. // Emit role changed for local JID
  1516. this.eventEmitter.emit(
  1517. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  1518. };
  1519. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  1520. const id = Strophe.getResourceFromJid(jid);
  1521. const participant = this.getParticipantById(id);
  1522. if (!participant) {
  1523. return;
  1524. }
  1525. participant.setRole(role);
  1526. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  1527. };
  1528. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  1529. const id = Strophe.getResourceFromJid(jid);
  1530. const participant = this.getParticipantById(id);
  1531. if (!participant) {
  1532. return;
  1533. }
  1534. if (participant._displayName === displayName) {
  1535. return;
  1536. }
  1537. participant._displayName = displayName;
  1538. this.eventEmitter.emit(
  1539. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1540. id,
  1541. displayName);
  1542. };
  1543. /**
  1544. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  1545. * the conference.
  1546. *
  1547. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  1548. * JitsiConference
  1549. */
  1550. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  1551. if (track.isP2P && !this.isP2PActive()) {
  1552. logger.info(
  1553. 'Trying to add remote P2P track, when not in P2P - IGNORED');
  1554. return;
  1555. } else if (!track.isP2P && this.isP2PActive()) {
  1556. logger.info(
  1557. 'Trying to add remote JVB track, when in P2P - IGNORED');
  1558. return;
  1559. }
  1560. const id = track.getParticipantId();
  1561. const participant = this.getParticipantById(id);
  1562. if (!participant) {
  1563. logger.error(`No participant found for id: ${id}`);
  1564. return;
  1565. }
  1566. // Add track to JitsiParticipant.
  1567. participant._tracks.push(track);
  1568. if (this.transcriber) {
  1569. this.transcriber.addTrack(track);
  1570. }
  1571. const emitter = this.eventEmitter;
  1572. track.addEventListener(
  1573. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1574. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  1575. track.addEventListener(
  1576. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1577. (audioLevel, tpc) => {
  1578. const activeTPC = this.getActivePeerConnection();
  1579. if (activeTPC === tpc) {
  1580. emitter.emit(
  1581. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1582. id,
  1583. audioLevel);
  1584. }
  1585. }
  1586. );
  1587. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  1588. };
  1589. /**
  1590. * Callback called by the Jingle plugin when 'session-answer' is received.
  1591. * @param {JingleSessionPC} session the Jingle session for which an answer was
  1592. * received.
  1593. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  1594. */
  1595. // eslint-disable-next-line no-unused-vars
  1596. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  1597. if (this.p2pJingleSession === session) {
  1598. logger.info('P2P setAnswer');
  1599. this.p2pJingleSession.setAnswer(answer);
  1600. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_STARTED, this.p2pJingleSession);
  1601. }
  1602. };
  1603. /**
  1604. * Callback called by the Jingle plugin when 'transport-info' is received.
  1605. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1606. * received
  1607. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1608. * element
  1609. */
  1610. // eslint-disable-next-line no-unused-vars
  1611. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1612. if (this.p2pJingleSession === session) {
  1613. logger.info('P2P addIceCandidates');
  1614. this.p2pJingleSession.addIceCandidates(transportInfo);
  1615. }
  1616. };
  1617. /**
  1618. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1619. * the conference.
  1620. *
  1621. * @param {JitsiRemoteTrack} removedTrack
  1622. */
  1623. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1624. this.getParticipants().forEach(participant => {
  1625. const tracks = participant.getTracks();
  1626. for (let i = 0; i < tracks.length; i++) {
  1627. if (tracks[i] === removedTrack) {
  1628. // Since the tracks have been compared and are
  1629. // considered equal the result of splice can be ignored.
  1630. participant._tracks.splice(i, 1);
  1631. this.eventEmitter.emit(
  1632. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1633. if (this.transcriber) {
  1634. this.transcriber.removeTrack(removedTrack);
  1635. }
  1636. break;
  1637. }
  1638. }
  1639. }, this);
  1640. };
  1641. /**
  1642. * Handles an incoming call event for the P2P jingle session.
  1643. */
  1644. JitsiConference.prototype._onIncomingCallP2P = function(
  1645. jingleSession,
  1646. jingleOffer) {
  1647. let rejectReason;
  1648. if (!browser.supportsP2P()) {
  1649. rejectReason = {
  1650. reason: 'unsupported-applications',
  1651. reasonDescription: 'P2P not supported',
  1652. errorMsg: 'This client does not support P2P connections'
  1653. };
  1654. } else if (!this.isP2PEnabled() && !this.isP2PTestModeEnabled()) {
  1655. rejectReason = {
  1656. reason: 'decline',
  1657. reasonDescription: 'P2P disabled',
  1658. errorMsg: 'P2P mode disabled in the configuration'
  1659. };
  1660. } else if (this.p2pJingleSession) {
  1661. // Reject incoming P2P call (already in progress)
  1662. rejectReason = {
  1663. reason: 'busy',
  1664. reasonDescription: 'P2P already in progress',
  1665. errorMsg: 'Duplicated P2P "session-initiate"'
  1666. };
  1667. } else if (!this._shouldBeInP2PMode()) {
  1668. rejectReason = {
  1669. reason: 'decline',
  1670. reasonDescription: 'P2P requirements not met',
  1671. errorMsg: 'Received P2P "session-initiate" when should not be in P2P mode'
  1672. };
  1673. Statistics.sendAnalytics(createJingleEvent(ACTION_P2P_DECLINED));
  1674. }
  1675. if (rejectReason) {
  1676. this._rejectIncomingCall(jingleSession, rejectReason);
  1677. } else {
  1678. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1679. }
  1680. };
  1681. /**
  1682. * Handles an incoming call event.
  1683. */
  1684. JitsiConference.prototype.onIncomingCall = function(
  1685. jingleSession,
  1686. jingleOffer,
  1687. now) {
  1688. // Handle incoming P2P call
  1689. if (jingleSession.isP2P) {
  1690. this._onIncomingCallP2P(jingleSession, jingleOffer);
  1691. } else {
  1692. if (!this.room.isFocus(jingleSession.remoteJid)) {
  1693. const description = 'Rejecting session-initiate from non-focus.';
  1694. this._rejectIncomingCall(
  1695. jingleSession, {
  1696. reason: 'security-error',
  1697. reasonDescription: description,
  1698. errorMsg: description
  1699. });
  1700. return;
  1701. }
  1702. this._acceptJvbIncomingCall(jingleSession, jingleOffer, now);
  1703. }
  1704. };
  1705. /**
  1706. * Accepts an incoming call event for the JVB jingle session.
  1707. */
  1708. JitsiConference.prototype._acceptJvbIncomingCall = function(
  1709. jingleSession,
  1710. jingleOffer,
  1711. now) {
  1712. // Accept incoming call
  1713. this.jvbJingleSession = jingleSession;
  1714. this.room.connectionTimes['session.initiate'] = now;
  1715. this._sendConferenceJoinAnalyticsEvent();
  1716. if (this.wasStopped) {
  1717. Statistics.sendAnalyticsAndLog(
  1718. createJingleEvent(ACTION_JINGLE_RESTART, { p2p: false }));
  1719. }
  1720. const serverRegion
  1721. = $(jingleOffer)
  1722. .find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]')
  1723. .attr('region');
  1724. this.eventEmitter.emit(
  1725. JitsiConferenceEvents.SERVER_REGION_CHANGED,
  1726. serverRegion);
  1727. this._maybeClearSITimeout();
  1728. Statistics.sendAnalytics(createJingleEvent(
  1729. ACTION_JINGLE_SI_RECEIVED,
  1730. {
  1731. p2p: false,
  1732. value: now
  1733. }));
  1734. try {
  1735. jingleSession.initialize(this.room, this.rtc, {
  1736. ...this.options.config,
  1737. enableInsertableStreams: this.isE2EEEnabled()
  1738. });
  1739. } catch (error) {
  1740. GlobalOnErrorHandler.callErrorHandler(error);
  1741. logger.error(error);
  1742. return;
  1743. }
  1744. // Open a channel with the videobridge.
  1745. this._setBridgeChannel(jingleOffer, jingleSession.peerconnection);
  1746. const localTracks = this._getInitialLocalTracks();
  1747. try {
  1748. jingleSession.acceptOffer(
  1749. jingleOffer,
  1750. () => {
  1751. // If for any reason invite for the JVB session arrived after
  1752. // the P2P has been established already the media transfer needs
  1753. // to be turned off here.
  1754. if (this.isP2PActive() && this.jvbJingleSession) {
  1755. this._suspendMediaTransferForJvbConnection();
  1756. }
  1757. this.eventEmitter.emit(
  1758. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  1759. jingleSession);
  1760. if (!this.isP2PActive()) {
  1761. this.eventEmitter.emit(
  1762. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  1763. jingleSession);
  1764. }
  1765. },
  1766. error => {
  1767. GlobalOnErrorHandler.callErrorHandler(error);
  1768. logger.error(
  1769. 'Failed to accept incoming Jingle session', error);
  1770. },
  1771. localTracks
  1772. );
  1773. // Start callstats as soon as peerconnection is initialized,
  1774. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1775. // happen in case if user doesn't have or denied permission to
  1776. // both camera and microphone.
  1777. logger.info('Starting CallStats for JVB connection...');
  1778. this.statistics.startCallStats(
  1779. this.jvbJingleSession.peerconnection,
  1780. 'jitsi' /* Remote user ID for JVB is 'jitsi' */);
  1781. this.statistics.startRemoteStats(this.jvbJingleSession.peerconnection);
  1782. } catch (e) {
  1783. GlobalOnErrorHandler.callErrorHandler(e);
  1784. logger.error(e);
  1785. }
  1786. };
  1787. /**
  1788. * Sets the BridgeChannel.
  1789. *
  1790. * @param {jQuery} offerIq a jQuery selector pointing to the jingle element of
  1791. * the offer IQ which may carry the WebSocket URL for the 'websocket'
  1792. * BridgeChannel mode.
  1793. * @param {TraceablePeerConnection} pc the peer connection which will be used
  1794. * to listen for new WebRTC Data Channels (in the 'datachannel' mode).
  1795. */
  1796. JitsiConference.prototype._setBridgeChannel = function(offerIq, pc) {
  1797. let wsUrl = null;
  1798. const webSocket
  1799. = $(offerIq)
  1800. .find('>content>transport>web-socket')
  1801. .first();
  1802. if (webSocket.length === 1) {
  1803. wsUrl = webSocket[0].getAttribute('url');
  1804. }
  1805. if (wsUrl) {
  1806. // If the offer contains a websocket use it.
  1807. this.rtc.initializeBridgeChannel(null, wsUrl);
  1808. } else {
  1809. // Otherwise, fall back to an attempt to use SCTP.
  1810. this.rtc.initializeBridgeChannel(pc, null);
  1811. }
  1812. };
  1813. /**
  1814. * Rejects incoming Jingle call.
  1815. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1816. * @param {object} [options]
  1817. * @param {string} options.reason the name of the reason element as defined
  1818. * by Jingle
  1819. * @param {string} options.reasonDescription the reason description which will
  1820. * be included in Jingle 'session-terminate' message.
  1821. * @param {string} options.errorMsg an error message to be logged on global
  1822. * error handler
  1823. * @private
  1824. */
  1825. JitsiConference.prototype._rejectIncomingCall = function(
  1826. jingleSession,
  1827. options) {
  1828. if (options && options.errorMsg) {
  1829. GlobalOnErrorHandler.callErrorHandler(new Error(options.errorMsg));
  1830. }
  1831. // Terminate the jingle session with a reason
  1832. jingleSession.terminate(
  1833. null /* success callback => we don't care */,
  1834. error => {
  1835. logger.warn(
  1836. 'An error occurred while trying to terminate'
  1837. + ' invalid Jingle session', error);
  1838. }, {
  1839. reason: options && options.reason,
  1840. reasonDescription: options && options.reasonDescription,
  1841. sendSessionTerminate: true
  1842. });
  1843. };
  1844. /**
  1845. * Handles the call ended event.
  1846. * XXX is this due to the remote side terminating the Jingle session?
  1847. *
  1848. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1849. * terminated.
  1850. * @param {String} reasonCondition the Jingle reason condition.
  1851. * @param {String|null} reasonText human readable reason text which may provide
  1852. * more details about why the call has been terminated.
  1853. */
  1854. JitsiConference.prototype.onCallEnded = function(
  1855. jingleSession,
  1856. reasonCondition,
  1857. reasonText) {
  1858. logger.info(
  1859. `Call ended: ${reasonCondition} - ${reasonText} P2P ?${
  1860. jingleSession.isP2P}`);
  1861. if (jingleSession === this.jvbJingleSession) {
  1862. this.wasStopped = true;
  1863. Statistics.sendAnalytics(
  1864. createJingleEvent(ACTION_JINGLE_TERMINATE, { p2p: false }));
  1865. // Stop the stats
  1866. if (this.statistics) {
  1867. this.statistics.stopRemoteStats(
  1868. this.jvbJingleSession.peerconnection);
  1869. logger.info('Stopping JVB CallStats');
  1870. this.statistics.stopCallStats(
  1871. this.jvbJingleSession.peerconnection);
  1872. }
  1873. // Current JVB JingleSession is no longer valid, so set it to null
  1874. this.jvbJingleSession = null;
  1875. // Let the RTC service do any cleanups
  1876. this.rtc.onCallEnded();
  1877. } else if (jingleSession === this.p2pJingleSession) {
  1878. // It's the responder who decides to enforce JVB mode, so that both
  1879. // initiator and responder are aware if it was intentional.
  1880. if (reasonCondition === 'decline' && reasonText === 'force JVB121') {
  1881. logger.info('In forced JVB 121 mode...');
  1882. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  1883. } else if (reasonCondition === 'connectivity-error'
  1884. && reasonText === 'ICE FAILED') {
  1885. // It can happen that the other peer detects ICE failed and
  1886. // terminates the session, before we get the event on our side.
  1887. // But we are able to parse the reason and mark it here.
  1888. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  1889. }
  1890. this._stopP2PSession();
  1891. } else {
  1892. logger.error(
  1893. 'Received onCallEnded for invalid session',
  1894. jingleSession.sid,
  1895. jingleSession.remoteJid,
  1896. reasonCondition,
  1897. reasonText);
  1898. }
  1899. };
  1900. /**
  1901. * Handles the suspend detected event. Leaves the room and fires suspended.
  1902. * @param {JingleSessionPC} jingleSession
  1903. */
  1904. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  1905. if (!jingleSession.isP2P) {
  1906. this.leave();
  1907. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1908. }
  1909. };
  1910. JitsiConference.prototype.updateDTMFSupport = function() {
  1911. let somebodySupportsDTMF = false;
  1912. const participants = this.getParticipants();
  1913. // check if at least 1 participant supports DTMF
  1914. for (let i = 0; i < participants.length; i += 1) {
  1915. if (participants[i].supportsDTMF()) {
  1916. somebodySupportsDTMF = true;
  1917. break;
  1918. }
  1919. }
  1920. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1921. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1922. this.eventEmitter.emit(
  1923. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1924. somebodySupportsDTMF);
  1925. }
  1926. };
  1927. /**
  1928. * Allows to check if there is at least one user in the conference
  1929. * that supports DTMF.
  1930. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1931. */
  1932. JitsiConference.prototype.isDTMFSupported = function() {
  1933. return this.somebodySupportsDTMF;
  1934. };
  1935. /**
  1936. * Returns the local user's ID
  1937. * @return {string} local user's ID
  1938. */
  1939. JitsiConference.prototype.myUserId = function() {
  1940. return (
  1941. this.room && this.room.myroomjid
  1942. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1943. : null);
  1944. };
  1945. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1946. const peerConnection = this.getActivePeerConnection();
  1947. if (peerConnection) {
  1948. peerConnection.sendTones(tones, duration, pause);
  1949. } else {
  1950. logger.warn('cannot sendTones: no peer connection');
  1951. }
  1952. };
  1953. /**
  1954. * Starts recording the current conference.
  1955. *
  1956. * @param {Object} options - Configuration for the recording. See
  1957. * {@link Chatroom#startRecording} for more info.
  1958. * @returns {Promise} See {@link Chatroom#startRecording} for more info.
  1959. */
  1960. JitsiConference.prototype.startRecording = function(options) {
  1961. if (this.room) {
  1962. return this.recordingManager.startRecording(options);
  1963. }
  1964. return Promise.reject(new Error('The conference is not created yet!'));
  1965. };
  1966. /**
  1967. * Stop a recording session.
  1968. *
  1969. * @param {string} sessionID - The ID of the recording session that
  1970. * should be stopped.
  1971. * @returns {Promise} See {@link Chatroom#stopRecording} for more info.
  1972. */
  1973. JitsiConference.prototype.stopRecording = function(sessionID) {
  1974. if (this.room) {
  1975. return this.recordingManager.stopRecording(sessionID);
  1976. }
  1977. return Promise.reject(new Error('The conference is not created yet!'));
  1978. };
  1979. /**
  1980. * Returns true if the SIP calls are supported and false otherwise
  1981. */
  1982. JitsiConference.prototype.isSIPCallingSupported = function() {
  1983. if (this.room) {
  1984. return this.room.isSIPCallingSupported();
  1985. }
  1986. return false;
  1987. };
  1988. /**
  1989. * Dials a number.
  1990. * @param number the number
  1991. */
  1992. JitsiConference.prototype.dial = function(number) {
  1993. if (this.room) {
  1994. return this.room.dial(number);
  1995. }
  1996. return new Promise((resolve, reject) => {
  1997. reject(new Error('The conference is not created yet!'));
  1998. });
  1999. };
  2000. /**
  2001. * Hangup an existing call
  2002. */
  2003. JitsiConference.prototype.hangup = function() {
  2004. if (this.room) {
  2005. return this.room.hangup();
  2006. }
  2007. return new Promise((resolve, reject) => {
  2008. reject(new Error('The conference is not created yet!'));
  2009. });
  2010. };
  2011. /**
  2012. * Starts the transcription service.
  2013. */
  2014. JitsiConference.prototype.startTranscriber = function() {
  2015. return this.dial('jitsi_meet_transcribe');
  2016. };
  2017. /**
  2018. * Stops the transcription service.
  2019. */
  2020. JitsiConference.prototype.stopTranscriber = JitsiConference.prototype.hangup;
  2021. /**
  2022. * Returns the phone number for joining the conference.
  2023. */
  2024. JitsiConference.prototype.getPhoneNumber = function() {
  2025. if (this.room) {
  2026. return this.room.getPhoneNumber();
  2027. }
  2028. return null;
  2029. };
  2030. /**
  2031. * Returns the pin for joining the conference with phone.
  2032. */
  2033. JitsiConference.prototype.getPhonePin = function() {
  2034. if (this.room) {
  2035. return this.room.getPhonePin();
  2036. }
  2037. return null;
  2038. };
  2039. /**
  2040. * Returns the meeting unique ID if any.
  2041. *
  2042. * @returns {string|undefined}
  2043. */
  2044. JitsiConference.prototype.getMeetingUniqueId = function() {
  2045. if (this.room) {
  2046. return this.room.getMeetingId();
  2047. }
  2048. };
  2049. /**
  2050. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  2051. * which connection is currently active.
  2052. *
  2053. * @return {TraceablePeerConnection|null} null if there isn't any active
  2054. * <tt>TraceablePeerConnection</tt> currently available.
  2055. * @public (FIXME how to make package local ?)
  2056. */
  2057. JitsiConference.prototype.getActivePeerConnection = function() {
  2058. if (this.isP2PActive()) {
  2059. return this.p2pJingleSession.peerconnection;
  2060. }
  2061. return this.jvbJingleSession ? this.jvbJingleSession.peerconnection : null;
  2062. };
  2063. /**
  2064. * Returns the connection state for the current room. Its ice connection state
  2065. * for its session.
  2066. * NOTE that "completed" ICE state which can appear on the P2P connection will
  2067. * be converted to "connected".
  2068. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  2069. * peer connection at this time.
  2070. */
  2071. JitsiConference.prototype.getConnectionState = function() {
  2072. const peerConnection = this.getActivePeerConnection();
  2073. return peerConnection ? peerConnection.getConnectionState() : null;
  2074. };
  2075. /**
  2076. * Make all new participants mute their audio/video on join.
  2077. * @param policy {Object} object with 2 boolean properties for video and audio:
  2078. * @param {boolean} audio if audio should be muted.
  2079. * @param {boolean} video if video should be muted.
  2080. */
  2081. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  2082. if (!this.isModerator()) {
  2083. return;
  2084. }
  2085. this.startMutedPolicy = policy;
  2086. this.room.addOrReplaceInPresence('startmuted', {
  2087. attributes: {
  2088. audio: policy.audio,
  2089. video: policy.video,
  2090. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  2091. }
  2092. }) && this.room.sendPresence();
  2093. };
  2094. /**
  2095. * Returns current start muted policy
  2096. * @returns {Object} with 2 properties - audio and video.
  2097. */
  2098. JitsiConference.prototype.getStartMutedPolicy = function() {
  2099. return this.startMutedPolicy;
  2100. };
  2101. /**
  2102. * Check if audio is muted on join.
  2103. */
  2104. JitsiConference.prototype.isStartAudioMuted = function() {
  2105. return this.startAudioMuted;
  2106. };
  2107. /**
  2108. * Check if video is muted on join.
  2109. */
  2110. JitsiConference.prototype.isStartVideoMuted = function() {
  2111. return this.startVideoMuted;
  2112. };
  2113. /**
  2114. * Returns measured connectionTimes.
  2115. */
  2116. JitsiConference.prototype.getConnectionTimes = function() {
  2117. return this.room.connectionTimes;
  2118. };
  2119. /**
  2120. * Sets a property for the local participant.
  2121. */
  2122. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  2123. this.sendCommand(`jitsi_participant_${name}`, { value });
  2124. };
  2125. /**
  2126. * Removes a property for the local participant and sends the updated presence.
  2127. */
  2128. JitsiConference.prototype.removeLocalParticipantProperty = function(name) {
  2129. this.removeCommand(`jitsi_participant_${name}`);
  2130. this.room.sendPresence();
  2131. };
  2132. /**
  2133. * Gets a local participant property.
  2134. *
  2135. * @return value of the local participant property if the tagName exists in the
  2136. * list of properties, otherwise returns undefined.
  2137. */
  2138. JitsiConference.prototype.getLocalParticipantProperty = function(name) {
  2139. const property = this.room.presMap.nodes.find(prop =>
  2140. prop.tagName === `jitsi_participant_${name}`
  2141. );
  2142. return property ? property.value : undefined;
  2143. };
  2144. /**
  2145. * Sends the given feedback through CallStats if enabled.
  2146. *
  2147. * @param overallFeedback an integer between 1 and 5 indicating the
  2148. * user feedback
  2149. * @param detailedFeedback detailed feedback from the user. Not yet used
  2150. * @returns {Promise} Resolves if feedback is submitted successfully.
  2151. */
  2152. JitsiConference.prototype.sendFeedback = function(
  2153. overallFeedback,
  2154. detailedFeedback) {
  2155. return this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  2156. };
  2157. /**
  2158. * Returns true if the callstats integration is enabled, otherwise returns
  2159. * false.
  2160. *
  2161. * @returns true if the callstats integration is enabled, otherwise returns
  2162. * false.
  2163. */
  2164. JitsiConference.prototype.isCallstatsEnabled = function() {
  2165. return this.statistics.isCallstatsEnabled();
  2166. };
  2167. /**
  2168. * Finds the SSRC of a given track
  2169. *
  2170. * @param track
  2171. * @returns {number|undefined} the SSRC of the specificed track, otherwise undefined.
  2172. */
  2173. JitsiConference.prototype.getSsrcByTrack = function(track) {
  2174. return track.isLocal() ? this.getActivePeerConnection()?.getLocalSSRC(track) : track.getSSRC();
  2175. };
  2176. /**
  2177. * Handles track attached to container (Calls associateStreamWithVideoTag method
  2178. * from statistics module)
  2179. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  2180. * @param container the container
  2181. */
  2182. JitsiConference.prototype._onTrackAttach = function(track, container) {
  2183. const isLocal = track.isLocal();
  2184. let ssrc = null;
  2185. const isP2P = track.isP2P;
  2186. const remoteUserId = isP2P ? track.getParticipantId() : 'jitsi';
  2187. const peerConnection
  2188. = isP2P
  2189. ? this.p2pJingleSession && this.p2pJingleSession.peerconnection
  2190. : this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  2191. if (isLocal) {
  2192. // Local tracks have SSRC stored on per peer connection basis.
  2193. if (peerConnection) {
  2194. ssrc = peerConnection.getLocalSSRC(track);
  2195. }
  2196. } else {
  2197. ssrc = track.getSSRC();
  2198. }
  2199. if (!container.id || !ssrc || !peerConnection) {
  2200. return;
  2201. }
  2202. this.statistics.associateStreamWithVideoTag(
  2203. peerConnection,
  2204. ssrc,
  2205. isLocal,
  2206. remoteUserId,
  2207. track.getUsageLabel(),
  2208. container.id);
  2209. };
  2210. /**
  2211. * Logs an "application log" message.
  2212. * @param message {string} The message to log. Note that while this can be a
  2213. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  2214. * log valid JSON strings, with an "id" field used for distinguishing between
  2215. * message types. E.g.: {id: "recorder_status", status: "off"}
  2216. */
  2217. JitsiConference.prototype.sendApplicationLog = function(message) {
  2218. Statistics.sendLog(message);
  2219. };
  2220. /**
  2221. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  2222. * focus.
  2223. * @param mucJid the full MUC address of the user to be checked.
  2224. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  2225. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  2226. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  2227. */
  2228. JitsiConference.prototype._isFocus = function(mucJid) {
  2229. return this.room ? this.room.isFocus(mucJid) : null;
  2230. };
  2231. /**
  2232. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  2233. */
  2234. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  2235. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  2236. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  2237. };
  2238. /**
  2239. * Sends a message via the data channel.
  2240. * @param to {string} the id of the endpoint that should receive the message.
  2241. * If "" the message will be sent to all participants.
  2242. * @param payload {object} the payload of the message.
  2243. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2244. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2245. */
  2246. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  2247. this.rtc.sendChannelMessage(to, payload);
  2248. };
  2249. /**
  2250. * Sends local stats via the bridge channel which then forwards to other endpoints selectively.
  2251. * @param {Object} payload The payload of the message.
  2252. * @throws NetworkError/InvalidStateError/Error if the operation fails or if there is no data channel created.
  2253. */
  2254. JitsiConference.prototype.sendEndpointStatsMessage = function(payload) {
  2255. this.rtc.sendEndpointStatsMessage(payload);
  2256. };
  2257. /**
  2258. * Sends a broadcast message via the data channel.
  2259. * @param payload {object} the payload of the message.
  2260. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2261. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2262. */
  2263. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  2264. this.sendEndpointMessage('', payload);
  2265. };
  2266. /**
  2267. * Sends a message to a given endpoint (if 'to' is a non-empty string), or
  2268. * broadcasts it to all endpoints in the conference.
  2269. * @param {string} to The ID of the endpoint/participant which is to receive
  2270. * the message, or '' to broadcast the message to all endpoints in the
  2271. * conference.
  2272. * @param {string|object} message the message to send. If this is of type
  2273. * 'string' it will be sent as a chat message. If it is of type 'object', it
  2274. * will be encapsulated in a format recognized by jitsi-meet and converted to
  2275. * JSON before being sent.
  2276. * @param {boolean} sendThroughVideobridge Whether to send the message through
  2277. * jitsi-videobridge (via the COLIBRI data channel or web socket), or through
  2278. * the XMPP MUC. Currently only objects can be sent through jitsi-videobridge.
  2279. */
  2280. JitsiConference.prototype.sendMessage = function(
  2281. message,
  2282. to = '',
  2283. sendThroughVideobridge = false) {
  2284. const messageType = typeof message;
  2285. // Through videobridge we support only objects. Through XMPP we support
  2286. // objects (encapsulated in a specific JSON format) and strings (i.e.
  2287. // regular chat messages).
  2288. if (messageType !== 'object'
  2289. && (sendThroughVideobridge || messageType !== 'string')) {
  2290. logger.error(`Can not send a message of type ${messageType}`);
  2291. return;
  2292. }
  2293. if (sendThroughVideobridge) {
  2294. this.sendEndpointMessage(to, message);
  2295. } else {
  2296. let messageToSend = message;
  2297. // Name of packet extension of message stanza to send the required
  2298. // message in.
  2299. let elementName = 'body';
  2300. if (messageType === 'object') {
  2301. elementName = 'json-message';
  2302. // Mark as valid JSON message if not already
  2303. if (!messageToSend.hasOwnProperty(JITSI_MEET_MUC_TYPE)) {
  2304. messageToSend[JITSI_MEET_MUC_TYPE] = '';
  2305. }
  2306. try {
  2307. messageToSend = JSON.stringify(messageToSend);
  2308. } catch (e) {
  2309. logger.error('Can not send a message, stringify failed: ', e);
  2310. return;
  2311. }
  2312. }
  2313. if (to) {
  2314. this.sendPrivateTextMessage(to, messageToSend, elementName);
  2315. } else {
  2316. // Broadcast
  2317. this.sendTextMessage(messageToSend, elementName);
  2318. }
  2319. }
  2320. };
  2321. JitsiConference.prototype.isConnectionInterrupted = function() {
  2322. return this.isP2PActive()
  2323. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  2324. };
  2325. /**
  2326. * Handles {@link XMPPEvents.CONNECTION_RESTARTED} event. This happens when the bridge goes down
  2327. * and Jicofo moves conferences away to a different bridge.
  2328. * @param {JingleSessionPC} session
  2329. * @private
  2330. */
  2331. JitsiConference.prototype._onConferenceRestarted = function(session) {
  2332. if (!session.isP2P && this.options.config.enableForcedReload) {
  2333. this.restartInProgress = true;
  2334. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONFERENCE_RESTARTED);
  2335. }
  2336. };
  2337. /**
  2338. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  2339. * @param {JingleSessionPC} session
  2340. * @private
  2341. */
  2342. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  2343. if (session.isP2P) {
  2344. this.isP2PConnectionInterrupted = true;
  2345. } else {
  2346. this.isJvbConnectionInterrupted = true;
  2347. }
  2348. if (session.isP2P === this.isP2PActive()) {
  2349. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  2350. }
  2351. };
  2352. /**
  2353. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  2354. * @param {JingleSessionPC} session
  2355. * @private
  2356. */
  2357. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  2358. // We do nothing for the JVB connection, because it's up to the Jicofo to
  2359. // eventually come up with the new offer (at least for the time being).
  2360. if (session.isP2P) {
  2361. // Add p2pFailed property to analytics to distinguish, between "good"
  2362. // and "bad" connection
  2363. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2364. if (this.p2pJingleSession) {
  2365. Statistics.sendAnalyticsAndLog(
  2366. createP2PEvent(
  2367. ACTION_P2P_FAILED,
  2368. {
  2369. initiator: this.p2pJingleSession.isInitiator
  2370. }));
  2371. }
  2372. this._stopP2PSession('connectivity-error', 'ICE FAILED');
  2373. } else if (session && this.jvbJingleSession === session) {
  2374. this._delayedIceFailed = new IceFailedHandling(this);
  2375. this._delayedIceFailed.start(session);
  2376. }
  2377. };
  2378. /**
  2379. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  2380. * @param {JingleSessionPC} session
  2381. * @private
  2382. */
  2383. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  2384. if (session.isP2P) {
  2385. this.isP2PConnectionInterrupted = false;
  2386. } else {
  2387. this.isJvbConnectionInterrupted = false;
  2388. this._delayedIceFailed && this._delayedIceFailed.cancel();
  2389. }
  2390. if (session.isP2P === this.isP2PActive()) {
  2391. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  2392. }
  2393. };
  2394. /**
  2395. * Accept incoming P2P Jingle call.
  2396. * @param {JingleSessionPC} jingleSession the session instance
  2397. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  2398. * @private
  2399. */
  2400. JitsiConference.prototype._acceptP2PIncomingCall = function(
  2401. jingleSession,
  2402. jingleOffer) {
  2403. this.isP2PConnectionInterrupted = false;
  2404. // Accept the offer
  2405. this.p2pJingleSession = jingleSession;
  2406. this._sendConferenceJoinAnalyticsEvent();
  2407. this.p2pJingleSession.initialize(
  2408. this.room,
  2409. this.rtc, {
  2410. ...this.options.config,
  2411. enableInsertableStreams: this.isE2EEEnabled()
  2412. });
  2413. logger.info('Starting CallStats for P2P connection...');
  2414. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2415. const participant = this.participants[remoteID];
  2416. if (participant) {
  2417. remoteID = participant.getStatsID() || remoteID;
  2418. }
  2419. this.statistics.startCallStats(
  2420. this.p2pJingleSession.peerconnection,
  2421. remoteID);
  2422. const localTracks = this._getInitialLocalTracks();
  2423. this.p2pJingleSession.acceptOffer(
  2424. jingleOffer,
  2425. () => {
  2426. logger.debug('Got RESULT for P2P "session-accept"');
  2427. this.eventEmitter.emit(
  2428. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  2429. this.p2pJingleSession);
  2430. },
  2431. error => {
  2432. logger.error(
  2433. 'Failed to accept incoming P2P Jingle session', error);
  2434. },
  2435. localTracks);
  2436. };
  2437. /**
  2438. * Adds remote tracks to the conference associated with the JVB session.
  2439. * @private
  2440. */
  2441. JitsiConference.prototype._addRemoteJVBTracks = function() {
  2442. this._addRemoteTracks(
  2443. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2444. };
  2445. /**
  2446. * Adds remote tracks to the conference associated with the P2P session.
  2447. * @private
  2448. */
  2449. JitsiConference.prototype._addRemoteP2PTracks = function() {
  2450. this._addRemoteTracks(
  2451. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2452. };
  2453. /**
  2454. * Generates fake "remote track added" events for given Jingle session.
  2455. * @param {string} logName the session's nickname which will appear in log
  2456. * messages.
  2457. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  2458. * @private
  2459. */
  2460. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  2461. for (const track of remoteTracks) {
  2462. logger.info(`Adding remote ${logName} track: ${track}`);
  2463. this.onRemoteTrackAdded(track);
  2464. }
  2465. };
  2466. /**
  2467. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  2468. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  2469. * the P2P connection if the event comes from the P2P session.
  2470. * @param {JingleSessionPC} jingleSession the session instance.
  2471. * @private
  2472. */
  2473. JitsiConference.prototype._onIceConnectionEstablished = function(
  2474. jingleSession) {
  2475. if (this.p2pJingleSession !== null) {
  2476. // store the establishment time of the p2p session as a field of the
  2477. // JitsiConference because the p2pJingleSession might get disposed (thus
  2478. // the value is lost).
  2479. this.p2pEstablishmentDuration
  2480. = this.p2pJingleSession.establishmentDuration;
  2481. }
  2482. if (this.jvbJingleSession !== null) {
  2483. this.jvbEstablishmentDuration
  2484. = this.jvbJingleSession.establishmentDuration;
  2485. }
  2486. let done = false;
  2487. const forceJVB121Ratio = this.options.config.forceJVB121Ratio;
  2488. // We don't care about the JVB case, there's nothing to be done
  2489. if (!jingleSession.isP2P) {
  2490. done = true;
  2491. } else if (this.p2pJingleSession !== jingleSession) {
  2492. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  2493. done = true;
  2494. } else if (!jingleSession.isInitiator
  2495. && typeof forceJVB121Ratio === 'number'
  2496. && Math.random() < forceJVB121Ratio) {
  2497. logger.info(`Forcing JVB 121 mode (ratio=${forceJVB121Ratio})...`);
  2498. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  2499. this._stopP2PSession('decline', 'force JVB121');
  2500. done = true;
  2501. }
  2502. if (!isNaN(this.p2pEstablishmentDuration)
  2503. && !isNaN(this.jvbEstablishmentDuration)) {
  2504. const establishmentDurationDiff
  2505. = this.p2pEstablishmentDuration - this.jvbEstablishmentDuration;
  2506. Statistics.sendAnalytics(
  2507. ICE_ESTABLISHMENT_DURATION_DIFF,
  2508. { value: establishmentDurationDiff });
  2509. }
  2510. if (jingleSession.isP2P === this.isP2PActive()) {
  2511. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_ESTABLISHED);
  2512. }
  2513. if (done) {
  2514. return;
  2515. }
  2516. // Update P2P status and emit events
  2517. this._setP2PStatus(true);
  2518. // Remove remote tracks
  2519. if (this.jvbJingleSession) {
  2520. this._removeRemoteJVBTracks();
  2521. } else {
  2522. logger.info('Not removing remote JVB tracks - no session yet');
  2523. }
  2524. this._addRemoteP2PTracks();
  2525. // Stop media transfer over the JVB connection
  2526. if (this.jvbJingleSession) {
  2527. this._suspendMediaTransferForJvbConnection();
  2528. }
  2529. logger.info('Starting remote stats with p2p connection');
  2530. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  2531. Statistics.sendAnalyticsAndLog(
  2532. createP2PEvent(
  2533. ACTION_P2P_ESTABLISHED,
  2534. {
  2535. initiator: this.p2pJingleSession.isInitiator
  2536. }));
  2537. };
  2538. /**
  2539. * Called when the chat room reads a new list of properties from jicofo's
  2540. * presence. The properties may have changed, but they don't have to.
  2541. *
  2542. * @param {Object} properties - The properties keyed by the property name
  2543. * ('key').
  2544. * @private
  2545. */
  2546. JitsiConference.prototype._updateProperties = function(properties = {}) {
  2547. const changed = !isEqual(properties, this.properties);
  2548. this.properties = properties;
  2549. if (changed) {
  2550. this.eventEmitter.emit(
  2551. JitsiConferenceEvents.PROPERTIES_CHANGED,
  2552. this.properties);
  2553. // Some of the properties need to be added to analytics events.
  2554. const analyticsKeys = [
  2555. // The number of jitsi-videobridge instances currently used for the
  2556. // conference.
  2557. 'bridge-count',
  2558. // The conference creation time (set by jicofo).
  2559. 'created-ms'
  2560. ];
  2561. analyticsKeys.forEach(key => {
  2562. if (properties[key] !== undefined) {
  2563. Statistics.analytics.addPermanentProperties({
  2564. [key.replace('-', '_')]: properties[key]
  2565. });
  2566. }
  2567. });
  2568. }
  2569. };
  2570. /**
  2571. * Gets a conference property with a given key.
  2572. *
  2573. * @param {string} key - The key.
  2574. * @returns {*} The value
  2575. */
  2576. JitsiConference.prototype.getProperty = function(key) {
  2577. return this.properties[key];
  2578. };
  2579. /**
  2580. * Clears the deferred start P2P task if it has been scheduled.
  2581. * @private
  2582. */
  2583. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  2584. if (this.deferredStartP2PTask) {
  2585. logger.info('Cleared deferred start P2P task');
  2586. clearTimeout(this.deferredStartP2PTask);
  2587. this.deferredStartP2PTask = null;
  2588. }
  2589. };
  2590. /**
  2591. * Removes from the conference remote tracks associated with the JVB
  2592. * connection.
  2593. * @private
  2594. */
  2595. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  2596. this._removeRemoteTracks(
  2597. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2598. };
  2599. /**
  2600. * Removes from the conference remote tracks associated with the P2P
  2601. * connection.
  2602. * @private
  2603. */
  2604. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  2605. this._removeRemoteTracks(
  2606. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2607. };
  2608. /**
  2609. * Generates fake "remote track removed" events for given Jingle session.
  2610. * @param {string} sessionNickname the session's nickname which will appear in
  2611. * log messages.
  2612. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  2613. * @private
  2614. */
  2615. JitsiConference.prototype._removeRemoteTracks = function(
  2616. sessionNickname,
  2617. remoteTracks) {
  2618. for (const track of remoteTracks) {
  2619. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  2620. this.onRemoteTrackRemoved(track);
  2621. }
  2622. };
  2623. /**
  2624. * Resumes media transfer over the JVB connection.
  2625. * @private
  2626. */
  2627. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  2628. logger.info('Resuming media transfer over the JVB connection...');
  2629. this.jvbJingleSession.setMediaTransferActive(true, true).then(
  2630. () => {
  2631. logger.info('Resumed media transfer over the JVB connection!');
  2632. },
  2633. error => {
  2634. logger.error(
  2635. 'Failed to resume media transfer over the JVB connection:',
  2636. error);
  2637. });
  2638. };
  2639. /**
  2640. * Sets new P2P status and updates some events/states hijacked from
  2641. * the <tt>JitsiConference</tt>.
  2642. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  2643. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  2644. * @private
  2645. */
  2646. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  2647. if (this.p2p === newStatus) {
  2648. logger.debug(`Called _setP2PStatus with the same status: ${newStatus}`);
  2649. return;
  2650. }
  2651. this.p2p = newStatus;
  2652. if (newStatus) {
  2653. logger.info('Peer to peer connection established!');
  2654. // When we end up in a valid P2P session need to reset the properties
  2655. // in case they have persisted, after session with another peer.
  2656. Statistics.analytics.addPermanentProperties({
  2657. p2pFailed: false,
  2658. forceJvb121: false
  2659. });
  2660. // Sync up video transfer active in case p2pJingleSession not existed
  2661. // when the lastN value was being adjusted.
  2662. const isVideoActive = this.getLastN() !== 0;
  2663. this.p2pJingleSession
  2664. .setMediaTransferActive(true, isVideoActive)
  2665. .catch(error => {
  2666. logger.error(
  2667. 'Failed to sync up P2P video transfer status'
  2668. + `(${isVideoActive})`, error);
  2669. });
  2670. } else {
  2671. logger.info('Peer to peer connection closed!');
  2672. }
  2673. // Put the JVB connection on hold/resume
  2674. if (this.jvbJingleSession) {
  2675. this.statistics.sendConnectionResumeOrHoldEvent(
  2676. this.jvbJingleSession.peerconnection, !newStatus);
  2677. }
  2678. // Clear dtmfManager, so that it can be recreated with new connection
  2679. this.dtmfManager = null;
  2680. // Update P2P status
  2681. this.eventEmitter.emit(
  2682. JitsiConferenceEvents.P2P_STATUS,
  2683. this,
  2684. this.p2p);
  2685. this.eventEmitter.emit(
  2686. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  2687. this._getActiveMediaSession());
  2688. // Refresh connection interrupted/restored
  2689. this.eventEmitter.emit(
  2690. this.isConnectionInterrupted()
  2691. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  2692. : JitsiConferenceEvents.CONNECTION_RESTORED);
  2693. };
  2694. /**
  2695. * Starts new P2P session.
  2696. * @param {string} remoteJid the JID of the remote participant
  2697. * @private
  2698. */
  2699. JitsiConference.prototype._startP2PSession = function(remoteJid) {
  2700. this._maybeClearDeferredStartP2P();
  2701. if (this.p2pJingleSession) {
  2702. logger.error('P2P session already started!');
  2703. return;
  2704. }
  2705. this.isP2PConnectionInterrupted = false;
  2706. this.p2pJingleSession
  2707. = this.xmpp.connection.jingle.newP2PJingleSession(
  2708. this.room.myroomjid,
  2709. remoteJid);
  2710. logger.info(
  2711. 'Created new P2P JingleSession', this.room.myroomjid, remoteJid);
  2712. this._sendConferenceJoinAnalyticsEvent();
  2713. this.p2pJingleSession.initialize(
  2714. this.room,
  2715. this.rtc, {
  2716. ...this.options.config,
  2717. enableInsertableStreams: this.isE2EEEnabled()
  2718. });
  2719. logger.info('Starting CallStats for P2P connection...');
  2720. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2721. const participant = this.participants[remoteID];
  2722. if (participant) {
  2723. remoteID = participant.getStatsID() || remoteID;
  2724. }
  2725. this.statistics.startCallStats(
  2726. this.p2pJingleSession.peerconnection,
  2727. remoteID);
  2728. const localTracks = this._getInitialLocalTracks();
  2729. this.p2pJingleSession.invite(localTracks);
  2730. };
  2731. /**
  2732. * Suspends media transfer over the JVB connection.
  2733. * @private
  2734. */
  2735. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  2736. logger.info('Suspending media transfer over the JVB connection...');
  2737. this.jvbJingleSession.setMediaTransferActive(false, false).then(
  2738. () => {
  2739. logger.info('Suspended media transfer over the JVB connection !');
  2740. },
  2741. error => {
  2742. logger.error(
  2743. 'Failed to suspend media transfer over the JVB connection:',
  2744. error);
  2745. });
  2746. };
  2747. /**
  2748. * Method when called will decide whether it's the time to start or stop
  2749. * the P2P session.
  2750. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  2751. * originates from the user left event.
  2752. * @private
  2753. */
  2754. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  2755. if (!browser.supportsP2P()
  2756. || !this.isP2PEnabled()
  2757. || this.isP2PTestModeEnabled()) {
  2758. logger.info('Auto P2P disabled');
  2759. return;
  2760. }
  2761. const peers = this.getParticipants();
  2762. const peerCount = peers.length;
  2763. // FIXME 1 peer and it must *support* P2P switching
  2764. const shouldBeInP2P = this._shouldBeInP2PMode();
  2765. // Clear deferred "start P2P" task
  2766. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  2767. this._maybeClearDeferredStartP2P();
  2768. }
  2769. // Start peer to peer session
  2770. if (!this.p2pJingleSession && shouldBeInP2P) {
  2771. const peer = peerCount && peers[0];
  2772. const myId = this.myUserId();
  2773. const peersId = peer.getId();
  2774. if (myId > peersId) {
  2775. logger.debug(
  2776. 'I\'m the bigger peersId - '
  2777. + 'the other peer should start P2P', myId, peersId);
  2778. return;
  2779. } else if (myId === peersId) {
  2780. logger.error('The same IDs ? ', myId, peersId);
  2781. return;
  2782. }
  2783. const jid = peer.getJid();
  2784. if (userLeftEvent) {
  2785. if (this.deferredStartP2PTask) {
  2786. logger.error('Deferred start P2P task\'s been set already!');
  2787. return;
  2788. }
  2789. logger.info(
  2790. `Will start P2P with: ${jid} after ${
  2791. this.backToP2PDelay} seconds...`);
  2792. this.deferredStartP2PTask = setTimeout(
  2793. this._startP2PSession.bind(this, jid),
  2794. this.backToP2PDelay * 1000);
  2795. } else {
  2796. logger.info(`Will start P2P with: ${jid}`);
  2797. this._startP2PSession(jid);
  2798. }
  2799. } else if (this.p2pJingleSession && !shouldBeInP2P) {
  2800. logger.info(`Will stop P2P with: ${this.p2pJingleSession.remoteJid}`);
  2801. // Log that there will be a switch back to the JVB connection
  2802. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  2803. Statistics.sendAnalyticsAndLog(
  2804. createP2PEvent(ACTION_P2P_SWITCH_TO_JVB));
  2805. }
  2806. this._stopP2PSession();
  2807. }
  2808. };
  2809. /**
  2810. * Tells whether or not this conference should be currently in the P2P mode.
  2811. *
  2812. * @private
  2813. * @returns {boolean}
  2814. */
  2815. JitsiConference.prototype._shouldBeInP2PMode = function() {
  2816. const peers = this.getParticipants();
  2817. const peerCount = peers.length;
  2818. const hasBotPeer = peers.find(p => p.getBotType() === 'poltergeist' || p.hasFeature(FEATURE_JIGASI)) !== undefined;
  2819. const shouldBeInP2P = peerCount === 1 && !hasBotPeer;
  2820. logger.debug(`P2P? peerCount: ${peerCount}, hasBotPeer: ${hasBotPeer} => ${shouldBeInP2P}`);
  2821. return shouldBeInP2P;
  2822. };
  2823. /**
  2824. * Stops the current P2P session.
  2825. * @param {string} [reason="success"] one of the Jingle "reason" element
  2826. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  2827. * @param {string} [reasonDescription="Turing off P2P session"] text
  2828. * description that will be included in the session terminate message
  2829. * @private
  2830. */
  2831. JitsiConference.prototype._stopP2PSession = function(
  2832. reason,
  2833. reasonDescription) {
  2834. if (!this.p2pJingleSession) {
  2835. logger.error('No P2P session to be stopped!');
  2836. return;
  2837. }
  2838. const wasP2PEstablished = this.isP2PActive();
  2839. // Swap remote tracks, but only if the P2P has been fully established
  2840. if (wasP2PEstablished) {
  2841. if (this.jvbJingleSession) {
  2842. this._resumeMediaTransferForJvbConnection();
  2843. }
  2844. // Remove remote P2P tracks
  2845. this._removeRemoteP2PTracks();
  2846. }
  2847. // Stop P2P stats
  2848. logger.info('Stopping remote stats for P2P connection');
  2849. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  2850. logger.info('Stopping CallStats for P2P connection');
  2851. this.statistics.stopCallStats(this.p2pJingleSession.peerconnection);
  2852. this.p2pJingleSession.terminate(
  2853. () => {
  2854. logger.info('P2P session terminate RESULT');
  2855. },
  2856. error => {
  2857. // Because both initiator and responder are simultaneously
  2858. // terminating their JingleSessions in case of the 'to JVB switch'
  2859. // when 3rd participant joins, both will dispose their sessions and
  2860. // reply with 'item-not-found' (see strophe.jingle.js). We don't
  2861. // want to log this as an error since it's expected behaviour.
  2862. //
  2863. // We want them both to terminate, because in case of initiator's
  2864. // crash the responder would stay in P2P mode until ICE fails which
  2865. // could take up to 20 seconds.
  2866. //
  2867. // NOTE lack of 'reason' is considered as graceful session terminate
  2868. // where both initiator and responder terminate their sessions
  2869. // simultaneously.
  2870. if (reason) {
  2871. logger.error(
  2872. 'An error occurred while trying to terminate'
  2873. + ' P2P Jingle session', error);
  2874. }
  2875. }, {
  2876. reason: reason ? reason : 'success',
  2877. reasonDescription: reasonDescription
  2878. ? reasonDescription : 'Turing off P2P session',
  2879. sendSessionTerminate: this.room
  2880. && this.getParticipantById(
  2881. Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid))
  2882. });
  2883. this.p2pJingleSession = null;
  2884. // Update P2P status and other affected events/states
  2885. this._setP2PStatus(false);
  2886. if (wasP2PEstablished) {
  2887. // Add back remote JVB tracks
  2888. if (this.jvbJingleSession) {
  2889. this._addRemoteJVBTracks();
  2890. } else {
  2891. logger.info('Not adding remote JVB tracks - no session yet');
  2892. }
  2893. }
  2894. };
  2895. /**
  2896. * Checks whether or not the conference is currently in the peer to peer mode.
  2897. * Being in peer to peer mode means that the direct connection has been
  2898. * established and the P2P connection is being used for media transmission.
  2899. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  2900. */
  2901. JitsiConference.prototype.isP2PActive = function() {
  2902. return this.p2p;
  2903. };
  2904. /**
  2905. * Returns the current ICE state of the P2P connection.
  2906. * NOTE: method is used by the jitsi-meet-torture tests.
  2907. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  2908. * no P2P connection.
  2909. */
  2910. JitsiConference.prototype.getP2PConnectionState = function() {
  2911. if (this.isP2PActive()) {
  2912. return this.p2pJingleSession.peerconnection.getConnectionState();
  2913. }
  2914. return null;
  2915. };
  2916. /**
  2917. * Manually starts new P2P session (should be used only in the tests).
  2918. */
  2919. JitsiConference.prototype.startP2PSession = function() {
  2920. const peers = this.getParticipants();
  2921. // Start peer to peer session
  2922. if (peers.length === 1) {
  2923. const peerJid = peers[0].getJid();
  2924. this._startP2PSession(peerJid);
  2925. } else {
  2926. throw new Error(
  2927. 'There must be exactly 1 participant to start the P2P session !');
  2928. }
  2929. };
  2930. /**
  2931. * Manually stops the current P2P session (should be used only in the tests)
  2932. */
  2933. JitsiConference.prototype.stopP2PSession = function() {
  2934. this._stopP2PSession();
  2935. };
  2936. /**
  2937. * Get a summary of how long current participants have been the dominant speaker
  2938. * @returns {object}
  2939. */
  2940. JitsiConference.prototype.getSpeakerStats = function() {
  2941. return this.speakerStatsCollector.getStats();
  2942. };
  2943. /**
  2944. * Sets the constraints for the video that is requested from the bridge.
  2945. *
  2946. * @param {Object} videoConstraints The constraints which are specified in the
  2947. * following format. The message updates the fields that are present and leaves the
  2948. * rest unchanged on the bridge. Therefore, any field that is not applicable anymore
  2949. * should be cleared by passing an empty object or list (whatever is applicable).
  2950. * {
  2951. * 'lastN': 20,
  2952. * 'selectedEndpoints': ['A', 'B', 'C'],
  2953. * 'onStageEndpoints': ['A'],
  2954. * 'defaultConstraints': { 'maxHeight': 180 },
  2955. * 'constraints': {
  2956. * 'A': { 'maxHeight': 720 }
  2957. * }
  2958. * }
  2959. */
  2960. JitsiConference.prototype.setReceiverConstraints = function(videoConstraints) {
  2961. this.receiveVideoController.setReceiverConstraints(videoConstraints);
  2962. };
  2963. /**
  2964. * Sets the maximum video size the local participant should receive from remote
  2965. * participants.
  2966. *
  2967. * @param {number} maxFrameHeight - the maximum frame height, in pixels,
  2968. * this receiver is willing to receive.
  2969. * @returns {void}
  2970. */
  2971. JitsiConference.prototype.setReceiverVideoConstraint = function(maxFrameHeight) {
  2972. this.receiveVideoController.setPreferredReceiveMaxFrameHeight(maxFrameHeight);
  2973. };
  2974. /**
  2975. * Sets the maximum video size the local participant should send to remote
  2976. * participants.
  2977. * @param {number} maxFrameHeight - The user preferred max frame height.
  2978. * @returns {Promise} promise that will be resolved when the operation is
  2979. * successful and rejected otherwise.
  2980. */
  2981. JitsiConference.prototype.setSenderVideoConstraint = function(maxFrameHeight) {
  2982. return this.sendVideoController.setPreferredSendMaxFrameHeight(maxFrameHeight);
  2983. };
  2984. /**
  2985. * Creates a video SIP GW session and returns it if service is enabled. Before
  2986. * creating a session one need to check whether video SIP GW service is
  2987. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2988. * if there are available nodes to serve this request, after creating the
  2989. * session those nodes can be taken and the request about using the
  2990. * created session can fail.
  2991. *
  2992. * @param {string} sipAddress - The sip address to be used.
  2993. * @param {string} displayName - The display name to be used for this session.
  2994. * @returns {JitsiVideoSIPGWSession|Error} Returns null if conference is not
  2995. * initialised and there is no room.
  2996. */
  2997. JitsiConference.prototype.createVideoSIPGWSession
  2998. = function(sipAddress, displayName) {
  2999. if (!this.room) {
  3000. return new Error(VideoSIPGWConstants.ERROR_NO_CONNECTION);
  3001. }
  3002. return this.videoSIPGWHandler
  3003. .createVideoSIPGWSession(sipAddress, displayName);
  3004. };
  3005. /**
  3006. * Sends a conference.join analytics event.
  3007. *
  3008. * @returns {void}
  3009. */
  3010. JitsiConference.prototype._sendConferenceJoinAnalyticsEvent = function() {
  3011. const meetingId = this.getMeetingUniqueId();
  3012. if (this._conferenceJoinAnalyticsEventSent || !meetingId || this.getActivePeerConnection() === null) {
  3013. return;
  3014. }
  3015. Statistics.sendAnalytics(createConferenceEvent('joined', {
  3016. meetingId,
  3017. participantId: `${meetingId}.${this._statsCurrentId}`
  3018. }));
  3019. this._conferenceJoinAnalyticsEventSent = Date.now();
  3020. };
  3021. /**
  3022. * Sends conference.left analytics event.
  3023. * @private
  3024. */
  3025. JitsiConference.prototype._sendConferenceLeftAnalyticsEvent = function() {
  3026. const meetingId = this.getMeetingUniqueId();
  3027. if (!meetingId || !this._conferenceJoinAnalyticsEventSent) {
  3028. return;
  3029. }
  3030. Statistics.sendAnalytics(createConferenceEvent('left', {
  3031. meetingId,
  3032. participantId: `${meetingId}.${this._statsCurrentId}`,
  3033. stats: {
  3034. duration: Math.floor((Date.now() - this._conferenceJoinAnalyticsEventSent) / 1000),
  3035. perf: this.getPerformanceStats()
  3036. }
  3037. }));
  3038. };
  3039. /**
  3040. * Restarts all active media sessions.
  3041. *
  3042. * @returns {void}
  3043. */
  3044. JitsiConference.prototype._restartMediaSessions = function() {
  3045. if (this.p2pJingleSession) {
  3046. this.stopP2PSession();
  3047. }
  3048. if (this.jvbJingleSession) {
  3049. this.jvbJingleSession.terminate(
  3050. null /* success callback => we don't care */,
  3051. error => {
  3052. logger.warn('An error occurred while trying to terminate the JVB session', error);
  3053. }, {
  3054. reason: 'success',
  3055. reasonDescription: 'restart required',
  3056. requestRestart: true,
  3057. sendSessionTerminate: true
  3058. });
  3059. }
  3060. this._maybeStartOrStopP2P(false);
  3061. };
  3062. /**
  3063. * Returns whether End-To-End encryption is enabled.
  3064. *
  3065. * @returns {boolean}
  3066. */
  3067. JitsiConference.prototype.isE2EEEnabled = function() {
  3068. return this._e2eEncryption && this._e2eEncryption.isEnabled();
  3069. };
  3070. /**
  3071. * Returns whether End-To-End encryption is supported. Note that not all participants
  3072. * in the conference may support it.
  3073. *
  3074. * @returns {boolean}
  3075. */
  3076. JitsiConference.prototype.isE2EESupported = function() {
  3077. return E2EEncryption.isSupported(this.options.config);
  3078. };
  3079. /**
  3080. * Enables / disables End-to-End encryption.
  3081. *
  3082. * @param {boolean} enabled whether to enable E2EE or not.
  3083. * @returns {void}
  3084. */
  3085. JitsiConference.prototype.toggleE2EE = function(enabled) {
  3086. if (!this.isE2EESupported()) {
  3087. logger.warn('Cannot enable / disable E2EE: platform is not supported.');
  3088. return;
  3089. }
  3090. this._e2eEncryption.setEnabled(enabled);
  3091. };
  3092. /**
  3093. * Returns <tt>true</tt> if lobby support is enabled in the backend.
  3094. *
  3095. * @returns {boolean} whether lobby is supported in the backend.
  3096. */
  3097. JitsiConference.prototype.isLobbySupported = function() {
  3098. return Boolean(this.room && this.room.getLobby().isSupported());
  3099. };
  3100. /**
  3101. * Returns <tt>true</tt> if the room has members only enabled.
  3102. *
  3103. * @returns {boolean} whether conference room is members only.
  3104. */
  3105. JitsiConference.prototype.isMembersOnly = function() {
  3106. return Boolean(this.room && this.room.membersOnlyEnabled);
  3107. };
  3108. /**
  3109. * Enables lobby by moderators
  3110. *
  3111. * @returns {Promise} resolves when lobby room is joined or rejects with the error.
  3112. */
  3113. JitsiConference.prototype.enableLobby = function() {
  3114. if (this.room && this.isModerator()) {
  3115. return this.room.getLobby().enable();
  3116. }
  3117. return Promise.reject(
  3118. new Error('The conference not started or user is not moderator'));
  3119. };
  3120. /**
  3121. * Disabled lobby by moderators
  3122. *
  3123. * @returns {void}
  3124. */
  3125. JitsiConference.prototype.disableLobby = function() {
  3126. if (this.room && this.isModerator()) {
  3127. this.room.getLobby().disable();
  3128. }
  3129. };
  3130. /**
  3131. * Joins the lobby room with display name and optional email or with a shared password to skip waiting.
  3132. *
  3133. * @param {string} displayName Display name should be set to show it to moderators.
  3134. * @param {string} email Optional email is used to present avatar to the moderator.
  3135. * @returns {Promise<never>}
  3136. */
  3137. JitsiConference.prototype.joinLobby = function(displayName, email) {
  3138. if (this.room) {
  3139. return this.room.getLobby().join(displayName, email);
  3140. }
  3141. return Promise.reject(new Error('The conference not started'));
  3142. };
  3143. /**
  3144. * Denies an occupant in the lobby room access to the conference.
  3145. * @param {string} id The participant id.
  3146. */
  3147. JitsiConference.prototype.lobbyDenyAccess = function(id) {
  3148. if (this.room) {
  3149. this.room.getLobby().denyAccess(id);
  3150. }
  3151. };
  3152. /**
  3153. * Approves the request to join the conference to a participant waiting in the lobby.
  3154. *
  3155. * @param {string} id The participant id.
  3156. */
  3157. JitsiConference.prototype.lobbyApproveAccess = function(id) {
  3158. if (this.room) {
  3159. this.room.getLobby().approveAccess(id);
  3160. }
  3161. };