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

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