Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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