Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

conference.js 69KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. const logger = require("jitsi-meet-logger").getLogger(__filename);
  3. import {openConnection} from './connection';
  4. import Invite from './modules/UI/invite/Invite';
  5. import ContactList from './modules/UI/side_pannels/contactlist/ContactList';
  6. import AuthHandler from './modules/UI/authentication/AuthHandler';
  7. import Recorder from './modules/recorder/Recorder';
  8. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  9. import { reload, reportError } from './modules/util/helpers';
  10. import UIEvents from './service/UI/UIEvents';
  11. import UIUtil from './modules/UI/util/UIUtil';
  12. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  13. import analytics from './modules/analytics/analytics';
  14. import EventEmitter from "events";
  15. import {
  16. AVATAR_ID_COMMAND,
  17. AVATAR_URL_COMMAND,
  18. conferenceFailed,
  19. conferenceJoined,
  20. conferenceLeft,
  21. EMAIL_COMMAND
  22. } from './react/features/base/conference';
  23. import {
  24. isFatalJitsiConnectionError
  25. } from './react/features/base/lib-jitsi-meet';
  26. import {
  27. changeParticipantAvatarID,
  28. changeParticipantAvatarURL,
  29. changeParticipantEmail,
  30. participantJoined,
  31. participantLeft,
  32. participantRoleChanged
  33. } from './react/features/base/participants';
  34. import {
  35. showDesktopPicker
  36. } from './react/features/desktop-picker';
  37. import {
  38. mediaPermissionPromptVisibilityChanged,
  39. suspendDetected
  40. } from './react/features/overlay';
  41. const ConnectionEvents = JitsiMeetJS.events.connection;
  42. const ConnectionErrors = JitsiMeetJS.errors.connection;
  43. const ConferenceEvents = JitsiMeetJS.events.conference;
  44. const ConferenceErrors = JitsiMeetJS.errors.conference;
  45. const TrackEvents = JitsiMeetJS.events.track;
  46. const TrackErrors = JitsiMeetJS.errors.track;
  47. const ConnectionQualityEvents = JitsiMeetJS.events.connectionQuality;
  48. const eventEmitter = new EventEmitter();
  49. let room, connection, localAudio, localVideo;
  50. /**
  51. * Indicates whether extension external installation is in progress or not.
  52. */
  53. let DSExternalInstallationInProgress = false;
  54. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/VideoContainer";
  55. /*
  56. * Logic to open a desktop picker put on the window global for
  57. * lib-jitsi-meet to detect and invoke
  58. */
  59. window.JitsiMeetScreenObtainer = {
  60. openDesktopPicker(onSourceChoose) {
  61. APP.store.dispatch(showDesktopPicker(onSourceChoose));
  62. }
  63. };
  64. /**
  65. * Known custom conference commands.
  66. */
  67. const commands = {
  68. AVATAR_ID: AVATAR_ID_COMMAND,
  69. AVATAR_URL: AVATAR_URL_COMMAND,
  70. CUSTOM_ROLE: "custom-role",
  71. EMAIL: EMAIL_COMMAND,
  72. ETHERPAD: "etherpad",
  73. SHARED_VIDEO: "shared-video"
  74. };
  75. /**
  76. * Max length of the display names. If we receive longer display name the
  77. * additional chars are going to be cut.
  78. */
  79. const MAX_DISPLAY_NAME_LENGTH = 50;
  80. /**
  81. * Open Connection. When authentication failed it shows auth dialog.
  82. * @param roomName the room name to use
  83. * @returns Promise<JitsiConnection>
  84. */
  85. function connect(roomName) {
  86. return openConnection({retry: true, roomName: roomName})
  87. .catch(function (err) {
  88. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  89. APP.UI.notifyTokenAuthFailed();
  90. } else {
  91. APP.UI.notifyConnectionFailed(err);
  92. }
  93. throw err;
  94. });
  95. }
  96. /**
  97. * Creates local media tracks and connects to room. Will show error
  98. * dialogs in case if accessing local microphone and/or camera failed. Will
  99. * show guidance overlay for users on how to give access to camera and/or
  100. * microphone,
  101. * @param {string} roomName
  102. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  103. */
  104. function createInitialLocalTracksAndConnect(roomName) {
  105. let audioAndVideoError,
  106. audioOnlyError;
  107. JitsiMeetJS.mediaDevices.addEventListener(
  108. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  109. browser =>
  110. APP.store.dispatch(
  111. mediaPermissionPromptVisibilityChanged(true, browser))
  112. );
  113. // First try to retrieve both audio and video.
  114. let tryCreateLocalTracks = createLocalTracks(
  115. { devices: ['audio', 'video'] }, true)
  116. .catch(err => {
  117. // If failed then try to retrieve only audio.
  118. audioAndVideoError = err;
  119. return createLocalTracks({ devices: ['audio'] }, true);
  120. })
  121. .catch(err => {
  122. // If audio failed too then just return empty array for tracks.
  123. audioOnlyError = err;
  124. return [];
  125. });
  126. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  127. .then(([tracks, con]) => {
  128. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  129. if (audioAndVideoError) {
  130. if (audioOnlyError) {
  131. // If both requests for 'audio' + 'video' and 'audio' only
  132. // failed, we assume that there is some problems with user's
  133. // microphone and show corresponding dialog.
  134. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  135. } else {
  136. // If request for 'audio' + 'video' failed, but request for
  137. // 'audio' only was OK, we assume that we had problems with
  138. // camera and show corresponding dialog.
  139. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  140. }
  141. }
  142. return [tracks, con];
  143. });
  144. }
  145. /**
  146. * Share data to other users.
  147. * @param command the command
  148. * @param {string} value new value
  149. */
  150. function sendData (command, value) {
  151. room.removeCommand(command);
  152. room.sendCommand(command, {value: value});
  153. }
  154. /**
  155. * Sets up initially the properties of the local participant - email, avatarID,
  156. * avatarURL, displayName, etc.
  157. */
  158. function _setupLocalParticipantProperties() {
  159. const email = APP.settings.getEmail();
  160. email && sendData(commands.EMAIL, email);
  161. const avatarUrl = APP.settings.getAvatarUrl();
  162. avatarUrl && sendData(commands.AVATAR_URL, avatarUrl);
  163. if (!email && !avatarUrl) {
  164. sendData(commands.AVATAR_ID, APP.settings.getAvatarId());
  165. }
  166. let nick = APP.settings.getDisplayName();
  167. if (config.useNicks && !nick) {
  168. nick = APP.UI.askForNickname();
  169. APP.settings.setDisplayName(nick);
  170. }
  171. nick && room.setDisplayName(nick);
  172. }
  173. /**
  174. * Get user nickname by user id.
  175. * @param {string} id user id
  176. * @returns {string?} user nickname or undefined if user is unknown.
  177. */
  178. function getDisplayName (id) {
  179. if (APP.conference.isLocalId(id)) {
  180. return APP.settings.getDisplayName();
  181. }
  182. let participant = room.getParticipantById(id);
  183. if (participant && participant.getDisplayName()) {
  184. return participant.getDisplayName();
  185. }
  186. }
  187. /**
  188. * Mute or unmute local audio stream if it exists.
  189. * @param {boolean} muted - if audio stream should be muted or unmuted.
  190. * @param {boolean} userInteraction - indicates if this local audio mute was a
  191. * result of user interaction
  192. */
  193. function muteLocalAudio (muted) {
  194. muteLocalMedia(localAudio, muted, 'Audio');
  195. }
  196. function muteLocalMedia(localMedia, muted, localMediaTypeString) {
  197. if (!localMedia) {
  198. return;
  199. }
  200. const method = muted ? 'mute' : 'unmute';
  201. localMedia[method]().catch(reason => {
  202. logger.warn(`${localMediaTypeString} ${method} was rejected:`, reason);
  203. });
  204. }
  205. /**
  206. * Mute or unmute local video stream if it exists.
  207. * @param {boolean} muted if video stream should be muted or unmuted.
  208. */
  209. function muteLocalVideo (muted) {
  210. muteLocalMedia(localVideo, muted, 'Video');
  211. }
  212. /**
  213. * Check if the welcome page is enabled and redirects to it.
  214. * If requested show a thank you dialog before that.
  215. * If we have a close page enabled, redirect to it without
  216. * showing any other dialog.
  217. *
  218. * @param {object} options used to decide which particular close page to show
  219. * or if close page is disabled, whether we should show the thankyou dialog
  220. * @param {boolean} options.thankYouDialogVisible - whether we should
  221. * show thank you dialog
  222. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  223. */
  224. function maybeRedirectToWelcomePage(options) {
  225. // if close page is enabled redirect to it, without further action
  226. if (config.enableClosePage) {
  227. // save whether current user is guest or not, before navigating
  228. // to close page
  229. window.sessionStorage.setItem('guest', APP.tokenData.isGuest);
  230. assignWindowLocationPathname('static/'
  231. + (options.feedbackSubmitted ? "close.html" : "close2.html"));
  232. return;
  233. }
  234. // else: show thankYou dialog only if there is no feedback
  235. if (options.thankYouDialogVisible)
  236. APP.UI.messageHandler.openMessageDialog(
  237. null, "dialog.thankYou", {appName:interfaceConfig.APP_NAME});
  238. // if Welcome page is enabled redirect to welcome page after 3 sec.
  239. if (config.enableWelcomePage) {
  240. setTimeout(() => {
  241. APP.settings.setWelcomePageEnabled(true);
  242. assignWindowLocationPathname('./');
  243. }, 3000);
  244. }
  245. }
  246. /**
  247. * Assigns a specific pathname to window.location.pathname taking into account
  248. * the context root of the Web app.
  249. *
  250. * @param {string} pathname - The pathname to assign to
  251. * window.location.pathname. If the specified pathname is relative, the context
  252. * root of the Web app will be prepended to the specified pathname before
  253. * assigning it to window.location.pathname.
  254. * @return {void}
  255. */
  256. function assignWindowLocationPathname(pathname) {
  257. const windowLocation = window.location;
  258. if (!pathname.startsWith('/')) {
  259. // XXX To support a deployment in a sub-directory, assume that the room
  260. // (name) is the last non-directory component of the path (name).
  261. let contextRoot = windowLocation.pathname;
  262. contextRoot
  263. = contextRoot.substring(0, contextRoot.lastIndexOf('/') + 1);
  264. // A pathname equal to ./ specifies the current directory. It will be
  265. // fine but pointless to include it because contextRoot is the current
  266. // directory.
  267. pathname.startsWith('./') && (pathname = pathname.substring(2));
  268. pathname = contextRoot + pathname;
  269. }
  270. windowLocation.pathname = pathname;
  271. }
  272. /**
  273. * Create local tracks of specified types.
  274. * @param {Object} options
  275. * @param {string[]} options.devices - required track types
  276. * ('audio', 'video' etc.)
  277. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  278. * undefined - one from settings will be used
  279. * @param {string|null} (options.micDeviceId) - microphone device id, if
  280. * undefined - one from settings will be used
  281. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  282. * for gUM permission prompt
  283. * @returns {Promise<JitsiLocalTrack[]>}
  284. */
  285. function createLocalTracks (options, checkForPermissionPrompt) {
  286. options || (options = {});
  287. return JitsiMeetJS
  288. .createLocalTracks({
  289. // copy array to avoid mutations inside library
  290. devices: options.devices.slice(0),
  291. resolution: config.resolution,
  292. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  293. options.cameraDeviceId === null
  294. ? APP.settings.getCameraDeviceId()
  295. : options.cameraDeviceId,
  296. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  297. options.micDeviceId === null
  298. ? APP.settings.getMicDeviceId()
  299. : options.micDeviceId,
  300. // adds any ff fake device settings if any
  301. firefox_fake_device: config.firefox_fake_device,
  302. desktopSharingExtensionExternalInstallation:
  303. options.desktopSharingExtensionExternalInstallation
  304. }, checkForPermissionPrompt).then( (tracks) => {
  305. tracks.forEach((track) => {
  306. track.on(TrackEvents.NO_DATA_FROM_SOURCE,
  307. APP.UI.showTrackNotWorkingDialog.bind(null, track));
  308. });
  309. return tracks;
  310. }).catch(function (err) {
  311. logger.error(
  312. 'failed to create local tracks', options.devices, err);
  313. return Promise.reject(err);
  314. });
  315. }
  316. /**
  317. * Changes the display name for the local user
  318. * @param nickname {string} the new display name
  319. */
  320. function changeLocalDisplayName(nickname = '') {
  321. const formattedNickname
  322. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  323. if (formattedNickname === APP.settings.getDisplayName()) {
  324. return;
  325. }
  326. APP.settings.setDisplayName(formattedNickname);
  327. room.setDisplayName(formattedNickname);
  328. APP.UI.changeDisplayName(APP.conference.getMyUserId(), formattedNickname);
  329. }
  330. class ConferenceConnector {
  331. constructor(resolve, reject, invite) {
  332. this._resolve = resolve;
  333. this._reject = reject;
  334. this._invite = invite;
  335. this.reconnectTimeout = null;
  336. room.on(ConferenceEvents.CONFERENCE_JOINED,
  337. this._handleConferenceJoined.bind(this));
  338. room.on(ConferenceEvents.CONFERENCE_FAILED,
  339. this._onConferenceFailed.bind(this));
  340. room.on(ConferenceEvents.CONFERENCE_ERROR,
  341. this._onConferenceError.bind(this));
  342. }
  343. _handleConferenceFailed(err) {
  344. this._unsubscribe();
  345. this._reject(err);
  346. }
  347. _onConferenceFailed(err, ...params) {
  348. APP.store.dispatch(conferenceFailed(room, err, ...params));
  349. logger.error('CONFERENCE FAILED:', err, ...params);
  350. APP.UI.hideRingOverLay();
  351. switch (err) {
  352. // room is locked by the password
  353. case ConferenceErrors.PASSWORD_REQUIRED:
  354. APP.UI.emitEvent(UIEvents.PASSWORD_REQUIRED);
  355. break;
  356. case ConferenceErrors.CONNECTION_ERROR:
  357. {
  358. let [msg] = params;
  359. APP.UI.notifyConnectionFailed(msg);
  360. }
  361. break;
  362. case ConferenceErrors.NOT_ALLOWED_ERROR:
  363. {
  364. // let's show some auth not allowed page
  365. assignWindowLocationPathname('static/authError.html');
  366. }
  367. break;
  368. // not enough rights to create conference
  369. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  370. // schedule reconnect to check if someone else created the room
  371. this.reconnectTimeout = setTimeout(function () {
  372. room.join();
  373. }, 5000);
  374. // notify user that auth is required
  375. AuthHandler.requireAuth(
  376. room, this._invite.getRoomLocker().password);
  377. break;
  378. case ConferenceErrors.RESERVATION_ERROR:
  379. {
  380. let [code, msg] = params;
  381. APP.UI.notifyReservationError(code, msg);
  382. }
  383. break;
  384. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  385. APP.UI.notifyGracefulShutdown();
  386. break;
  387. case ConferenceErrors.JINGLE_FATAL_ERROR:
  388. APP.UI.notifyInternalError();
  389. break;
  390. case ConferenceErrors.CONFERENCE_DESTROYED:
  391. {
  392. let [reason] = params;
  393. APP.UI.hideStats();
  394. APP.UI.notifyConferenceDestroyed(reason);
  395. }
  396. break;
  397. // FIXME FOCUS_DISCONNECTED is confusing event name.
  398. // What really happens there is that the library is not ready yet,
  399. // because Jicofo is not available, but it is going to give
  400. // it another try.
  401. case ConferenceErrors.FOCUS_DISCONNECTED:
  402. {
  403. let [focus, retrySec] = params;
  404. APP.UI.notifyFocusDisconnected(focus, retrySec);
  405. }
  406. break;
  407. case ConferenceErrors.FOCUS_LEFT:
  408. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  409. // FIXME the conference should be stopped by the library and not by
  410. // the app. Both the errors above are unrecoverable from the library
  411. // perspective.
  412. room.leave().then(() => connection.disconnect());
  413. break;
  414. case ConferenceErrors.CONFERENCE_MAX_USERS:
  415. connection.disconnect();
  416. APP.UI.notifyMaxUsersLimitReached();
  417. break;
  418. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  419. reload();
  420. break;
  421. default:
  422. this._handleConferenceFailed(err, ...params);
  423. }
  424. }
  425. _onConferenceError(err, ...params) {
  426. logger.error('CONFERENCE Error:', err, params);
  427. switch (err) {
  428. case ConferenceErrors.CHAT_ERROR:
  429. {
  430. let [code, msg] = params;
  431. APP.UI.showChatError(code, msg);
  432. }
  433. break;
  434. default:
  435. logger.error("Unknown error.", err);
  436. }
  437. }
  438. _unsubscribe() {
  439. room.off(
  440. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  441. room.off(
  442. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  443. if (this.reconnectTimeout !== null) {
  444. clearTimeout(this.reconnectTimeout);
  445. }
  446. AuthHandler.closeAuth();
  447. }
  448. _handleConferenceJoined() {
  449. this._unsubscribe();
  450. this._resolve();
  451. }
  452. connect() {
  453. room.join();
  454. }
  455. }
  456. /**
  457. * Disconnects the connection.
  458. * @returns resolved Promise. We need this in order to make the Promise.all
  459. * call in hangup() to resolve when all operations are finished.
  460. */
  461. function disconnect() {
  462. connection.disconnect();
  463. APP.API.notifyConferenceLeft(APP.conference.roomName);
  464. return Promise.resolve();
  465. }
  466. /**
  467. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  468. *
  469. * @param {JitsiMeetJS.connection.error} error - The reported error.
  470. * @returns {void}
  471. * @private
  472. */
  473. function _connectionFailedHandler(error) {
  474. if (isFatalJitsiConnectionError(error)) {
  475. APP.connection.removeEventListener(
  476. ConnectionEvents.CONNECTION_FAILED,
  477. _connectionFailedHandler);
  478. if (room)
  479. room.leave();
  480. }
  481. }
  482. export default {
  483. isModerator: false,
  484. audioMuted: false,
  485. videoMuted: false,
  486. isSharingScreen: false,
  487. isDesktopSharingEnabled: false,
  488. /*
  489. * Whether the local "raisedHand" flag is on.
  490. */
  491. isHandRaised: false,
  492. /*
  493. * Whether the local participant is the dominant speaker in the conference.
  494. */
  495. isDominantSpeaker: false,
  496. /**
  497. * Open new connection and join to the conference.
  498. * @param {object} options
  499. * @param {string} roomName name of the conference
  500. * @returns {Promise}
  501. */
  502. init(options) {
  503. this.roomName = options.roomName;
  504. // attaches global error handler, if there is already one, respect it
  505. if(JitsiMeetJS.getGlobalOnErrorHandler){
  506. var oldOnErrorHandler = window.onerror;
  507. window.onerror = function (message, source, lineno, colno, error) {
  508. JitsiMeetJS.getGlobalOnErrorHandler(
  509. message, source, lineno, colno, error);
  510. if(oldOnErrorHandler)
  511. oldOnErrorHandler(message, source, lineno, colno, error);
  512. };
  513. var oldOnUnhandledRejection = window.onunhandledrejection;
  514. window.onunhandledrejection = function(event) {
  515. JitsiMeetJS.getGlobalOnErrorHandler(
  516. null, null, null, null, event.reason);
  517. if(oldOnUnhandledRejection)
  518. oldOnUnhandledRejection(event);
  519. };
  520. }
  521. return JitsiMeetJS.init(
  522. Object.assign(
  523. {enableAnalyticsLogging: analytics.isEnabled()}, config)
  524. ).then(() => {
  525. analytics.init();
  526. return createInitialLocalTracksAndConnect(options.roomName);
  527. }).then(([tracks, con]) => {
  528. logger.log('initialized with %s local tracks', tracks.length);
  529. con.addEventListener(
  530. ConnectionEvents.CONNECTION_FAILED,
  531. _connectionFailedHandler);
  532. APP.connection = connection = con;
  533. this.isDesktopSharingEnabled =
  534. JitsiMeetJS.isDesktopSharingEnabled();
  535. APP.remoteControl.init();
  536. this._createRoom(tracks);
  537. if (UIUtil.isButtonEnabled('contacts')
  538. && !interfaceConfig.filmStripOnly) {
  539. APP.UI.ContactList = new ContactList(room);
  540. }
  541. // if user didn't give access to mic or camera or doesn't have
  542. // them at all, we disable corresponding toolbar buttons
  543. if (!tracks.find((t) => t.isAudioTrack())) {
  544. APP.UI.setMicrophoneButtonEnabled(false);
  545. }
  546. if (!tracks.find((t) => t.isVideoTrack())) {
  547. APP.UI.setCameraButtonEnabled(false);
  548. }
  549. this._initDeviceList();
  550. if (config.iAmRecorder)
  551. this.recorder = new Recorder();
  552. // XXX The API will take care of disconnecting from the XMPP
  553. // server (and, thus, leaving the room) on unload.
  554. return new Promise((resolve, reject) => {
  555. (new ConferenceConnector(
  556. resolve, reject, this.invite)).connect();
  557. });
  558. });
  559. },
  560. /**
  561. * Check if id is id of the local user.
  562. * @param {string} id id to check
  563. * @returns {boolean}
  564. */
  565. isLocalId (id) {
  566. return this.getMyUserId() === id;
  567. },
  568. /**
  569. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  570. * @param mute true for mute and false for unmute.
  571. */
  572. muteAudio (mute) {
  573. muteLocalAudio(mute);
  574. },
  575. /**
  576. * Returns whether local audio is muted or not.
  577. * @returns {boolean}
  578. */
  579. isLocalAudioMuted() {
  580. return this.audioMuted;
  581. },
  582. /**
  583. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  584. */
  585. toggleAudioMuted () {
  586. this.muteAudio(!this.audioMuted);
  587. },
  588. /**
  589. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  590. * @param mute true for mute and false for unmute.
  591. */
  592. muteVideo (mute) {
  593. muteLocalVideo(mute);
  594. },
  595. /**
  596. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  597. */
  598. toggleVideoMuted () {
  599. this.muteVideo(!this.videoMuted);
  600. },
  601. /**
  602. * Retrieve list of conference participants (without local user).
  603. * @returns {JitsiParticipant[]}
  604. */
  605. listMembers () {
  606. return room.getParticipants();
  607. },
  608. /**
  609. * Retrieve list of ids of conference participants (without local user).
  610. * @returns {string[]}
  611. */
  612. listMembersIds () {
  613. return room.getParticipants().map(p => p.getId());
  614. },
  615. /**
  616. * Checks whether the participant identified by id is a moderator.
  617. * @id id to search for participant
  618. * @return {boolean} whether the participant is moderator
  619. */
  620. isParticipantModerator (id) {
  621. let user = room.getParticipantById(id);
  622. return user && user.isModerator();
  623. },
  624. /**
  625. * Check if SIP is supported.
  626. * @returns {boolean}
  627. */
  628. sipGatewayEnabled () {
  629. return room.isSIPCallingSupported();
  630. },
  631. get membersCount () {
  632. return room.getParticipants().length + 1;
  633. },
  634. /**
  635. * Returns true if the callstats integration is enabled, otherwise returns
  636. * false.
  637. *
  638. * @returns true if the callstats integration is enabled, otherwise returns
  639. * false.
  640. */
  641. isCallstatsEnabled () {
  642. return room && room.isCallstatsEnabled();
  643. },
  644. /**
  645. * Sends the given feedback through CallStats if enabled.
  646. *
  647. * @param overallFeedback an integer between 1 and 5 indicating the
  648. * user feedback
  649. * @param detailedFeedback detailed feedback from the user. Not yet used
  650. */
  651. sendFeedback (overallFeedback, detailedFeedback) {
  652. return room.sendFeedback (overallFeedback, detailedFeedback);
  653. },
  654. /**
  655. * Get speaker stats that track total dominant speaker time.
  656. *
  657. * @returns {object} A hash with keys being user ids and values being the
  658. * library's SpeakerStats model used for calculating time as dominant
  659. * speaker.
  660. */
  661. getSpeakerStats() {
  662. return room.getSpeakerStats();
  663. },
  664. /**
  665. * Returns the connection times stored in the library.
  666. */
  667. getConnectionTimes () {
  668. return this._room.getConnectionTimes();
  669. },
  670. // used by torture currently
  671. isJoined () {
  672. return this._room
  673. && this._room.isJoined();
  674. },
  675. getConnectionState () {
  676. return this._room
  677. && this._room.getConnectionState();
  678. },
  679. /**
  680. * Obtains current P2P ICE connection state.
  681. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  682. * P2P connection
  683. */
  684. getP2PConnectionState () {
  685. return this._room
  686. && this._room.getP2PConnectionState();
  687. },
  688. /**
  689. * Starts P2P (for tests only)
  690. * @private
  691. */
  692. _startP2P () {
  693. try {
  694. this._room && this._room.startP2PSession();
  695. } catch (error) {
  696. logger.error("Start P2P failed", error);
  697. throw error;
  698. }
  699. },
  700. /**
  701. * Stops P2P (for tests only)
  702. * @private
  703. */
  704. _stopP2P () {
  705. try {
  706. this._room && this._room.stopP2PSession();
  707. } catch (error) {
  708. logger.error("Stop P2P failed", error);
  709. throw error;
  710. }
  711. },
  712. /**
  713. * Checks whether or not our connection is currently in interrupted and
  714. * reconnect attempts are in progress.
  715. *
  716. * @returns {boolean} true if the connection is in interrupted state or
  717. * false otherwise.
  718. */
  719. isConnectionInterrupted () {
  720. return this._room.isConnectionInterrupted();
  721. },
  722. /**
  723. * Finds JitsiParticipant for given id.
  724. *
  725. * @param {string} id participant's identifier(MUC nickname).
  726. *
  727. * @returns {JitsiParticipant|null} participant instance for given id or
  728. * null if not found.
  729. */
  730. getParticipantById (id) {
  731. return room ? room.getParticipantById(id) : null;
  732. },
  733. /**
  734. * Checks whether the user identified by given id is currently connected.
  735. *
  736. * @param {string} id participant's identifier(MUC nickname)
  737. *
  738. * @returns {boolean|null} true if participant's connection is ok or false
  739. * if the user is having connectivity issues.
  740. */
  741. isParticipantConnectionActive (id) {
  742. let participant = this.getParticipantById(id);
  743. return participant ? participant.isConnectionActive() : null;
  744. },
  745. /**
  746. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  747. * the given <tt>id</tt>.
  748. *
  749. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  750. *
  751. * @return {string} the participant's display name or the default string if
  752. * absent.
  753. */
  754. getParticipantDisplayName (id) {
  755. let displayName = getDisplayName(id);
  756. if (displayName) {
  757. return displayName;
  758. } else {
  759. if (APP.conference.isLocalId(id)) {
  760. return APP.translation.generateTranslationHTML(
  761. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  762. } else {
  763. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  764. }
  765. }
  766. },
  767. getMyUserId () {
  768. return this._room
  769. && this._room.myUserId();
  770. },
  771. /**
  772. * Indicates if recording is supported in this conference.
  773. */
  774. isRecordingSupported() {
  775. return this._room && this._room.isRecordingSupported();
  776. },
  777. /**
  778. * Returns the recording state or undefined if the room is not defined.
  779. */
  780. getRecordingState() {
  781. return (this._room) ? this._room.getRecordingState() : undefined;
  782. },
  783. /**
  784. * Will be filled with values only when config.debug is enabled.
  785. * Its used by torture to check audio levels.
  786. */
  787. audioLevelsMap: {},
  788. /**
  789. * Returns the stored audio level (stored only if config.debug is enabled)
  790. * @param id the id for the user audio level to return (the id value is
  791. * returned for the participant using getMyUserId() method)
  792. */
  793. getPeerSSRCAudioLevel (id) {
  794. return this.audioLevelsMap[id];
  795. },
  796. /**
  797. * @return {number} the number of participants in the conference with at
  798. * least one track.
  799. */
  800. getNumberOfParticipantsWithTracks() {
  801. return this._room.getParticipants()
  802. .filter((p) => p.getTracks().length > 0)
  803. .length;
  804. },
  805. /**
  806. * Returns the stats.
  807. */
  808. getStats() {
  809. return room.connectionQuality.getStats();
  810. },
  811. // end used by torture
  812. getLogs () {
  813. return room.getLogs();
  814. },
  815. /**
  816. * Download logs, a function that can be called from console while
  817. * debugging.
  818. * @param filename (optional) specify target filename
  819. */
  820. saveLogs (filename = 'meetlog.json') {
  821. // this can be called from console and will not have reference to this
  822. // that's why we reference the global var
  823. let logs = APP.conference.getLogs();
  824. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  825. let elem = document.createElement('a');
  826. elem.download = filename;
  827. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  828. elem.dataset.downloadurl
  829. = ['text/json', elem.download, elem.href].join(':');
  830. elem.dispatchEvent(new MouseEvent('click', {
  831. view: window,
  832. bubbles: true,
  833. cancelable: false
  834. }));
  835. },
  836. /**
  837. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  838. * desire to keep room private to this instance and (2) the need of other
  839. * modules to send and receive commands to and from participants.
  840. * Eventually, this instance remains in control with respect to the
  841. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  842. * JitsiConference) is to be used in the implementation of the Command(s)
  843. * API of this instance.
  844. */
  845. commands: {
  846. /**
  847. * Known custom conference commands.
  848. */
  849. defaults: commands,
  850. /**
  851. * Receives notifications from other participants about commands aka
  852. * custom events (sent by sendCommand or sendCommandOnce methods).
  853. * @param command {String} the name of the command
  854. * @param handler {Function} handler for the command
  855. */
  856. addCommandListener () {
  857. room.addCommandListener.apply(room, arguments);
  858. },
  859. /**
  860. * Removes command.
  861. * @param name {String} the name of the command.
  862. */
  863. removeCommand () {
  864. room.removeCommand.apply(room, arguments);
  865. },
  866. /**
  867. * Sends command.
  868. * @param name {String} the name of the command.
  869. * @param values {Object} with keys and values that will be sent.
  870. */
  871. sendCommand () {
  872. room.sendCommand.apply(room, arguments);
  873. },
  874. /**
  875. * Sends command one time.
  876. * @param name {String} the name of the command.
  877. * @param values {Object} with keys and values that will be sent.
  878. */
  879. sendCommandOnce () {
  880. room.sendCommandOnce.apply(room, arguments);
  881. }
  882. },
  883. _createRoom (localTracks) {
  884. room = connection.initJitsiConference(APP.conference.roomName,
  885. this._getConferenceOptions());
  886. this._setLocalAudioVideoStreams(localTracks);
  887. this.invite = new Invite(room);
  888. this._room = room; // FIXME do not use this
  889. _setupLocalParticipantProperties();
  890. this._setupListeners();
  891. },
  892. /**
  893. * Sets local video and audio streams.
  894. * @param {JitsiLocalTrack[]} tracks=[]
  895. * @returns {Promise[]}
  896. * @private
  897. */
  898. _setLocalAudioVideoStreams(tracks = []) {
  899. return tracks.map(track => {
  900. if (track.isAudioTrack()) {
  901. return this.useAudioStream(track);
  902. } else if (track.isVideoTrack()) {
  903. return this.useVideoStream(track);
  904. } else {
  905. logger.error(
  906. "Ignored not an audio nor a video track: ", track);
  907. return Promise.resolve();
  908. }
  909. });
  910. },
  911. _getConferenceOptions() {
  912. let options = config;
  913. if(config.enableRecording && !config.recordingType) {
  914. options.recordingType = (config.hosts &&
  915. (typeof config.hosts.jirecon != "undefined"))?
  916. "jirecon" : "colibri";
  917. }
  918. return options;
  919. },
  920. /**
  921. * Start using provided video stream.
  922. * Stops previous video stream.
  923. * @param {JitsiLocalTrack} [stream] new stream to use or null
  924. * @returns {Promise}
  925. */
  926. useVideoStream (newStream) {
  927. return room.replaceTrack(localVideo, newStream)
  928. .then(() => {
  929. // We call dispose after doing the replace because
  930. // dispose will try and do a new o/a after the
  931. // track removes itself. Doing it after means
  932. // the JitsiLocalTrack::conference member is already
  933. // cleared, so it won't try and do the o/a
  934. if (localVideo) {
  935. localVideo.dispose();
  936. }
  937. localVideo = newStream;
  938. if (newStream) {
  939. this.videoMuted = newStream.isMuted();
  940. this.isSharingScreen = newStream.videoType === 'desktop';
  941. APP.UI.addLocalStream(newStream);
  942. newStream.videoType === 'camera'
  943. && APP.UI.setCameraButtonEnabled(true);
  944. } else {
  945. this.videoMuted = false;
  946. this.isSharingScreen = false;
  947. }
  948. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  949. APP.UI.updateDesktopSharingButtons();
  950. });
  951. },
  952. /**
  953. * Start using provided audio stream.
  954. * Stops previous audio stream.
  955. * @param {JitsiLocalTrack} [stream] new stream to use or null
  956. * @returns {Promise}
  957. */
  958. useAudioStream (newStream) {
  959. return room.replaceTrack(localAudio, newStream)
  960. .then(() => {
  961. // We call dispose after doing the replace because
  962. // dispose will try and do a new o/a after the
  963. // track removes itself. Doing it after means
  964. // the JitsiLocalTrack::conference member is already
  965. // cleared, so it won't try and do the o/a
  966. if (localAudio) {
  967. localAudio.dispose();
  968. }
  969. localAudio = newStream;
  970. if (newStream) {
  971. this.audioMuted = newStream.isMuted();
  972. APP.UI.addLocalStream(newStream);
  973. } else {
  974. this.audioMuted = false;
  975. }
  976. APP.UI.setMicrophoneButtonEnabled(true);
  977. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  978. });
  979. },
  980. videoSwitchInProgress: false,
  981. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  982. if (this.videoSwitchInProgress) {
  983. logger.warn("Switch in progress.");
  984. return;
  985. }
  986. if (!this.isDesktopSharingEnabled) {
  987. logger.warn("Cannot toggle screen sharing: not supported.");
  988. return;
  989. }
  990. this.videoSwitchInProgress = true;
  991. let externalInstallation = false;
  992. if (shareScreen) {
  993. this.screenSharingPromise = createLocalTracks({
  994. devices: ['desktop'],
  995. desktopSharingExtensionExternalInstallation: {
  996. interval: 500,
  997. checkAgain: () => {
  998. return DSExternalInstallationInProgress;
  999. },
  1000. listener: (status, url) => {
  1001. switch(status) {
  1002. case "waitingForExtension":
  1003. DSExternalInstallationInProgress = true;
  1004. externalInstallation = true;
  1005. APP.UI.showExtensionExternalInstallationDialog(
  1006. url);
  1007. break;
  1008. case "extensionFound":
  1009. if(externalInstallation) //close the dialog
  1010. $.prompt.close();
  1011. break;
  1012. default:
  1013. //Unknown status
  1014. }
  1015. }
  1016. }
  1017. }).then(([stream]) => {
  1018. DSExternalInstallationInProgress = false;
  1019. // close external installation dialog on success.
  1020. if(externalInstallation)
  1021. $.prompt.close();
  1022. stream.on(
  1023. TrackEvents.LOCAL_TRACK_STOPPED,
  1024. () => {
  1025. // if stream was stopped during screensharing session
  1026. // then we should switch to video
  1027. // otherwise we stopped it because we already switched
  1028. // to video, so nothing to do here
  1029. if (this.isSharingScreen) {
  1030. this.toggleScreenSharing(false);
  1031. }
  1032. }
  1033. );
  1034. return this.useVideoStream(stream);
  1035. }).then(() => {
  1036. this.videoSwitchInProgress = false;
  1037. JitsiMeetJS.analytics.sendEvent(
  1038. 'conference.sharingDesktop.start');
  1039. logger.log('sharing local desktop');
  1040. }).catch((err) => {
  1041. // close external installation dialog to show the error.
  1042. if(externalInstallation)
  1043. $.prompt.close();
  1044. this.videoSwitchInProgress = false;
  1045. this.toggleScreenSharing(false);
  1046. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1047. return;
  1048. }
  1049. logger.error('failed to share local desktop', err);
  1050. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1051. APP.UI.showExtensionRequiredDialog(
  1052. config.desktopSharingFirefoxExtensionURL
  1053. );
  1054. return;
  1055. }
  1056. // Handling:
  1057. // TrackErrors.PERMISSION_DENIED
  1058. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1059. // TrackErrors.GENERAL
  1060. // and any other
  1061. let dialogTxt;
  1062. let dialogTitleKey;
  1063. if (err.name === TrackErrors.PERMISSION_DENIED) {
  1064. dialogTxt = APP.translation.generateTranslationHTML(
  1065. "dialog.screenSharingPermissionDeniedError");
  1066. dialogTitleKey = "dialog.error";
  1067. } else {
  1068. dialogTxt = APP.translation.generateTranslationHTML(
  1069. "dialog.failtoinstall");
  1070. dialogTitleKey = "dialog.permissionDenied";
  1071. }
  1072. APP.UI.messageHandler.openDialog(
  1073. dialogTitleKey, dialogTxt, false);
  1074. });
  1075. } else {
  1076. APP.remoteControl.receiver.stop();
  1077. this.screenSharingPromise = createLocalTracks(
  1078. { devices: ['video'] })
  1079. .then(
  1080. ([stream]) => this.useVideoStream(stream)
  1081. ).then(() => {
  1082. this.videoSwitchInProgress = false;
  1083. JitsiMeetJS.analytics.sendEvent(
  1084. 'conference.sharingDesktop.stop');
  1085. logger.log('sharing local video');
  1086. }).catch((err) => {
  1087. this.useVideoStream(null);
  1088. this.videoSwitchInProgress = false;
  1089. logger.error('failed to share local video', err);
  1090. });
  1091. }
  1092. },
  1093. /**
  1094. * Setup interaction between conference and UI.
  1095. */
  1096. _setupListeners () {
  1097. // add local streams when joined to the conference
  1098. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1099. APP.store.dispatch(conferenceJoined(room));
  1100. APP.UI.mucJoined();
  1101. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1102. APP.UI.markVideoInterrupted(false);
  1103. });
  1104. room.on(
  1105. ConferenceEvents.CONFERENCE_LEFT,
  1106. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1107. room.on(
  1108. ConferenceEvents.AUTH_STATUS_CHANGED,
  1109. function (authEnabled, authLogin) {
  1110. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1111. }
  1112. );
  1113. room.on(ConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1114. user => APP.UI.onUserFeaturesChanged(user));
  1115. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1116. if (user.isHidden())
  1117. return;
  1118. APP.store.dispatch(participantJoined({
  1119. id,
  1120. name: user.getDisplayName(),
  1121. role: user.getRole()
  1122. }));
  1123. logger.log('USER %s connnected', id, user);
  1124. APP.API.notifyUserJoined(id);
  1125. APP.UI.addUser(user);
  1126. // check the roles for the new user and reflect them
  1127. APP.UI.updateUserRole(user);
  1128. });
  1129. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1130. APP.store.dispatch(participantLeft(id, user));
  1131. logger.log('USER %s LEFT', id, user);
  1132. APP.API.notifyUserLeft(id);
  1133. APP.UI.removeUser(id, user.getDisplayName());
  1134. APP.UI.onSharedVideoStop(id);
  1135. });
  1136. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1137. APP.store.dispatch(participantRoleChanged(id, role));
  1138. if (this.isLocalId(id)) {
  1139. logger.info(`My role changed, new role: ${role}`);
  1140. if (this.isModerator !== room.isModerator()) {
  1141. this.isModerator = room.isModerator();
  1142. APP.UI.updateLocalRole(room.isModerator());
  1143. }
  1144. } else {
  1145. let user = room.getParticipantById(id);
  1146. if (user) {
  1147. APP.UI.updateUserRole(user);
  1148. }
  1149. }
  1150. });
  1151. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1152. if(!track || track.isLocal())
  1153. return;
  1154. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1155. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1156. });
  1157. APP.UI.addRemoteStream(track);
  1158. });
  1159. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1160. if(!track || track.isLocal())
  1161. return;
  1162. APP.UI.removeRemoteStream(track);
  1163. });
  1164. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1165. if(!track)
  1166. return;
  1167. const handler = (track.getType() === "audio")?
  1168. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1169. let id;
  1170. const mute = track.isMuted();
  1171. if(track.isLocal()){
  1172. id = APP.conference.getMyUserId();
  1173. if(track.getType() === "audio") {
  1174. this.audioMuted = mute;
  1175. } else {
  1176. this.videoMuted = mute;
  1177. }
  1178. } else {
  1179. id = track.getParticipantId();
  1180. }
  1181. handler(id , mute);
  1182. });
  1183. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1184. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1185. lvl = 0;
  1186. }
  1187. if(config.debug)
  1188. {
  1189. this.audioLevelsMap[id] = lvl;
  1190. if(config.debugAudioLevels)
  1191. logger.log("AudioLevel:" + id + "/" + lvl);
  1192. }
  1193. APP.UI.setAudioLevel(id, lvl);
  1194. });
  1195. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1196. APP.UI.showToolbar(6000);
  1197. APP.UI.showCustomToolbarPopup('#talkWhileMutedPopup', true, 5000);
  1198. });
  1199. room.on(
  1200. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1201. (leavingIds, enteringIds) => {
  1202. APP.UI.handleLastNEndpoints(leavingIds, enteringIds);
  1203. });
  1204. room.on(
  1205. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1206. (id, isActive) => {
  1207. APP.UI.participantConnectionStatusChanged(id, isActive);
  1208. });
  1209. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1210. if (this.isLocalId(id)) {
  1211. this.isDominantSpeaker = true;
  1212. this.setRaisedHand(false);
  1213. } else {
  1214. this.isDominantSpeaker = false;
  1215. var participant = room.getParticipantById(id);
  1216. if (participant) {
  1217. APP.UI.setRaisedHandStatus(participant, false);
  1218. }
  1219. }
  1220. APP.UI.markDominantSpeaker(id);
  1221. });
  1222. if (!interfaceConfig.filmStripOnly) {
  1223. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1224. APP.UI.markVideoInterrupted(true);
  1225. });
  1226. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1227. APP.UI.markVideoInterrupted(false);
  1228. });
  1229. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1230. let nick = getDisplayName(id);
  1231. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1232. APP.UI.addMessage(id, nick, text, ts);
  1233. });
  1234. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1235. APP.API.notifySendingChatMessage(message);
  1236. room.sendTextMessage(message);
  1237. });
  1238. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1239. try {
  1240. // do not try to select participant if there is none (we
  1241. // are alone in the room), otherwise an error will be
  1242. // thrown cause reporting mechanism is not available
  1243. // (datachannels currently)
  1244. if (room.getParticipants().length === 0)
  1245. return;
  1246. room.selectParticipant(id);
  1247. } catch (e) {
  1248. JitsiMeetJS.analytics.sendEvent(
  1249. 'selectParticipant.failed');
  1250. reportError(e);
  1251. }
  1252. });
  1253. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1254. (smallVideo, isPinned) => {
  1255. let smallVideoId = smallVideo.getId();
  1256. let isLocal = APP.conference.isLocalId(smallVideoId);
  1257. let eventName
  1258. = (isPinned ? "pinned" : "unpinned") + "." +
  1259. (isLocal ? "local" : "remote");
  1260. let participantCount = room.getParticipantCount();
  1261. JitsiMeetJS.analytics.sendEvent(
  1262. eventName,
  1263. { value: participantCount });
  1264. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1265. // the participant is on the large video ?
  1266. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1267. && !isLocal) {
  1268. // When the library starts supporting multiple pins we
  1269. // would pass the isPinned parameter together with the
  1270. // identifier, but currently we send null to indicate that
  1271. // we unpin the last pinned.
  1272. try {
  1273. room.pinParticipant(isPinned ? smallVideoId : null);
  1274. } catch (e) {
  1275. reportError(e);
  1276. }
  1277. }
  1278. });
  1279. }
  1280. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1281. APP.UI.showLocalConnectionInterrupted(true);
  1282. });
  1283. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1284. APP.UI.showLocalConnectionInterrupted(false);
  1285. });
  1286. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1287. const formattedDisplayName
  1288. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1289. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1290. APP.UI.changeDisplayName(id, formattedDisplayName);
  1291. });
  1292. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1293. (participant, name, oldValue, newValue) => {
  1294. if (name === "raisedHand") {
  1295. APP.UI.setRaisedHandStatus(participant, newValue);
  1296. }
  1297. });
  1298. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1299. logger.log("Received recorder status change: ", status, error);
  1300. APP.UI.updateRecordingState(status);
  1301. });
  1302. room.on(ConferenceEvents.KICKED, () => {
  1303. APP.UI.hideStats();
  1304. APP.UI.notifyKicked();
  1305. // FIXME close
  1306. });
  1307. room.on(ConferenceEvents.SUSPEND_DETECTED, () => {
  1308. APP.store.dispatch(suspendDetected());
  1309. // After wake up, we will be in a state where conference is left
  1310. // there will be dialog shown to user.
  1311. // We do not want video/audio as we show an overlay and after it
  1312. // user need to rejoin or close, while waking up we can detect
  1313. // camera wakeup as a problem with device.
  1314. // We also do not care about device change, which happens
  1315. // on resume after suspending PC.
  1316. if (this.deviceChangeListener)
  1317. JitsiMeetJS.mediaDevices.removeEventListener(
  1318. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1319. this.deviceChangeListener);
  1320. // stop local video
  1321. if (localVideo) {
  1322. localVideo.dispose();
  1323. }
  1324. // stop local audio
  1325. if (localAudio) {
  1326. localAudio.dispose();
  1327. }
  1328. });
  1329. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1330. APP.UI.updateDTMFSupport(isDTMFSupported);
  1331. });
  1332. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1333. // Wait a little bit more just to be sure that we won't miss the
  1334. // extension installation
  1335. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1336. });
  1337. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1338. window.open(
  1339. url, "extension_store_window",
  1340. "resizable,scrollbars=yes,status=1");
  1341. });
  1342. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1343. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1344. room.on(ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  1345. (stats) => {
  1346. APP.UI.updateLocalStats(stats.connectionQuality, stats);
  1347. });
  1348. room.on(ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  1349. (id, stats) => {
  1350. APP.UI.updateRemoteStats(id, stats.connectionQuality, stats);
  1351. });
  1352. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1353. APP.UI.initEtherpad(value);
  1354. });
  1355. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1356. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1357. APP.store.dispatch(changeParticipantEmail(from, data.value));
  1358. APP.UI.setUserEmail(from, data.value);
  1359. });
  1360. room.addCommandListener(
  1361. this.commands.defaults.AVATAR_URL,
  1362. (data, from) => {
  1363. APP.store.dispatch(
  1364. changeParticipantAvatarURL(from, data.value));
  1365. APP.UI.setUserAvatarUrl(from, data.value);
  1366. });
  1367. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1368. (data, from) => {
  1369. APP.store.dispatch(
  1370. changeParticipantAvatarID(from, data.value));
  1371. APP.UI.setUserAvatarID(from, data.value);
  1372. });
  1373. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1374. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1375. (startAudioMuted, startVideoMuted) => {
  1376. room.setStartMutedPolicy({
  1377. audio: startAudioMuted,
  1378. video: startVideoMuted
  1379. });
  1380. }
  1381. );
  1382. room.on(
  1383. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1384. ({ audio, video }) => {
  1385. APP.UI.onStartMutedChanged(audio, video);
  1386. }
  1387. );
  1388. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1389. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1390. && APP.UI.notifyInitiallyMuted();
  1391. });
  1392. room.on(
  1393. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1394. APP.UI.updateDevicesAvailability(id, devices);
  1395. }
  1396. );
  1397. // call hangup
  1398. APP.UI.addListener(UIEvents.HANGUP, () => {
  1399. this.hangup(true);
  1400. });
  1401. // logout
  1402. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1403. AuthHandler.logout(room).then(url => {
  1404. if (url) {
  1405. UIUtil.redirect(url);
  1406. } else {
  1407. this.hangup(true);
  1408. }
  1409. });
  1410. });
  1411. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1412. room.dial(sipNumber);
  1413. });
  1414. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1415. (id, oldResolution, newResolution, delay) => {
  1416. var logObject = {
  1417. id: "resolution_change",
  1418. participant: id,
  1419. oldValue: oldResolution,
  1420. newValue: newResolution,
  1421. delay: delay
  1422. };
  1423. room.sendApplicationLog(JSON.stringify(logObject));
  1424. // We only care about the delay between simulcast streams.
  1425. // Longer delays will be caused by something else and will just
  1426. // poison the data.
  1427. if (delay < 2000) {
  1428. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1429. {value: delay});
  1430. }
  1431. });
  1432. // Starts or stops the recording for the conference.
  1433. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1434. room.toggleRecording(options);
  1435. });
  1436. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1437. room.setSubject(topic);
  1438. });
  1439. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1440. APP.UI.setSubject(subject);
  1441. });
  1442. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1443. room.kickParticipant(id);
  1444. });
  1445. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1446. room.muteParticipant(id);
  1447. });
  1448. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1449. AuthHandler.authenticate(room);
  1450. });
  1451. APP.UI.addListener(
  1452. UIEvents.VIDEO_DEVICE_CHANGED,
  1453. (cameraDeviceId) => {
  1454. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1455. createLocalTracks({
  1456. devices: ['video'],
  1457. cameraDeviceId: cameraDeviceId,
  1458. micDeviceId: null
  1459. })
  1460. .then(([stream]) => {
  1461. this.useVideoStream(stream);
  1462. logger.log('switched local video device');
  1463. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1464. })
  1465. .catch((err) => {
  1466. APP.UI.showDeviceErrorDialog(null, err);
  1467. APP.UI.setSelectedCameraFromSettings();
  1468. });
  1469. }
  1470. );
  1471. APP.UI.addListener(
  1472. UIEvents.AUDIO_DEVICE_CHANGED,
  1473. (micDeviceId) => {
  1474. JitsiMeetJS.analytics.sendEvent(
  1475. 'settings.changeDevice.audioIn');
  1476. createLocalTracks({
  1477. devices: ['audio'],
  1478. cameraDeviceId: null,
  1479. micDeviceId: micDeviceId
  1480. })
  1481. .then(([stream]) => {
  1482. this.useAudioStream(stream);
  1483. logger.log('switched local audio device');
  1484. APP.settings.setMicDeviceId(micDeviceId, true);
  1485. })
  1486. .catch((err) => {
  1487. APP.UI.showDeviceErrorDialog(err, null);
  1488. APP.UI.setSelectedMicFromSettings();
  1489. });
  1490. }
  1491. );
  1492. APP.UI.addListener(
  1493. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1494. (audioOutputDeviceId) => {
  1495. JitsiMeetJS.analytics.sendEvent(
  1496. 'settings.changeDevice.audioOut');
  1497. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1498. .then(() => logger.log('changed audio output device'))
  1499. .catch((err) => {
  1500. logger.warn('Failed to change audio output device. ' +
  1501. 'Default or previously set audio output device ' +
  1502. 'will be used instead.', err);
  1503. APP.UI.setSelectedAudioOutputFromSettings();
  1504. });
  1505. }
  1506. );
  1507. APP.UI.addListener(
  1508. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1509. );
  1510. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1511. (url, state, time, isMuted, volume) => {
  1512. // send start and stop commands once, and remove any updates
  1513. // that had left
  1514. if (state === 'stop' || state === 'start' || state === 'playing') {
  1515. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1516. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1517. value: url,
  1518. attributes: {
  1519. state: state,
  1520. time: time,
  1521. muted: isMuted,
  1522. volume: volume
  1523. }
  1524. });
  1525. }
  1526. else {
  1527. // in case of paused, in order to allow late users to join
  1528. // paused
  1529. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1530. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1531. value: url,
  1532. attributes: {
  1533. state: state,
  1534. time: time,
  1535. muted: isMuted,
  1536. volume: volume
  1537. }
  1538. });
  1539. }
  1540. });
  1541. room.addCommandListener(
  1542. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1543. if (attributes.state === 'stop') {
  1544. APP.UI.onSharedVideoStop(id, attributes);
  1545. }
  1546. else if (attributes.state === 'start') {
  1547. APP.UI.onSharedVideoStart(id, value, attributes);
  1548. }
  1549. else if (attributes.state === 'playing'
  1550. || attributes.state === 'pause') {
  1551. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1552. }
  1553. });
  1554. },
  1555. /**
  1556. * Adds any room listener.
  1557. * @param {string} eventName one of the ConferenceEvents
  1558. * @param {Function} listener the function to be called when the event
  1559. * occurs
  1560. */
  1561. addConferenceListener(eventName, listener) {
  1562. room.on(eventName, listener);
  1563. },
  1564. /**
  1565. * Removes any room listener.
  1566. * @param {string} eventName one of the ConferenceEvents
  1567. * @param {Function} listener the listener to be removed.
  1568. */
  1569. removeConferenceListener(eventName, listener) {
  1570. room.off(eventName, listener);
  1571. },
  1572. /**
  1573. * Inits list of current devices and event listener for device change.
  1574. * @private
  1575. */
  1576. _initDeviceList() {
  1577. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1578. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1579. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1580. // Ugly way to synchronize real device IDs with local
  1581. // storage and settings menu. This is a workaround until
  1582. // getConstraints() method will be implemented in browsers.
  1583. if (localAudio) {
  1584. APP.settings.setMicDeviceId(
  1585. localAudio.getDeviceId(), false);
  1586. }
  1587. if (localVideo) {
  1588. APP.settings.setCameraDeviceId(
  1589. localVideo.getDeviceId(), false);
  1590. }
  1591. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1592. APP.UI.onAvailableDevicesChanged(devices);
  1593. });
  1594. this.deviceChangeListener = (devices) =>
  1595. window.setTimeout(
  1596. () => this._onDeviceListChanged(devices), 0);
  1597. JitsiMeetJS.mediaDevices.addEventListener(
  1598. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1599. this.deviceChangeListener);
  1600. }
  1601. },
  1602. /**
  1603. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1604. * handle change of available media devices.
  1605. * @private
  1606. * @param {MediaDeviceInfo[]} devices
  1607. * @returns {Promise}
  1608. */
  1609. _onDeviceListChanged(devices) {
  1610. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1611. // Event handler can be fired before direct
  1612. // enumerateDevices() call, so handle this situation here.
  1613. if (!currentDevices.audioinput &&
  1614. !currentDevices.videoinput &&
  1615. !currentDevices.audiooutput) {
  1616. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1617. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1618. }
  1619. let newDevices =
  1620. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1621. devices, this.isSharingScreen, localVideo, localAudio);
  1622. let promises = [];
  1623. let audioWasMuted = this.audioMuted;
  1624. let videoWasMuted = this.videoMuted;
  1625. let availableAudioInputDevices =
  1626. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1627. let availableVideoInputDevices =
  1628. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1629. if (typeof newDevices.audiooutput !== 'undefined') {
  1630. // Just ignore any errors in catch block.
  1631. promises.push(APP.settings
  1632. .setAudioOutputDeviceId(newDevices.audiooutput)
  1633. .catch());
  1634. }
  1635. promises.push(
  1636. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1637. createLocalTracks,
  1638. newDevices.videoinput,
  1639. newDevices.audioinput)
  1640. .then(tracks =>
  1641. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1642. .then(() => {
  1643. // If audio was muted before, or we unplugged current device
  1644. // and selected new one, then mute new audio track.
  1645. if (audioWasMuted ||
  1646. currentDevices.audioinput.length >
  1647. availableAudioInputDevices.length) {
  1648. muteLocalAudio(true);
  1649. }
  1650. // If video was muted before, or we unplugged current device
  1651. // and selected new one, then mute new video track.
  1652. if (videoWasMuted ||
  1653. currentDevices.videoinput.length >
  1654. availableVideoInputDevices.length) {
  1655. muteLocalVideo(true);
  1656. }
  1657. }));
  1658. return Promise.all(promises)
  1659. .then(() => {
  1660. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1661. APP.UI.onAvailableDevicesChanged(devices);
  1662. });
  1663. },
  1664. /**
  1665. * Toggles the local "raised hand" status.
  1666. */
  1667. maybeToggleRaisedHand() {
  1668. this.setRaisedHand(!this.isHandRaised);
  1669. },
  1670. /**
  1671. * Sets the local "raised hand" status to a particular value.
  1672. */
  1673. setRaisedHand(raisedHand) {
  1674. if (raisedHand !== this.isHandRaised)
  1675. {
  1676. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1677. this.isHandRaised = raisedHand;
  1678. // Advertise the updated status
  1679. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1680. // Update the view
  1681. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1682. }
  1683. },
  1684. /**
  1685. * Log event to callstats and analytics.
  1686. * @param {string} name the event name
  1687. * @param {int} value the value (it's int because google analytics supports
  1688. * only int).
  1689. * @param {string} label short text which provides more info about the event
  1690. * which allows to distinguish between few event cases of the same name
  1691. * NOTE: Should be used after conference.init
  1692. */
  1693. logEvent(name, value, label) {
  1694. if(JitsiMeetJS.analytics) {
  1695. JitsiMeetJS.analytics.sendEvent(name, {value, label});
  1696. }
  1697. if(room) {
  1698. room.sendApplicationLog(JSON.stringify({name, value, label}));
  1699. }
  1700. },
  1701. /**
  1702. * Methods logs an application event given in the JSON format.
  1703. * @param {string} logJSON an event to be logged in JSON format
  1704. */
  1705. logJSON(logJSON) {
  1706. if (room) {
  1707. room.sendApplicationLog(logJSON);
  1708. }
  1709. },
  1710. /**
  1711. * Disconnect from the conference and optionally request user feedback.
  1712. * @param {boolean} [requestFeedback=false] if user feedback should be
  1713. * requested
  1714. */
  1715. hangup (requestFeedback = false) {
  1716. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  1717. APP.UI.hideRingOverLay();
  1718. let requestFeedbackPromise = requestFeedback
  1719. ? APP.UI.requestFeedbackOnHangup()
  1720. // false - because the thank you dialog shouldn't be displayed
  1721. .catch(() => Promise.resolve(false))
  1722. : Promise.resolve(true);// true - because the thank you dialog
  1723. //should be displayed
  1724. // All promises are returning Promise.resolve to make Promise.all to
  1725. // be resolved when both Promises are finished. Otherwise Promise.all
  1726. // will reject on first rejected Promise and we can redirect the page
  1727. // before all operations are done.
  1728. Promise.all([
  1729. requestFeedbackPromise,
  1730. room.leave().then(disconnect, disconnect)
  1731. ]).then(values => {
  1732. APP.API.notifyReadyToClose();
  1733. maybeRedirectToWelcomePage(values[0]);
  1734. });
  1735. },
  1736. /**
  1737. * Changes the email for the local user
  1738. * @param email {string} the new email
  1739. */
  1740. changeLocalEmail(email = '') {
  1741. email = email.trim();
  1742. if (email === APP.settings.getEmail()) {
  1743. return;
  1744. }
  1745. APP.store.dispatch(changeParticipantEmail(room.myUserId(), email));
  1746. APP.settings.setEmail(email);
  1747. APP.UI.setUserEmail(room.myUserId(), email);
  1748. sendData(commands.EMAIL, email);
  1749. },
  1750. /**
  1751. * Changes the avatar url for the local user
  1752. * @param url {string} the new url
  1753. */
  1754. changeLocalAvatarUrl(url = '') {
  1755. url = url.trim();
  1756. if (url === APP.settings.getAvatarUrl()) {
  1757. return;
  1758. }
  1759. APP.store.dispatch(changeParticipantAvatarURL(room.myUserId(), url));
  1760. APP.settings.setAvatarUrl(url);
  1761. APP.UI.setUserAvatarUrl(room.myUserId(), url);
  1762. sendData(commands.AVATAR_URL, url);
  1763. },
  1764. /**
  1765. * Sends a message via the data channel.
  1766. * @param {string} to the id of the endpoint that should receive the
  1767. * message. If "" - the message will be sent to all participants.
  1768. * @param {object} payload the payload of the message.
  1769. * @throws NetworkError or InvalidStateError or Error if the operation
  1770. * fails.
  1771. */
  1772. sendEndpointMessage (to, payload) {
  1773. room.sendEndpointMessage(to, payload);
  1774. },
  1775. /**
  1776. * Adds new listener.
  1777. * @param {String} eventName the name of the event
  1778. * @param {Function} listener the listener.
  1779. */
  1780. addListener (eventName, listener) {
  1781. eventEmitter.addListener(eventName, listener);
  1782. },
  1783. /**
  1784. * Removes listener.
  1785. * @param {String} eventName the name of the event that triggers the
  1786. * listener
  1787. * @param {Function} listener the listener.
  1788. */
  1789. removeListener (eventName, listener) {
  1790. eventEmitter.removeListener(eventName, listener);
  1791. },
  1792. /**
  1793. * Checks if the participant given by participantId is currently in the
  1794. * last N set if there's one supported.
  1795. *
  1796. * @param participantId the identifier of the participant
  1797. * @returns {boolean} {true} if the participant given by the participantId
  1798. * is currently in the last N set or if there's no last N set at this point
  1799. * and {false} otherwise
  1800. */
  1801. isInLastN (participantId) {
  1802. return room.isInLastN(participantId);
  1803. }
  1804. };