Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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