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

conference.js 70KB

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