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

JitsiConference.js 99KB

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