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

conference.js 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  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.localId, 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. default:
  362. this._handleConferenceFailed(err, ...params);
  363. }
  364. }
  365. _onConferenceError(err, ...params) {
  366. console.error('CONFERENCE Error:', err, params);
  367. switch (err) {
  368. case ConferenceErrors.CHAT_ERROR:
  369. {
  370. let [code, msg] = params;
  371. APP.UI.showChatError(code, msg);
  372. }
  373. break;
  374. default:
  375. console.error("Unknown error.");
  376. }
  377. }
  378. _unsubscribe() {
  379. room.off(
  380. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  381. room.off(
  382. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  383. if (this.reconnectTimeout !== null) {
  384. clearTimeout(this.reconnectTimeout);
  385. }
  386. AuthHandler.closeAuth();
  387. }
  388. _handleConferenceJoined() {
  389. this._unsubscribe();
  390. this._resolve();
  391. }
  392. connect() {
  393. room.join();
  394. }
  395. }
  396. export default {
  397. localId: undefined,
  398. isModerator: false,
  399. audioMuted: false,
  400. videoMuted: false,
  401. isSharingScreen: false,
  402. isDesktopSharingEnabled: false,
  403. /*
  404. * Whether the local "raisedHand" flag is on.
  405. */
  406. isHandRaised: false,
  407. /*
  408. * Whether the local participant is the dominant speaker in the conference.
  409. */
  410. isDominantSpeaker: false,
  411. /**
  412. * Open new connection and join to the conference.
  413. * @param {object} options
  414. * @param {string} roomName name of the conference
  415. * @returns {Promise}
  416. */
  417. init(options) {
  418. this.roomName = options.roomName;
  419. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  420. // attaches global error handler, if there is already one, respect it
  421. if(JitsiMeetJS.getGlobalOnErrorHandler){
  422. var oldOnErrorHandler = window.onerror;
  423. window.onerror = function (message, source, lineno, colno, error) {
  424. JitsiMeetJS.getGlobalOnErrorHandler(
  425. message, source, lineno, colno, error);
  426. if(oldOnErrorHandler)
  427. oldOnErrorHandler(message, source, lineno, colno, error);
  428. };
  429. var oldOnUnhandledRejection = window.onunhandledrejection;
  430. window.onunhandledrejection = function(event) {
  431. JitsiMeetJS.getGlobalOnErrorHandler(
  432. null, null, null, null, event.reason);
  433. if(oldOnUnhandledRejection)
  434. oldOnUnhandledRejection(event);
  435. };
  436. }
  437. return JitsiMeetJS.init(config)
  438. .then(() => createInitialLocalTracksAndConnect(options.roomName))
  439. .then(([tracks, con]) => {
  440. console.log('initialized with %s local tracks', tracks.length);
  441. APP.connection = connection = con;
  442. this._createRoom(tracks);
  443. this.isDesktopSharingEnabled =
  444. JitsiMeetJS.isDesktopSharingEnabled();
  445. // if user didn't give access to mic or camera or doesn't have
  446. // them at all, we disable corresponding toolbar buttons
  447. if (!tracks.find((t) => t.isAudioTrack())) {
  448. APP.UI.disableMicrophoneButton();
  449. }
  450. if (!tracks.find((t) => t.isVideoTrack())) {
  451. APP.UI.disableCameraButton();
  452. }
  453. this._initDeviceList();
  454. if (config.iAmRecorder)
  455. this.recorder = new Recorder();
  456. // XXX The API will take care of disconnecting from the XMPP
  457. // server (and, thus, leaving the room) on unload.
  458. return new Promise((resolve, reject) => {
  459. (new ConferenceConnector(resolve, reject)).connect();
  460. });
  461. });
  462. },
  463. /**
  464. * Check if id is id of the local user.
  465. * @param {string} id id to check
  466. * @returns {boolean}
  467. */
  468. isLocalId (id) {
  469. return this.localId === id;
  470. },
  471. /**
  472. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  473. * @param mute true for mute and false for unmute.
  474. */
  475. muteAudio (mute) {
  476. muteLocalAudio(mute);
  477. },
  478. /**
  479. * Returns whether local audio is muted or not.
  480. * @returns {boolean}
  481. */
  482. isLocalAudioMuted() {
  483. return this.audioMuted;
  484. },
  485. /**
  486. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  487. */
  488. toggleAudioMuted () {
  489. this.muteAudio(!this.audioMuted);
  490. },
  491. /**
  492. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  493. * @param mute true for mute and false for unmute.
  494. */
  495. muteVideo (mute) {
  496. muteLocalVideo(mute);
  497. },
  498. /**
  499. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  500. */
  501. toggleVideoMuted () {
  502. this.muteVideo(!this.videoMuted);
  503. },
  504. /**
  505. * Retrieve list of conference participants (without local user).
  506. * @returns {JitsiParticipant[]}
  507. */
  508. listMembers () {
  509. return room.getParticipants();
  510. },
  511. /**
  512. * Retrieve list of ids of conference participants (without local user).
  513. * @returns {string[]}
  514. */
  515. listMembersIds () {
  516. return room.getParticipants().map(p => p.getId());
  517. },
  518. /**
  519. * Checks whether the participant identified by id is a moderator.
  520. * @id id to search for participant
  521. * @return {boolean} whether the participant is moderator
  522. */
  523. isParticipantModerator (id) {
  524. let user = room.getParticipantById(id);
  525. return user && user.isModerator();
  526. },
  527. /**
  528. * Check if SIP is supported.
  529. * @returns {boolean}
  530. */
  531. sipGatewayEnabled () {
  532. return room.isSIPCallingSupported();
  533. },
  534. get membersCount () {
  535. return room.getParticipants().length + 1;
  536. },
  537. /**
  538. * Returns true if the callstats integration is enabled, otherwise returns
  539. * false.
  540. *
  541. * @returns true if the callstats integration is enabled, otherwise returns
  542. * false.
  543. */
  544. isCallstatsEnabled () {
  545. return room.isCallstatsEnabled();
  546. },
  547. /**
  548. * Sends the given feedback through CallStats if enabled.
  549. *
  550. * @param overallFeedback an integer between 1 and 5 indicating the
  551. * user feedback
  552. * @param detailedFeedback detailed feedback from the user. Not yet used
  553. */
  554. sendFeedback (overallFeedback, detailedFeedback) {
  555. return room.sendFeedback (overallFeedback, detailedFeedback);
  556. },
  557. // used by torture currently
  558. isJoined () {
  559. return this._room
  560. && this._room.isJoined();
  561. },
  562. getConnectionState () {
  563. return this._room
  564. && this._room.getConnectionState();
  565. },
  566. getMyUserId () {
  567. return this._room
  568. && this._room.myUserId();
  569. },
  570. /**
  571. * Indicates if recording is supported in this conference.
  572. */
  573. isRecordingSupported() {
  574. return this._room && this._room.isRecordingSupported();
  575. },
  576. /**
  577. * Returns the recording state or undefined if the room is not defined.
  578. */
  579. getRecordingState() {
  580. return (this._room) ? this._room.getRecordingState() : undefined;
  581. },
  582. /**
  583. * Will be filled with values only when config.debug is enabled.
  584. * Its used by torture to check audio levels.
  585. */
  586. audioLevelsMap: {},
  587. /**
  588. * Returns the stored audio level (stored only if config.debug is enabled)
  589. * @param id the id for the user audio level to return (the id value is
  590. * returned for the participant using getMyUserId() method)
  591. */
  592. getPeerSSRCAudioLevel (id) {
  593. return this.audioLevelsMap[id];
  594. },
  595. /**
  596. * @return {number} the number of participants in the conference with at
  597. * least one track.
  598. */
  599. getNumberOfParticipantsWithTracks() {
  600. return this._room.getParticipants()
  601. .filter((p) => p.getTracks().length > 0)
  602. .length;
  603. },
  604. /**
  605. * Returns the stats.
  606. */
  607. getStats() {
  608. return ConnectionQuality.getStats();
  609. },
  610. // end used by torture
  611. getLogs () {
  612. return room.getLogs();
  613. },
  614. /**
  615. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  616. * desire to keep room private to this instance and (2) the need of other
  617. * modules to send and receive commands to and from participants.
  618. * Eventually, this instance remains in control with respect to the
  619. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  620. * JitsiConference) is to be used in the implementation of the Command(s)
  621. * API of this instance.
  622. */
  623. commands: {
  624. /**
  625. * Known custom conference commands.
  626. */
  627. defaults: commands,
  628. /**
  629. * Receives notifications from other participants about commands aka
  630. * custom events (sent by sendCommand or sendCommandOnce methods).
  631. * @param command {String} the name of the command
  632. * @param handler {Function} handler for the command
  633. */
  634. addCommandListener () {
  635. room.addCommandListener.apply(room, arguments);
  636. },
  637. /**
  638. * Removes command.
  639. * @param name {String} the name of the command.
  640. */
  641. removeCommand () {
  642. room.removeCommand.apply(room, arguments);
  643. },
  644. /**
  645. * Sends command.
  646. * @param name {String} the name of the command.
  647. * @param values {Object} with keys and values that will be sent.
  648. */
  649. sendCommand () {
  650. room.sendCommand.apply(room, arguments);
  651. },
  652. /**
  653. * Sends command one time.
  654. * @param name {String} the name of the command.
  655. * @param values {Object} with keys and values that will be sent.
  656. */
  657. sendCommandOnce () {
  658. room.sendCommandOnce.apply(room, arguments);
  659. }
  660. },
  661. _createRoom (localTracks) {
  662. room = connection.initJitsiConference(APP.conference.roomName,
  663. this._getConferenceOptions());
  664. this.localId = room.myUserId();
  665. this._setLocalAudioVideoStreams(localTracks);
  666. roomLocker = createRoomLocker(room);
  667. this._room = room; // FIXME do not use this
  668. let email = APP.settings.getEmail();
  669. email && sendData(this.commands.defaults.EMAIL, email);
  670. let avatarUrl = APP.settings.getAvatarUrl();
  671. avatarUrl && sendData(this.commands.defaults.AVATAR_URL,
  672. avatarUrl);
  673. let nick = APP.settings.getDisplayName();
  674. if (config.useNicks && !nick) {
  675. nick = APP.UI.askForNickname();
  676. APP.settings.setDisplayName(nick);
  677. }
  678. nick && room.setDisplayName(nick);
  679. this._setupListeners();
  680. },
  681. /**
  682. * Sets local video and audio streams.
  683. * @param {JitsiLocalTrack[]} tracks=[]
  684. * @returns {Promise[]}
  685. * @private
  686. */
  687. _setLocalAudioVideoStreams(tracks = []) {
  688. return tracks.map(track => {
  689. if (track.isAudioTrack()) {
  690. return this.useAudioStream(track);
  691. } else if (track.isVideoTrack()) {
  692. return this.useVideoStream(track);
  693. } else {
  694. console.error(
  695. "Ignored not an audio nor a video track: ", track);
  696. return Promise.resolve();
  697. }
  698. });
  699. },
  700. _getConferenceOptions() {
  701. let options = config;
  702. if(config.enableRecording && !config.recordingType) {
  703. options.recordingType = (config.hosts &&
  704. (typeof config.hosts.jirecon != "undefined"))?
  705. "jirecon" : "colibri";
  706. }
  707. return options;
  708. },
  709. /**
  710. * Start using provided video stream.
  711. * Stops previous video stream.
  712. * @param {JitsiLocalTrack} [stream] new stream to use or null
  713. * @returns {Promise}
  714. */
  715. useVideoStream (stream) {
  716. let promise = Promise.resolve();
  717. if (localVideo) {
  718. // this calls room.removeTrack internally
  719. // so we don't need to remove it manually
  720. promise = localVideo.dispose();
  721. }
  722. localVideo = stream;
  723. return promise.then(function () {
  724. if (stream) {
  725. return room.addTrack(stream);
  726. }
  727. }).then(() => {
  728. if (stream) {
  729. this.videoMuted = stream.isMuted();
  730. this.isSharingScreen = stream.videoType === 'desktop';
  731. APP.UI.addLocalStream(stream);
  732. stream.videoType === 'camera' && APP.UI.enableCameraButton();
  733. } else {
  734. this.videoMuted = false;
  735. this.isSharingScreen = false;
  736. }
  737. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  738. APP.UI.updateDesktopSharingButtons();
  739. });
  740. },
  741. /**
  742. * Start using provided audio stream.
  743. * Stops previous audio stream.
  744. * @param {JitsiLocalTrack} [stream] new stream to use or null
  745. * @returns {Promise}
  746. */
  747. useAudioStream (stream) {
  748. let promise = Promise.resolve();
  749. if (localAudio) {
  750. // this calls room.removeTrack internally
  751. // so we don't need to remove it manually
  752. promise = localAudio.dispose();
  753. }
  754. localAudio = stream;
  755. return promise.then(function () {
  756. if (stream) {
  757. return room.addTrack(stream);
  758. }
  759. }).then(() => {
  760. if (stream) {
  761. this.audioMuted = stream.isMuted();
  762. APP.UI.addLocalStream(stream);
  763. } else {
  764. this.audioMuted = false;
  765. }
  766. APP.UI.enableMicrophoneButton();
  767. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  768. });
  769. },
  770. videoSwitchInProgress: false,
  771. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  772. if (this.videoSwitchInProgress) {
  773. console.warn("Switch in progress.");
  774. return;
  775. }
  776. if (!this.isDesktopSharingEnabled) {
  777. console.warn("Cannot toggle screen sharing: not supported.");
  778. return;
  779. }
  780. this.videoSwitchInProgress = true;
  781. if (shareScreen) {
  782. createLocalTracks({ devices: ['desktop'] }).then(([stream]) => {
  783. stream.on(
  784. TrackEvents.LOCAL_TRACK_STOPPED,
  785. () => {
  786. // if stream was stopped during screensharing session
  787. // then we should switch to video
  788. // otherwise we stopped it because we already switched
  789. // to video, so nothing to do here
  790. if (this.isSharingScreen) {
  791. this.toggleScreenSharing(false);
  792. }
  793. }
  794. );
  795. return this.useVideoStream(stream);
  796. }).then(() => {
  797. this.videoSwitchInProgress = false;
  798. console.log('sharing local desktop');
  799. }).catch((err) => {
  800. this.videoSwitchInProgress = false;
  801. this.toggleScreenSharing(false);
  802. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  803. return;
  804. }
  805. console.error('failed to share local desktop', err);
  806. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  807. APP.UI.showExtensionRequiredDialog(
  808. config.desktopSharingFirefoxExtensionURL
  809. );
  810. return;
  811. }
  812. // Handling:
  813. // TrackErrors.PERMISSION_DENIED
  814. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  815. // TrackErrors.GENERAL
  816. // and any other
  817. let dialogTxt;
  818. let dialogTitle;
  819. if (err.name === TrackErrors.PERMISSION_DENIED) {
  820. dialogTxt = APP.translation.generateTranslationHTML(
  821. "dialog.screenSharingPermissionDeniedError");
  822. dialogTitle = APP.translation.generateTranslationHTML(
  823. "dialog.error");
  824. } else {
  825. dialogTxt = APP.translation.generateTranslationHTML(
  826. "dialog.failtoinstall");
  827. dialogTitle = APP.translation.generateTranslationHTML(
  828. "dialog.permissionDenied");
  829. }
  830. APP.UI.messageHandler.openDialog(dialogTitle, dialogTxt, false);
  831. });
  832. } else {
  833. createLocalTracks({ devices: ['video'] }).then(
  834. ([stream]) => this.useVideoStream(stream)
  835. ).then(() => {
  836. this.videoSwitchInProgress = false;
  837. console.log('sharing local video');
  838. }).catch((err) => {
  839. this.useVideoStream(null);
  840. this.videoSwitchInProgress = false;
  841. console.error('failed to share local video', err);
  842. });
  843. }
  844. },
  845. /**
  846. * Setup interaction between conference and UI.
  847. */
  848. _setupListeners () {
  849. // add local streams when joined to the conference
  850. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  851. APP.UI.mucJoined();
  852. APP.API.notifyConferenceJoined(APP.conference.roomName);
  853. });
  854. room.on(
  855. ConferenceEvents.AUTH_STATUS_CHANGED,
  856. function (authEnabled, authLogin) {
  857. APP.UI.updateAuthInfo(authEnabled, authLogin);
  858. }
  859. );
  860. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  861. if (user.isHidden())
  862. return;
  863. console.log('USER %s connnected', id, user);
  864. APP.API.notifyUserJoined(id);
  865. APP.UI.addUser(id, user.getDisplayName());
  866. // check the roles for the new user and reflect them
  867. APP.UI.updateUserRole(user);
  868. });
  869. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  870. console.log('USER %s LEFT', id, user);
  871. APP.API.notifyUserLeft(id);
  872. APP.UI.removeUser(id, user.getDisplayName());
  873. APP.UI.onSharedVideoStop(id);
  874. });
  875. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  876. if (this.isLocalId(id)) {
  877. console.info(`My role changed, new role: ${role}`);
  878. this.isModerator = room.isModerator();
  879. APP.UI.updateLocalRole(room.isModerator());
  880. } else {
  881. let user = room.getParticipantById(id);
  882. if (user) {
  883. APP.UI.updateUserRole(user);
  884. }
  885. }
  886. });
  887. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  888. if(!track || track.isLocal())
  889. return;
  890. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  891. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  892. });
  893. APP.UI.addRemoteStream(track);
  894. });
  895. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  896. if(!track || track.isLocal())
  897. return;
  898. APP.UI.removeRemoteStream(track);
  899. });
  900. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  901. if(!track)
  902. return;
  903. const handler = (track.getType() === "audio")?
  904. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  905. let id;
  906. const mute = track.isMuted();
  907. if(track.isLocal()){
  908. id = this.localId;
  909. if(track.getType() === "audio") {
  910. this.audioMuted = mute;
  911. } else {
  912. this.videoMuted = mute;
  913. }
  914. } else {
  915. id = track.getParticipantId();
  916. }
  917. handler(id , mute);
  918. });
  919. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  920. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  921. lvl = 0;
  922. }
  923. if(config.debug)
  924. {
  925. this.audioLevelsMap[id] = lvl;
  926. if(config.debugAudioLevels)
  927. console.log("AudioLevel:" + id + "/" + lvl);
  928. }
  929. APP.UI.setAudioLevel(id, lvl);
  930. });
  931. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  932. //FIXME
  933. if (config.muteLocalVideoIfNotInLastN) {
  934. // TODO mute or unmute if required
  935. // mark video on UI
  936. // APP.UI.markVideoMuted(true/false);
  937. }
  938. });
  939. room.on(
  940. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  941. APP.UI.handleLastNEndpoints(ids, enteringIds);
  942. });
  943. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  944. if (this.isLocalId(id)) {
  945. this.isDominantSpeaker = true;
  946. this.setRaisedHand(false);
  947. } else {
  948. this.isDominantSpeaker = false;
  949. var participant = room.getParticipantById(id);
  950. if (participant) {
  951. APP.UI.setRaisedHandStatus(participant, false);
  952. }
  953. }
  954. APP.UI.markDominantSpeaker(id);
  955. });
  956. if (!interfaceConfig.filmStripOnly) {
  957. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  958. APP.UI.markVideoInterrupted(true);
  959. });
  960. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  961. APP.UI.markVideoInterrupted(false);
  962. });
  963. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  964. let nick = getDisplayName(id);
  965. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  966. APP.UI.addMessage(id, nick, text, ts);
  967. });
  968. }
  969. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  970. APP.API.notifyDisplayNameChanged(id, displayName);
  971. APP.UI.changeDisplayName(id, displayName);
  972. });
  973. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  974. (participant, name, oldValue, newValue) => {
  975. if (name === "raisedHand") {
  976. APP.UI.setRaisedHandStatus(participant, newValue);
  977. }
  978. });
  979. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  980. console.log("Received recorder status change: ", status, error);
  981. APP.UI.updateRecordingState(status);
  982. });
  983. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  984. APP.UI.updateUserStatus(id, status);
  985. });
  986. room.on(ConferenceEvents.KICKED, () => {
  987. APP.UI.hideStats();
  988. APP.UI.notifyKicked();
  989. // FIXME close
  990. });
  991. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  992. APP.UI.updateDTMFSupport(isDTMFSupported);
  993. });
  994. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  995. if (room.isModerator()) {
  996. let promise = roomLocker.isLocked
  997. ? roomLocker.askToUnlock()
  998. : roomLocker.askToLock();
  999. promise.then(() => {
  1000. APP.UI.markRoomLocked(roomLocker.isLocked);
  1001. });
  1002. } else {
  1003. roomLocker.notifyModeratorRequired();
  1004. }
  1005. });
  1006. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1007. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1008. if (!interfaceConfig.filmStripOnly) {
  1009. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1010. APP.API.notifySendingChatMessage(message);
  1011. room.sendTextMessage(message);
  1012. });
  1013. }
  1014. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1015. ConnectionQuality.updateLocalStats(stats);
  1016. });
  1017. ConnectionQuality.addListener(
  1018. CQEvents.LOCALSTATS_UPDATED,
  1019. (percent, stats) => {
  1020. APP.UI.updateLocalStats(percent, stats);
  1021. // send local stats to other users
  1022. room.sendCommandOnce(this.commands.defaults.CONNECTION_QUALITY,
  1023. {
  1024. children: ConnectionQuality.convertToMUCStats(stats),
  1025. attributes: {
  1026. xmlns: 'http://jitsi.org/jitmeet/stats'
  1027. }
  1028. });
  1029. }
  1030. );
  1031. // listen to remote stats
  1032. room.addCommandListener(this.commands.defaults.CONNECTION_QUALITY,
  1033. (values, from) => {
  1034. ConnectionQuality.updateRemoteStats(from, values);
  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. // Starts or stops the recording for the conference.
  1102. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1103. room.toggleRecording(options);
  1104. });
  1105. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1106. room.setSubject(topic);
  1107. });
  1108. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1109. APP.UI.setSubject(subject);
  1110. });
  1111. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1112. room.kickParticipant(id);
  1113. });
  1114. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1115. room.muteParticipant(id);
  1116. });
  1117. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1118. AuthHandler.authenticate(room);
  1119. });
  1120. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1121. room.selectParticipant(id);
  1122. });
  1123. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1124. var smallVideoId = smallVideo.getId();
  1125. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1126. && !APP.conference.isLocalId(smallVideoId))
  1127. if (isPinned)
  1128. room.pinParticipant(smallVideoId);
  1129. // When the library starts supporting multiple pins we would
  1130. // pass the isPinned parameter together with the identifier,
  1131. // but currently we send null to indicate that we unpin the
  1132. // last pinned.
  1133. else
  1134. room.pinParticipant(null);
  1135. });
  1136. APP.UI.addListener(
  1137. UIEvents.VIDEO_DEVICE_CHANGED,
  1138. (cameraDeviceId) => {
  1139. createLocalTracks({
  1140. devices: ['video'],
  1141. cameraDeviceId: cameraDeviceId,
  1142. micDeviceId: null
  1143. })
  1144. .then(([stream]) => {
  1145. this.useVideoStream(stream);
  1146. console.log('switched local video device');
  1147. APP.settings.setCameraDeviceId(cameraDeviceId);
  1148. })
  1149. .catch((err) => {
  1150. APP.UI.showDeviceErrorDialog(null, err);
  1151. APP.UI.setSelectedCameraFromSettings();
  1152. });
  1153. }
  1154. );
  1155. APP.UI.addListener(
  1156. UIEvents.AUDIO_DEVICE_CHANGED,
  1157. (micDeviceId) => {
  1158. createLocalTracks({
  1159. devices: ['audio'],
  1160. cameraDeviceId: null,
  1161. micDeviceId: micDeviceId
  1162. })
  1163. .then(([stream]) => {
  1164. this.useAudioStream(stream);
  1165. console.log('switched local audio device');
  1166. APP.settings.setMicDeviceId(micDeviceId);
  1167. })
  1168. .catch((err) => {
  1169. APP.UI.showDeviceErrorDialog(err, null);
  1170. APP.UI.setSelectedMicFromSettings();
  1171. });
  1172. }
  1173. );
  1174. APP.UI.addListener(
  1175. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1176. (audioOutputDeviceId) => {
  1177. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1178. .then(() => console.log('changed audio output device'))
  1179. .catch((err) => {
  1180. console.warn('Failed to change audio output device. ' +
  1181. 'Default or previously set audio output device ' +
  1182. 'will be used instead.', err);
  1183. APP.UI.setSelectedAudioOutputFromSettings();
  1184. });
  1185. }
  1186. );
  1187. APP.UI.addListener(
  1188. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1189. );
  1190. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1191. (url, state, time, isMuted, volume) => {
  1192. // send start and stop commands once, and remove any updates
  1193. // that had left
  1194. if (state === 'stop' || state === 'start' || state === 'playing') {
  1195. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1196. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1197. value: url,
  1198. attributes: {
  1199. state: state,
  1200. time: time,
  1201. muted: isMuted,
  1202. volume: volume
  1203. }
  1204. });
  1205. }
  1206. else {
  1207. // in case of paused, in order to allow late users to join
  1208. // paused
  1209. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1210. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1211. value: url,
  1212. attributes: {
  1213. state: state,
  1214. time: time,
  1215. muted: isMuted,
  1216. volume: volume
  1217. }
  1218. });
  1219. }
  1220. });
  1221. room.addCommandListener(
  1222. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1223. if (attributes.state === 'stop') {
  1224. APP.UI.onSharedVideoStop(id, attributes);
  1225. }
  1226. else if (attributes.state === 'start') {
  1227. APP.UI.onSharedVideoStart(id, value, attributes);
  1228. }
  1229. else if (attributes.state === 'playing'
  1230. || attributes.state === 'pause') {
  1231. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1232. }
  1233. });
  1234. },
  1235. /**
  1236. * Adds any room listener.
  1237. * @param eventName one of the ConferenceEvents
  1238. * @param callBack the function to be called when the event occurs
  1239. */
  1240. addConferenceListener(eventName, callBack) {
  1241. room.on(eventName, callBack);
  1242. },
  1243. /**
  1244. * Inits list of current devices and event listener for device change.
  1245. * @private
  1246. */
  1247. _initDeviceList() {
  1248. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1249. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1250. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1251. // Ugly way to synchronize real device IDs with local
  1252. // storage and settings menu. This is a workaround until
  1253. // getConstraints() method will be implemented in browsers.
  1254. if (localAudio) {
  1255. localAudio._setRealDeviceIdFromDeviceList(devices);
  1256. APP.settings.setMicDeviceId(localAudio.getDeviceId());
  1257. }
  1258. if (localVideo) {
  1259. localVideo._setRealDeviceIdFromDeviceList(devices);
  1260. APP.settings.setCameraDeviceId(localVideo.getDeviceId());
  1261. }
  1262. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1263. APP.UI.onAvailableDevicesChanged(devices);
  1264. });
  1265. JitsiMeetJS.mediaDevices.addEventListener(
  1266. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1267. (devices) =>
  1268. window.setTimeout(
  1269. () => this._onDeviceListChanged(devices), 0));
  1270. }
  1271. },
  1272. /**
  1273. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1274. * handle change of available media devices.
  1275. * @private
  1276. * @param {MediaDeviceInfo[]} devices
  1277. * @returns {Promise}
  1278. */
  1279. _onDeviceListChanged(devices) {
  1280. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1281. // Event handler can be fired before direct
  1282. // enumerateDevices() call, so handle this situation here.
  1283. if (!currentDevices.audioinput &&
  1284. !currentDevices.videoinput &&
  1285. !currentDevices.audiooutput) {
  1286. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1287. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1288. }
  1289. let newDevices =
  1290. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1291. devices, this.isSharingScreen, localVideo, localAudio);
  1292. let promises = [];
  1293. let audioWasMuted = this.audioMuted;
  1294. let videoWasMuted = this.videoMuted;
  1295. let availableAudioInputDevices =
  1296. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1297. let availableVideoInputDevices =
  1298. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1299. if (typeof newDevices.audiooutput !== 'undefined') {
  1300. // Just ignore any errors in catch block.
  1301. promises.push(APP.settings
  1302. .setAudioOutputDeviceId(newDevices.audiooutput)
  1303. .catch());
  1304. }
  1305. promises.push(
  1306. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1307. createLocalTracks,
  1308. newDevices.videoinput,
  1309. newDevices.audioinput)
  1310. .then(tracks =>
  1311. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1312. .then(() => {
  1313. // If audio was muted before, or we unplugged current device
  1314. // and selected new one, then mute new audio track.
  1315. if (audioWasMuted ||
  1316. currentDevices.audioinput.length >
  1317. availableAudioInputDevices.length) {
  1318. muteLocalAudio(true);
  1319. }
  1320. // If video was muted before, or we unplugged current device
  1321. // and selected new one, then mute new video track.
  1322. if (videoWasMuted ||
  1323. currentDevices.videoinput.length >
  1324. availableVideoInputDevices.length) {
  1325. muteLocalVideo(true);
  1326. }
  1327. }));
  1328. return Promise.all(promises)
  1329. .then(() => {
  1330. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1331. APP.UI.onAvailableDevicesChanged(devices);
  1332. });
  1333. },
  1334. /**
  1335. * Toggles the local "raised hand" status, if the current state allows
  1336. * toggling.
  1337. */
  1338. maybeToggleRaisedHand() {
  1339. // If we are the dominant speaker, we don't enable "raise hand".
  1340. if (this.isHandRaised || !this.isDominantSpeaker) {
  1341. this.setRaisedHand(!this.isHandRaised);
  1342. }
  1343. },
  1344. /**
  1345. * Sets the local "raised hand" status to a particular value.
  1346. */
  1347. setRaisedHand(raisedHand) {
  1348. if (raisedHand !== this.isHandRaised)
  1349. {
  1350. this.isHandRaised = raisedHand;
  1351. // Advertise the updated status
  1352. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1353. // Update the view
  1354. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1355. }
  1356. }
  1357. };