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

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