Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

conference.js 60KB

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