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

JitsiConference.js 76KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436
  1. /* global __filename, Strophe, Promise */
  2. import AvgRTPStatsReporter from './modules/statistics/AvgRTPStatsReporter';
  3. import ComponentsVersions from './modules/version/ComponentsVersions';
  4. import ConnectionQuality from './modules/connectivity/ConnectionQuality';
  5. import { getLogger } from 'jitsi-meet-logger';
  6. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  7. import EventEmitter from 'events';
  8. import * as JingleSessionState from './modules/xmpp/JingleSessionState';
  9. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  10. import JitsiConferenceEventManager from './JitsiConferenceEventManager';
  11. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  12. import JitsiDTMFManager from './modules/DTMF/JitsiDTMFManager';
  13. import JitsiParticipant from './JitsiParticipant';
  14. import JitsiTrackError from './JitsiTrackError';
  15. import * as JitsiTrackErrors from './JitsiTrackErrors';
  16. import * as JitsiTrackEvents from './JitsiTrackEvents';
  17. import * as MediaType from './service/RTC/MediaType';
  18. import ParticipantConnectionStatusHandler
  19. from './modules/connectivity/ParticipantConnectionStatus';
  20. import RTC from './modules/RTC/RTC';
  21. import RTCBrowserType from './modules/RTC/RTCBrowserType';
  22. import * as RTCEvents from './service/RTC/RTCEvents';
  23. import Statistics from './modules/statistics/statistics';
  24. import TalkMutedDetection from './modules/TalkMutedDetection';
  25. import Transcriber from './modules/transcription/transcriber';
  26. import VideoType from './service/RTC/VideoType';
  27. import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
  28. import * as XMPPEvents from './service/xmpp/XMPPEvents';
  29. import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
  30. const logger = getLogger(__filename);
  31. /**
  32. * Creates a JitsiConference object with the given name and properties.
  33. * Note: this constructor is not a part of the public API (objects should be
  34. * created using JitsiConnection.createConference).
  35. * @param options.config properties / settings related to the conference that
  36. * will be created.
  37. * @param options.name the name of the conference
  38. * @param options.connection the JitsiConnection object for this
  39. * JitsiConference.
  40. * @param {number} [options.config.avgRtpStatsN=15] how many samples are to be
  41. * collected by {@link AvgRTPStatsReporter}, before arithmetic mean is
  42. * calculated and submitted to the analytics module.
  43. * @param {boolean} [options.config.enableP2P] when set to <tt>true</tt>
  44. * the peer to peer mode will be enabled. It means that when there are only 2
  45. * participants in the conference an attempt to make direct connection will be
  46. * made. If the connection succeeds the conference will stop sending data
  47. * through the JVB connection and will use the direct one instead.
  48. * @param {number} [options.config.backToP2PDelay=5] a delay given in seconds,
  49. * before the conference switches back to P2P, after the 3rd participant has
  50. * left the room.
  51. * @param {number} [options.config.channelLastN=-1] The requested amount of
  52. * videos are going to be delivered after the value is in effect. Set to -1 for
  53. * unlimited or all available videos.
  54. * @constructor
  55. *
  56. * FIXME Make all methods which are called from lib-internal classes
  57. * to non-public (use _). To name a few:
  58. * {@link JitsiConference.onLocalRoleChanged}
  59. * {@link JitsiConference.onUserRoleChanged}
  60. * {@link JitsiConference.onMemberLeft}
  61. * and so on...
  62. */
  63. export default function JitsiConference(options) {
  64. if (!options.name || options.name.toLowerCase() !== options.name) {
  65. const errmsg
  66. = 'Invalid conference name (no conference name passed or it '
  67. + 'contains invalid characters like capital letters)!';
  68. logger.error(errmsg);
  69. throw new Error(errmsg);
  70. }
  71. this.eventEmitter = new EventEmitter();
  72. this.options = options;
  73. this.eventManager = new JitsiConferenceEventManager(this);
  74. this.participants = {};
  75. this._init(options);
  76. this.componentsVersions = new ComponentsVersions(this);
  77. /**
  78. * Jingle session instance for the JVB connection.
  79. * @type {JingleSessionPC}
  80. */
  81. this.jvbJingleSession = null;
  82. this.lastDominantSpeaker = null;
  83. this.dtmfManager = null;
  84. this.somebodySupportsDTMF = false;
  85. this.authEnabled = false;
  86. this.startAudioMuted = false;
  87. this.startVideoMuted = false;
  88. this.startMutedPolicy = {
  89. audio: false,
  90. video: false
  91. };
  92. this.availableDevices = {
  93. audio: undefined,
  94. video: undefined
  95. };
  96. this.isMutedByFocus = false;
  97. // Flag indicates if the 'onCallEnded' method was ever called on this
  98. // instance. Used to log extra analytics event for debugging purpose.
  99. // We need to know if the potential issue happened before or after
  100. // the restart.
  101. this.wasStopped = false;
  102. /**
  103. * The object which monitors local and remote connection statistics (e.g.
  104. * sending bitrate) and calculates a number which represents the connection
  105. * quality.
  106. */
  107. this.connectionQuality
  108. = new ConnectionQuality(this, this.eventEmitter, options);
  109. /**
  110. * Reports average RTP statistics to the analytics module.
  111. * @type {AvgRTPStatsReporter}
  112. */
  113. this.avgRtpStatsReporter
  114. = new AvgRTPStatsReporter(this, options.config.avgRtpStatsN || 15);
  115. /**
  116. * Indicates whether the connection is interrupted or not.
  117. */
  118. this.isJvbConnectionInterrupted = false;
  119. /**
  120. * The object which tracks active speaker times
  121. */
  122. this.speakerStatsCollector = new SpeakerStatsCollector(this);
  123. /* P2P related fields below: */
  124. /**
  125. * Stores reference to deferred start P2P task. It's created when 3rd
  126. * participant leaves the room in order to avoid ping pong effect (it
  127. * could be just a page reload).
  128. * @type {number|null}
  129. */
  130. this.deferredStartP2PTask = null;
  131. const delay = parseInt(options.config.backToP2PDelay, 10);
  132. /**
  133. * A delay given in seconds, before the conference switches back to P2P
  134. * after the 3rd participant has left.
  135. * @type {number}
  136. */
  137. this.backToP2PDelay = isNaN(delay) ? 5 : delay;
  138. logger.info(`backToP2PDelay: ${this.backToP2PDelay}`);
  139. /**
  140. * If set to <tt>true</tt> it means the P2P ICE is no longer connected.
  141. * When <tt>false</tt> it means that P2P ICE (media) connection is up
  142. * and running.
  143. * @type {boolean}
  144. */
  145. this.isP2PConnectionInterrupted = false;
  146. /**
  147. * Flag set to <tt>true</tt> when P2P session has been established
  148. * (ICE has been connected) and this conference is currently in the peer to
  149. * peer mode (P2P connection is the active one).
  150. * @type {boolean}
  151. */
  152. this.p2p = false;
  153. /**
  154. * A JingleSession for the direct peer to peer connection.
  155. * @type {JingleSessionPC}
  156. */
  157. this.p2pJingleSession = null;
  158. }
  159. // FIXME convert JitsiConference to ES6 - ASAP !
  160. JitsiConference.prototype.constructor = JitsiConference;
  161. /**
  162. * Initializes the conference object properties
  163. * @param options {object}
  164. * @param options.connection {JitsiConnection} overrides this.connection
  165. */
  166. JitsiConference.prototype._init = function(options = {}) {
  167. // Override connection and xmpp properties (Useful if the connection
  168. // reloaded)
  169. if (options.connection) {
  170. this.connection = options.connection;
  171. this.xmpp = this.connection.xmpp;
  172. // Setup XMPP events only if we have new connection object.
  173. this.eventManager.setupXMPPListeners();
  174. }
  175. this.room = this.xmpp.createRoom(this.options.name, this.options.config);
  176. // Connection interrupted/restored listeners
  177. this._onIceConnectionInterrupted
  178. = this._onIceConnectionInterrupted.bind(this);
  179. this.room.addListener(
  180. XMPPEvents.CONNECTION_INTERRUPTED, this._onIceConnectionInterrupted);
  181. this._onIceConnectionRestored = this._onIceConnectionRestored.bind(this);
  182. this.room.addListener(
  183. XMPPEvents.CONNECTION_RESTORED, this._onIceConnectionRestored);
  184. this._onIceConnectionEstablished
  185. = this._onIceConnectionEstablished.bind(this);
  186. this.room.addListener(
  187. XMPPEvents.CONNECTION_ESTABLISHED, this._onIceConnectionEstablished);
  188. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  189. if (!this.rtc) {
  190. this.rtc = new RTC(this, options);
  191. this.eventManager.setupRTCListeners();
  192. }
  193. this.participantConnectionStatus
  194. = new ParticipantConnectionStatusHandler(
  195. this.rtc,
  196. this,
  197. { // Both these options are not public API, leaving it here only
  198. // as an entry point through config for tuning up purposes.
  199. // Default values should be adjusted as soon as optimal values
  200. // are discovered.
  201. rtcMuteTimeout:
  202. this.options.config._peerConnStatusRtcMuteTimeout,
  203. outOfLastNTimeout:
  204. this.options.config._peerConnStatusOutOfLastNTimeout
  205. });
  206. this.participantConnectionStatus.init();
  207. if (!this.statistics) {
  208. this.statistics = new Statistics(this.xmpp, {
  209. callStatsID: this.options.config.callStatsID,
  210. callStatsSecret: this.options.config.callStatsSecret,
  211. callStatsConfIDNamespace:
  212. this.options.config.callStatsConfIDNamespace
  213. || window.location.hostname,
  214. callStatsCustomScriptUrl:
  215. this.options.config.callStatsCustomScriptUrl,
  216. callStatsAliasName: this.myUserId(),
  217. roomName: this.options.name
  218. });
  219. }
  220. this.eventManager.setupChatRoomListeners();
  221. // Always add listeners because on reload we are executing leave and the
  222. // listeners are removed from statistics module.
  223. this.eventManager.setupStatisticsListeners();
  224. if (this.options.config.enableTalkWhileMuted) {
  225. // eslint-disable-next-line no-new
  226. new TalkMutedDetection(
  227. this,
  228. () =>
  229. this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED));
  230. }
  231. if ('channelLastN' in options.config) {
  232. this.setLastN(options.config.channelLastN);
  233. }
  234. };
  235. /**
  236. * Joins the conference.
  237. * @param password {string} the password
  238. */
  239. JitsiConference.prototype.join = function(password) {
  240. if (this.room) {
  241. this.room.join(password);
  242. }
  243. };
  244. /**
  245. * Check if joined to the conference.
  246. */
  247. JitsiConference.prototype.isJoined = function() {
  248. return this.room && this.room.joined;
  249. };
  250. /**
  251. * Leaves the conference.
  252. * @returns {Promise}
  253. */
  254. JitsiConference.prototype.leave = function() {
  255. if (this.participantConnectionStatus) {
  256. this.participantConnectionStatus.dispose();
  257. this.participantConnectionStatus = null;
  258. }
  259. if (this.avgRtpStatsReporter) {
  260. this.avgRtpStatsReporter.dispose();
  261. this.avgRtpStatsReporter = null;
  262. }
  263. this.getLocalTracks().forEach(track => this.onLocalTrackRemoved(track));
  264. this.rtc.closeAllDataChannels();
  265. if (this.statistics) {
  266. this.statistics.dispose();
  267. }
  268. // Close both JVb and P2P JingleSessions
  269. if (this.jvbJingleSession) {
  270. this.jvbJingleSession.close();
  271. this.jvbJingleSession = null;
  272. }
  273. if (this.p2pJingleSession) {
  274. this.p2pJingleSession.close();
  275. this.p2pJingleSession = null;
  276. }
  277. // leave the conference
  278. if (this.room) {
  279. const room = this.room;
  280. // Unregister connection state listeners
  281. room.removeListener(
  282. XMPPEvents.CONNECTION_INTERRUPTED,
  283. this._onIceConnectionInterrupted);
  284. room.removeListener(
  285. XMPPEvents.CONNECTION_RESTORED,
  286. this._onIceConnectionRestored);
  287. room.removeListener(
  288. XMPPEvents.CONNECTION_ESTABLISHED,
  289. this._onIceConnectionEstablished);
  290. this.room = null;
  291. return room.leave().catch(() => {
  292. // remove all participants because currently the conference won't
  293. // be usable anyway. This is done on success automatically by the
  294. // ChatRoom instance.
  295. this.getParticipants().forEach(
  296. participant => this.onMemberLeft(participant.getJid()));
  297. });
  298. }
  299. // If this.room == null we are calling second time leave().
  300. return Promise.reject(
  301. new Error('The conference is has been already left'));
  302. };
  303. /**
  304. * Returns name of this conference.
  305. */
  306. JitsiConference.prototype.getName = function() {
  307. return this.options.name;
  308. };
  309. /**
  310. * Check if authentication is enabled for this conference.
  311. */
  312. JitsiConference.prototype.isAuthEnabled = function() {
  313. return this.authEnabled;
  314. };
  315. /**
  316. * Check if user is logged in.
  317. */
  318. JitsiConference.prototype.isLoggedIn = function() {
  319. return Boolean(this.authIdentity);
  320. };
  321. /**
  322. * Get authorized login.
  323. */
  324. JitsiConference.prototype.getAuthLogin = function() {
  325. return this.authIdentity;
  326. };
  327. /**
  328. * Check if external authentication is enabled for this conference.
  329. */
  330. JitsiConference.prototype.isExternalAuthEnabled = function() {
  331. return this.room && this.room.moderator.isExternalAuthEnabled();
  332. };
  333. /**
  334. * Get url for external authentication.
  335. * @param {boolean} [urlForPopup] if true then return url for login popup,
  336. * else url of login page.
  337. * @returns {Promise}
  338. */
  339. JitsiConference.prototype.getExternalAuthUrl = function(urlForPopup) {
  340. return new Promise((resolve, reject) => {
  341. if (!this.isExternalAuthEnabled()) {
  342. reject();
  343. return;
  344. }
  345. if (urlForPopup) {
  346. this.room.moderator.getPopupLoginUrl(resolve, reject);
  347. } else {
  348. this.room.moderator.getLoginUrl(resolve, reject);
  349. }
  350. });
  351. };
  352. /**
  353. * Returns the local tracks of the given media type, or all local tracks if no
  354. * specific type is given.
  355. * @param {MediaType} [mediaType] Optional media type (audio or video).
  356. */
  357. JitsiConference.prototype.getLocalTracks = function(mediaType) {
  358. let tracks = [];
  359. if (this.rtc) {
  360. tracks = this.rtc.getLocalTracks(mediaType);
  361. }
  362. return tracks;
  363. };
  364. /**
  365. * Obtains local audio track.
  366. * @return {JitsiLocalTrack|null}
  367. */
  368. JitsiConference.prototype.getLocalAudioTrack = function() {
  369. return this.rtc ? this.rtc.getLocalAudioTrack() : null;
  370. };
  371. /**
  372. * Obtains local video track.
  373. * @return {JitsiLocalTrack|null}
  374. */
  375. JitsiConference.prototype.getLocalVideoTrack = function() {
  376. return this.rtc ? this.rtc.getLocalVideoTrack() : null;
  377. };
  378. /**
  379. * Attaches a handler for events(For example - "participant joined".) in the
  380. * conference. All possible event are defined in JitsiConferenceEvents.
  381. * @param eventId the event ID.
  382. * @param handler handler for the event.
  383. *
  384. * Note: consider adding eventing functionality by extending an EventEmitter
  385. * impl, instead of rolling ourselves
  386. */
  387. JitsiConference.prototype.on = function(eventId, handler) {
  388. if (this.eventEmitter) {
  389. this.eventEmitter.on(eventId, handler);
  390. }
  391. };
  392. /**
  393. * Removes event listener
  394. * @param eventId the event ID.
  395. * @param [handler] optional, the specific handler to unbind
  396. *
  397. * Note: consider adding eventing functionality by extending an EventEmitter
  398. * impl, instead of rolling ourselves
  399. */
  400. JitsiConference.prototype.off = function(eventId, handler) {
  401. if (this.eventEmitter) {
  402. this.eventEmitter.removeListener(eventId, handler);
  403. }
  404. };
  405. // Common aliases for event emitter
  406. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  407. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  408. /**
  409. * Receives notifications from other participants about commands / custom events
  410. * (sent by sendCommand or sendCommandOnce methods).
  411. * @param command {String} the name of the command
  412. * @param handler {Function} handler for the command
  413. */
  414. JitsiConference.prototype.addCommandListener = function(command, handler) {
  415. if (this.room) {
  416. this.room.addPresenceListener(command, handler);
  417. }
  418. };
  419. /**
  420. * Removes command listener
  421. * @param command {String} the name of the command
  422. */
  423. JitsiConference.prototype.removeCommandListener = function(command) {
  424. if (this.room) {
  425. this.room.removePresenceListener(command);
  426. }
  427. };
  428. /**
  429. * Sends text message to the other participants in the conference
  430. * @param message the text message.
  431. */
  432. JitsiConference.prototype.sendTextMessage = function(message) {
  433. if (this.room) {
  434. this.room.sendMessage(message);
  435. }
  436. };
  437. /**
  438. * Send presence command.
  439. * @param name {String} the name of the command.
  440. * @param values {Object} with keys and values that will be sent.
  441. **/
  442. JitsiConference.prototype.sendCommand = function(name, values) {
  443. if (this.room) {
  444. this.room.addToPresence(name, values);
  445. this.room.sendPresence();
  446. }
  447. };
  448. /**
  449. * Send presence command one time.
  450. * @param name {String} the name of the command.
  451. * @param values {Object} with keys and values that will be sent.
  452. **/
  453. JitsiConference.prototype.sendCommandOnce = function(name, values) {
  454. this.sendCommand(name, values);
  455. this.removeCommand(name);
  456. };
  457. /**
  458. * Removes presence command.
  459. * @param name {String} the name of the command.
  460. **/
  461. JitsiConference.prototype.removeCommand = function(name) {
  462. if (this.room) {
  463. this.room.removeFromPresence(name);
  464. }
  465. };
  466. /**
  467. * Sets the display name for this conference.
  468. * @param name the display name to set
  469. */
  470. JitsiConference.prototype.setDisplayName = function(name) {
  471. if (this.room) {
  472. // remove previously set nickname
  473. this.room.removeFromPresence('nick');
  474. this.room.addToPresence('nick', {
  475. attributes: { xmlns: 'http://jabber.org/protocol/nick' },
  476. value: name
  477. });
  478. this.room.sendPresence();
  479. }
  480. };
  481. /**
  482. * Set new subject for this conference. (available only for moderator)
  483. * @param {string} subject new subject
  484. */
  485. JitsiConference.prototype.setSubject = function(subject) {
  486. if (this.room && this.isModerator()) {
  487. this.room.setSubject(subject);
  488. }
  489. };
  490. /**
  491. * Get a transcriber object for all current participants in this conference
  492. * @return {Transcriber} the transcriber object
  493. */
  494. JitsiConference.prototype.getTranscriber = function() {
  495. if (this.transcriber === undefined) {
  496. this.transcriber = new Transcriber();
  497. // add all existing local audio tracks to the transcriber
  498. const localAudioTracks = this.getLocalTracks(MediaType.AUDIO);
  499. for (const localAudio of localAudioTracks) {
  500. this.transcriber.addTrack(localAudio);
  501. }
  502. // and all remote audio tracks
  503. const remoteAudioTracks = this.rtc.getRemoteTracks(MediaType.AUDIO);
  504. for (const remoteTrack of remoteAudioTracks) {
  505. this.transcriber.addTrack(remoteTrack);
  506. }
  507. }
  508. return this.transcriber;
  509. };
  510. /**
  511. * Adds JitsiLocalTrack object to the conference.
  512. * @param track the JitsiLocalTrack object.
  513. * @returns {Promise<JitsiLocalTrack>}
  514. * @throws {Error} if the specified track is a video track and there is already
  515. * another video track in the conference.
  516. */
  517. JitsiConference.prototype.addTrack = function(track) {
  518. if (track.isVideoTrack()) {
  519. // Ensure there's exactly 1 local video track in the conference.
  520. const localVideoTrack = this.rtc.getLocalVideoTrack();
  521. if (localVideoTrack) {
  522. // Don't be excessively harsh and severe if the API client happens
  523. // to attempt to add the same local video track twice.
  524. if (track === localVideoTrack) {
  525. return Promise.resolve(track);
  526. }
  527. return Promise.reject(new Error(
  528. 'cannot add second video track to the conference'));
  529. }
  530. }
  531. return this.replaceTrack(null, track);
  532. };
  533. /**
  534. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event (for local tracks).
  535. * @param {TraceablePeerConnection|null} tpc
  536. * @param audioLevel the audio level
  537. */
  538. JitsiConference.prototype._fireAudioLevelChangeEvent
  539. = function(tpc, audioLevel) {
  540. const activeTpc = this.getActivePeerConnection();
  541. // There will be no TraceablePeerConnection if audio levels do not come from
  542. // a peerconnection. LocalStatsCollector.js measures audio levels using Web
  543. // Audio Analyser API and emits local audio levels events through
  544. // JitsiTrack.setAudioLevel, but does not provide TPC instance which is
  545. // optional.
  546. if (tpc === null || activeTpc === tpc) {
  547. this.eventEmitter.emit(
  548. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  549. this.myUserId(), audioLevel);
  550. }
  551. };
  552. /**
  553. * Fires TRACK_MUTE_CHANGED change conference event.
  554. * @param track the JitsiTrack object related to the event.
  555. */
  556. JitsiConference.prototype._fireMuteChangeEvent = function(track) {
  557. // check if track was muted by focus and now is unmuted by user
  558. if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
  559. this.isMutedByFocus = false;
  560. // unmute local user on server
  561. this.room.muteParticipant(this.room.myroomjid, false);
  562. }
  563. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  564. };
  565. /**
  566. * Clear JitsiLocalTrack properties and listeners.
  567. * @param track the JitsiLocalTrack object.
  568. */
  569. JitsiConference.prototype.onLocalTrackRemoved = function(track) {
  570. track._setConference(null);
  571. this.rtc.removeLocalTrack(track);
  572. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  573. track.muteHandler);
  574. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  575. track.audioLevelHandler);
  576. // send event for stopping screen sharing
  577. // FIXME: we assume we have only one screen sharing track
  578. // if we change this we need to fix this check
  579. if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP) {
  580. this.statistics.sendScreenSharingEvent(false);
  581. }
  582. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  583. };
  584. /**
  585. * Removes JitsiLocalTrack from the conference and performs
  586. * a new offer/answer cycle.
  587. * @param {JitsiLocalTrack} track
  588. * @returns {Promise}
  589. */
  590. JitsiConference.prototype.removeTrack = function(track) {
  591. return this.replaceTrack(track, null);
  592. };
  593. /**
  594. * Replaces oldTrack with newTrack and performs a single offer/answer
  595. * cycle after both operations are done. Either oldTrack or newTrack
  596. * can be null; replacing a valid 'oldTrack' with a null 'newTrack'
  597. * effectively just removes 'oldTrack'
  598. * @param {JitsiLocalTrack} oldTrack the current stream in use to be replaced
  599. * @param {JitsiLocalTrack} newTrack the new stream to use
  600. * @returns {Promise} resolves when the replacement is finished
  601. */
  602. JitsiConference.prototype.replaceTrack = function(oldTrack, newTrack) {
  603. // First do the removal of the oldTrack at the JitsiConference level
  604. if (oldTrack) {
  605. if (oldTrack.disposed) {
  606. return Promise.reject(
  607. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  608. }
  609. }
  610. if (newTrack) {
  611. if (newTrack.disposed) {
  612. return Promise.reject(
  613. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  614. }
  615. }
  616. // Now replace the stream at the lower levels
  617. return this._doReplaceTrack(oldTrack, newTrack)
  618. .then(() => {
  619. if (oldTrack) {
  620. this.onLocalTrackRemoved(oldTrack);
  621. }
  622. if (newTrack) {
  623. // Now handle the addition of the newTrack at the
  624. // JitsiConference level
  625. this._setupNewTrack(newTrack);
  626. }
  627. return Promise.resolve();
  628. }, error => Promise.reject(new Error(error)));
  629. };
  630. /**
  631. * Replaces the tracks at the lower level by going through the Jingle session
  632. * and WebRTC peer connection. The method will resolve immediately if there is
  633. * currently no JingleSession started.
  634. * @param {JitsiLocalTrack|null} oldTrack the track to be removed during
  635. * the process or <tt>null</t> if the method should act as "add track"
  636. * @param {JitsiLocalTrack|null} newTrack the new track to be added or
  637. * <tt>null</tt> if the method should act as "remove track"
  638. * @return {Promise} resolved when the process is done or rejected with a string
  639. * which describes the error.
  640. * @private
  641. */
  642. JitsiConference.prototype._doReplaceTrack = function(oldTrack, newTrack) {
  643. const replaceTrackPromises = [];
  644. if (this.jvbJingleSession) {
  645. replaceTrackPromises.push(
  646. this.jvbJingleSession.replaceTrack(oldTrack, newTrack));
  647. } else {
  648. logger.info('_doReplaceTrack - no JVB JingleSession');
  649. }
  650. if (this.p2pJingleSession) {
  651. replaceTrackPromises.push(
  652. this.p2pJingleSession.replaceTrack(oldTrack, newTrack));
  653. } else {
  654. logger.info('_doReplaceTrack - no P2P JingleSession');
  655. }
  656. return Promise.all(replaceTrackPromises);
  657. };
  658. /**
  659. * Operations related to creating a new track
  660. * @param {JitsiLocalTrack} newTrack the new track being created
  661. */
  662. JitsiConference.prototype._setupNewTrack = function(newTrack) {
  663. if (newTrack.isAudioTrack() || (newTrack.isVideoTrack()
  664. && newTrack.videoType !== VideoType.DESKTOP)) {
  665. // Report active device to statistics
  666. const devices = RTC.getCurrentlyAvailableMediaDevices();
  667. const device
  668. = devices.find(
  669. d =>
  670. d.kind === `${newTrack.getTrack().kind}input`
  671. && d.label === newTrack.getTrack().label);
  672. if (device) {
  673. Statistics.sendActiveDeviceListEvent(
  674. RTC.getEventDataForActiveDevice(device));
  675. }
  676. }
  677. if (newTrack.isVideoTrack()) {
  678. this.removeCommand('videoType');
  679. this.sendCommand('videoType', {
  680. value: newTrack.videoType,
  681. attributes: {
  682. xmlns: 'http://jitsi.org/jitmeet/video'
  683. }
  684. });
  685. }
  686. this.rtc.addLocalTrack(newTrack);
  687. // ensure that we're sharing proper "is muted" state
  688. if (newTrack.isAudioTrack()) {
  689. this.room.setAudioMute(newTrack.isMuted());
  690. } else {
  691. this.room.setVideoMute(newTrack.isMuted());
  692. }
  693. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  694. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  695. newTrack.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  696. newTrack.muteHandler);
  697. newTrack.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  698. newTrack.audioLevelHandler);
  699. newTrack._setConference(this);
  700. // send event for starting screen sharing
  701. // FIXME: we assume we have only one screen sharing track
  702. // if we change this we need to fix this check
  703. if (newTrack.isVideoTrack() && newTrack.videoType === VideoType.DESKTOP) {
  704. this.statistics.sendScreenSharingEvent(true);
  705. }
  706. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  707. };
  708. /**
  709. * Method called by the {@link JitsiLocalTrack} (a video one) in order to add
  710. * back the underlying WebRTC MediaStream to the PeerConnection (which has
  711. * removed on video mute).
  712. * @param {JitsiLocalTrack} track the local track that will be added as part of
  713. * the unmute operation.
  714. * @return {Promise} resolved when the process is done or rejected with a string
  715. * which describes the error.
  716. */
  717. JitsiConference.prototype._addLocalTrackAsUnmute = function(track) {
  718. const addAsUnmutePromises = [];
  719. if (this.jvbJingleSession) {
  720. addAsUnmutePromises.push(this.jvbJingleSession.addTrackAsUnmute(track));
  721. } else {
  722. logger.info(
  723. 'Add local MediaStream as unmute -'
  724. + ' no JVB Jingle session started yet');
  725. }
  726. if (this.p2pJingleSession) {
  727. addAsUnmutePromises.push(this.p2pJingleSession.addTrackAsUnmute(track));
  728. } else {
  729. logger.info(
  730. 'Add local MediaStream as unmute -'
  731. + ' no P2P Jingle session started yet');
  732. }
  733. return Promise.all(addAsUnmutePromises);
  734. };
  735. /**
  736. * Method called by the {@link JitsiLocalTrack} (a video one) in order to remove
  737. * the underlying WebRTC MediaStream from the PeerConnection. The purpose of
  738. * that is to stop sending any data and turn off the HW camera device.
  739. * @param {JitsiLocalTrack} track the local track that will be removed.
  740. * @return {Promise}
  741. */
  742. JitsiConference.prototype._removeLocalTrackAsMute = function(track) {
  743. const removeAsMutePromises = [];
  744. if (this.jvbJingleSession) {
  745. removeAsMutePromises.push(
  746. this.jvbJingleSession.removeTrackAsMute(track));
  747. } else {
  748. logger.info(
  749. 'Remove local MediaStream - no JVB JingleSession started yet');
  750. }
  751. if (this.p2pJingleSession) {
  752. removeAsMutePromises.push(
  753. this.p2pJingleSession.removeTrackAsMute(track));
  754. } else {
  755. logger.info(
  756. 'Remove local MediaStream - no P2P JingleSession started yet');
  757. }
  758. return Promise.all(removeAsMutePromises);
  759. };
  760. /**
  761. * Get role of the local user.
  762. * @returns {string} user role: 'moderator' or 'none'
  763. */
  764. JitsiConference.prototype.getRole = function() {
  765. return this.room.role;
  766. };
  767. /**
  768. * Check if local user is moderator.
  769. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  770. * we're no longer in the conference room then <tt>null</tt> is returned.
  771. */
  772. JitsiConference.prototype.isModerator = function() {
  773. return this.room ? this.room.isModerator() : null;
  774. };
  775. /**
  776. * Set password for the room.
  777. * @param {string} password new password for the room.
  778. * @returns {Promise}
  779. */
  780. JitsiConference.prototype.lock = function(password) {
  781. if (!this.isModerator()) {
  782. return Promise.reject();
  783. }
  784. return new Promise((resolve, reject) => {
  785. this.room.lockRoom(
  786. password || '',
  787. () => resolve(),
  788. err => reject(err),
  789. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  790. });
  791. };
  792. /**
  793. * Remove password from the room.
  794. * @returns {Promise}
  795. */
  796. JitsiConference.prototype.unlock = function() {
  797. return this.lock();
  798. };
  799. /**
  800. * Elects the participant with the given id to be the selected participant in
  801. * order to receive higher video quality (if simulcast is enabled).
  802. * Or cache it if channel is not created and send it once channel is available.
  803. * @param participantId the identifier of the participant
  804. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  805. */
  806. JitsiConference.prototype.selectParticipant = function(participantId) {
  807. this.rtc.selectEndpoint(participantId);
  808. };
  809. /**
  810. * Elects the participant with the given id to be the pinned participant in
  811. * order to always receive video for this participant (even when last n is
  812. * enabled).
  813. * @param participantId the identifier of the participant
  814. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  815. */
  816. JitsiConference.prototype.pinParticipant = function(participantId) {
  817. this.rtc.pinEndpoint(participantId);
  818. };
  819. /**
  820. * Selects a new value for "lastN". The requested amount of videos are going
  821. * to be delivered after the value is in effect. Set to -1 for unlimited or
  822. * all available videos.
  823. * @param lastN the new number of videos the user would like to receive.
  824. * @throws Error or RangeError if the given value is not a number or is smaller
  825. * than -1.
  826. */
  827. JitsiConference.prototype.setLastN = function(lastN) {
  828. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  829. throw new Error(`Invalid value for lastN: ${lastN}`);
  830. }
  831. const n = Number(lastN);
  832. if (n < -1) {
  833. throw new RangeError('lastN cannot be smaller than -1');
  834. }
  835. this.rtc.setLastN(n);
  836. };
  837. /**
  838. * Checks if the participant given by participantId is currently included in
  839. * the last N.
  840. * @param {string} participantId the identifier of the participant we would
  841. * like to check.
  842. * @return {boolean} true if the participant with id is in the last N set or
  843. * if there's no last N set, false otherwise.
  844. * @deprecated this method should never be used to figure out the UI, but
  845. * {@link ParticipantConnectionStatus} should be used instead.
  846. */
  847. JitsiConference.prototype.isInLastN = function(participantId) {
  848. return this.rtc.isInLastN(participantId);
  849. };
  850. /**
  851. * @return Array<JitsiParticipant> an array of all participants in this
  852. * conference.
  853. */
  854. JitsiConference.prototype.getParticipants = function() {
  855. return Object.keys(this.participants).map(function(key) {
  856. return this.participants[key];
  857. }, this);
  858. };
  859. /**
  860. * Returns the number of participants in the conference, including the local
  861. * participant.
  862. * @param countHidden {boolean} Whether or not to include hidden participants
  863. * in the count. Default: false.
  864. **/
  865. JitsiConference.prototype.getParticipantCount
  866. = function(countHidden = false) {
  867. let participants = this.getParticipants();
  868. if (!countHidden) {
  869. participants = participants.filter(p => !p.isHidden());
  870. }
  871. // Add one for the local participant.
  872. return participants.length + 1;
  873. };
  874. /**
  875. * @returns {JitsiParticipant} the participant in this conference with the
  876. * specified id (or undefined if there isn't one).
  877. * @param id the id of the participant.
  878. */
  879. JitsiConference.prototype.getParticipantById = function(id) {
  880. return this.participants[id];
  881. };
  882. /**
  883. * Kick participant from this conference.
  884. * @param {string} id id of the participant to kick
  885. */
  886. JitsiConference.prototype.kickParticipant = function(id) {
  887. const participant = this.getParticipantById(id);
  888. if (!participant) {
  889. return;
  890. }
  891. this.room.kick(participant.getJid());
  892. };
  893. /**
  894. * Mutes a participant.
  895. * @param {string} id The id of the participant to mute.
  896. */
  897. JitsiConference.prototype.muteParticipant = function(id) {
  898. const participant = this.getParticipantById(id);
  899. if (!participant) {
  900. return;
  901. }
  902. this.room.muteParticipant(participant.getJid(), true);
  903. };
  904. /* eslint-disable max-params */
  905. /**
  906. * Notifies this JitsiConference that a new member has joined its chat room.
  907. *
  908. * FIXME This should NOT be exposed!
  909. *
  910. * @param jid the jid of the participant in the MUC
  911. * @param nick the display name of the participant
  912. * @param role the role of the participant in the MUC
  913. * @param isHidden indicates if this is a hidden participant (system
  914. * participant for example a recorder).
  915. */
  916. JitsiConference.prototype.onMemberJoined = function(jid, nick, role, isHidden) {
  917. const id = Strophe.getResourceFromJid(jid);
  918. if (id === 'focus' || this.myUserId() === id) {
  919. return;
  920. }
  921. const participant = new JitsiParticipant(jid, this, nick, isHidden);
  922. participant._role = role;
  923. this.participants[id] = participant;
  924. this.eventEmitter.emit(
  925. JitsiConferenceEvents.USER_JOINED,
  926. id,
  927. participant);
  928. this.xmpp.caps.getFeatures(jid)
  929. .then(features => {
  930. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  931. this.updateDTMFSupport();
  932. },
  933. error => logger.error(`Failed to discover features of ${jid}`, error));
  934. this._maybeStartOrStopP2P();
  935. };
  936. /* eslint-enable max-params */
  937. JitsiConference.prototype.onMemberLeft = function(jid) {
  938. const id = Strophe.getResourceFromJid(jid);
  939. if (id === 'focus' || this.myUserId() === id) {
  940. return;
  941. }
  942. const participant = this.participants[id];
  943. delete this.participants[id];
  944. const removedTracks = this.rtc.removeRemoteTracks(id);
  945. removedTracks.forEach(
  946. track =>
  947. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track));
  948. // there can be no participant in case the member that left is focus
  949. if (participant) {
  950. this.eventEmitter.emit(
  951. JitsiConferenceEvents.USER_LEFT, id, participant);
  952. }
  953. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  954. };
  955. /**
  956. * Method called on local MUC role change.
  957. * @param {string} role the name of new user's role as defined by XMPP MUC.
  958. */
  959. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  960. // Emit role changed for local JID
  961. this.eventEmitter.emit(
  962. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  963. // Maybe start P2P
  964. this._maybeStartOrStopP2P();
  965. };
  966. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  967. const id = Strophe.getResourceFromJid(jid);
  968. const participant = this.getParticipantById(id);
  969. if (!participant) {
  970. return;
  971. }
  972. participant._role = role;
  973. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  974. };
  975. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  976. const id = Strophe.getResourceFromJid(jid);
  977. const participant = this.getParticipantById(id);
  978. if (!participant) {
  979. return;
  980. }
  981. if (participant._displayName === displayName) {
  982. return;
  983. }
  984. participant._displayName = displayName;
  985. this.eventEmitter.emit(
  986. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  987. id,
  988. displayName);
  989. };
  990. /**
  991. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  992. * the conference.
  993. *
  994. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  995. * JitsiConference
  996. */
  997. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  998. if (track.isP2P && !this.isP2PActive()) {
  999. logger.info(
  1000. 'Trying to add remote P2P track, when not in P2P - IGNORED');
  1001. return;
  1002. } else if (!track.isP2P && this.isP2PActive()) {
  1003. logger.info(
  1004. 'Trying to add remote JVB track, when in P2P - IGNORED');
  1005. return;
  1006. }
  1007. const id = track.getParticipantId();
  1008. const participant = this.getParticipantById(id);
  1009. if (!participant) {
  1010. logger.error(`No participant found for id: ${id}`);
  1011. return;
  1012. }
  1013. // Add track to JitsiParticipant.
  1014. participant._tracks.push(track);
  1015. if (this.transcriber) {
  1016. this.transcriber.addTrack(track);
  1017. }
  1018. const emitter = this.eventEmitter;
  1019. track.addEventListener(
  1020. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1021. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  1022. track.addEventListener(
  1023. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1024. (tpc, audioLevel) => {
  1025. const activeTPC = this.getActivePeerConnection();
  1026. if (activeTPC === tpc) {
  1027. emitter.emit(
  1028. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1029. id,
  1030. audioLevel);
  1031. }
  1032. }
  1033. );
  1034. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  1035. };
  1036. /**
  1037. * Callback called by the Jingle plugin when 'session-answer' is received.
  1038. * @param {JingleSessionPC} session the Jingle session for which an answer was
  1039. * received.
  1040. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  1041. */
  1042. // eslint-disable-next-line no-unused-vars
  1043. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  1044. if (this.p2pJingleSession === session) {
  1045. logger.info('P2P setAnswer');
  1046. this.p2pJingleSession.setAnswer(answer);
  1047. }
  1048. };
  1049. /**
  1050. * Callback called by the Jingle plugin when 'transport-info' is received.
  1051. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1052. * received
  1053. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1054. * element
  1055. */
  1056. // eslint-disable-next-line no-unused-vars
  1057. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1058. if (this.p2pJingleSession === session) {
  1059. logger.info('P2P addIceCandidates');
  1060. this.p2pJingleSession.addIceCandidates(transportInfo);
  1061. }
  1062. };
  1063. /**
  1064. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1065. * the conference.
  1066. *
  1067. * @param {JitsiRemoteTrack} removedTrack
  1068. */
  1069. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1070. let consumed = false;
  1071. this.getParticipants().forEach(participant => {
  1072. const tracks = participant.getTracks();
  1073. for (let i = 0; i < tracks.length; i++) {
  1074. if (tracks[i] === removedTrack) {
  1075. // Since the tracks have been compared and are
  1076. // considered equal the result of splice can be ignored.
  1077. participant._tracks.splice(i, 1);
  1078. this.eventEmitter.emit(
  1079. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1080. if (this.transcriber) {
  1081. this.transcriber.removeTrack(removedTrack);
  1082. }
  1083. consumed = true;
  1084. break;
  1085. }
  1086. }
  1087. }, this);
  1088. if (!consumed) {
  1089. if ((this.isP2PActive() && !removedTrack.isP2P)
  1090. || (!this.isP2PActive() && removedTrack.isP2P)) {
  1091. // A remote track can be removed either as a result of
  1092. // 'source-remove' or the P2P logic which removes remote tracks
  1093. // explicitly when switching between JVB and P2P connections.
  1094. // The check above filters out the P2P logic case which should not
  1095. // result in an error (which just goes over all remote tracks).
  1096. return;
  1097. }
  1098. logger.error(
  1099. 'Failed to match remote track on remove'
  1100. + ' with any of the participants',
  1101. removedTrack.getStreamId(),
  1102. removedTrack.getParticipantId());
  1103. }
  1104. };
  1105. /**
  1106. * Handles incoming call event.
  1107. */
  1108. JitsiConference.prototype.onIncomingCall
  1109. = function(jingleSession, jingleOffer, now) {
  1110. // Handle incoming P2P call
  1111. if (jingleSession.isP2P) {
  1112. const role = this.room.getMemberRole(jingleSession.peerjid);
  1113. if (role !== 'moderator') {
  1114. // Reject incoming P2P call
  1115. this._rejectIncomingCallNonModerator(jingleSession);
  1116. } else if (!RTCBrowserType.isP2PSupported()) {
  1117. // Reject incoming P2P call (already in progress)
  1118. this._rejectIncomingCall(
  1119. jingleSession, {
  1120. reasonTag: 'unsupported-applications',
  1121. reasonMsg: 'P2P not supported',
  1122. errorMsg: 'This client does not support P2P connections'
  1123. });
  1124. } else if (this.p2pJingleSession) {
  1125. // Reject incoming P2P call (already in progress)
  1126. this._rejectIncomingCall(
  1127. jingleSession, {
  1128. reasonTag: 'busy',
  1129. reasonMsg: 'P2P already in progress',
  1130. errorMsg: 'Duplicated P2P "session-initiate"'
  1131. });
  1132. } else {
  1133. // Accept incoming P2P call
  1134. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1135. }
  1136. return;
  1137. } else if (!this.room.isFocus(jingleSession.peerjid)) {
  1138. this._rejectIncomingCall(jingleSession);
  1139. return;
  1140. }
  1141. // Accept incoming call
  1142. this.jvbJingleSession = jingleSession;
  1143. this.room.connectionTimes['session.initiate'] = now;
  1144. // Log "session.restart"
  1145. if (this.wasStopped) {
  1146. Statistics.sendEventToAll('session.restart');
  1147. }
  1148. // add info whether call is cross-region
  1149. let crossRegion = null;
  1150. if (window.jitsiRegionInfo) {
  1151. crossRegion = window.jitsiRegionInfo.CrossRegion;
  1152. }
  1153. Statistics.analytics.sendEvent(
  1154. 'session.initiate', {
  1155. value: now - this.room.connectionTimes['muc.joined'],
  1156. label: crossRegion
  1157. });
  1158. try {
  1159. jingleSession.initialize(false /* initiator */, this.room, this.rtc);
  1160. } catch (error) {
  1161. GlobalOnErrorHandler.callErrorHandler(error);
  1162. }
  1163. this.rtc.initializeDataChannels(jingleSession.peerconnection);
  1164. // Add local tracks to the session
  1165. try {
  1166. jingleSession.acceptOffer(
  1167. jingleOffer,
  1168. null /* success */,
  1169. error => {
  1170. GlobalOnErrorHandler.callErrorHandler(error);
  1171. logger.error(
  1172. 'Failed to accept incoming Jingle session', error);
  1173. },
  1174. this.getLocalTracks()
  1175. );
  1176. // Start callstats as soon as peerconnection is initialized,
  1177. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1178. // happen in case if user doesn't have or denied permission to
  1179. // both camera and microphone.
  1180. logger.info('Starting CallStats for JVB connection...');
  1181. this.statistics.startCallStats(
  1182. this.jvbJingleSession.peerconnection,
  1183. 'jitsi' /* Remote user ID for JVB is 'jitsi' */);
  1184. this.statistics.startRemoteStats(this.jvbJingleSession.peerconnection);
  1185. } catch (e) {
  1186. GlobalOnErrorHandler.callErrorHandler(e);
  1187. logger.error(e);
  1188. }
  1189. };
  1190. /**
  1191. * Rejects incoming Jingle call with 'security-error'. Method should be used to
  1192. * reject calls initiated by unauthorised entities.
  1193. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1194. * @private
  1195. */
  1196. JitsiConference.prototype._rejectIncomingCallNonModerator
  1197. = function(jingleSession) {
  1198. this._rejectIncomingCall(
  1199. jingleSession,
  1200. {
  1201. reasonTag: 'security-error',
  1202. reasonMsg: 'Only focus can start new sessions',
  1203. errorMsg: 'Rejecting session-initiate from non-focus and'
  1204. + `non-moderator user: ${jingleSession.peerjid}`
  1205. });
  1206. };
  1207. /**
  1208. * Rejects incoming Jingle call.
  1209. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1210. * @param {object} [options]
  1211. * @param {string} options.reasonTag the name of the reason element as defined
  1212. * by Jingle
  1213. * @param {string} options.reasonMsg the reason description which will
  1214. * be included in Jingle 'session-terminate' message.
  1215. * @param {string} options.errorMsg an error message to be logged on global
  1216. * error handler
  1217. * @private
  1218. */
  1219. JitsiConference.prototype._rejectIncomingCall
  1220. = function(jingleSession, options) {
  1221. if (options && options.errorMsg) {
  1222. GlobalOnErrorHandler.callErrorHandler(new Error(options.errorMsg));
  1223. }
  1224. // Terminate the jingle session with a reason
  1225. jingleSession.terminate(
  1226. options && options.reasonTag,
  1227. options && options.reasonMsg,
  1228. null /* success callback => we don't care */,
  1229. error => {
  1230. logger.warn(
  1231. 'An error occurred while trying to terminate'
  1232. + ' invalid Jingle session', error);
  1233. });
  1234. };
  1235. /**
  1236. * Handles the call ended event.
  1237. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1238. * terminated.
  1239. * @param {String} reasonCondition the Jingle reason condition.
  1240. * @param {String|null} reasonText human readable reason text which may provide
  1241. * more details about why the call has been terminated.
  1242. */
  1243. JitsiConference.prototype.onCallEnded
  1244. = function(jingleSession, reasonCondition, reasonText) {
  1245. logger.info(
  1246. `Call ended: ${reasonCondition} - ${reasonText
  1247. } P2P ?${jingleSession.isP2P}`);
  1248. if (jingleSession === this.jvbJingleSession) {
  1249. this.wasStopped = true;
  1250. // Send session.terminate event
  1251. Statistics.sendEventToAll('session.terminate');
  1252. // Stop the stats
  1253. if (this.statistics) {
  1254. this.statistics.stopRemoteStats(
  1255. this.jvbJingleSession.peerconnection);
  1256. logger.info('Stopping JVB CallStats');
  1257. this.statistics.stopCallStats(
  1258. this.jvbJingleSession.peerconnection);
  1259. }
  1260. // Current JVB JingleSession is no longer valid, so set it to null
  1261. this.jvbJingleSession = null;
  1262. // Let the RTC service do any cleanups
  1263. this.rtc.onCallEnded();
  1264. } else if (jingleSession === this.p2pJingleSession) {
  1265. this._stopP2PSession();
  1266. } else {
  1267. logger.error(
  1268. 'Received onCallEnded for invalid session',
  1269. jingleSession.sid,
  1270. jingleSession.peerjid,
  1271. reasonCondition,
  1272. reasonText);
  1273. }
  1274. };
  1275. /**
  1276. * Handles the suspend detected event. Leaves the room and fires suspended.
  1277. * @param {JingleSessionPC} jingleSession
  1278. */
  1279. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  1280. if (!jingleSession.isP2P) {
  1281. this.leave();
  1282. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1283. }
  1284. };
  1285. JitsiConference.prototype.updateDTMFSupport = function() {
  1286. let somebodySupportsDTMF = false;
  1287. const participants = this.getParticipants();
  1288. // check if at least 1 participant supports DTMF
  1289. for (let i = 0; i < participants.length; i += 1) {
  1290. if (participants[i].supportsDTMF()) {
  1291. somebodySupportsDTMF = true;
  1292. break;
  1293. }
  1294. }
  1295. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1296. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1297. this.eventEmitter.emit(
  1298. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1299. somebodySupportsDTMF);
  1300. }
  1301. };
  1302. /**
  1303. * Allows to check if there is at least one user in the conference
  1304. * that supports DTMF.
  1305. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1306. */
  1307. JitsiConference.prototype.isDTMFSupported = function() {
  1308. return this.somebodySupportsDTMF;
  1309. };
  1310. /**
  1311. * Returns the local user's ID
  1312. * @return {string} local user's ID
  1313. */
  1314. JitsiConference.prototype.myUserId = function() {
  1315. return (
  1316. this.room
  1317. && this.room.myroomjid
  1318. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1319. : null);
  1320. };
  1321. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1322. if (!this.dtmfManager) {
  1323. const peerConnection = this.getActivePeerConnection();
  1324. if (!peerConnection) {
  1325. logger.warn('cannot sendTones: no peer connection');
  1326. return;
  1327. }
  1328. const localAudio = this.getLocalAudioTrack();
  1329. if (!localAudio) {
  1330. logger.warn('cannot sendTones: no local audio stream');
  1331. return;
  1332. }
  1333. this.dtmfManager = new JitsiDTMFManager(localAudio, peerConnection);
  1334. }
  1335. this.dtmfManager.sendTones(tones, duration, pause);
  1336. };
  1337. /**
  1338. * Returns true if recording is supported and false if not.
  1339. */
  1340. JitsiConference.prototype.isRecordingSupported = function() {
  1341. if (this.room) {
  1342. return this.room.isRecordingSupported();
  1343. }
  1344. return false;
  1345. };
  1346. /**
  1347. * Returns null if the recording is not supported, "on" if the recording started
  1348. * and "off" if the recording is not started.
  1349. */
  1350. JitsiConference.prototype.getRecordingState = function() {
  1351. return this.room ? this.room.getRecordingState() : undefined;
  1352. };
  1353. /**
  1354. * Returns the url of the recorded video.
  1355. */
  1356. JitsiConference.prototype.getRecordingURL = function() {
  1357. return this.room ? this.room.getRecordingURL() : null;
  1358. };
  1359. /**
  1360. * Starts/stops the recording
  1361. */
  1362. JitsiConference.prototype.toggleRecording = function(options) {
  1363. if (this.room) {
  1364. return this.room.toggleRecording(options, (status, error) => {
  1365. this.eventEmitter.emit(
  1366. JitsiConferenceEvents.RECORDER_STATE_CHANGED, status, error);
  1367. });
  1368. }
  1369. this.eventEmitter.emit(
  1370. JitsiConferenceEvents.RECORDER_STATE_CHANGED, 'error',
  1371. new Error('The conference is not created yet!'));
  1372. };
  1373. /**
  1374. * Returns true if the SIP calls are supported and false otherwise
  1375. */
  1376. JitsiConference.prototype.isSIPCallingSupported = function() {
  1377. if (this.room) {
  1378. return this.room.isSIPCallingSupported();
  1379. }
  1380. return false;
  1381. };
  1382. /**
  1383. * Dials a number.
  1384. * @param number the number
  1385. */
  1386. JitsiConference.prototype.dial = function(number) {
  1387. if (this.room) {
  1388. return this.room.dial(number);
  1389. }
  1390. return new Promise((resolve, reject) => {
  1391. reject(new Error('The conference is not created yet!'));
  1392. });
  1393. };
  1394. /**
  1395. * Hangup an existing call
  1396. */
  1397. JitsiConference.prototype.hangup = function() {
  1398. if (this.room) {
  1399. return this.room.hangup();
  1400. }
  1401. return new Promise((resolve, reject) => {
  1402. reject(new Error('The conference is not created yet!'));
  1403. });
  1404. };
  1405. /**
  1406. * Returns the phone number for joining the conference.
  1407. */
  1408. JitsiConference.prototype.getPhoneNumber = function() {
  1409. if (this.room) {
  1410. return this.room.getPhoneNumber();
  1411. }
  1412. return null;
  1413. };
  1414. /**
  1415. * Returns the pin for joining the conference with phone.
  1416. */
  1417. JitsiConference.prototype.getPhonePin = function() {
  1418. if (this.room) {
  1419. return this.room.getPhonePin();
  1420. }
  1421. return null;
  1422. };
  1423. /**
  1424. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  1425. * which connection is currently active.
  1426. *
  1427. * @return {TraceablePeerConnection|null} null if there isn't any active
  1428. * <tt>TraceablePeerConnection</tt> currently available.
  1429. * @public (FIXME how to make package local ?)
  1430. */
  1431. JitsiConference.prototype.getActivePeerConnection = function() {
  1432. if (this.isP2PActive()) {
  1433. return this.p2pJingleSession.peerconnection;
  1434. }
  1435. return this.jvbJingleSession ? this.jvbJingleSession.peerconnection : null;
  1436. };
  1437. /**
  1438. * Returns the connection state for the current room. Its ice connection state
  1439. * for its session.
  1440. * NOTE that "completed" ICE state which can appear on the P2P connection will
  1441. * be converted to "connected".
  1442. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  1443. * peer connection at this time.
  1444. */
  1445. JitsiConference.prototype.getConnectionState = function() {
  1446. const peerConnection = this.getActivePeerConnection();
  1447. return peerConnection ? peerConnection.getConnectionState() : null;
  1448. };
  1449. /**
  1450. * Make all new participants mute their audio/video on join.
  1451. * @param policy {Object} object with 2 boolean properties for video and audio:
  1452. * @param {boolean} audio if audio should be muted.
  1453. * @param {boolean} video if video should be muted.
  1454. */
  1455. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  1456. if (!this.isModerator()) {
  1457. return;
  1458. }
  1459. this.startMutedPolicy = policy;
  1460. this.room.removeFromPresence('startmuted');
  1461. this.room.addToPresence('startmuted', {
  1462. attributes: {
  1463. audio: policy.audio,
  1464. video: policy.video,
  1465. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  1466. }
  1467. });
  1468. this.room.sendPresence();
  1469. };
  1470. /**
  1471. * Returns current start muted policy
  1472. * @returns {Object} with 2 properties - audio and video.
  1473. */
  1474. JitsiConference.prototype.getStartMutedPolicy = function() {
  1475. return this.startMutedPolicy;
  1476. };
  1477. /**
  1478. * Check if audio is muted on join.
  1479. */
  1480. JitsiConference.prototype.isStartAudioMuted = function() {
  1481. return this.startAudioMuted;
  1482. };
  1483. /**
  1484. * Check if video is muted on join.
  1485. */
  1486. JitsiConference.prototype.isStartVideoMuted = function() {
  1487. return this.startVideoMuted;
  1488. };
  1489. /**
  1490. * Get object with internal logs.
  1491. */
  1492. JitsiConference.prototype.getLogs = function() {
  1493. const data = this.xmpp.getJingleLog();
  1494. const metadata = {};
  1495. metadata.time = new Date();
  1496. metadata.url = window.location.href;
  1497. metadata.ua = navigator.userAgent;
  1498. const log = this.xmpp.getXmppLog();
  1499. if (log) {
  1500. metadata.xmpp = log;
  1501. }
  1502. data.metadata = metadata;
  1503. return data;
  1504. };
  1505. /**
  1506. * Returns measured connectionTimes.
  1507. */
  1508. JitsiConference.prototype.getConnectionTimes = function() {
  1509. return this.room.connectionTimes;
  1510. };
  1511. /**
  1512. * Sets a property for the local participant.
  1513. */
  1514. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  1515. this.sendCommand(`jitsi_participant_${name}`, { value });
  1516. };
  1517. /**
  1518. * Sends the given feedback through CallStats if enabled.
  1519. *
  1520. * @param overallFeedback an integer between 1 and 5 indicating the
  1521. * user feedback
  1522. * @param detailedFeedback detailed feedback from the user. Not yet used
  1523. */
  1524. JitsiConference.prototype.sendFeedback
  1525. = function(overallFeedback, detailedFeedback) {
  1526. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  1527. };
  1528. /**
  1529. * Returns true if the callstats integration is enabled, otherwise returns
  1530. * false.
  1531. *
  1532. * @returns true if the callstats integration is enabled, otherwise returns
  1533. * false.
  1534. */
  1535. JitsiConference.prototype.isCallstatsEnabled = function() {
  1536. return this.statistics.isCallstatsEnabled();
  1537. };
  1538. /**
  1539. * Handles track attached to container (Calls associateStreamWithVideoTag method
  1540. * from statistics module)
  1541. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  1542. * @param container the container
  1543. */
  1544. JitsiConference.prototype._onTrackAttach = function(track, container) {
  1545. const isLocal = track.isLocal();
  1546. let ssrc = null;
  1547. const isP2P = track.isP2P;
  1548. const remoteUserId = isP2P ? track.getParticipantId() : 'jitsi';
  1549. const peerConnection
  1550. = isP2P
  1551. ? this.p2pJingleSession && this.p2pJingleSession.peerconnection
  1552. : this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  1553. if (isLocal) {
  1554. // Local tracks have SSRC stored on per peer connection basis
  1555. if (peerConnection) {
  1556. ssrc = peerConnection.getLocalSSRC(track);
  1557. }
  1558. } else {
  1559. ssrc = track.getSSRC();
  1560. }
  1561. if (!container.id || !ssrc || !peerConnection) {
  1562. return;
  1563. }
  1564. this.statistics.associateStreamWithVideoTag(
  1565. peerConnection,
  1566. ssrc,
  1567. isLocal,
  1568. remoteUserId,
  1569. track.getUsageLabel(),
  1570. container.id);
  1571. };
  1572. /**
  1573. * Logs an "application log" message.
  1574. * @param message {string} The message to log. Note that while this can be a
  1575. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  1576. * log valid JSON strings, with an "id" field used for distinguishing between
  1577. * message types. E.g.: {id: "recorder_status", status: "off"}
  1578. */
  1579. JitsiConference.prototype.sendApplicationLog = function(message) {
  1580. Statistics.sendLog(message);
  1581. };
  1582. /**
  1583. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1584. * focus.
  1585. * @param mucJid the full MUC address of the user to be checked.
  1586. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  1587. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  1588. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  1589. */
  1590. JitsiConference.prototype._isFocus = function(mucJid) {
  1591. return this.room ? this.room.isFocus(mucJid) : null;
  1592. };
  1593. /**
  1594. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  1595. */
  1596. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  1597. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  1598. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  1599. };
  1600. /**
  1601. * Sends a message via the data channel.
  1602. * @param to {string} the id of the endpoint that should receive the message.
  1603. * If "" the message will be sent to all participants.
  1604. * @param payload {object} the payload of the message.
  1605. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1606. */
  1607. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  1608. this.rtc.sendDataChannelMessage(to, payload);
  1609. };
  1610. /**
  1611. * Sends a broadcast message via the data channel.
  1612. * @param payload {object} the payload of the message.
  1613. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1614. */
  1615. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  1616. this.sendEndpointMessage('', payload);
  1617. };
  1618. JitsiConference.prototype.isConnectionInterrupted = function() {
  1619. return this.isP2PActive()
  1620. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  1621. };
  1622. /**
  1623. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  1624. * @param {JingleSessionPC} session
  1625. * @private
  1626. */
  1627. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  1628. if (session.isP2P) {
  1629. this.isP2PConnectionInterrupted = true;
  1630. } else {
  1631. this.isJvbConnectionInterrupted = true;
  1632. }
  1633. if (session.isP2P === this.isP2PActive()) {
  1634. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  1635. }
  1636. };
  1637. /**
  1638. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  1639. * @param {JingleSessionPC} session
  1640. * @private
  1641. */
  1642. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  1643. // We do nothing for the JVB connection, because it's up to the Jicofo to
  1644. // eventually come up with the new offer (at least for the time being).
  1645. if (session.isP2P) {
  1646. if (this.p2pJingleSession && this.p2pJingleSession.isInitiator) {
  1647. Statistics.sendEventToAll('p2p.failed');
  1648. }
  1649. this._stopP2PSession('connectivity-error', 'ICE FAILED');
  1650. }
  1651. };
  1652. /**
  1653. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  1654. * @param {JingleSessionPC} session
  1655. * @private
  1656. */
  1657. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  1658. if (session.isP2P) {
  1659. this.isP2PConnectionInterrupted = false;
  1660. } else {
  1661. this.isJvbConnectionInterrupted = false;
  1662. }
  1663. if (session.isP2P === this.isP2PActive()) {
  1664. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  1665. }
  1666. };
  1667. /**
  1668. * Accept incoming P2P Jingle call.
  1669. * @param {JingleSessionPC} jingleSession the session instance
  1670. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  1671. * @private
  1672. */
  1673. JitsiConference.prototype._acceptP2PIncomingCall
  1674. = function(jingleSession, jingleOffer) {
  1675. jingleSession.setSSRCOwnerJid(this.room.myroomjid);
  1676. this.isP2PConnectionInterrupted = false;
  1677. // Accept the offer
  1678. this.p2pJingleSession = jingleSession;
  1679. this.p2pJingleSession.initialize(
  1680. false /* initiator */, this.room, this.rtc);
  1681. logger.info('Starting CallStats for P2P connection...');
  1682. this.statistics.startCallStats(
  1683. this.p2pJingleSession.peerconnection,
  1684. Strophe.getResourceFromJid(this.p2pJingleSession.peerjid));
  1685. const localTracks = this.getLocalTracks();
  1686. this.p2pJingleSession.acceptOffer(
  1687. jingleOffer,
  1688. () => {
  1689. logger.debug('Got RESULT for P2P "session-accept"');
  1690. },
  1691. error => {
  1692. logger.error(
  1693. 'Failed to accept incoming P2P Jingle session', error);
  1694. },
  1695. localTracks);
  1696. };
  1697. /**
  1698. * Adds remote tracks to the conference associated with the JVB session.
  1699. * @private
  1700. */
  1701. JitsiConference.prototype._addRemoteJVBTracks = function() {
  1702. this._addRemoteTracks(
  1703. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  1704. };
  1705. /**
  1706. * Adds remote tracks to the conference associated with the P2P session.
  1707. * @private
  1708. */
  1709. JitsiConference.prototype._addRemoteP2PTracks = function() {
  1710. this._addRemoteTracks(
  1711. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  1712. };
  1713. /**
  1714. * Generates fake "remote track added" events for given Jingle session.
  1715. * @param {string} logName the session's nickname which will appear in log
  1716. * messages.
  1717. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  1718. * @private
  1719. */
  1720. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  1721. for (const track of remoteTracks) {
  1722. logger.info(`Adding remote ${logName} track: ${track}`);
  1723. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, track);
  1724. }
  1725. };
  1726. /**
  1727. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  1728. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  1729. * the P2P connection if the event comes from the P2P session.
  1730. * @param {JingleSessionPC} jingleSession the session instance.
  1731. * @private
  1732. */
  1733. JitsiConference.prototype._onIceConnectionEstablished
  1734. = function(jingleSession) {
  1735. // We don't care about the JVB case, there's nothing to be done
  1736. if (!jingleSession.isP2P) {
  1737. return;
  1738. } else if (this.p2pJingleSession !== jingleSession) {
  1739. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  1740. return;
  1741. }
  1742. // Update P2P status and emit events
  1743. this._setP2PStatus(true);
  1744. // Remove remote tracks
  1745. if (this.jvbJingleSession) {
  1746. this._removeRemoteJVBTracks();
  1747. } else {
  1748. logger.info('Not removing remote JVB tracks - no session yet');
  1749. }
  1750. // Add remote tracks
  1751. this._addRemoteP2PTracks();
  1752. // Stop media transfer over the JVB connection
  1753. if (this.jvbJingleSession) {
  1754. this._suspendMediaTransferForJvbConnection();
  1755. }
  1756. // Start remote stats
  1757. logger.info('Starting remote stats with p2p connection');
  1758. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  1759. // Log the P2P established event
  1760. if (this.p2pJingleSession.isInitiator) {
  1761. Statistics.sendEventToAll('p2p.established');
  1762. }
  1763. };
  1764. /**
  1765. * Clears the deferred start P2P task if it has been scheduled.
  1766. * @private
  1767. */
  1768. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  1769. if (this.deferredStartP2PTask) {
  1770. logger.info('Cleared deferred start P2P task');
  1771. clearTimeout(this.deferredStartP2PTask);
  1772. this.deferredStartP2PTask = null;
  1773. }
  1774. };
  1775. /**
  1776. * Removes from the conference remote tracks associated with the JVB
  1777. * connection.
  1778. * @private
  1779. */
  1780. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  1781. this._removeRemoteTracks(
  1782. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  1783. };
  1784. /**
  1785. * Removes from the conference remote tracks associated with the P2P
  1786. * connection.
  1787. * @private
  1788. */
  1789. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  1790. this._removeRemoteTracks(
  1791. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  1792. };
  1793. /**
  1794. * Generates fake "remote track removed" events for given Jingle session.
  1795. * @param {string} sessionNickname the session's nickname which will appear in
  1796. * log messages.
  1797. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  1798. * @private
  1799. */
  1800. JitsiConference.prototype._removeRemoteTracks
  1801. = function(sessionNickname, remoteTracks) {
  1802. for (const track of remoteTracks) {
  1803. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  1804. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, track);
  1805. }
  1806. };
  1807. /**
  1808. * Resumes media transfer over the JVB connection.
  1809. * @private
  1810. */
  1811. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  1812. logger.info('Resuming media transfer over the JVB connection...');
  1813. this.jvbJingleSession.setMediaTransferActive(true).then(
  1814. () => {
  1815. logger.info('Resumed media transfer over the JVB connection!');
  1816. },
  1817. error => {
  1818. logger.error(
  1819. 'Failed to resume media transfer over the JVB connection:',
  1820. error);
  1821. });
  1822. };
  1823. /**
  1824. * Sets new P2P status and updates some events/states hijacked from
  1825. * the <tt>JitsiConference</tt>.
  1826. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  1827. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  1828. * @private
  1829. */
  1830. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  1831. if (this.p2p === newStatus) {
  1832. logger.error(`Called _setP2PStatus with the same status: ${newStatus}`);
  1833. return;
  1834. }
  1835. this.p2p = newStatus;
  1836. if (newStatus) {
  1837. logger.info('Peer to peer connection established!');
  1838. } else {
  1839. logger.info('Peer to peer connection closed!');
  1840. }
  1841. // Put the JVB connection on hold/resume
  1842. if (this.jvbJingleSession) {
  1843. this.statistics.sendConnectionResumeOrHoldEvent(
  1844. this.jvbJingleSession.peerconnection, !newStatus);
  1845. }
  1846. // Clear dtmfManager, so that it can be recreated with new connection
  1847. this.dtmfManager = null;
  1848. // Update P2P status
  1849. this.eventEmitter.emit(
  1850. JitsiConferenceEvents.P2P_STATUS,
  1851. this,
  1852. this.p2p);
  1853. // Refresh connection interrupted/restored
  1854. this.eventEmitter.emit(
  1855. this.isConnectionInterrupted()
  1856. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  1857. : JitsiConferenceEvents.CONNECTION_RESTORED);
  1858. };
  1859. /**
  1860. * Starts new P2P session.
  1861. * @param {string} peerJid the JID of the remote participant
  1862. * @private
  1863. */
  1864. JitsiConference.prototype._startP2PSession = function(peerJid) {
  1865. this._maybeClearDeferredStartP2P();
  1866. if (this.p2pJingleSession) {
  1867. logger.error('P2P session already started!');
  1868. return;
  1869. }
  1870. this.isP2PConnectionInterrupted = false;
  1871. this.p2pJingleSession
  1872. = this.xmpp.connection.jingle.newP2PJingleSession(
  1873. this.room.myroomjid,
  1874. peerJid);
  1875. this.p2pJingleSession.setSSRCOwnerJid(this.room.myroomjid);
  1876. logger.info('Created new P2P JingleSession', this.room.myroomjid, peerJid);
  1877. this.p2pJingleSession.initialize(true /* initiator */, this.room, this.rtc);
  1878. logger.info('Starting CallStats for P2P connection...');
  1879. this.statistics.startCallStats(
  1880. this.p2pJingleSession.peerconnection,
  1881. Strophe.getResourceFromJid(this.p2pJingleSession.peerjid));
  1882. // NOTE one may consider to start P2P with the local tracks detached,
  1883. // but no data will be sent until ICE succeeds anyway. And we switch
  1884. // immediately once the P2P ICE connects.
  1885. const localTracks = this.getLocalTracks();
  1886. this.p2pJingleSession.invite(localTracks);
  1887. };
  1888. /**
  1889. * Suspends media transfer over the JVB connection.
  1890. * @private
  1891. */
  1892. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  1893. logger.info('Suspending media transfer over the JVB connection...');
  1894. this.jvbJingleSession.setMediaTransferActive(false).then(
  1895. () => {
  1896. logger.info('Suspended media transfer over the JVB connection !');
  1897. },
  1898. error => {
  1899. logger.error(
  1900. 'Failed to suspend media transfer over the JVB connection:',
  1901. error);
  1902. });
  1903. };
  1904. /**
  1905. * Method when called will decide whether it's the time to start or stop
  1906. * the P2P session.
  1907. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  1908. * originates from the user left event.
  1909. * @private
  1910. */
  1911. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  1912. if (!this.options.config.enableP2P || !RTCBrowserType.isP2PSupported()) {
  1913. logger.info('Auto P2P disabled');
  1914. return;
  1915. }
  1916. const peers = this.getParticipants();
  1917. const peerCount = peers.length;
  1918. const isModerator = this.isModerator();
  1919. // FIXME 1 peer and it must *support* P2P switching
  1920. const shouldBeInP2P = peerCount === 1;
  1921. logger.debug(
  1922. `P2P? isModerator: ${isModerator
  1923. }, peerCount: ${peerCount} => ${shouldBeInP2P}`);
  1924. // Clear deferred "start P2P" task
  1925. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  1926. this._maybeClearDeferredStartP2P();
  1927. }
  1928. // Start peer to peer session
  1929. if (isModerator && !this.p2pJingleSession && shouldBeInP2P) {
  1930. const peer = peerCount && peers[0];
  1931. // Everyone is a moderator ?
  1932. if (isModerator && peer.getRole() === 'moderator') {
  1933. const myId = this.myUserId();
  1934. const peersId = peer.getId();
  1935. if (myId > peersId) {
  1936. logger.debug(
  1937. 'Everyone\'s a moderator - '
  1938. + 'the other peer should start P2P', myId, peersId);
  1939. return;
  1940. } else if (myId === peersId) {
  1941. logger.error('The same IDs ? ', myId, peersId);
  1942. return;
  1943. }
  1944. }
  1945. const jid = peer.getJid();
  1946. if (userLeftEvent) {
  1947. if (this.deferredStartP2PTask) {
  1948. logger.error('Deferred start P2P task\'s been set already!');
  1949. return;
  1950. }
  1951. logger.info(
  1952. `Will start P2P with: ${jid
  1953. } after ${this.backToP2PDelay} seconds...`);
  1954. this.deferredStartP2PTask = setTimeout(
  1955. this._startP2PSession.bind(this, jid),
  1956. this.backToP2PDelay * 1000);
  1957. } else {
  1958. logger.info(`Will start P2P with: ${jid}`);
  1959. this._startP2PSession(jid);
  1960. }
  1961. } else if (isModerator && this.p2pJingleSession && !shouldBeInP2P) {
  1962. logger.info(`Will stop P2P with: ${this.p2pJingleSession.peerjid}`);
  1963. // Log that there will be a switch back to the JVB connection
  1964. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  1965. Statistics.sendEventToAll('p2p.switch_to_jvb');
  1966. }
  1967. this._stopP2PSession();
  1968. }
  1969. };
  1970. /**
  1971. * Stops the current P2P session.
  1972. * @param {string} [reason="success"] one of the Jingle "reason" element
  1973. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  1974. * @param {string} [reasonDescription="Turing off P2P session"] text
  1975. * description that will be included in the session terminate message
  1976. * @private
  1977. */
  1978. JitsiConference.prototype._stopP2PSession
  1979. = function(reason, reasonDescription) {
  1980. if (!this.p2pJingleSession) {
  1981. logger.error('No P2P session to be stopped!');
  1982. return;
  1983. }
  1984. const wasP2PEstablished = this.isP2PActive();
  1985. // Swap remote tracks, but only if the P2P has been fully established
  1986. if (wasP2PEstablished) {
  1987. this._resumeMediaTransferForJvbConnection();
  1988. // Remove remote P2P tracks
  1989. this._removeRemoteP2PTracks();
  1990. }
  1991. // Stop P2P stats
  1992. logger.info('Stopping remote stats for P2P connection');
  1993. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  1994. logger.info('Stopping CallStats for P2P connection');
  1995. this.statistics.stopCallStats(
  1996. this.p2pJingleSession.peerconnection);
  1997. if (JingleSessionState.ENDED !== this.p2pJingleSession.state) {
  1998. this.p2pJingleSession.terminate(
  1999. reason ? reason : 'success',
  2000. reasonDescription
  2001. ? reasonDescription : 'Turing off P2P session',
  2002. () => {
  2003. logger.info('P2P session terminate RESULT');
  2004. },
  2005. error => {
  2006. logger.warn(
  2007. 'An error occurred while trying to terminate'
  2008. + ' P2P Jingle session', error);
  2009. });
  2010. }
  2011. this.p2pJingleSession = null;
  2012. // Update P2P status and other affected events/states
  2013. this._setP2PStatus(false);
  2014. if (wasP2PEstablished) {
  2015. // Add back remote JVB tracks
  2016. if (this.jvbJingleSession) {
  2017. this._addRemoteJVBTracks();
  2018. } else {
  2019. logger.info('Not adding remote JVB tracks - no session yet');
  2020. }
  2021. }
  2022. };
  2023. /**
  2024. * Checks whether or not the conference is currently in the peer to peer mode.
  2025. * Being in peer to peer mode means that the direct connection has been
  2026. * established and the P2P connection is being used for media transmission.
  2027. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  2028. */
  2029. JitsiConference.prototype.isP2PActive = function() {
  2030. return this.p2p;
  2031. };
  2032. /**
  2033. * Returns the current ICE state of the P2P connection.
  2034. * NOTE: method is used by the jitsi-meet-torture tests.
  2035. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  2036. * no P2P connection.
  2037. */
  2038. JitsiConference.prototype.getP2PConnectionState = function() {
  2039. if (this.isP2PActive()) {
  2040. return this.p2pJingleSession.peerconnection.getConnectionState();
  2041. }
  2042. return null;
  2043. };
  2044. /**
  2045. * Manually starts new P2P session (should be used only in the tests).
  2046. */
  2047. JitsiConference.prototype.startP2PSession = function() {
  2048. const peers = this.getParticipants();
  2049. // Start peer to peer session
  2050. if (peers.length === 1) {
  2051. const peerJid = peers[0].getJid();
  2052. this._startP2PSession(peerJid);
  2053. } else {
  2054. throw new Error(
  2055. 'There must be exactly 1 participant to start the P2P session !');
  2056. }
  2057. };
  2058. /**
  2059. * Manually stops the current P2P session (should be used only in the tests)
  2060. */
  2061. JitsiConference.prototype.stopP2PSession = function() {
  2062. this._stopP2PSession();
  2063. };
  2064. /**
  2065. * Get a summary of how long current participants have been the dominant speaker
  2066. * @returns {object}
  2067. */
  2068. JitsiConference.prototype.getSpeakerStats = function() {
  2069. return this.speakerStatsCollector.getStats();
  2070. };
  2071. /**
  2072. * Get video SIP GW handler, if missing will create one.
  2073. *
  2074. * @returns {VideoSIPGW} video SIP GW handler.
  2075. */
  2076. JitsiConference.prototype._getVideoSIPGWHandle = function() {
  2077. if (!this.videoSIPGWHandler) {
  2078. this.videoSIPGWHandler = new VideoSIPGW(this.room);
  2079. logger.info('Created VideoSIPGW');
  2080. }
  2081. return this.videoSIPGWHandler;
  2082. };
  2083. /**
  2084. * Checks whether video SIP GW service is available.
  2085. *
  2086. * @returns {boolean} whether video SIP GW service is available.
  2087. */
  2088. JitsiConference.prototype.isVideoSIPGWAvailable = function() {
  2089. return this._getVideoSIPGWHandle().isVideoSIPGWAvailable();
  2090. };
  2091. /**
  2092. * Creates a video SIP GW session and returns it if service is enabled. Before
  2093. * creating a session one need to check whether video SIP GW service is
  2094. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2095. * if there are available nodes to serve this request, after creating the
  2096. * session those nodes can be taken and the request about using the
  2097. * created session can fail.
  2098. *
  2099. * @param {string} sipAddress - The sip address to be used.
  2100. * @param {string} displayName - The display name to be used for this session.
  2101. * @returns {JitsiVideoSIPGWSession|null} Returns null if conference is not
  2102. * initialised and there is no room.
  2103. */
  2104. JitsiConference.prototype.createVideoSIPGWSession
  2105. = function(sipAddress, displayName) {
  2106. if (!this.room) {
  2107. return null;
  2108. }
  2109. return this._getVideoSIPGWHandle()
  2110. .createVideoSIPGWSession(sipAddress, displayName);
  2111. };