modified lib-jitsi-meet dev repo
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JitsiConference.js 128KB

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