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

JitsiConference.js 116KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636
  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. * Kick participant from this conference.
  1277. * @param {string} id id of the participant to kick
  1278. * @param {string} reason reason of the participant to kick
  1279. */
  1280. JitsiConference.prototype.kickParticipant = function(id, reason) {
  1281. const participant = this.getParticipantById(id);
  1282. if (!participant) {
  1283. return;
  1284. }
  1285. this.room.kick(participant.getJid(), reason);
  1286. };
  1287. /**
  1288. * Maybe clears the timeout which emits {@link ACTION_JINGLE_SI_TIMEOUT}
  1289. * analytics event.
  1290. * @private
  1291. */
  1292. JitsiConference.prototype._maybeClearSITimeout = function() {
  1293. if (this._sessionInitiateTimeout
  1294. && (this.jvbJingleSession || this.getParticipantCount() < 2)) {
  1295. window.clearTimeout(this._sessionInitiateTimeout);
  1296. this._sessionInitiateTimeout = null;
  1297. }
  1298. };
  1299. /**
  1300. * Sets a timeout which will emit {@link ACTION_JINGLE_SI_TIMEOUT} analytics
  1301. * event.
  1302. * @private
  1303. */
  1304. JitsiConference.prototype._maybeSetSITimeout = function() {
  1305. // Jicofo is supposed to invite if there are at least 2 participants
  1306. if (!this.jvbJingleSession
  1307. && this.getParticipantCount() >= 2
  1308. && !this._sessionInitiateTimeout) {
  1309. this._sessionInitiateTimeout = window.setTimeout(() => {
  1310. this._sessionInitiateTimeout = null;
  1311. Statistics.sendAnalytics(createJingleEvent(
  1312. ACTION_JINGLE_SI_TIMEOUT,
  1313. {
  1314. p2p: false,
  1315. value: JINGLE_SI_TIMEOUT
  1316. }));
  1317. }, JINGLE_SI_TIMEOUT);
  1318. }
  1319. };
  1320. /**
  1321. * Mutes a participant.
  1322. * @param {string} id The id of the participant to mute.
  1323. */
  1324. JitsiConference.prototype.muteParticipant = function(id, mediaType) {
  1325. const muteMediaType = mediaType ? mediaType : MediaType.AUDIO;
  1326. if (muteMediaType !== MediaType.AUDIO && muteMediaType !== MediaType.VIDEO) {
  1327. logger.error(`Unsupported media type: ${muteMediaType}`);
  1328. return;
  1329. }
  1330. const participant = this.getParticipantById(id);
  1331. if (!participant) {
  1332. return;
  1333. }
  1334. this.room.muteParticipant(participant.getJid(), true, muteMediaType);
  1335. };
  1336. /* eslint-disable max-params */
  1337. /**
  1338. * Notifies this JitsiConference that a new member has joined its chat room.
  1339. *
  1340. * FIXME This should NOT be exposed!
  1341. *
  1342. * @param jid the jid of the participant in the MUC
  1343. * @param nick the display name of the participant
  1344. * @param role the role of the participant in the MUC
  1345. * @param isHidden indicates if this is a hidden participant (system
  1346. * participant for example a recorder).
  1347. * @param statsID the participant statsID (optional)
  1348. * @param status the initial status if any
  1349. * @param identity the member identity, if any
  1350. * @param botType the member botType, if any
  1351. * @param fullJid the member full jid, if any
  1352. * @param features the member botType, if any
  1353. */
  1354. JitsiConference.prototype.onMemberJoined = function(
  1355. jid, nick, role, isHidden, statsID, status, identity, botType, fullJid, features) {
  1356. const id = Strophe.getResourceFromJid(jid);
  1357. if (id === 'focus' || this.myUserId() === id) {
  1358. return;
  1359. }
  1360. const participant
  1361. = new JitsiParticipant(jid, this, nick, isHidden, statsID, status, identity);
  1362. participant.setRole(role);
  1363. participant.setBotType(botType);
  1364. participant.setFeatures(features);
  1365. this.participants[id] = participant;
  1366. this.eventEmitter.emit(
  1367. JitsiConferenceEvents.USER_JOINED,
  1368. id,
  1369. participant);
  1370. this._updateFeatures(participant);
  1371. // maybeStart only if we had finished joining as then we will have information for the number of participants
  1372. if (this.isJoined()) {
  1373. this._maybeStartOrStopP2P();
  1374. }
  1375. this._maybeSetSITimeout();
  1376. };
  1377. /* eslint-enable max-params */
  1378. /**
  1379. * Get notified when we joined the room.
  1380. *
  1381. * FIXME This should NOT be exposed!
  1382. *
  1383. * @private
  1384. */
  1385. JitsiConference.prototype._onMucJoined = function() {
  1386. this._maybeStartOrStopP2P();
  1387. };
  1388. /**
  1389. * Updates features for a participant.
  1390. * @param {JitsiParticipant} participant - The participant to query for features.
  1391. * @returns {void}
  1392. * @private
  1393. */
  1394. JitsiConference.prototype._updateFeatures = function(participant) {
  1395. participant.getFeatures()
  1396. .then(features => {
  1397. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  1398. this.updateDTMFSupport();
  1399. if (features.has(FEATURE_JIGASI)) {
  1400. participant.setProperty('features_jigasi', true);
  1401. }
  1402. if (features.has(FEATURE_E2EE)) {
  1403. participant.setProperty('features_e2ee', true);
  1404. }
  1405. })
  1406. .catch(() => false);
  1407. };
  1408. /**
  1409. * Get notified when member bot type had changed.
  1410. * @param jid the member jid
  1411. * @param botType the new botType value
  1412. * @private
  1413. */
  1414. JitsiConference.prototype._onMemberBotTypeChanged = function(jid, botType) {
  1415. // find the participant and mark it as non bot, as the real one will join
  1416. // in a moment
  1417. const peers = this.getParticipants();
  1418. const botParticipant = peers.find(p => p.getJid() === jid);
  1419. if (botParticipant) {
  1420. botParticipant.setBotType(botType);
  1421. const id = Strophe.getResourceFromJid(jid);
  1422. this.eventEmitter.emit(
  1423. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1424. id,
  1425. botType);
  1426. }
  1427. // if botType changed to undefined, botType was removed, in case of
  1428. // poltergeist mode this is the moment when the poltergeist had exited and
  1429. // the real participant had already replaced it.
  1430. // In this case we can check and try p2p
  1431. if (!botParticipant.getBotType()) {
  1432. this._maybeStartOrStopP2P();
  1433. }
  1434. };
  1435. JitsiConference.prototype.onMemberLeft = function(jid) {
  1436. const id = Strophe.getResourceFromJid(jid);
  1437. if (id === 'focus' || this.myUserId() === id) {
  1438. return;
  1439. }
  1440. const participant = this.participants[id];
  1441. delete this.participants[id];
  1442. // Remove the ssrcs from the remote description.
  1443. const mediaSessions = this._getMediaSessions();
  1444. const removePromises = [];
  1445. for (const session of mediaSessions) {
  1446. removePromises.push(session.removeRemoteStreamsOnLeave(id));
  1447. }
  1448. Promise.allSettled(removePromises)
  1449. .then(results => {
  1450. let removedTracks = [];
  1451. results.map(result => result.value).forEach(value => {
  1452. if (value) {
  1453. removedTracks = removedTracks.concat(value);
  1454. }
  1455. });
  1456. removedTracks.forEach(track => {
  1457. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  1458. });
  1459. // There can be no participant in case the member that left is focus.
  1460. if (participant) {
  1461. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  1462. }
  1463. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  1464. this._maybeClearSITimeout();
  1465. });
  1466. };
  1467. /**
  1468. * Designates an event indicating that we were kicked from the XMPP MUC.
  1469. * @param {boolean} isSelfPresence - whether it is for local participant
  1470. * or another participant.
  1471. * @param {string} actorId - the id of the participant who was initiator
  1472. * of the kick.
  1473. * @param {string?} kickedParticipantId - when it is not a kick for local participant,
  1474. * this is the id of the participant which was kicked.
  1475. * @param {string} reason - reason of the participant to kick
  1476. */
  1477. JitsiConference.prototype.onMemberKicked = function(isSelfPresence, actorId, kickedParticipantId, reason) {
  1478. // This check which be true when we kick someone else. With the introduction of lobby
  1479. // the ChatRoom KICKED event is now also emitted for ourselves (the kicker) so we want to
  1480. // avoid emitting an event where `undefined` kicked someone.
  1481. if (actorId === this.myUserId()) {
  1482. return;
  1483. }
  1484. const actorParticipant = this.participants[actorId];
  1485. if (isSelfPresence) {
  1486. this.eventEmitter.emit(
  1487. JitsiConferenceEvents.KICKED, actorParticipant, reason);
  1488. this.leave();
  1489. return;
  1490. }
  1491. const kickedParticipant = this.participants[kickedParticipantId];
  1492. this.eventEmitter.emit(
  1493. JitsiConferenceEvents.PARTICIPANT_KICKED, actorParticipant, kickedParticipant, reason);
  1494. };
  1495. /**
  1496. * Method called on local MUC role change.
  1497. * @param {string} role the name of new user's role as defined by XMPP MUC.
  1498. */
  1499. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  1500. // Emit role changed for local JID
  1501. this.eventEmitter.emit(
  1502. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  1503. };
  1504. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  1505. const id = Strophe.getResourceFromJid(jid);
  1506. const participant = this.getParticipantById(id);
  1507. if (!participant) {
  1508. return;
  1509. }
  1510. participant.setRole(role);
  1511. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  1512. };
  1513. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  1514. const id = Strophe.getResourceFromJid(jid);
  1515. const participant = this.getParticipantById(id);
  1516. if (!participant) {
  1517. return;
  1518. }
  1519. if (participant._displayName === displayName) {
  1520. return;
  1521. }
  1522. participant._displayName = displayName;
  1523. this.eventEmitter.emit(
  1524. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1525. id,
  1526. displayName);
  1527. };
  1528. /**
  1529. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  1530. * the conference.
  1531. *
  1532. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  1533. * JitsiConference
  1534. */
  1535. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  1536. if (track.isP2P && !this.isP2PActive()) {
  1537. logger.info(
  1538. 'Trying to add remote P2P track, when not in P2P - IGNORED');
  1539. return;
  1540. } else if (!track.isP2P && this.isP2PActive()) {
  1541. logger.info(
  1542. 'Trying to add remote JVB track, when in P2P - IGNORED');
  1543. return;
  1544. }
  1545. const id = track.getParticipantId();
  1546. const participant = this.getParticipantById(id);
  1547. if (!participant) {
  1548. logger.error(`No participant found for id: ${id}`);
  1549. return;
  1550. }
  1551. // Add track to JitsiParticipant.
  1552. participant._tracks.push(track);
  1553. if (this.transcriber) {
  1554. this.transcriber.addTrack(track);
  1555. }
  1556. const emitter = this.eventEmitter;
  1557. track.addEventListener(
  1558. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1559. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  1560. track.addEventListener(
  1561. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1562. (audioLevel, tpc) => {
  1563. const activeTPC = this.getActivePeerConnection();
  1564. if (activeTPC === tpc) {
  1565. emitter.emit(
  1566. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1567. id,
  1568. audioLevel);
  1569. }
  1570. }
  1571. );
  1572. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  1573. };
  1574. /**
  1575. * Callback called by the Jingle plugin when 'session-answer' is received.
  1576. * @param {JingleSessionPC} session the Jingle session for which an answer was
  1577. * received.
  1578. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  1579. */
  1580. // eslint-disable-next-line no-unused-vars
  1581. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  1582. if (this.p2pJingleSession === session) {
  1583. logger.info('P2P setAnswer');
  1584. this.p2pJingleSession.setAnswer(answer);
  1585. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_STARTED, this.p2pJingleSession);
  1586. }
  1587. };
  1588. /**
  1589. * Callback called by the Jingle plugin when 'transport-info' is received.
  1590. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1591. * received
  1592. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1593. * element
  1594. */
  1595. // eslint-disable-next-line no-unused-vars
  1596. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1597. if (this.p2pJingleSession === session) {
  1598. logger.info('P2P addIceCandidates');
  1599. this.p2pJingleSession.addIceCandidates(transportInfo);
  1600. }
  1601. };
  1602. /**
  1603. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1604. * the conference.
  1605. *
  1606. * @param {JitsiRemoteTrack} removedTrack
  1607. */
  1608. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1609. this.getParticipants().forEach(participant => {
  1610. const tracks = participant.getTracks();
  1611. for (let i = 0; i < tracks.length; i++) {
  1612. if (tracks[i] === removedTrack) {
  1613. // Since the tracks have been compared and are
  1614. // considered equal the result of splice can be ignored.
  1615. participant._tracks.splice(i, 1);
  1616. this.eventEmitter.emit(
  1617. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1618. if (this.transcriber) {
  1619. this.transcriber.removeTrack(removedTrack);
  1620. }
  1621. break;
  1622. }
  1623. }
  1624. }, this);
  1625. };
  1626. /**
  1627. * Handles an incoming call event for the P2P jingle session.
  1628. */
  1629. JitsiConference.prototype._onIncomingCallP2P = function(
  1630. jingleSession,
  1631. jingleOffer) {
  1632. let rejectReason;
  1633. if (!browser.supportsP2P()) {
  1634. rejectReason = {
  1635. reason: 'unsupported-applications',
  1636. reasonDescription: 'P2P not supported',
  1637. errorMsg: 'This client does not support P2P connections'
  1638. };
  1639. } else if (!this.isP2PEnabled() && !this.isP2PTestModeEnabled()) {
  1640. rejectReason = {
  1641. reason: 'decline',
  1642. reasonDescription: 'P2P disabled',
  1643. errorMsg: 'P2P mode disabled in the configuration'
  1644. };
  1645. } else if (this.p2pJingleSession) {
  1646. // Reject incoming P2P call (already in progress)
  1647. rejectReason = {
  1648. reason: 'busy',
  1649. reasonDescription: 'P2P already in progress',
  1650. errorMsg: 'Duplicated P2P "session-initiate"'
  1651. };
  1652. } else if (!this._shouldBeInP2PMode()) {
  1653. rejectReason = {
  1654. reason: 'decline',
  1655. reasonDescription: 'P2P requirements not met',
  1656. errorMsg: 'Received P2P "session-initiate" when should not be in P2P mode'
  1657. };
  1658. Statistics.sendAnalytics(createJingleEvent(ACTION_P2P_DECLINED));
  1659. }
  1660. if (rejectReason) {
  1661. this._rejectIncomingCall(jingleSession, rejectReason);
  1662. } else {
  1663. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1664. }
  1665. };
  1666. /**
  1667. * Handles an incoming call event.
  1668. */
  1669. JitsiConference.prototype.onIncomingCall = function(
  1670. jingleSession,
  1671. jingleOffer,
  1672. now) {
  1673. // Handle incoming P2P call
  1674. if (jingleSession.isP2P) {
  1675. this._onIncomingCallP2P(jingleSession, jingleOffer);
  1676. } else {
  1677. if (!this.room.isFocus(jingleSession.remoteJid)) {
  1678. const description = 'Rejecting session-initiate from non-focus.';
  1679. this._rejectIncomingCall(
  1680. jingleSession, {
  1681. reason: 'security-error',
  1682. reasonDescription: description,
  1683. errorMsg: description
  1684. });
  1685. return;
  1686. }
  1687. this._acceptJvbIncomingCall(jingleSession, jingleOffer, now);
  1688. }
  1689. };
  1690. /**
  1691. * Accepts an incoming call event for the JVB jingle session.
  1692. */
  1693. JitsiConference.prototype._acceptJvbIncomingCall = function(
  1694. jingleSession,
  1695. jingleOffer,
  1696. now) {
  1697. // Accept incoming call
  1698. this.jvbJingleSession = jingleSession;
  1699. this.room.connectionTimes['session.initiate'] = now;
  1700. this._sendConferenceJoinAnalyticsEvent();
  1701. if (this.wasStopped) {
  1702. Statistics.sendAnalyticsAndLog(
  1703. createJingleEvent(ACTION_JINGLE_RESTART, { p2p: false }));
  1704. }
  1705. const serverRegion
  1706. = $(jingleOffer)
  1707. .find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]')
  1708. .attr('region');
  1709. this.eventEmitter.emit(
  1710. JitsiConferenceEvents.SERVER_REGION_CHANGED,
  1711. serverRegion);
  1712. this._maybeClearSITimeout();
  1713. Statistics.sendAnalytics(createJingleEvent(
  1714. ACTION_JINGLE_SI_RECEIVED,
  1715. {
  1716. p2p: false,
  1717. value: now
  1718. }));
  1719. try {
  1720. jingleSession.initialize(this.room, this.rtc, {
  1721. ...this.options.config,
  1722. enableInsertableStreams: this._isE2EEEnabled()
  1723. });
  1724. } catch (error) {
  1725. GlobalOnErrorHandler.callErrorHandler(error);
  1726. logger.error(error);
  1727. return;
  1728. }
  1729. // Open a channel with the videobridge.
  1730. this._setBridgeChannel(jingleOffer, jingleSession.peerconnection);
  1731. const localTracks = this._getInitialLocalTracks();
  1732. try {
  1733. jingleSession.acceptOffer(
  1734. jingleOffer,
  1735. () => {
  1736. // If for any reason invite for the JVB session arrived after
  1737. // the P2P has been established already the media transfer needs
  1738. // to be turned off here.
  1739. if (this.isP2PActive() && this.jvbJingleSession) {
  1740. this._suspendMediaTransferForJvbConnection();
  1741. }
  1742. this.eventEmitter.emit(
  1743. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  1744. jingleSession);
  1745. if (!this.isP2PActive()) {
  1746. this.eventEmitter.emit(
  1747. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  1748. jingleSession);
  1749. }
  1750. },
  1751. error => {
  1752. GlobalOnErrorHandler.callErrorHandler(error);
  1753. logger.error(
  1754. 'Failed to accept incoming Jingle session', error);
  1755. },
  1756. localTracks
  1757. );
  1758. // Start callstats as soon as peerconnection is initialized,
  1759. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1760. // happen in case if user doesn't have or denied permission to
  1761. // both camera and microphone.
  1762. logger.info('Starting CallStats for JVB connection...');
  1763. this.statistics.startCallStats(
  1764. this.jvbJingleSession.peerconnection,
  1765. 'jitsi' /* Remote user ID for JVB is 'jitsi' */);
  1766. this.statistics.startRemoteStats(this.jvbJingleSession.peerconnection);
  1767. } catch (e) {
  1768. GlobalOnErrorHandler.callErrorHandler(e);
  1769. logger.error(e);
  1770. }
  1771. };
  1772. /**
  1773. * Sets the BridgeChannel.
  1774. *
  1775. * @param {jQuery} offerIq a jQuery selector pointing to the jingle element of
  1776. * the offer IQ which may carry the WebSocket URL for the 'websocket'
  1777. * BridgeChannel mode.
  1778. * @param {TraceablePeerConnection} pc the peer connection which will be used
  1779. * to listen for new WebRTC Data Channels (in the 'datachannel' mode).
  1780. */
  1781. JitsiConference.prototype._setBridgeChannel = function(offerIq, pc) {
  1782. let wsUrl = null;
  1783. const webSocket
  1784. = $(offerIq)
  1785. .find('>content>transport>web-socket')
  1786. .first();
  1787. if (webSocket.length === 1) {
  1788. wsUrl = webSocket[0].getAttribute('url');
  1789. }
  1790. if (wsUrl) {
  1791. // If the offer contains a websocket use it.
  1792. this.rtc.initializeBridgeChannel(null, wsUrl);
  1793. } else {
  1794. // Otherwise, fall back to an attempt to use SCTP.
  1795. this.rtc.initializeBridgeChannel(pc, null);
  1796. }
  1797. };
  1798. /**
  1799. * Rejects incoming Jingle call.
  1800. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1801. * @param {object} [options]
  1802. * @param {string} options.reason the name of the reason element as defined
  1803. * by Jingle
  1804. * @param {string} options.reasonDescription the reason description which will
  1805. * be included in Jingle 'session-terminate' message.
  1806. * @param {string} options.errorMsg an error message to be logged on global
  1807. * error handler
  1808. * @private
  1809. */
  1810. JitsiConference.prototype._rejectIncomingCall = function(
  1811. jingleSession,
  1812. options) {
  1813. if (options && options.errorMsg) {
  1814. GlobalOnErrorHandler.callErrorHandler(new Error(options.errorMsg));
  1815. }
  1816. // Terminate the jingle session with a reason
  1817. jingleSession.terminate(
  1818. null /* success callback => we don't care */,
  1819. error => {
  1820. logger.warn(
  1821. 'An error occurred while trying to terminate'
  1822. + ' invalid Jingle session', error);
  1823. }, {
  1824. reason: options && options.reason,
  1825. reasonDescription: options && options.reasonDescription,
  1826. sendSessionTerminate: true
  1827. });
  1828. };
  1829. /**
  1830. * Handles the call ended event.
  1831. * XXX is this due to the remote side terminating the Jingle session?
  1832. *
  1833. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1834. * terminated.
  1835. * @param {String} reasonCondition the Jingle reason condition.
  1836. * @param {String|null} reasonText human readable reason text which may provide
  1837. * more details about why the call has been terminated.
  1838. */
  1839. JitsiConference.prototype.onCallEnded = function(
  1840. jingleSession,
  1841. reasonCondition,
  1842. reasonText) {
  1843. logger.info(
  1844. `Call ended: ${reasonCondition} - ${reasonText} P2P ?${
  1845. jingleSession.isP2P}`);
  1846. if (jingleSession === this.jvbJingleSession) {
  1847. this.wasStopped = true;
  1848. Statistics.sendAnalytics(
  1849. createJingleEvent(ACTION_JINGLE_TERMINATE, { p2p: false }));
  1850. // Stop the stats
  1851. if (this.statistics) {
  1852. this.statistics.stopRemoteStats(
  1853. this.jvbJingleSession.peerconnection);
  1854. logger.info('Stopping JVB CallStats');
  1855. this.statistics.stopCallStats(
  1856. this.jvbJingleSession.peerconnection);
  1857. }
  1858. // Current JVB JingleSession is no longer valid, so set it to null
  1859. this.jvbJingleSession = null;
  1860. // Let the RTC service do any cleanups
  1861. this.rtc.onCallEnded();
  1862. } else if (jingleSession === this.p2pJingleSession) {
  1863. // It's the responder who decides to enforce JVB mode, so that both
  1864. // initiator and responder are aware if it was intentional.
  1865. if (reasonCondition === 'decline' && reasonText === 'force JVB121') {
  1866. logger.info('In forced JVB 121 mode...');
  1867. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  1868. } else if (reasonCondition === 'connectivity-error'
  1869. && reasonText === 'ICE FAILED') {
  1870. // It can happen that the other peer detects ICE failed and
  1871. // terminates the session, before we get the event on our side.
  1872. // But we are able to parse the reason and mark it here.
  1873. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  1874. }
  1875. this._stopP2PSession();
  1876. } else {
  1877. logger.error(
  1878. 'Received onCallEnded for invalid session',
  1879. jingleSession.sid,
  1880. jingleSession.remoteJid,
  1881. reasonCondition,
  1882. reasonText);
  1883. }
  1884. };
  1885. /**
  1886. * Handles the suspend detected event. Leaves the room and fires suspended.
  1887. * @param {JingleSessionPC} jingleSession
  1888. */
  1889. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  1890. if (!jingleSession.isP2P) {
  1891. this.leave();
  1892. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1893. }
  1894. };
  1895. JitsiConference.prototype.updateDTMFSupport = function() {
  1896. let somebodySupportsDTMF = false;
  1897. const participants = this.getParticipants();
  1898. // check if at least 1 participant supports DTMF
  1899. for (let i = 0; i < participants.length; i += 1) {
  1900. if (participants[i].supportsDTMF()) {
  1901. somebodySupportsDTMF = true;
  1902. break;
  1903. }
  1904. }
  1905. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1906. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1907. this.eventEmitter.emit(
  1908. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1909. somebodySupportsDTMF);
  1910. }
  1911. };
  1912. /**
  1913. * Allows to check if there is at least one user in the conference
  1914. * that supports DTMF.
  1915. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1916. */
  1917. JitsiConference.prototype.isDTMFSupported = function() {
  1918. return this.somebodySupportsDTMF;
  1919. };
  1920. /**
  1921. * Returns the local user's ID
  1922. * @return {string} local user's ID
  1923. */
  1924. JitsiConference.prototype.myUserId = function() {
  1925. return (
  1926. this.room && this.room.myroomjid
  1927. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1928. : null);
  1929. };
  1930. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1931. const peerConnection = this.getActivePeerConnection();
  1932. if (peerConnection) {
  1933. peerConnection.sendTones(tones, duration, pause);
  1934. } else {
  1935. logger.warn('cannot sendTones: no peer connection');
  1936. }
  1937. };
  1938. /**
  1939. * Starts recording the current conference.
  1940. *
  1941. * @param {Object} options - Configuration for the recording. See
  1942. * {@link Chatroom#startRecording} for more info.
  1943. * @returns {Promise} See {@link Chatroom#startRecording} for more info.
  1944. */
  1945. JitsiConference.prototype.startRecording = function(options) {
  1946. if (this.room) {
  1947. return this.recordingManager.startRecording(options);
  1948. }
  1949. return Promise.reject(new Error('The conference is not created yet!'));
  1950. };
  1951. /**
  1952. * Stop a recording session.
  1953. *
  1954. * @param {string} sessionID - The ID of the recording session that
  1955. * should be stopped.
  1956. * @returns {Promise} See {@link Chatroom#stopRecording} for more info.
  1957. */
  1958. JitsiConference.prototype.stopRecording = function(sessionID) {
  1959. if (this.room) {
  1960. return this.recordingManager.stopRecording(sessionID);
  1961. }
  1962. return Promise.reject(new Error('The conference is not created yet!'));
  1963. };
  1964. /**
  1965. * Returns true if the SIP calls are supported and false otherwise
  1966. */
  1967. JitsiConference.prototype.isSIPCallingSupported = function() {
  1968. if (this.room) {
  1969. return this.room.isSIPCallingSupported();
  1970. }
  1971. return false;
  1972. };
  1973. /**
  1974. * Dials a number.
  1975. * @param number the number
  1976. */
  1977. JitsiConference.prototype.dial = function(number) {
  1978. if (this.room) {
  1979. return this.room.dial(number);
  1980. }
  1981. return new Promise((resolve, reject) => {
  1982. reject(new Error('The conference is not created yet!'));
  1983. });
  1984. };
  1985. /**
  1986. * Hangup an existing call
  1987. */
  1988. JitsiConference.prototype.hangup = function() {
  1989. if (this.room) {
  1990. return this.room.hangup();
  1991. }
  1992. return new Promise((resolve, reject) => {
  1993. reject(new Error('The conference is not created yet!'));
  1994. });
  1995. };
  1996. /**
  1997. * Starts the transcription service.
  1998. */
  1999. JitsiConference.prototype.startTranscriber = function() {
  2000. return this.dial('jitsi_meet_transcribe');
  2001. };
  2002. /**
  2003. * Stops the transcription service.
  2004. */
  2005. JitsiConference.prototype.stopTranscriber = JitsiConference.prototype.hangup;
  2006. /**
  2007. * Returns the phone number for joining the conference.
  2008. */
  2009. JitsiConference.prototype.getPhoneNumber = function() {
  2010. if (this.room) {
  2011. return this.room.getPhoneNumber();
  2012. }
  2013. return null;
  2014. };
  2015. /**
  2016. * Returns the pin for joining the conference with phone.
  2017. */
  2018. JitsiConference.prototype.getPhonePin = function() {
  2019. if (this.room) {
  2020. return this.room.getPhonePin();
  2021. }
  2022. return null;
  2023. };
  2024. /**
  2025. * Returns the meeting unique ID if any.
  2026. *
  2027. * @returns {string|undefined}
  2028. */
  2029. JitsiConference.prototype.getMeetingUniqueId = function() {
  2030. if (this.room) {
  2031. return this.room.getMeetingId();
  2032. }
  2033. };
  2034. /**
  2035. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  2036. * which connection is currently active.
  2037. *
  2038. * @return {TraceablePeerConnection|null} null if there isn't any active
  2039. * <tt>TraceablePeerConnection</tt> currently available.
  2040. * @public (FIXME how to make package local ?)
  2041. */
  2042. JitsiConference.prototype.getActivePeerConnection = function() {
  2043. if (this.isP2PActive()) {
  2044. return this.p2pJingleSession.peerconnection;
  2045. }
  2046. return this.jvbJingleSession ? this.jvbJingleSession.peerconnection : null;
  2047. };
  2048. /**
  2049. * Returns the connection state for the current room. Its ice connection state
  2050. * for its session.
  2051. * NOTE that "completed" ICE state which can appear on the P2P connection will
  2052. * be converted to "connected".
  2053. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  2054. * peer connection at this time.
  2055. */
  2056. JitsiConference.prototype.getConnectionState = function() {
  2057. const peerConnection = this.getActivePeerConnection();
  2058. return peerConnection ? peerConnection.getConnectionState() : null;
  2059. };
  2060. /**
  2061. * Make all new participants mute their audio/video on join.
  2062. * @param policy {Object} object with 2 boolean properties for video and audio:
  2063. * @param {boolean} audio if audio should be muted.
  2064. * @param {boolean} video if video should be muted.
  2065. */
  2066. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  2067. if (!this.isModerator()) {
  2068. return;
  2069. }
  2070. this.startMutedPolicy = policy;
  2071. this.room.addOrReplaceInPresence('startmuted', {
  2072. attributes: {
  2073. audio: policy.audio,
  2074. video: policy.video,
  2075. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  2076. }
  2077. }) && this.room.sendPresence();
  2078. };
  2079. /**
  2080. * Returns current start muted policy
  2081. * @returns {Object} with 2 properties - audio and video.
  2082. */
  2083. JitsiConference.prototype.getStartMutedPolicy = function() {
  2084. return this.startMutedPolicy;
  2085. };
  2086. /**
  2087. * Check if audio is muted on join.
  2088. */
  2089. JitsiConference.prototype.isStartAudioMuted = function() {
  2090. return this.startAudioMuted;
  2091. };
  2092. /**
  2093. * Check if video is muted on join.
  2094. */
  2095. JitsiConference.prototype.isStartVideoMuted = function() {
  2096. return this.startVideoMuted;
  2097. };
  2098. /**
  2099. * Returns measured connectionTimes.
  2100. */
  2101. JitsiConference.prototype.getConnectionTimes = function() {
  2102. return this.room.connectionTimes;
  2103. };
  2104. /**
  2105. * Sets a property for the local participant.
  2106. */
  2107. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  2108. this.sendCommand(`jitsi_participant_${name}`, { value });
  2109. };
  2110. /**
  2111. * Removes a property for the local participant and sends the updated presence.
  2112. */
  2113. JitsiConference.prototype.removeLocalParticipantProperty = function(name) {
  2114. this.removeCommand(`jitsi_participant_${name}`);
  2115. this.room.sendPresence();
  2116. };
  2117. /**
  2118. * Gets a local participant property.
  2119. *
  2120. * @return value of the local participant property if the tagName exists in the
  2121. * list of properties, otherwise returns undefined.
  2122. */
  2123. JitsiConference.prototype.getLocalParticipantProperty = function(name) {
  2124. const property = this.room.presMap.nodes.find(prop =>
  2125. prop.tagName === `jitsi_participant_${name}`
  2126. );
  2127. return property ? property.value : undefined;
  2128. };
  2129. /**
  2130. * Sends the given feedback through CallStats if enabled.
  2131. *
  2132. * @param overallFeedback an integer between 1 and 5 indicating the
  2133. * user feedback
  2134. * @param detailedFeedback detailed feedback from the user. Not yet used
  2135. * @returns {Promise} Resolves if feedback is submitted successfully.
  2136. */
  2137. JitsiConference.prototype.sendFeedback = function(
  2138. overallFeedback,
  2139. detailedFeedback) {
  2140. return this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  2141. };
  2142. /**
  2143. * Returns true if the callstats integration is enabled, otherwise returns
  2144. * false.
  2145. *
  2146. * @returns true if the callstats integration is enabled, otherwise returns
  2147. * false.
  2148. */
  2149. JitsiConference.prototype.isCallstatsEnabled = function() {
  2150. return this.statistics.isCallstatsEnabled();
  2151. };
  2152. /**
  2153. * Finds the SSRC of a given track
  2154. *
  2155. * @param track
  2156. * @returns {number|undefined} the SSRC of the specificed track, otherwise undefined.
  2157. */
  2158. JitsiConference.prototype.getSsrcByTrack = function(track) {
  2159. return track.isLocal() ? this.getActivePeerConnection()?.getLocalSSRC(track) : track.getSSRC();
  2160. };
  2161. /**
  2162. * Handles track attached to container (Calls associateStreamWithVideoTag method
  2163. * from statistics module)
  2164. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  2165. * @param container the container
  2166. */
  2167. JitsiConference.prototype._onTrackAttach = function(track, container) {
  2168. const isLocal = track.isLocal();
  2169. let ssrc = null;
  2170. const isP2P = track.isP2P;
  2171. const remoteUserId = isP2P ? track.getParticipantId() : 'jitsi';
  2172. const peerConnection
  2173. = isP2P
  2174. ? this.p2pJingleSession && this.p2pJingleSession.peerconnection
  2175. : this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  2176. if (isLocal) {
  2177. // Local tracks have SSRC stored on per peer connection basis.
  2178. if (peerConnection) {
  2179. ssrc = peerConnection.getLocalSSRC(track);
  2180. }
  2181. } else {
  2182. ssrc = track.getSSRC();
  2183. }
  2184. if (!container.id || !ssrc || !peerConnection) {
  2185. return;
  2186. }
  2187. this.statistics.associateStreamWithVideoTag(
  2188. peerConnection,
  2189. ssrc,
  2190. isLocal,
  2191. remoteUserId,
  2192. track.getUsageLabel(),
  2193. container.id);
  2194. };
  2195. /**
  2196. * Logs an "application log" message.
  2197. * @param message {string} The message to log. Note that while this can be a
  2198. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  2199. * log valid JSON strings, with an "id" field used for distinguishing between
  2200. * message types. E.g.: {id: "recorder_status", status: "off"}
  2201. */
  2202. JitsiConference.prototype.sendApplicationLog = function(message) {
  2203. Statistics.sendLog(message);
  2204. };
  2205. /**
  2206. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  2207. * focus.
  2208. * @param mucJid the full MUC address of the user to be checked.
  2209. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  2210. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  2211. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  2212. */
  2213. JitsiConference.prototype._isFocus = function(mucJid) {
  2214. return this.room ? this.room.isFocus(mucJid) : null;
  2215. };
  2216. /**
  2217. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  2218. */
  2219. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  2220. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  2221. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  2222. };
  2223. /**
  2224. * Sends a message via the data channel.
  2225. * @param to {string} the id of the endpoint that should receive the message.
  2226. * If "" the message will be sent to all participants.
  2227. * @param payload {object} the payload of the message.
  2228. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2229. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2230. */
  2231. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  2232. this.rtc.sendChannelMessage(to, payload);
  2233. };
  2234. /**
  2235. * Sends a broadcast message via the data channel.
  2236. * @param payload {object} the payload of the message.
  2237. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2238. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2239. */
  2240. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  2241. this.sendEndpointMessage('', payload);
  2242. };
  2243. /**
  2244. * Sends a message to a given endpoint (if 'to' is a non-empty string), or
  2245. * broadcasts it to all endpoints in the conference.
  2246. * @param {string} to The ID of the endpoint/participant which is to receive
  2247. * the message, or '' to broadcast the message to all endpoints in the
  2248. * conference.
  2249. * @param {string|object} message the message to send. If this is of type
  2250. * 'string' it will be sent as a chat message. If it is of type 'object', it
  2251. * will be encapsulated in a format recognized by jitsi-meet and converted to
  2252. * JSON before being sent.
  2253. * @param {boolean} sendThroughVideobridge Whether to send the message through
  2254. * jitsi-videobridge (via the COLIBRI data channel or web socket), or through
  2255. * the XMPP MUC. Currently only objects can be sent through jitsi-videobridge.
  2256. */
  2257. JitsiConference.prototype.sendMessage = function(
  2258. message,
  2259. to = '',
  2260. sendThroughVideobridge = false) {
  2261. const messageType = typeof message;
  2262. // Through videobridge we support only objects. Through XMPP we support
  2263. // objects (encapsulated in a specific JSON format) and strings (i.e.
  2264. // regular chat messages).
  2265. if (messageType !== 'object'
  2266. && (sendThroughVideobridge || messageType !== 'string')) {
  2267. logger.error(`Can not send a message of type ${messageType}`);
  2268. return;
  2269. }
  2270. if (sendThroughVideobridge) {
  2271. this.sendEndpointMessage(to, message);
  2272. } else {
  2273. let messageToSend = message;
  2274. // Name of packet extension of message stanza to send the required
  2275. // message in.
  2276. let elementName = 'body';
  2277. if (messageType === 'object') {
  2278. elementName = 'json-message';
  2279. // Mark as valid JSON message if not already
  2280. if (!messageToSend.hasOwnProperty(JITSI_MEET_MUC_TYPE)) {
  2281. messageToSend[JITSI_MEET_MUC_TYPE] = '';
  2282. }
  2283. try {
  2284. messageToSend = JSON.stringify(messageToSend);
  2285. } catch (e) {
  2286. logger.error('Can not send a message, stringify failed: ', e);
  2287. return;
  2288. }
  2289. }
  2290. if (to) {
  2291. this.sendPrivateTextMessage(to, messageToSend, elementName);
  2292. } else {
  2293. // Broadcast
  2294. this.sendTextMessage(messageToSend, elementName);
  2295. }
  2296. }
  2297. };
  2298. JitsiConference.prototype.isConnectionInterrupted = function() {
  2299. return this.isP2PActive()
  2300. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  2301. };
  2302. /**
  2303. * Handles {@link XMPPEvents.CONNECTION_RESTARTED} event. This happens when the bridge goes down
  2304. * and Jicofo moves conferences away to a different bridge.
  2305. * @param {JingleSessionPC} session
  2306. * @private
  2307. */
  2308. JitsiConference.prototype._onConferenceRestarted = function(session) {
  2309. if (!session.isP2P && this.options.config.enableForcedReload) {
  2310. this.restartInProgress = true;
  2311. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONFERENCE_RESTARTED);
  2312. }
  2313. };
  2314. /**
  2315. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  2316. * @param {JingleSessionPC} session
  2317. * @private
  2318. */
  2319. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  2320. if (session.isP2P) {
  2321. this.isP2PConnectionInterrupted = true;
  2322. } else {
  2323. this.isJvbConnectionInterrupted = true;
  2324. }
  2325. if (session.isP2P === this.isP2PActive()) {
  2326. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  2327. }
  2328. };
  2329. /**
  2330. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  2331. * @param {JingleSessionPC} session
  2332. * @private
  2333. */
  2334. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  2335. // We do nothing for the JVB connection, because it's up to the Jicofo to
  2336. // eventually come up with the new offer (at least for the time being).
  2337. if (session.isP2P) {
  2338. // Add p2pFailed property to analytics to distinguish, between "good"
  2339. // and "bad" connection
  2340. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2341. if (this.p2pJingleSession) {
  2342. Statistics.sendAnalyticsAndLog(
  2343. createP2PEvent(
  2344. ACTION_P2P_FAILED,
  2345. {
  2346. initiator: this.p2pJingleSession.isInitiator
  2347. }));
  2348. }
  2349. this._stopP2PSession('connectivity-error', 'ICE FAILED');
  2350. } else if (session && this.jvbJingleSession === session) {
  2351. this._delayedIceFailed = new IceFailedHandling(this);
  2352. this._delayedIceFailed.start(session);
  2353. }
  2354. };
  2355. /**
  2356. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  2357. * @param {JingleSessionPC} session
  2358. * @private
  2359. */
  2360. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  2361. if (session.isP2P) {
  2362. this.isP2PConnectionInterrupted = false;
  2363. } else {
  2364. this.isJvbConnectionInterrupted = false;
  2365. this._delayedIceFailed && this._delayedIceFailed.cancel();
  2366. }
  2367. if (session.isP2P === this.isP2PActive()) {
  2368. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  2369. }
  2370. };
  2371. /**
  2372. * Accept incoming P2P Jingle call.
  2373. * @param {JingleSessionPC} jingleSession the session instance
  2374. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  2375. * @private
  2376. */
  2377. JitsiConference.prototype._acceptP2PIncomingCall = function(
  2378. jingleSession,
  2379. jingleOffer) {
  2380. this.isP2PConnectionInterrupted = false;
  2381. // Accept the offer
  2382. this.p2pJingleSession = jingleSession;
  2383. this._sendConferenceJoinAnalyticsEvent();
  2384. this.p2pJingleSession.initialize(
  2385. this.room,
  2386. this.rtc, {
  2387. ...this.options.config,
  2388. enableInsertableStreams: this._isE2EEEnabled()
  2389. });
  2390. logger.info('Starting CallStats for P2P connection...');
  2391. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2392. const participant = this.participants[remoteID];
  2393. if (participant) {
  2394. remoteID = participant.getStatsID() || remoteID;
  2395. }
  2396. this.statistics.startCallStats(
  2397. this.p2pJingleSession.peerconnection,
  2398. remoteID);
  2399. const localTracks = this._getInitialLocalTracks();
  2400. this.p2pJingleSession.acceptOffer(
  2401. jingleOffer,
  2402. () => {
  2403. logger.debug('Got RESULT for P2P "session-accept"');
  2404. this.eventEmitter.emit(
  2405. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  2406. this.p2pJingleSession);
  2407. },
  2408. error => {
  2409. logger.error(
  2410. 'Failed to accept incoming P2P Jingle session', error);
  2411. },
  2412. localTracks);
  2413. };
  2414. /**
  2415. * Adds remote tracks to the conference associated with the JVB session.
  2416. * @private
  2417. */
  2418. JitsiConference.prototype._addRemoteJVBTracks = function() {
  2419. this._addRemoteTracks(
  2420. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2421. };
  2422. /**
  2423. * Adds remote tracks to the conference associated with the P2P session.
  2424. * @private
  2425. */
  2426. JitsiConference.prototype._addRemoteP2PTracks = function() {
  2427. this._addRemoteTracks(
  2428. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2429. };
  2430. /**
  2431. * Generates fake "remote track added" events for given Jingle session.
  2432. * @param {string} logName the session's nickname which will appear in log
  2433. * messages.
  2434. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  2435. * @private
  2436. */
  2437. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  2438. for (const track of remoteTracks) {
  2439. logger.info(`Adding remote ${logName} track: ${track}`);
  2440. this.onRemoteTrackAdded(track);
  2441. }
  2442. };
  2443. /**
  2444. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  2445. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  2446. * the P2P connection if the event comes from the P2P session.
  2447. * @param {JingleSessionPC} jingleSession the session instance.
  2448. * @private
  2449. */
  2450. JitsiConference.prototype._onIceConnectionEstablished = function(
  2451. jingleSession) {
  2452. if (this.p2pJingleSession !== null) {
  2453. // store the establishment time of the p2p session as a field of the
  2454. // JitsiConference because the p2pJingleSession might get disposed (thus
  2455. // the value is lost).
  2456. this.p2pEstablishmentDuration
  2457. = this.p2pJingleSession.establishmentDuration;
  2458. }
  2459. if (this.jvbJingleSession !== null) {
  2460. this.jvbEstablishmentDuration
  2461. = this.jvbJingleSession.establishmentDuration;
  2462. }
  2463. let done = false;
  2464. const forceJVB121Ratio = this.options.config.forceJVB121Ratio;
  2465. // We don't care about the JVB case, there's nothing to be done
  2466. if (!jingleSession.isP2P) {
  2467. done = true;
  2468. } else if (this.p2pJingleSession !== jingleSession) {
  2469. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  2470. done = true;
  2471. } else if (!jingleSession.isInitiator
  2472. && typeof forceJVB121Ratio === 'number'
  2473. && Math.random() < forceJVB121Ratio) {
  2474. logger.info(`Forcing JVB 121 mode (ratio=${forceJVB121Ratio})...`);
  2475. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  2476. this._stopP2PSession('decline', 'force JVB121');
  2477. done = true;
  2478. }
  2479. if (!isNaN(this.p2pEstablishmentDuration)
  2480. && !isNaN(this.jvbEstablishmentDuration)) {
  2481. const establishmentDurationDiff
  2482. = this.p2pEstablishmentDuration - this.jvbEstablishmentDuration;
  2483. Statistics.sendAnalytics(
  2484. ICE_ESTABLISHMENT_DURATION_DIFF,
  2485. { value: establishmentDurationDiff });
  2486. }
  2487. if (jingleSession.isP2P === this.isP2PActive()) {
  2488. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_ESTABLISHED);
  2489. }
  2490. if (done) {
  2491. return;
  2492. }
  2493. // Update P2P status and emit events
  2494. this._setP2PStatus(true);
  2495. // Remove remote tracks
  2496. if (this.jvbJingleSession) {
  2497. this._removeRemoteJVBTracks();
  2498. } else {
  2499. logger.info('Not removing remote JVB tracks - no session yet');
  2500. }
  2501. this._addRemoteP2PTracks();
  2502. // Stop media transfer over the JVB connection
  2503. if (this.jvbJingleSession) {
  2504. this._suspendMediaTransferForJvbConnection();
  2505. }
  2506. logger.info('Starting remote stats with p2p connection');
  2507. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  2508. Statistics.sendAnalyticsAndLog(
  2509. createP2PEvent(
  2510. ACTION_P2P_ESTABLISHED,
  2511. {
  2512. initiator: this.p2pJingleSession.isInitiator
  2513. }));
  2514. };
  2515. /**
  2516. * Called when the chat room reads a new list of properties from jicofo's
  2517. * presence. The properties may have changed, but they don't have to.
  2518. *
  2519. * @param {Object} properties - The properties keyed by the property name
  2520. * ('key').
  2521. * @private
  2522. */
  2523. JitsiConference.prototype._updateProperties = function(properties = {}) {
  2524. const changed = !isEqual(properties, this.properties);
  2525. this.properties = properties;
  2526. if (changed) {
  2527. this.eventEmitter.emit(
  2528. JitsiConferenceEvents.PROPERTIES_CHANGED,
  2529. this.properties);
  2530. // Some of the properties need to be added to analytics events.
  2531. const analyticsKeys = [
  2532. // The number of jitsi-videobridge instances currently used for the
  2533. // conference.
  2534. 'bridge-count',
  2535. // The conference creation time (set by jicofo).
  2536. 'created-ms'
  2537. ];
  2538. analyticsKeys.forEach(key => {
  2539. if (properties[key] !== undefined) {
  2540. Statistics.analytics.addPermanentProperties({
  2541. [key.replace('-', '_')]: properties[key]
  2542. });
  2543. }
  2544. });
  2545. }
  2546. };
  2547. /**
  2548. * Gets a conference property with a given key.
  2549. *
  2550. * @param {string} key - The key.
  2551. * @returns {*} The value
  2552. */
  2553. JitsiConference.prototype.getProperty = function(key) {
  2554. return this.properties[key];
  2555. };
  2556. /**
  2557. * Clears the deferred start P2P task if it has been scheduled.
  2558. * @private
  2559. */
  2560. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  2561. if (this.deferredStartP2PTask) {
  2562. logger.info('Cleared deferred start P2P task');
  2563. clearTimeout(this.deferredStartP2PTask);
  2564. this.deferredStartP2PTask = null;
  2565. }
  2566. };
  2567. /**
  2568. * Removes from the conference remote tracks associated with the JVB
  2569. * connection.
  2570. * @private
  2571. */
  2572. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  2573. this._removeRemoteTracks(
  2574. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2575. };
  2576. /**
  2577. * Removes from the conference remote tracks associated with the P2P
  2578. * connection.
  2579. * @private
  2580. */
  2581. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  2582. this._removeRemoteTracks(
  2583. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2584. };
  2585. /**
  2586. * Generates fake "remote track removed" events for given Jingle session.
  2587. * @param {string} sessionNickname the session's nickname which will appear in
  2588. * log messages.
  2589. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  2590. * @private
  2591. */
  2592. JitsiConference.prototype._removeRemoteTracks = function(
  2593. sessionNickname,
  2594. remoteTracks) {
  2595. for (const track of remoteTracks) {
  2596. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  2597. this.onRemoteTrackRemoved(track);
  2598. }
  2599. };
  2600. /**
  2601. * Resumes media transfer over the JVB connection.
  2602. * @private
  2603. */
  2604. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  2605. logger.info('Resuming media transfer over the JVB connection...');
  2606. this.jvbJingleSession.setMediaTransferActive(true, true).then(
  2607. () => {
  2608. logger.info('Resumed media transfer over the JVB connection!');
  2609. },
  2610. error => {
  2611. logger.error(
  2612. 'Failed to resume media transfer over the JVB connection:',
  2613. error);
  2614. });
  2615. };
  2616. /**
  2617. * Sets new P2P status and updates some events/states hijacked from
  2618. * the <tt>JitsiConference</tt>.
  2619. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  2620. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  2621. * @private
  2622. */
  2623. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  2624. if (this.p2p === newStatus) {
  2625. logger.debug(`Called _setP2PStatus with the same status: ${newStatus}`);
  2626. return;
  2627. }
  2628. this.p2p = newStatus;
  2629. if (newStatus) {
  2630. logger.info('Peer to peer connection established!');
  2631. // When we end up in a valid P2P session need to reset the properties
  2632. // in case they have persisted, after session with another peer.
  2633. Statistics.analytics.addPermanentProperties({
  2634. p2pFailed: false,
  2635. forceJvb121: false
  2636. });
  2637. // Sync up video transfer active in case p2pJingleSession not existed
  2638. // when the lastN value was being adjusted.
  2639. const isVideoActive = this.getLastN() !== 0;
  2640. this.p2pJingleSession
  2641. .setMediaTransferActive(true, isVideoActive)
  2642. .catch(error => {
  2643. logger.error(
  2644. 'Failed to sync up P2P video transfer status'
  2645. + `(${isVideoActive})`, error);
  2646. });
  2647. } else {
  2648. logger.info('Peer to peer connection closed!');
  2649. }
  2650. // Put the JVB connection on hold/resume
  2651. if (this.jvbJingleSession) {
  2652. this.statistics.sendConnectionResumeOrHoldEvent(
  2653. this.jvbJingleSession.peerconnection, !newStatus);
  2654. }
  2655. // Clear dtmfManager, so that it can be recreated with new connection
  2656. this.dtmfManager = null;
  2657. // Update P2P status
  2658. this.eventEmitter.emit(
  2659. JitsiConferenceEvents.P2P_STATUS,
  2660. this,
  2661. this.p2p);
  2662. this.eventEmitter.emit(
  2663. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  2664. this._getActiveMediaSession());
  2665. // Refresh connection interrupted/restored
  2666. this.eventEmitter.emit(
  2667. this.isConnectionInterrupted()
  2668. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  2669. : JitsiConferenceEvents.CONNECTION_RESTORED);
  2670. };
  2671. /**
  2672. * Starts new P2P session.
  2673. * @param {string} remoteJid the JID of the remote participant
  2674. * @private
  2675. */
  2676. JitsiConference.prototype._startP2PSession = function(remoteJid) {
  2677. this._maybeClearDeferredStartP2P();
  2678. if (this.p2pJingleSession) {
  2679. logger.error('P2P session already started!');
  2680. return;
  2681. }
  2682. this.isP2PConnectionInterrupted = false;
  2683. this.p2pJingleSession
  2684. = this.xmpp.connection.jingle.newP2PJingleSession(
  2685. this.room.myroomjid,
  2686. remoteJid);
  2687. logger.info(
  2688. 'Created new P2P JingleSession', this.room.myroomjid, remoteJid);
  2689. this._sendConferenceJoinAnalyticsEvent();
  2690. this.p2pJingleSession.initialize(
  2691. this.room,
  2692. this.rtc, {
  2693. ...this.options.config,
  2694. enableInsertableStreams: this._isE2EEEnabled()
  2695. });
  2696. logger.info('Starting CallStats for P2P connection...');
  2697. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2698. const participant = this.participants[remoteID];
  2699. if (participant) {
  2700. remoteID = participant.getStatsID() || remoteID;
  2701. }
  2702. this.statistics.startCallStats(
  2703. this.p2pJingleSession.peerconnection,
  2704. remoteID);
  2705. const localTracks = this._getInitialLocalTracks();
  2706. this.p2pJingleSession.invite(localTracks);
  2707. };
  2708. /**
  2709. * Suspends media transfer over the JVB connection.
  2710. * @private
  2711. */
  2712. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  2713. logger.info('Suspending media transfer over the JVB connection...');
  2714. this.jvbJingleSession.setMediaTransferActive(false, false).then(
  2715. () => {
  2716. logger.info('Suspended media transfer over the JVB connection !');
  2717. },
  2718. error => {
  2719. logger.error(
  2720. 'Failed to suspend media transfer over the JVB connection:',
  2721. error);
  2722. });
  2723. };
  2724. /**
  2725. * Method when called will decide whether it's the time to start or stop
  2726. * the P2P session.
  2727. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  2728. * originates from the user left event.
  2729. * @private
  2730. */
  2731. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  2732. if (!browser.supportsP2P()
  2733. || !this.isP2PEnabled()
  2734. || this.isP2PTestModeEnabled()) {
  2735. logger.info('Auto P2P disabled');
  2736. return;
  2737. }
  2738. const peers = this.getParticipants();
  2739. const peerCount = peers.length;
  2740. // FIXME 1 peer and it must *support* P2P switching
  2741. const shouldBeInP2P = this._shouldBeInP2PMode();
  2742. // Clear deferred "start P2P" task
  2743. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  2744. this._maybeClearDeferredStartP2P();
  2745. }
  2746. // Start peer to peer session
  2747. if (!this.p2pJingleSession && shouldBeInP2P) {
  2748. const peer = peerCount && peers[0];
  2749. const myId = this.myUserId();
  2750. const peersId = peer.getId();
  2751. if (myId > peersId) {
  2752. logger.debug(
  2753. 'I\'m the bigger peersId - '
  2754. + 'the other peer should start P2P', myId, peersId);
  2755. return;
  2756. } else if (myId === peersId) {
  2757. logger.error('The same IDs ? ', myId, peersId);
  2758. return;
  2759. }
  2760. const jid = peer.getJid();
  2761. if (userLeftEvent) {
  2762. if (this.deferredStartP2PTask) {
  2763. logger.error('Deferred start P2P task\'s been set already!');
  2764. return;
  2765. }
  2766. logger.info(
  2767. `Will start P2P with: ${jid} after ${
  2768. this.backToP2PDelay} seconds...`);
  2769. this.deferredStartP2PTask = setTimeout(
  2770. this._startP2PSession.bind(this, jid),
  2771. this.backToP2PDelay * 1000);
  2772. } else {
  2773. logger.info(`Will start P2P with: ${jid}`);
  2774. this._startP2PSession(jid);
  2775. }
  2776. } else if (this.p2pJingleSession && !shouldBeInP2P) {
  2777. logger.info(`Will stop P2P with: ${this.p2pJingleSession.remoteJid}`);
  2778. // Log that there will be a switch back to the JVB connection
  2779. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  2780. Statistics.sendAnalyticsAndLog(
  2781. createP2PEvent(ACTION_P2P_SWITCH_TO_JVB));
  2782. }
  2783. this._stopP2PSession();
  2784. }
  2785. };
  2786. /**
  2787. * Tells whether or not this conference should be currently in the P2P mode.
  2788. *
  2789. * @private
  2790. * @returns {boolean}
  2791. */
  2792. JitsiConference.prototype._shouldBeInP2PMode = function() {
  2793. const peers = this.getParticipants();
  2794. const peerCount = peers.length;
  2795. const hasBotPeer = peers.find(p => p.getBotType() === 'poltergeist' || p.hasFeature(FEATURE_JIGASI)) !== undefined;
  2796. const shouldBeInP2P = peerCount === 1 && !hasBotPeer;
  2797. logger.debug(`P2P? peerCount: ${peerCount}, hasBotPeer: ${hasBotPeer} => ${shouldBeInP2P}`);
  2798. return shouldBeInP2P;
  2799. };
  2800. /**
  2801. * Stops the current P2P session.
  2802. * @param {string} [reason="success"] one of the Jingle "reason" element
  2803. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  2804. * @param {string} [reasonDescription="Turing off P2P session"] text
  2805. * description that will be included in the session terminate message
  2806. * @private
  2807. */
  2808. JitsiConference.prototype._stopP2PSession = function(
  2809. reason,
  2810. reasonDescription) {
  2811. if (!this.p2pJingleSession) {
  2812. logger.error('No P2P session to be stopped!');
  2813. return;
  2814. }
  2815. const wasP2PEstablished = this.isP2PActive();
  2816. // Swap remote tracks, but only if the P2P has been fully established
  2817. if (wasP2PEstablished) {
  2818. if (this.jvbJingleSession) {
  2819. this._resumeMediaTransferForJvbConnection();
  2820. }
  2821. // Remove remote P2P tracks
  2822. this._removeRemoteP2PTracks();
  2823. }
  2824. // Stop P2P stats
  2825. logger.info('Stopping remote stats for P2P connection');
  2826. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  2827. logger.info('Stopping CallStats for P2P connection');
  2828. this.statistics.stopCallStats(this.p2pJingleSession.peerconnection);
  2829. this.p2pJingleSession.terminate(
  2830. () => {
  2831. logger.info('P2P session terminate RESULT');
  2832. },
  2833. error => {
  2834. // Because both initiator and responder are simultaneously
  2835. // terminating their JingleSessions in case of the 'to JVB switch'
  2836. // when 3rd participant joins, both will dispose their sessions and
  2837. // reply with 'item-not-found' (see strophe.jingle.js). We don't
  2838. // want to log this as an error since it's expected behaviour.
  2839. //
  2840. // We want them both to terminate, because in case of initiator's
  2841. // crash the responder would stay in P2P mode until ICE fails which
  2842. // could take up to 20 seconds.
  2843. //
  2844. // NOTE lack of 'reason' is considered as graceful session terminate
  2845. // where both initiator and responder terminate their sessions
  2846. // simultaneously.
  2847. if (reason) {
  2848. logger.error(
  2849. 'An error occurred while trying to terminate'
  2850. + ' P2P Jingle session', error);
  2851. }
  2852. }, {
  2853. reason: reason ? reason : 'success',
  2854. reasonDescription: reasonDescription
  2855. ? reasonDescription : 'Turing off P2P session',
  2856. sendSessionTerminate: this.room
  2857. && this.getParticipantById(
  2858. Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid))
  2859. });
  2860. this.p2pJingleSession = null;
  2861. // Update P2P status and other affected events/states
  2862. this._setP2PStatus(false);
  2863. if (wasP2PEstablished) {
  2864. // Add back remote JVB tracks
  2865. if (this.jvbJingleSession) {
  2866. this._addRemoteJVBTracks();
  2867. } else {
  2868. logger.info('Not adding remote JVB tracks - no session yet');
  2869. }
  2870. }
  2871. };
  2872. /**
  2873. * Checks whether or not the conference is currently in the peer to peer mode.
  2874. * Being in peer to peer mode means that the direct connection has been
  2875. * established and the P2P connection is being used for media transmission.
  2876. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  2877. */
  2878. JitsiConference.prototype.isP2PActive = function() {
  2879. return this.p2p;
  2880. };
  2881. /**
  2882. * Returns the current ICE state of the P2P connection.
  2883. * NOTE: method is used by the jitsi-meet-torture tests.
  2884. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  2885. * no P2P connection.
  2886. */
  2887. JitsiConference.prototype.getP2PConnectionState = function() {
  2888. if (this.isP2PActive()) {
  2889. return this.p2pJingleSession.peerconnection.getConnectionState();
  2890. }
  2891. return null;
  2892. };
  2893. /**
  2894. * Manually starts new P2P session (should be used only in the tests).
  2895. */
  2896. JitsiConference.prototype.startP2PSession = function() {
  2897. const peers = this.getParticipants();
  2898. // Start peer to peer session
  2899. if (peers.length === 1) {
  2900. const peerJid = peers[0].getJid();
  2901. this._startP2PSession(peerJid);
  2902. } else {
  2903. throw new Error(
  2904. 'There must be exactly 1 participant to start the P2P session !');
  2905. }
  2906. };
  2907. /**
  2908. * Manually stops the current P2P session (should be used only in the tests)
  2909. */
  2910. JitsiConference.prototype.stopP2PSession = function() {
  2911. this._stopP2PSession();
  2912. };
  2913. /**
  2914. * Get a summary of how long current participants have been the dominant speaker
  2915. * @returns {object}
  2916. */
  2917. JitsiConference.prototype.getSpeakerStats = function() {
  2918. return this.speakerStatsCollector.getStats();
  2919. };
  2920. /**
  2921. * Sets the constraints for the video that is requested from the bridge.
  2922. *
  2923. * @param {Object} videoConstraints The constraints which are specified in the
  2924. * following format. The message updates the fields that are present and leaves the
  2925. * rest unchanged on the bridge. Therefore, any field that is not applicable anymore
  2926. * should be cleared by passing an empty object or list (whatever is applicable).
  2927. * {
  2928. * 'lastN': 20,
  2929. * 'selectedEndpoints': ['A', 'B', 'C'],
  2930. * 'onStageEndpoints': ['A'],
  2931. * 'defaultConstraints': { 'maxHeight': 180 },
  2932. * 'constraints': {
  2933. * 'A': { 'maxHeight': 720 }
  2934. * }
  2935. * }
  2936. */
  2937. JitsiConference.prototype.setReceiverConstraints = function(videoConstraints) {
  2938. this.receiveVideoController.setReceiverConstraints(videoConstraints);
  2939. };
  2940. /**
  2941. * Sets the maximum video size the local participant should receive from remote
  2942. * participants.
  2943. *
  2944. * @param {number} maxFrameHeight - the maximum frame height, in pixels,
  2945. * this receiver is willing to receive.
  2946. * @returns {void}
  2947. */
  2948. JitsiConference.prototype.setReceiverVideoConstraint = function(maxFrameHeight) {
  2949. this.receiveVideoController.setPreferredReceiveMaxFrameHeight(maxFrameHeight);
  2950. };
  2951. /**
  2952. * Sets the maximum video size the local participant should send to remote
  2953. * participants.
  2954. * @param {number} maxFrameHeight - The user preferred max frame height.
  2955. * @returns {Promise} promise that will be resolved when the operation is
  2956. * successful and rejected otherwise.
  2957. */
  2958. JitsiConference.prototype.setSenderVideoConstraint = function(maxFrameHeight) {
  2959. return this.sendVideoController.setPreferredSendMaxFrameHeight(maxFrameHeight);
  2960. };
  2961. /**
  2962. * Creates a video SIP GW session and returns it if service is enabled. Before
  2963. * creating a session one need to check whether video SIP GW service is
  2964. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2965. * if there are available nodes to serve this request, after creating the
  2966. * session those nodes can be taken and the request about using the
  2967. * created session can fail.
  2968. *
  2969. * @param {string} sipAddress - The sip address to be used.
  2970. * @param {string} displayName - The display name to be used for this session.
  2971. * @returns {JitsiVideoSIPGWSession|Error} Returns null if conference is not
  2972. * initialised and there is no room.
  2973. */
  2974. JitsiConference.prototype.createVideoSIPGWSession
  2975. = function(sipAddress, displayName) {
  2976. if (!this.room) {
  2977. return new Error(VideoSIPGWConstants.ERROR_NO_CONNECTION);
  2978. }
  2979. return this.videoSIPGWHandler
  2980. .createVideoSIPGWSession(sipAddress, displayName);
  2981. };
  2982. /**
  2983. * Sends a conference.join analytics event.
  2984. *
  2985. * @returns {void}
  2986. */
  2987. JitsiConference.prototype._sendConferenceJoinAnalyticsEvent = function() {
  2988. const meetingId = this.getMeetingUniqueId();
  2989. if (this._conferenceJoinAnalyticsEventSent || !meetingId || this.getActivePeerConnection() === null) {
  2990. return;
  2991. }
  2992. Statistics.sendAnalytics(createConferenceEvent('joined', {
  2993. meetingId,
  2994. participantId: `${meetingId}.${this._statsCurrentId}`
  2995. }));
  2996. this._conferenceJoinAnalyticsEventSent = Date.now();
  2997. };
  2998. /**
  2999. * Sends conference.left analytics event.
  3000. * @private
  3001. */
  3002. JitsiConference.prototype._sendConferenceLeftAnalyticsEvent = function() {
  3003. const meetingId = this.getMeetingUniqueId();
  3004. if (!meetingId || !this._conferenceJoinAnalyticsEventSent) {
  3005. return;
  3006. }
  3007. Statistics.sendAnalytics(createConferenceEvent('left', {
  3008. meetingId,
  3009. participantId: `${meetingId}.${this._statsCurrentId}`,
  3010. stats: {
  3011. duration: Math.floor((Date.now() - this._conferenceJoinAnalyticsEventSent) / 1000),
  3012. perf: this.getPerformanceStats()
  3013. }
  3014. }));
  3015. };
  3016. /**
  3017. * Restarts all active media sessions.
  3018. *
  3019. * @returns {void}
  3020. */
  3021. JitsiConference.prototype._restartMediaSessions = function() {
  3022. if (this.p2pJingleSession) {
  3023. this.stopP2PSession();
  3024. }
  3025. if (this.jvbJingleSession) {
  3026. this.jvbJingleSession.terminate(
  3027. null /* success callback => we don't care */,
  3028. error => {
  3029. logger.warn('An error occurred while trying to terminate the JVB session', error);
  3030. }, {
  3031. reason: 'success',
  3032. reasonDescription: 'restart required',
  3033. requestRestart: true,
  3034. sendSessionTerminate: true
  3035. });
  3036. }
  3037. this._maybeStartOrStopP2P(false);
  3038. };
  3039. /**
  3040. * Returns whether End-To-End encryption is enabled.
  3041. *
  3042. * @returns {boolean}
  3043. */
  3044. JitsiConference.prototype._isE2EEEnabled = function() {
  3045. return this._e2eEncryption && this._e2eEncryption.isEnabled();
  3046. };
  3047. /**
  3048. * Returns whether End-To-End encryption is supported. Note that not all participants
  3049. * in the conference may support it.
  3050. *
  3051. * @returns {boolean}
  3052. */
  3053. JitsiConference.prototype.isE2EESupported = function() {
  3054. return E2EEncryption.isSupported(this.options.config);
  3055. };
  3056. /**
  3057. * Enables / disables End-to-End encryption.
  3058. *
  3059. * @param {boolean} enabled whether to enable E2EE or not.
  3060. * @returns {void}
  3061. */
  3062. JitsiConference.prototype.toggleE2EE = function(enabled) {
  3063. if (!this.isE2EESupported()) {
  3064. logger.warn('Cannot enable / disable E2EE: platform is not supported.');
  3065. return;
  3066. }
  3067. this._e2eEncryption.setEnabled(enabled);
  3068. };
  3069. /**
  3070. * Returns <tt>true</tt> if lobby support is enabled in the backend.
  3071. *
  3072. * @returns {boolean} whether lobby is supported in the backend.
  3073. */
  3074. JitsiConference.prototype.isLobbySupported = function() {
  3075. return Boolean(this.room && this.room.getLobby().isSupported());
  3076. };
  3077. /**
  3078. * Returns <tt>true</tt> if the room has members only enabled.
  3079. *
  3080. * @returns {boolean} whether conference room is members only.
  3081. */
  3082. JitsiConference.prototype.isMembersOnly = function() {
  3083. return Boolean(this.room && this.room.membersOnlyEnabled);
  3084. };
  3085. /**
  3086. * Enables lobby by moderators
  3087. *
  3088. * @returns {Promise} resolves when lobby room is joined or rejects with the error.
  3089. */
  3090. JitsiConference.prototype.enableLobby = function() {
  3091. if (this.room && this.isModerator()) {
  3092. return this.room.getLobby().enable();
  3093. }
  3094. return Promise.reject(
  3095. new Error('The conference not started or user is not moderator'));
  3096. };
  3097. /**
  3098. * Disabled lobby by moderators
  3099. *
  3100. * @returns {void}
  3101. */
  3102. JitsiConference.prototype.disableLobby = function() {
  3103. if (this.room && this.isModerator()) {
  3104. this.room.getLobby().disable();
  3105. }
  3106. };
  3107. /**
  3108. * Joins the lobby room with display name and optional email or with a shared password to skip waiting.
  3109. *
  3110. * @param {string} displayName Display name should be set to show it to moderators.
  3111. * @param {string} email Optional email is used to present avatar to the moderator.
  3112. * @returns {Promise<never>}
  3113. */
  3114. JitsiConference.prototype.joinLobby = function(displayName, email) {
  3115. if (this.room) {
  3116. return this.room.getLobby().join(displayName, email);
  3117. }
  3118. return Promise.reject(new Error('The conference not started'));
  3119. };
  3120. /**
  3121. * Denies an occupant in the lobby room access to the conference.
  3122. * @param {string} id The participant id.
  3123. */
  3124. JitsiConference.prototype.lobbyDenyAccess = function(id) {
  3125. if (this.room) {
  3126. this.room.getLobby().denyAccess(id);
  3127. }
  3128. };
  3129. /**
  3130. * Approves the request to join the conference to a participant waiting in the lobby.
  3131. *
  3132. * @param {string} id The participant id.
  3133. */
  3134. JitsiConference.prototype.lobbyApproveAccess = function(id) {
  3135. if (this.room) {
  3136. this.room.getLobby().approveAccess(id);
  3137. }
  3138. };