You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 87KB

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