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 83KB

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