Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 61KB

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