You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 52KB

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