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

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