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

conference.js 74KB

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