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

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