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

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