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 70KB

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