Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

conference.js 69KB

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