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

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