Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

conference.js 51KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522
  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. 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. let room, connection, localAudio, localVideo, roomLocker;
  19. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/LargeVideo";
  20. /**
  21. * Known custom conference commands.
  22. */
  23. const commands = {
  24. CONNECTION_QUALITY: "stats",
  25. EMAIL: "email",
  26. AVATAR_URL: "avatar-url",
  27. ETHERPAD: "etherpad",
  28. SHARED_VIDEO: "shared-video",
  29. CUSTOM_ROLE: "custom-role"
  30. };
  31. /**
  32. * Open Connection. When authentication failed it shows auth dialog.
  33. * @param roomName the room name to use
  34. * @returns Promise<JitsiConnection>
  35. */
  36. function connect(roomName) {
  37. return openConnection({retry: true, roomName: roomName})
  38. .catch(function (err) {
  39. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  40. APP.UI.notifyTokenAuthFailed();
  41. } else {
  42. APP.UI.notifyConnectionFailed(err);
  43. }
  44. throw err;
  45. });
  46. }
  47. /**
  48. * Creates local media tracks and connects to room. Will show error
  49. * dialogs in case if accessing local microphone and/or camera failed. Will
  50. * show guidance overlay for users on how to give access to camera and/or
  51. * microphone,
  52. * @param {string} roomName
  53. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  54. */
  55. function createInitialLocalTracksAndConnect(roomName) {
  56. let audioAndVideoError,
  57. audioOnlyError;
  58. JitsiMeetJS.mediaDevices.addEventListener(
  59. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  60. browser => APP.UI.showUserMediaPermissionsGuidanceOverlay(browser));
  61. // First try to retrieve both audio and video.
  62. let tryCreateLocalTracks = createLocalTracks(
  63. { devices: ['audio', 'video'] }, true)
  64. .catch(err => {
  65. // If failed then try to retrieve only audio.
  66. audioAndVideoError = err;
  67. return createLocalTracks({ devices: ['audio'] }, true);
  68. })
  69. .catch(err => {
  70. // If audio failed too then just return empty array for tracks.
  71. audioOnlyError = err;
  72. return [];
  73. });
  74. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  75. .then(([tracks, con]) => {
  76. APP.UI.hideUserMediaPermissionsGuidanceOverlay();
  77. if (audioAndVideoError) {
  78. if (audioOnlyError) {
  79. // If both requests for 'audio' + 'video' and 'audio' only
  80. // failed, we assume that there is some problems with user's
  81. // microphone and show corresponding dialog.
  82. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  83. } else {
  84. // If request for 'audio' + 'video' failed, but request for
  85. // 'audio' only was OK, we assume that we had problems with
  86. // camera and show corresponding dialog.
  87. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  88. }
  89. }
  90. return [tracks, con];
  91. });
  92. }
  93. /**
  94. * Share data to other users.
  95. * @param command the command
  96. * @param {string} value new value
  97. */
  98. function sendData (command, value) {
  99. room.removeCommand(command);
  100. room.sendCommand(command, {value: value});
  101. }
  102. /**
  103. * Get user nickname by user id.
  104. * @param {string} id user id
  105. * @returns {string?} user nickname or undefined if user is unknown.
  106. */
  107. function getDisplayName (id) {
  108. if (APP.conference.isLocalId(id)) {
  109. return APP.settings.getDisplayName();
  110. }
  111. let participant = room.getParticipantById(id);
  112. if (participant && participant.getDisplayName()) {
  113. return participant.getDisplayName();
  114. }
  115. }
  116. /**
  117. * Mute or unmute local audio stream if it exists.
  118. * @param {boolean} muted if audio stream should be muted or unmuted.
  119. * @param {boolean} indicates if this local audio mute was a result of user
  120. * interaction
  121. *
  122. */
  123. function muteLocalAudio (muted, userInteraction) {
  124. if (!localAudio) {
  125. return;
  126. }
  127. if (muted) {
  128. localAudio.mute().then(function(value) {},
  129. function(value) {
  130. console.warn('Audio Mute was rejected:', value);
  131. }
  132. );
  133. } else {
  134. localAudio.unmute().then(function(value) {},
  135. function(value) {
  136. console.warn('Audio unmute was rejected:', value);
  137. }
  138. );
  139. }
  140. }
  141. /**
  142. * Mute or unmute local video stream if it exists.
  143. * @param {boolean} muted if video stream should be muted or unmuted.
  144. */
  145. function muteLocalVideo (muted) {
  146. if (!localVideo) {
  147. return;
  148. }
  149. if (muted) {
  150. localVideo.mute().then(function(value) {},
  151. function(value) {
  152. console.warn('Video mute was rejected:', value);
  153. }
  154. );
  155. } else {
  156. localVideo.unmute().then(function(value) {},
  157. function(value) {
  158. console.warn('Video unmute was rejected:', value);
  159. }
  160. );
  161. }
  162. }
  163. /**
  164. * Check if the welcome page is enabled and redirects to it.
  165. */
  166. function maybeRedirectToWelcomePage() {
  167. if (!config.enableWelcomePage) {
  168. return;
  169. }
  170. // redirect to welcome page
  171. setTimeout(() => {
  172. APP.settings.setWelcomePageEnabled(true);
  173. window.location.pathname = "/";
  174. }, 3000);
  175. }
  176. /**
  177. * Executes connection.disconnect and shows the feedback dialog
  178. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  179. * @returns Promise.
  180. */
  181. function disconnectAndShowFeedback(requestFeedback) {
  182. APP.UI.hideRingOverLay();
  183. connection.disconnect();
  184. APP.API.notifyConferenceLeft(APP.conference.roomName);
  185. if (requestFeedback) {
  186. return APP.UI.requestFeedback();
  187. } else {
  188. return Promise.resolve();
  189. }
  190. }
  191. /**
  192. * Disconnect from the conference and optionally request user feedback.
  193. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  194. */
  195. function hangup (requestFeedback = false) {
  196. const errCallback = (f, err) => {
  197. console.error('Error occurred during hanging up: ', err);
  198. return f();
  199. };
  200. const disconnect = disconnectAndShowFeedback.bind(null, requestFeedback);
  201. APP.conference._room.leave()
  202. .then(disconnect)
  203. .catch(errCallback.bind(null, disconnect))
  204. .then(maybeRedirectToWelcomePage)
  205. .catch(errCallback.bind(null, maybeRedirectToWelcomePage));
  206. }
  207. /**
  208. * Create local tracks of specified types.
  209. * @param {Object} options
  210. * @param {string[]} options.devices - required track types
  211. * ('audio', 'video' etc.)
  212. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  213. * undefined - one from settings will be used
  214. * @param {string|null} (options.micDeviceId) - microphone device id, if
  215. * undefined - one from settings will be used
  216. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  217. * for gUM permission prompt
  218. * @returns {Promise<JitsiLocalTrack[]>}
  219. */
  220. function createLocalTracks (options, checkForPermissionPrompt) {
  221. options || (options = {});
  222. return JitsiMeetJS
  223. .createLocalTracks({
  224. // copy array to avoid mutations inside library
  225. devices: options.devices.slice(0),
  226. resolution: config.resolution,
  227. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  228. options.cameraDeviceId === null
  229. ? APP.settings.getCameraDeviceId()
  230. : options.cameraDeviceId,
  231. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  232. options.micDeviceId === null
  233. ? APP.settings.getMicDeviceId()
  234. : options.micDeviceId,
  235. // adds any ff fake device settings if any
  236. firefox_fake_device: config.firefox_fake_device
  237. }, checkForPermissionPrompt)
  238. .catch(function (err) {
  239. console.error(
  240. 'failed to create local tracks', options.devices, err);
  241. return Promise.reject(err);
  242. });
  243. }
  244. /**
  245. * Changes the email for the local user
  246. * @param email {string} the new email
  247. */
  248. function changeLocalEmail(email = '') {
  249. email = email.trim();
  250. if (email === APP.settings.getEmail()) {
  251. return;
  252. }
  253. APP.settings.setEmail(email);
  254. APP.UI.setUserEmail(room.myUserId(), email);
  255. sendData(commands.EMAIL, email);
  256. }
  257. /**
  258. * Changes the local avatar url for the local user
  259. * @param avatarUrl {string} the new avatar url
  260. */
  261. function changeLocalAvatarUrl(avatarUrl = '') {
  262. avatarUrl = avatarUrl.trim();
  263. if (avatarUrl === APP.settings.getAvatarUrl()) {
  264. return;
  265. }
  266. APP.settings.setAvatarUrl(avatarUrl);
  267. APP.UI.setUserAvatarUrl(room.myUserId(), avatarUrl);
  268. sendData(commands.AVATAR_URL, avatarUrl);
  269. }
  270. /**
  271. * Changes the display name for the local user
  272. * @param nickname {string} the new display name
  273. */
  274. function changeLocalDisplayName(nickname = '') {
  275. nickname = nickname.trim();
  276. if (nickname === APP.settings.getDisplayName()) {
  277. return;
  278. }
  279. APP.settings.setDisplayName(nickname);
  280. room.setDisplayName(nickname);
  281. APP.UI.changeDisplayName(APP.conference.getMyUserId(), nickname);
  282. }
  283. class ConferenceConnector {
  284. constructor(resolve, reject) {
  285. this._resolve = resolve;
  286. this._reject = reject;
  287. this.reconnectTimeout = null;
  288. room.on(ConferenceEvents.CONFERENCE_JOINED,
  289. this._handleConferenceJoined.bind(this));
  290. room.on(ConferenceEvents.CONFERENCE_FAILED,
  291. this._onConferenceFailed.bind(this));
  292. room.on(ConferenceEvents.CONFERENCE_ERROR,
  293. this._onConferenceError.bind(this));
  294. }
  295. _handleConferenceFailed(err, msg) {
  296. this._unsubscribe();
  297. this._reject(err);
  298. }
  299. _onConferenceFailed(err, ...params) {
  300. console.error('CONFERENCE FAILED:', err, ...params);
  301. APP.UI.hideRingOverLay();
  302. switch (err) {
  303. // room is locked by the password
  304. case ConferenceErrors.PASSWORD_REQUIRED:
  305. APP.UI.markRoomLocked(true);
  306. roomLocker.requirePassword().then(function () {
  307. room.join(roomLocker.password);
  308. });
  309. break;
  310. case ConferenceErrors.CONNECTION_ERROR:
  311. {
  312. let [msg] = params;
  313. APP.UI.notifyConnectionFailed(msg);
  314. }
  315. break;
  316. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  317. APP.UI.notifyBridgeDown();
  318. break;
  319. // not enough rights to create conference
  320. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  321. // schedule reconnect to check if someone else created the room
  322. this.reconnectTimeout = setTimeout(function () {
  323. room.join();
  324. }, 5000);
  325. // notify user that auth is required
  326. AuthHandler.requireAuth(room, roomLocker.password);
  327. break;
  328. case ConferenceErrors.RESERVATION_ERROR:
  329. {
  330. let [code, msg] = params;
  331. APP.UI.notifyReservationError(code, msg);
  332. }
  333. break;
  334. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  335. APP.UI.notifyGracefulShutdown();
  336. break;
  337. case ConferenceErrors.JINGLE_FATAL_ERROR:
  338. APP.UI.notifyInternalError();
  339. break;
  340. case ConferenceErrors.CONFERENCE_DESTROYED:
  341. {
  342. let [reason] = params;
  343. APP.UI.hideStats();
  344. APP.UI.notifyConferenceDestroyed(reason);
  345. }
  346. break;
  347. case ConferenceErrors.FOCUS_DISCONNECTED:
  348. {
  349. let [focus, retrySec] = params;
  350. APP.UI.notifyFocusDisconnected(focus, retrySec);
  351. }
  352. break;
  353. case ConferenceErrors.FOCUS_LEFT:
  354. room.leave().then(() => connection.disconnect());
  355. APP.UI.notifyFocusLeft();
  356. break;
  357. case ConferenceErrors.CONFERENCE_MAX_USERS:
  358. connection.disconnect();
  359. APP.UI.notifyMaxUsersLimitReached();
  360. break;
  361. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  362. window.location.reload();
  363. break;
  364. default:
  365. this._handleConferenceFailed(err, ...params);
  366. }
  367. }
  368. _onConferenceError(err, ...params) {
  369. console.error('CONFERENCE Error:', err, params);
  370. switch (err) {
  371. case ConferenceErrors.CHAT_ERROR:
  372. {
  373. let [code, msg] = params;
  374. APP.UI.showChatError(code, msg);
  375. }
  376. break;
  377. default:
  378. console.error("Unknown error.");
  379. }
  380. }
  381. _unsubscribe() {
  382. room.off(
  383. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  384. room.off(
  385. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  386. if (this.reconnectTimeout !== null) {
  387. clearTimeout(this.reconnectTimeout);
  388. }
  389. AuthHandler.closeAuth();
  390. }
  391. _handleConferenceJoined() {
  392. this._unsubscribe();
  393. this._resolve();
  394. }
  395. connect() {
  396. room.join();
  397. }
  398. }
  399. export default {
  400. isModerator: false,
  401. audioMuted: false,
  402. videoMuted: false,
  403. isSharingScreen: false,
  404. isDesktopSharingEnabled: false,
  405. /*
  406. * Whether the local "raisedHand" flag is on.
  407. */
  408. isHandRaised: false,
  409. /*
  410. * Whether the local participant is the dominant speaker in the conference.
  411. */
  412. isDominantSpeaker: false,
  413. /**
  414. * Open new connection and join to the conference.
  415. * @param {object} options
  416. * @param {string} roomName name of the conference
  417. * @returns {Promise}
  418. */
  419. init(options) {
  420. this.roomName = options.roomName;
  421. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  422. // attaches global error handler, if there is already one, respect it
  423. if(JitsiMeetJS.getGlobalOnErrorHandler){
  424. var oldOnErrorHandler = window.onerror;
  425. window.onerror = function (message, source, lineno, colno, error) {
  426. JitsiMeetJS.getGlobalOnErrorHandler(
  427. message, source, lineno, colno, error);
  428. if(oldOnErrorHandler)
  429. oldOnErrorHandler(message, source, lineno, colno, error);
  430. };
  431. var oldOnUnhandledRejection = window.onunhandledrejection;
  432. window.onunhandledrejection = function(event) {
  433. JitsiMeetJS.getGlobalOnErrorHandler(
  434. null, null, null, null, event.reason);
  435. if(oldOnUnhandledRejection)
  436. oldOnUnhandledRejection(event);
  437. };
  438. }
  439. return JitsiMeetJS.init(config)
  440. .then(() => createInitialLocalTracksAndConnect(options.roomName))
  441. .then(([tracks, con]) => {
  442. console.log('initialized with %s local tracks', tracks.length);
  443. APP.connection = connection = con;
  444. this._createRoom(tracks);
  445. this.isDesktopSharingEnabled =
  446. JitsiMeetJS.isDesktopSharingEnabled();
  447. // if user didn't give access to mic or camera or doesn't have
  448. // them at all, we disable corresponding toolbar buttons
  449. if (!tracks.find((t) => t.isAudioTrack())) {
  450. APP.UI.disableMicrophoneButton();
  451. }
  452. if (!tracks.find((t) => t.isVideoTrack())) {
  453. APP.UI.disableCameraButton();
  454. }
  455. this._initDeviceList();
  456. if (config.iAmRecorder)
  457. this.recorder = new Recorder();
  458. // XXX The API will take care of disconnecting from the XMPP
  459. // server (and, thus, leaving the room) on unload.
  460. return new Promise((resolve, reject) => {
  461. (new ConferenceConnector(resolve, reject)).connect();
  462. });
  463. });
  464. },
  465. /**
  466. * Check if id is id of the local user.
  467. * @param {string} id id to check
  468. * @returns {boolean}
  469. */
  470. isLocalId (id) {
  471. return this.getMyUserId() === id;
  472. },
  473. /**
  474. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  475. * @param mute true for mute and false for unmute.
  476. */
  477. muteAudio (mute) {
  478. muteLocalAudio(mute);
  479. },
  480. /**
  481. * Returns whether local audio is muted or not.
  482. * @returns {boolean}
  483. */
  484. isLocalAudioMuted() {
  485. return this.audioMuted;
  486. },
  487. /**
  488. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  489. */
  490. toggleAudioMuted () {
  491. this.muteAudio(!this.audioMuted);
  492. },
  493. /**
  494. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  495. * @param mute true for mute and false for unmute.
  496. */
  497. muteVideo (mute) {
  498. muteLocalVideo(mute);
  499. },
  500. /**
  501. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  502. */
  503. toggleVideoMuted () {
  504. this.muteVideo(!this.videoMuted);
  505. },
  506. /**
  507. * Retrieve list of conference participants (without local user).
  508. * @returns {JitsiParticipant[]}
  509. */
  510. listMembers () {
  511. return room.getParticipants();
  512. },
  513. /**
  514. * Retrieve list of ids of conference participants (without local user).
  515. * @returns {string[]}
  516. */
  517. listMembersIds () {
  518. return room.getParticipants().map(p => p.getId());
  519. },
  520. /**
  521. * Checks whether the participant identified by id is a moderator.
  522. * @id id to search for participant
  523. * @return {boolean} whether the participant is moderator
  524. */
  525. isParticipantModerator (id) {
  526. let user = room.getParticipantById(id);
  527. return user && user.isModerator();
  528. },
  529. /**
  530. * Check if SIP is supported.
  531. * @returns {boolean}
  532. */
  533. sipGatewayEnabled () {
  534. return room.isSIPCallingSupported();
  535. },
  536. get membersCount () {
  537. return room.getParticipants().length + 1;
  538. },
  539. /**
  540. * Returns true if the callstats integration is enabled, otherwise returns
  541. * false.
  542. *
  543. * @returns true if the callstats integration is enabled, otherwise returns
  544. * false.
  545. */
  546. isCallstatsEnabled () {
  547. return room.isCallstatsEnabled();
  548. },
  549. /**
  550. * Sends the given feedback through CallStats if enabled.
  551. *
  552. * @param overallFeedback an integer between 1 and 5 indicating the
  553. * user feedback
  554. * @param detailedFeedback detailed feedback from the user. Not yet used
  555. */
  556. sendFeedback (overallFeedback, detailedFeedback) {
  557. return room.sendFeedback (overallFeedback, detailedFeedback);
  558. },
  559. // used by torture currently
  560. isJoined () {
  561. return this._room
  562. && this._room.isJoined();
  563. },
  564. getConnectionState () {
  565. return this._room
  566. && this._room.getConnectionState();
  567. },
  568. getMyUserId () {
  569. return this._room
  570. && this._room.myUserId();
  571. },
  572. /**
  573. * Indicates if recording is supported in this conference.
  574. */
  575. isRecordingSupported() {
  576. return this._room && this._room.isRecordingSupported();
  577. },
  578. /**
  579. * Returns the recording state or undefined if the room is not defined.
  580. */
  581. getRecordingState() {
  582. return (this._room) ? this._room.getRecordingState() : undefined;
  583. },
  584. /**
  585. * Will be filled with values only when config.debug is enabled.
  586. * Its used by torture to check audio levels.
  587. */
  588. audioLevelsMap: {},
  589. /**
  590. * Returns the stored audio level (stored only if config.debug is enabled)
  591. * @param id the id for the user audio level to return (the id value is
  592. * returned for the participant using getMyUserId() method)
  593. */
  594. getPeerSSRCAudioLevel (id) {
  595. return this.audioLevelsMap[id];
  596. },
  597. /**
  598. * @return {number} the number of participants in the conference with at
  599. * least one track.
  600. */
  601. getNumberOfParticipantsWithTracks() {
  602. return this._room.getParticipants()
  603. .filter((p) => p.getTracks().length > 0)
  604. .length;
  605. },
  606. /**
  607. * Returns the stats.
  608. */
  609. getStats() {
  610. return ConnectionQuality.getStats();
  611. },
  612. // end used by torture
  613. getLogs () {
  614. return room.getLogs();
  615. },
  616. /**
  617. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  618. * desire to keep room private to this instance and (2) the need of other
  619. * modules to send and receive commands to and from participants.
  620. * Eventually, this instance remains in control with respect to the
  621. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  622. * JitsiConference) is to be used in the implementation of the Command(s)
  623. * API of this instance.
  624. */
  625. commands: {
  626. /**
  627. * Known custom conference commands.
  628. */
  629. defaults: commands,
  630. /**
  631. * Receives notifications from other participants about commands aka
  632. * custom events (sent by sendCommand or sendCommandOnce methods).
  633. * @param command {String} the name of the command
  634. * @param handler {Function} handler for the command
  635. */
  636. addCommandListener () {
  637. room.addCommandListener.apply(room, arguments);
  638. },
  639. /**
  640. * Removes command.
  641. * @param name {String} the name of the command.
  642. */
  643. removeCommand () {
  644. room.removeCommand.apply(room, arguments);
  645. },
  646. /**
  647. * Sends command.
  648. * @param name {String} the name of the command.
  649. * @param values {Object} with keys and values that will be sent.
  650. */
  651. sendCommand () {
  652. room.sendCommand.apply(room, arguments);
  653. },
  654. /**
  655. * Sends command one time.
  656. * @param name {String} the name of the command.
  657. * @param values {Object} with keys and values that will be sent.
  658. */
  659. sendCommandOnce () {
  660. room.sendCommandOnce.apply(room, arguments);
  661. }
  662. },
  663. _createRoom (localTracks) {
  664. room = connection.initJitsiConference(APP.conference.roomName,
  665. this._getConferenceOptions());
  666. this._setLocalAudioVideoStreams(localTracks);
  667. roomLocker = createRoomLocker(room);
  668. this._room = room; // FIXME do not use this
  669. let email = APP.settings.getEmail();
  670. email && sendData(this.commands.defaults.EMAIL, email);
  671. let avatarUrl = APP.settings.getAvatarUrl();
  672. avatarUrl && sendData(this.commands.defaults.AVATAR_URL,
  673. avatarUrl);
  674. let nick = APP.settings.getDisplayName();
  675. if (config.useNicks && !nick) {
  676. nick = APP.UI.askForNickname();
  677. APP.settings.setDisplayName(nick);
  678. }
  679. nick && room.setDisplayName(nick);
  680. this._setupListeners();
  681. },
  682. /**
  683. * Sets local video and audio streams.
  684. * @param {JitsiLocalTrack[]} tracks=[]
  685. * @returns {Promise[]}
  686. * @private
  687. */
  688. _setLocalAudioVideoStreams(tracks = []) {
  689. return tracks.map(track => {
  690. if (track.isAudioTrack()) {
  691. return this.useAudioStream(track);
  692. } else if (track.isVideoTrack()) {
  693. return this.useVideoStream(track);
  694. } else {
  695. console.error(
  696. "Ignored not an audio nor a video track: ", track);
  697. return Promise.resolve();
  698. }
  699. });
  700. },
  701. _getConferenceOptions() {
  702. let options = config;
  703. if(config.enableRecording && !config.recordingType) {
  704. options.recordingType = (config.hosts &&
  705. (typeof config.hosts.jirecon != "undefined"))?
  706. "jirecon" : "colibri";
  707. }
  708. return options;
  709. },
  710. /**
  711. * Start using provided video stream.
  712. * Stops previous video stream.
  713. * @param {JitsiLocalTrack} [stream] new stream to use or null
  714. * @returns {Promise}
  715. */
  716. useVideoStream (stream) {
  717. let promise = Promise.resolve();
  718. if (localVideo) {
  719. // this calls room.removeTrack internally
  720. // so we don't need to remove it manually
  721. promise = localVideo.dispose();
  722. }
  723. localVideo = stream;
  724. return promise.then(function () {
  725. if (stream) {
  726. return room.addTrack(stream);
  727. }
  728. }).then(() => {
  729. if (stream) {
  730. this.videoMuted = stream.isMuted();
  731. this.isSharingScreen = stream.videoType === 'desktop';
  732. APP.UI.addLocalStream(stream);
  733. stream.videoType === 'camera' && APP.UI.enableCameraButton();
  734. } else {
  735. this.videoMuted = false;
  736. this.isSharingScreen = false;
  737. }
  738. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  739. APP.UI.updateDesktopSharingButtons();
  740. });
  741. },
  742. /**
  743. * Start using provided audio stream.
  744. * Stops previous audio stream.
  745. * @param {JitsiLocalTrack} [stream] new stream to use or null
  746. * @returns {Promise}
  747. */
  748. useAudioStream (stream) {
  749. let promise = Promise.resolve();
  750. if (localAudio) {
  751. // this calls room.removeTrack internally
  752. // so we don't need to remove it manually
  753. promise = localAudio.dispose();
  754. }
  755. localAudio = stream;
  756. return promise.then(function () {
  757. if (stream) {
  758. return room.addTrack(stream);
  759. }
  760. }).then(() => {
  761. if (stream) {
  762. this.audioMuted = stream.isMuted();
  763. APP.UI.addLocalStream(stream);
  764. } else {
  765. this.audioMuted = false;
  766. }
  767. APP.UI.enableMicrophoneButton();
  768. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  769. });
  770. },
  771. videoSwitchInProgress: false,
  772. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  773. if (this.videoSwitchInProgress) {
  774. console.warn("Switch in progress.");
  775. return;
  776. }
  777. if (!this.isDesktopSharingEnabled) {
  778. console.warn("Cannot toggle screen sharing: not supported.");
  779. return;
  780. }
  781. this.videoSwitchInProgress = true;
  782. if (shareScreen) {
  783. createLocalTracks({ devices: ['desktop'] }).then(([stream]) => {
  784. stream.on(
  785. TrackEvents.LOCAL_TRACK_STOPPED,
  786. () => {
  787. // if stream was stopped during screensharing session
  788. // then we should switch to video
  789. // otherwise we stopped it because we already switched
  790. // to video, so nothing to do here
  791. if (this.isSharingScreen) {
  792. this.toggleScreenSharing(false);
  793. }
  794. }
  795. );
  796. return this.useVideoStream(stream);
  797. }).then(() => {
  798. this.videoSwitchInProgress = false;
  799. console.log('sharing local desktop');
  800. }).catch((err) => {
  801. this.videoSwitchInProgress = false;
  802. this.toggleScreenSharing(false);
  803. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  804. return;
  805. }
  806. console.error('failed to share local desktop', err);
  807. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  808. APP.UI.showExtensionRequiredDialog(
  809. config.desktopSharingFirefoxExtensionURL
  810. );
  811. return;
  812. }
  813. // Handling:
  814. // TrackErrors.PERMISSION_DENIED
  815. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  816. // TrackErrors.GENERAL
  817. // and any other
  818. let dialogTxt;
  819. let dialogTitle;
  820. if (err.name === TrackErrors.PERMISSION_DENIED) {
  821. dialogTxt = APP.translation.generateTranslationHTML(
  822. "dialog.screenSharingPermissionDeniedError");
  823. dialogTitle = APP.translation.generateTranslationHTML(
  824. "dialog.error");
  825. } else {
  826. dialogTxt = APP.translation.generateTranslationHTML(
  827. "dialog.failtoinstall");
  828. dialogTitle = APP.translation.generateTranslationHTML(
  829. "dialog.permissionDenied");
  830. }
  831. APP.UI.messageHandler.openDialog(dialogTitle, dialogTxt, false);
  832. });
  833. } else {
  834. createLocalTracks({ devices: ['video'] }).then(
  835. ([stream]) => this.useVideoStream(stream)
  836. ).then(() => {
  837. this.videoSwitchInProgress = false;
  838. console.log('sharing local video');
  839. }).catch((err) => {
  840. this.useVideoStream(null);
  841. this.videoSwitchInProgress = false;
  842. console.error('failed to share local video', err);
  843. });
  844. }
  845. },
  846. /**
  847. * Setup interaction between conference and UI.
  848. */
  849. _setupListeners () {
  850. // add local streams when joined to the conference
  851. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  852. APP.UI.mucJoined();
  853. APP.API.notifyConferenceJoined(APP.conference.roomName);
  854. });
  855. room.on(
  856. ConferenceEvents.AUTH_STATUS_CHANGED,
  857. function (authEnabled, authLogin) {
  858. APP.UI.updateAuthInfo(authEnabled, authLogin);
  859. }
  860. );
  861. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  862. if (user.isHidden())
  863. return;
  864. console.log('USER %s connnected', id, user);
  865. APP.API.notifyUserJoined(id);
  866. APP.UI.addUser(id, user.getDisplayName());
  867. // check the roles for the new user and reflect them
  868. APP.UI.updateUserRole(user);
  869. });
  870. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  871. console.log('USER %s LEFT', id, user);
  872. APP.API.notifyUserLeft(id);
  873. APP.UI.removeUser(id, user.getDisplayName());
  874. APP.UI.onSharedVideoStop(id);
  875. });
  876. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  877. if (this.isLocalId(id)) {
  878. console.info(`My role changed, new role: ${role}`);
  879. this.isModerator = room.isModerator();
  880. APP.UI.updateLocalRole(room.isModerator());
  881. } else {
  882. let user = room.getParticipantById(id);
  883. if (user) {
  884. APP.UI.updateUserRole(user);
  885. }
  886. }
  887. });
  888. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  889. if(!track || track.isLocal())
  890. return;
  891. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  892. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  893. });
  894. APP.UI.addRemoteStream(track);
  895. });
  896. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  897. if(!track || track.isLocal())
  898. return;
  899. APP.UI.removeRemoteStream(track);
  900. });
  901. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  902. if(!track)
  903. return;
  904. const handler = (track.getType() === "audio")?
  905. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  906. let id;
  907. const mute = track.isMuted();
  908. if(track.isLocal()){
  909. id = APP.conference.getMyUserId();
  910. if(track.getType() === "audio") {
  911. this.audioMuted = mute;
  912. } else {
  913. this.videoMuted = mute;
  914. }
  915. } else {
  916. id = track.getParticipantId();
  917. }
  918. handler(id , mute);
  919. });
  920. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  921. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  922. lvl = 0;
  923. }
  924. if(config.debug)
  925. {
  926. this.audioLevelsMap[id] = lvl;
  927. if(config.debugAudioLevels)
  928. console.log("AudioLevel:" + id + "/" + lvl);
  929. }
  930. APP.UI.setAudioLevel(id, lvl);
  931. });
  932. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  933. //FIXME
  934. if (config.muteLocalVideoIfNotInLastN) {
  935. // TODO mute or unmute if required
  936. // mark video on UI
  937. // APP.UI.markVideoMuted(true/false);
  938. }
  939. });
  940. room.on(
  941. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  942. APP.UI.handleLastNEndpoints(ids, enteringIds);
  943. });
  944. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  945. if (this.isLocalId(id)) {
  946. this.isDominantSpeaker = true;
  947. this.setRaisedHand(false);
  948. } else {
  949. this.isDominantSpeaker = false;
  950. var participant = room.getParticipantById(id);
  951. if (participant) {
  952. APP.UI.setRaisedHandStatus(participant, false);
  953. }
  954. }
  955. APP.UI.markDominantSpeaker(id);
  956. });
  957. if (!interfaceConfig.filmStripOnly) {
  958. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  959. APP.UI.markVideoInterrupted(true);
  960. });
  961. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  962. APP.UI.markVideoInterrupted(false);
  963. });
  964. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  965. let nick = getDisplayName(id);
  966. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  967. APP.UI.addMessage(id, nick, text, ts);
  968. });
  969. }
  970. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  971. APP.API.notifyDisplayNameChanged(id, displayName);
  972. APP.UI.changeDisplayName(id, displayName);
  973. });
  974. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  975. (participant, name, oldValue, newValue) => {
  976. if (name === "raisedHand") {
  977. APP.UI.setRaisedHandStatus(participant, newValue);
  978. }
  979. });
  980. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  981. console.log("Received recorder status change: ", status, error);
  982. APP.UI.updateRecordingState(status);
  983. });
  984. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  985. APP.UI.updateUserStatus(id, status);
  986. });
  987. room.on(ConferenceEvents.KICKED, () => {
  988. APP.UI.hideStats();
  989. APP.UI.notifyKicked();
  990. // FIXME close
  991. });
  992. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  993. APP.UI.updateDTMFSupport(isDTMFSupported);
  994. });
  995. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  996. if (room.isModerator()) {
  997. let promise = roomLocker.isLocked
  998. ? roomLocker.askToUnlock()
  999. : roomLocker.askToLock();
  1000. promise.then(() => {
  1001. APP.UI.markRoomLocked(roomLocker.isLocked);
  1002. });
  1003. } else {
  1004. roomLocker.notifyModeratorRequired();
  1005. }
  1006. });
  1007. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1008. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1009. if (!interfaceConfig.filmStripOnly) {
  1010. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1011. APP.API.notifySendingChatMessage(message);
  1012. room.sendTextMessage(message);
  1013. });
  1014. }
  1015. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1016. ConnectionQuality.updateLocalStats(stats);
  1017. });
  1018. ConnectionQuality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1019. (percent, stats) => {
  1020. APP.UI.updateLocalStats(percent, stats);
  1021. room.broadcastEndpointMessage({
  1022. type: this.commands.defaults.CONNECTION_QUALITY,
  1023. values: stats });
  1024. });
  1025. room.on(ConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1026. (participant, payload) => {
  1027. switch(payload.type) {
  1028. case this.commands.defaults.CONNECTION_QUALITY:
  1029. ConnectionQuality.updateRemoteStats(participant.getId(),
  1030. payload.values);
  1031. break;
  1032. default:
  1033. console.warn("Unknown datachannel message", payload);
  1034. }
  1035. });
  1036. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1037. (id, percent, stats) => {
  1038. APP.UI.updateRemoteStats(id, percent, stats);
  1039. });
  1040. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1041. APP.UI.initEtherpad(value);
  1042. });
  1043. APP.UI.addListener(UIEvents.EMAIL_CHANGED, changeLocalEmail);
  1044. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1045. APP.UI.setUserEmail(from, data.value);
  1046. });
  1047. APP.UI.addListener(UIEvents.AVATAR_URL_CHANGED, changeLocalAvatarUrl);
  1048. room.addCommandListener(this.commands.defaults.AVATAR_URL,
  1049. (data, from) => {
  1050. APP.UI.setUserAvatarUrl(from, data.value);
  1051. });
  1052. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1053. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1054. (startAudioMuted, startVideoMuted) => {
  1055. room.setStartMutedPolicy({
  1056. audio: startAudioMuted,
  1057. video: startVideoMuted
  1058. });
  1059. }
  1060. );
  1061. room.on(
  1062. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1063. ({ audio, video }) => {
  1064. APP.UI.onStartMutedChanged(audio, video);
  1065. }
  1066. );
  1067. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1068. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1069. && APP.UI.notifyInitiallyMuted();
  1070. });
  1071. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  1072. APP.UI.inviteParticipants(
  1073. roomUrl,
  1074. APP.conference.roomName,
  1075. roomLocker.password,
  1076. APP.settings.getDisplayName()
  1077. );
  1078. });
  1079. room.on(
  1080. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1081. APP.UI.updateDevicesAvailability(id, devices);
  1082. }
  1083. );
  1084. // call hangup
  1085. APP.UI.addListener(UIEvents.HANGUP, () => {
  1086. hangup(true);
  1087. });
  1088. // logout
  1089. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1090. AuthHandler.logout(room).then(function (url) {
  1091. if (url) {
  1092. window.location.href = url;
  1093. } else {
  1094. hangup(true);
  1095. }
  1096. });
  1097. });
  1098. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1099. room.dial(sipNumber);
  1100. });
  1101. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1102. (id, oldResolution, newResolution, delay) => {
  1103. room.sendApplicationLog("Resolution change id=" + id
  1104. + " old=" + oldResolution + " new=" + newResolution
  1105. + " delay=" + delay);
  1106. });
  1107. // Starts or stops the recording for the conference.
  1108. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1109. room.toggleRecording(options);
  1110. });
  1111. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1112. room.setSubject(topic);
  1113. });
  1114. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1115. APP.UI.setSubject(subject);
  1116. });
  1117. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1118. room.kickParticipant(id);
  1119. });
  1120. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1121. room.muteParticipant(id);
  1122. });
  1123. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1124. AuthHandler.authenticate(room);
  1125. });
  1126. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1127. room.selectParticipant(id);
  1128. });
  1129. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1130. var smallVideoId = smallVideo.getId();
  1131. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1132. && !APP.conference.isLocalId(smallVideoId))
  1133. if (isPinned)
  1134. room.pinParticipant(smallVideoId);
  1135. // When the library starts supporting multiple pins we would
  1136. // pass the isPinned parameter together with the identifier,
  1137. // but currently we send null to indicate that we unpin the
  1138. // last pinned.
  1139. else
  1140. room.pinParticipant(null);
  1141. });
  1142. APP.UI.addListener(
  1143. UIEvents.VIDEO_DEVICE_CHANGED,
  1144. (cameraDeviceId) => {
  1145. createLocalTracks({
  1146. devices: ['video'],
  1147. cameraDeviceId: cameraDeviceId,
  1148. micDeviceId: null
  1149. })
  1150. .then(([stream]) => {
  1151. this.useVideoStream(stream);
  1152. console.log('switched local video device');
  1153. APP.settings.setCameraDeviceId(cameraDeviceId);
  1154. })
  1155. .catch((err) => {
  1156. APP.UI.showDeviceErrorDialog(null, err);
  1157. APP.UI.setSelectedCameraFromSettings();
  1158. });
  1159. }
  1160. );
  1161. APP.UI.addListener(
  1162. UIEvents.AUDIO_DEVICE_CHANGED,
  1163. (micDeviceId) => {
  1164. createLocalTracks({
  1165. devices: ['audio'],
  1166. cameraDeviceId: null,
  1167. micDeviceId: micDeviceId
  1168. })
  1169. .then(([stream]) => {
  1170. this.useAudioStream(stream);
  1171. console.log('switched local audio device');
  1172. APP.settings.setMicDeviceId(micDeviceId);
  1173. })
  1174. .catch((err) => {
  1175. APP.UI.showDeviceErrorDialog(err, null);
  1176. APP.UI.setSelectedMicFromSettings();
  1177. });
  1178. }
  1179. );
  1180. APP.UI.addListener(
  1181. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1182. (audioOutputDeviceId) => {
  1183. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1184. .then(() => console.log('changed audio output device'))
  1185. .catch((err) => {
  1186. console.warn('Failed to change audio output device. ' +
  1187. 'Default or previously set audio output device ' +
  1188. 'will be used instead.', err);
  1189. APP.UI.setSelectedAudioOutputFromSettings();
  1190. });
  1191. }
  1192. );
  1193. APP.UI.addListener(
  1194. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1195. );
  1196. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1197. (url, state, time, isMuted, volume) => {
  1198. // send start and stop commands once, and remove any updates
  1199. // that had left
  1200. if (state === 'stop' || state === 'start' || state === 'playing') {
  1201. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1202. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1203. value: url,
  1204. attributes: {
  1205. state: state,
  1206. time: time,
  1207. muted: isMuted,
  1208. volume: volume
  1209. }
  1210. });
  1211. }
  1212. else {
  1213. // in case of paused, in order to allow late users to join
  1214. // paused
  1215. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1216. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1217. value: url,
  1218. attributes: {
  1219. state: state,
  1220. time: time,
  1221. muted: isMuted,
  1222. volume: volume
  1223. }
  1224. });
  1225. }
  1226. });
  1227. room.addCommandListener(
  1228. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1229. if (attributes.state === 'stop') {
  1230. APP.UI.onSharedVideoStop(id, attributes);
  1231. }
  1232. else if (attributes.state === 'start') {
  1233. APP.UI.onSharedVideoStart(id, value, attributes);
  1234. }
  1235. else if (attributes.state === 'playing'
  1236. || attributes.state === 'pause') {
  1237. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1238. }
  1239. });
  1240. },
  1241. /**
  1242. * Adds any room listener.
  1243. * @param eventName one of the ConferenceEvents
  1244. * @param callBack the function to be called when the event occurs
  1245. */
  1246. addConferenceListener(eventName, callBack) {
  1247. room.on(eventName, callBack);
  1248. },
  1249. /**
  1250. * Inits list of current devices and event listener for device change.
  1251. * @private
  1252. */
  1253. _initDeviceList() {
  1254. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1255. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1256. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1257. // Ugly way to synchronize real device IDs with local
  1258. // storage and settings menu. This is a workaround until
  1259. // getConstraints() method will be implemented in browsers.
  1260. if (localAudio) {
  1261. localAudio._setRealDeviceIdFromDeviceList(devices);
  1262. APP.settings.setMicDeviceId(localAudio.getDeviceId());
  1263. }
  1264. if (localVideo) {
  1265. localVideo._setRealDeviceIdFromDeviceList(devices);
  1266. APP.settings.setCameraDeviceId(localVideo.getDeviceId());
  1267. }
  1268. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1269. APP.UI.onAvailableDevicesChanged(devices);
  1270. });
  1271. JitsiMeetJS.mediaDevices.addEventListener(
  1272. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1273. (devices) =>
  1274. window.setTimeout(
  1275. () => this._onDeviceListChanged(devices), 0));
  1276. }
  1277. },
  1278. /**
  1279. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1280. * handle change of available media devices.
  1281. * @private
  1282. * @param {MediaDeviceInfo[]} devices
  1283. * @returns {Promise}
  1284. */
  1285. _onDeviceListChanged(devices) {
  1286. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1287. // Event handler can be fired before direct
  1288. // enumerateDevices() call, so handle this situation here.
  1289. if (!currentDevices.audioinput &&
  1290. !currentDevices.videoinput &&
  1291. !currentDevices.audiooutput) {
  1292. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1293. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1294. }
  1295. let newDevices =
  1296. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1297. devices, this.isSharingScreen, localVideo, localAudio);
  1298. let promises = [];
  1299. let audioWasMuted = this.audioMuted;
  1300. let videoWasMuted = this.videoMuted;
  1301. let availableAudioInputDevices =
  1302. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1303. let availableVideoInputDevices =
  1304. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1305. if (typeof newDevices.audiooutput !== 'undefined') {
  1306. // Just ignore any errors in catch block.
  1307. promises.push(APP.settings
  1308. .setAudioOutputDeviceId(newDevices.audiooutput)
  1309. .catch());
  1310. }
  1311. promises.push(
  1312. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1313. createLocalTracks,
  1314. newDevices.videoinput,
  1315. newDevices.audioinput)
  1316. .then(tracks =>
  1317. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1318. .then(() => {
  1319. // If audio was muted before, or we unplugged current device
  1320. // and selected new one, then mute new audio track.
  1321. if (audioWasMuted ||
  1322. currentDevices.audioinput.length >
  1323. availableAudioInputDevices.length) {
  1324. muteLocalAudio(true);
  1325. }
  1326. // If video was muted before, or we unplugged current device
  1327. // and selected new one, then mute new video track.
  1328. if (videoWasMuted ||
  1329. currentDevices.videoinput.length >
  1330. availableVideoInputDevices.length) {
  1331. muteLocalVideo(true);
  1332. }
  1333. }));
  1334. return Promise.all(promises)
  1335. .then(() => {
  1336. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1337. APP.UI.onAvailableDevicesChanged(devices);
  1338. });
  1339. },
  1340. /**
  1341. * Toggles the local "raised hand" status, if the current state allows
  1342. * toggling.
  1343. */
  1344. maybeToggleRaisedHand() {
  1345. // If we are the dominant speaker, we don't enable "raise hand".
  1346. if (this.isHandRaised || !this.isDominantSpeaker) {
  1347. this.setRaisedHand(!this.isHandRaised);
  1348. }
  1349. },
  1350. /**
  1351. * Sets the local "raised hand" status to a particular value.
  1352. */
  1353. setRaisedHand(raisedHand) {
  1354. if (raisedHand !== this.isHandRaised)
  1355. {
  1356. this.isHandRaised = raisedHand;
  1357. // Advertise the updated status
  1358. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1359. // Update the view
  1360. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1361. }
  1362. }
  1363. };