Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

conference.js 71KB

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