Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

conference.js 61KB

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