Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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