您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 78KB

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