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

JitsiConference.js 110KB

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