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

JitsiConference.js 129KB

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