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

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