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

conference.js 52KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567
  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. /**
  566. * Returns the connection times stored in the library.
  567. */
  568. getConnectionTimes () {
  569. return this._room.getConnectionTimes();
  570. },
  571. // used by torture currently
  572. isJoined () {
  573. return this._room
  574. && this._room.isJoined();
  575. },
  576. getConnectionState () {
  577. return this._room
  578. && this._room.getConnectionState();
  579. },
  580. getMyUserId () {
  581. return this._room
  582. && this._room.myUserId();
  583. },
  584. /**
  585. * Indicates if recording is supported in this conference.
  586. */
  587. isRecordingSupported() {
  588. return this._room && this._room.isRecordingSupported();
  589. },
  590. /**
  591. * Returns the recording state or undefined if the room is not defined.
  592. */
  593. getRecordingState() {
  594. return (this._room) ? this._room.getRecordingState() : undefined;
  595. },
  596. /**
  597. * Will be filled with values only when config.debug is enabled.
  598. * Its used by torture to check audio levels.
  599. */
  600. audioLevelsMap: {},
  601. /**
  602. * Returns the stored audio level (stored only if config.debug is enabled)
  603. * @param id the id for the user audio level to return (the id value is
  604. * returned for the participant using getMyUserId() method)
  605. */
  606. getPeerSSRCAudioLevel (id) {
  607. return this.audioLevelsMap[id];
  608. },
  609. /**
  610. * @return {number} the number of participants in the conference with at
  611. * least one track.
  612. */
  613. getNumberOfParticipantsWithTracks() {
  614. return this._room.getParticipants()
  615. .filter((p) => p.getTracks().length > 0)
  616. .length;
  617. },
  618. /**
  619. * Returns the stats.
  620. */
  621. getStats() {
  622. return ConnectionQuality.getStats();
  623. },
  624. // end used by torture
  625. getLogs () {
  626. return room.getLogs();
  627. },
  628. /**
  629. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  630. * desire to keep room private to this instance and (2) the need of other
  631. * modules to send and receive commands to and from participants.
  632. * Eventually, this instance remains in control with respect to the
  633. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  634. * JitsiConference) is to be used in the implementation of the Command(s)
  635. * API of this instance.
  636. */
  637. commands: {
  638. /**
  639. * Known custom conference commands.
  640. */
  641. defaults: commands,
  642. /**
  643. * Receives notifications from other participants about commands aka
  644. * custom events (sent by sendCommand or sendCommandOnce methods).
  645. * @param command {String} the name of the command
  646. * @param handler {Function} handler for the command
  647. */
  648. addCommandListener () {
  649. room.addCommandListener.apply(room, arguments);
  650. },
  651. /**
  652. * Removes command.
  653. * @param name {String} the name of the command.
  654. */
  655. removeCommand () {
  656. room.removeCommand.apply(room, arguments);
  657. },
  658. /**
  659. * Sends command.
  660. * @param name {String} the name of the command.
  661. * @param values {Object} with keys and values that will be sent.
  662. */
  663. sendCommand () {
  664. room.sendCommand.apply(room, arguments);
  665. },
  666. /**
  667. * Sends command one time.
  668. * @param name {String} the name of the command.
  669. * @param values {Object} with keys and values that will be sent.
  670. */
  671. sendCommandOnce () {
  672. room.sendCommandOnce.apply(room, arguments);
  673. }
  674. },
  675. _createRoom (localTracks) {
  676. room = connection.initJitsiConference(APP.conference.roomName,
  677. this._getConferenceOptions());
  678. this._setLocalAudioVideoStreams(localTracks);
  679. roomLocker = createRoomLocker(room);
  680. this._room = room; // FIXME do not use this
  681. let email = APP.settings.getEmail();
  682. email && sendData(this.commands.defaults.EMAIL, email);
  683. let avatarUrl = APP.settings.getAvatarUrl();
  684. avatarUrl && sendData(this.commands.defaults.AVATAR_URL,
  685. avatarUrl);
  686. let nick = APP.settings.getDisplayName();
  687. if (config.useNicks && !nick) {
  688. nick = APP.UI.askForNickname();
  689. APP.settings.setDisplayName(nick);
  690. }
  691. nick && room.setDisplayName(nick);
  692. this._setupListeners();
  693. },
  694. /**
  695. * Sets local video and audio streams.
  696. * @param {JitsiLocalTrack[]} tracks=[]
  697. * @returns {Promise[]}
  698. * @private
  699. */
  700. _setLocalAudioVideoStreams(tracks = []) {
  701. return tracks.map(track => {
  702. if (track.isAudioTrack()) {
  703. return this.useAudioStream(track);
  704. } else if (track.isVideoTrack()) {
  705. return this.useVideoStream(track);
  706. } else {
  707. console.error(
  708. "Ignored not an audio nor a video track: ", track);
  709. return Promise.resolve();
  710. }
  711. });
  712. },
  713. _getConferenceOptions() {
  714. let options = config;
  715. if(config.enableRecording && !config.recordingType) {
  716. options.recordingType = (config.hosts &&
  717. (typeof config.hosts.jirecon != "undefined"))?
  718. "jirecon" : "colibri";
  719. }
  720. return options;
  721. },
  722. /**
  723. * Start using provided video stream.
  724. * Stops previous video stream.
  725. * @param {JitsiLocalTrack} [stream] new stream to use or null
  726. * @returns {Promise}
  727. */
  728. useVideoStream (stream) {
  729. let promise = Promise.resolve();
  730. if (localVideo) {
  731. // this calls room.removeTrack internally
  732. // so we don't need to remove it manually
  733. promise = localVideo.dispose();
  734. }
  735. localVideo = stream;
  736. return promise.then(function () {
  737. if (stream) {
  738. return room.addTrack(stream);
  739. }
  740. }).then(() => {
  741. if (stream) {
  742. this.videoMuted = stream.isMuted();
  743. this.isSharingScreen = stream.videoType === 'desktop';
  744. APP.UI.addLocalStream(stream);
  745. stream.videoType === 'camera' && APP.UI.enableCameraButton();
  746. } else {
  747. this.videoMuted = false;
  748. this.isSharingScreen = false;
  749. }
  750. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  751. APP.UI.updateDesktopSharingButtons();
  752. });
  753. },
  754. /**
  755. * Start using provided audio stream.
  756. * Stops previous audio stream.
  757. * @param {JitsiLocalTrack} [stream] new stream to use or null
  758. * @returns {Promise}
  759. */
  760. useAudioStream (stream) {
  761. let promise = Promise.resolve();
  762. if (localAudio) {
  763. // this calls room.removeTrack internally
  764. // so we don't need to remove it manually
  765. promise = localAudio.dispose();
  766. }
  767. localAudio = stream;
  768. return promise.then(function () {
  769. if (stream) {
  770. return room.addTrack(stream);
  771. }
  772. }).then(() => {
  773. if (stream) {
  774. this.audioMuted = stream.isMuted();
  775. APP.UI.addLocalStream(stream);
  776. } else {
  777. this.audioMuted = false;
  778. }
  779. APP.UI.enableMicrophoneButton();
  780. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  781. });
  782. },
  783. videoSwitchInProgress: false,
  784. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  785. if (this.videoSwitchInProgress) {
  786. console.warn("Switch in progress.");
  787. return;
  788. }
  789. if (!this.isDesktopSharingEnabled) {
  790. console.warn("Cannot toggle screen sharing: not supported.");
  791. return;
  792. }
  793. this.videoSwitchInProgress = true;
  794. if (shareScreen) {
  795. createLocalTracks({ devices: ['desktop'] }).then(([stream]) => {
  796. stream.on(
  797. TrackEvents.LOCAL_TRACK_STOPPED,
  798. () => {
  799. // if stream was stopped during screensharing session
  800. // then we should switch to video
  801. // otherwise we stopped it because we already switched
  802. // to video, so nothing to do here
  803. if (this.isSharingScreen) {
  804. this.toggleScreenSharing(false);
  805. }
  806. }
  807. );
  808. return this.useVideoStream(stream);
  809. }).then(() => {
  810. this.videoSwitchInProgress = false;
  811. AnalyticsAdapter.sendEvent('conference.sharingDesktop.start');
  812. console.log('sharing local desktop');
  813. }).catch((err) => {
  814. this.videoSwitchInProgress = false;
  815. this.toggleScreenSharing(false);
  816. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  817. return;
  818. }
  819. console.error('failed to share local desktop', err);
  820. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  821. APP.UI.showExtensionRequiredDialog(
  822. config.desktopSharingFirefoxExtensionURL
  823. );
  824. return;
  825. }
  826. // Handling:
  827. // TrackErrors.PERMISSION_DENIED
  828. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  829. // TrackErrors.GENERAL
  830. // and any other
  831. let dialogTxt;
  832. let dialogTitle;
  833. if (err.name === TrackErrors.PERMISSION_DENIED) {
  834. dialogTxt = APP.translation.generateTranslationHTML(
  835. "dialog.screenSharingPermissionDeniedError");
  836. dialogTitle = APP.translation.generateTranslationHTML(
  837. "dialog.error");
  838. } else {
  839. dialogTxt = APP.translation.generateTranslationHTML(
  840. "dialog.failtoinstall");
  841. dialogTitle = APP.translation.generateTranslationHTML(
  842. "dialog.permissionDenied");
  843. }
  844. APP.UI.messageHandler.openDialog(dialogTitle, dialogTxt, false);
  845. });
  846. } else {
  847. createLocalTracks({ devices: ['video'] }).then(
  848. ([stream]) => this.useVideoStream(stream)
  849. ).then(() => {
  850. this.videoSwitchInProgress = false;
  851. AnalyticsAdapter.sendEvent('conference.sharingDesktop.stop');
  852. console.log('sharing local video');
  853. }).catch((err) => {
  854. this.useVideoStream(null);
  855. this.videoSwitchInProgress = false;
  856. console.error('failed to share local video', err);
  857. });
  858. }
  859. },
  860. /**
  861. * Setup interaction between conference and UI.
  862. */
  863. _setupListeners () {
  864. // add local streams when joined to the conference
  865. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  866. APP.UI.mucJoined();
  867. APP.API.notifyConferenceJoined(APP.conference.roomName);
  868. connectionIsInterrupted = false;
  869. APP.UI.markVideoInterrupted(false);
  870. });
  871. room.on(
  872. ConferenceEvents.AUTH_STATUS_CHANGED,
  873. function (authEnabled, authLogin) {
  874. APP.UI.updateAuthInfo(authEnabled, authLogin);
  875. }
  876. );
  877. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  878. if (user.isHidden())
  879. return;
  880. console.log('USER %s connnected', id, user);
  881. APP.API.notifyUserJoined(id);
  882. APP.UI.addUser(id, user.getDisplayName());
  883. // check the roles for the new user and reflect them
  884. APP.UI.updateUserRole(user);
  885. });
  886. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  887. console.log('USER %s LEFT', id, user);
  888. APP.API.notifyUserLeft(id);
  889. APP.UI.removeUser(id, user.getDisplayName());
  890. APP.UI.onSharedVideoStop(id);
  891. });
  892. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  893. if (this.isLocalId(id)) {
  894. console.info(`My role changed, new role: ${role}`);
  895. this.isModerator = room.isModerator();
  896. APP.UI.updateLocalRole(room.isModerator());
  897. } else {
  898. let user = room.getParticipantById(id);
  899. if (user) {
  900. APP.UI.updateUserRole(user);
  901. }
  902. }
  903. });
  904. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  905. if(!track || track.isLocal())
  906. return;
  907. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  908. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  909. });
  910. APP.UI.addRemoteStream(track);
  911. });
  912. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  913. if(!track || track.isLocal())
  914. return;
  915. APP.UI.removeRemoteStream(track);
  916. });
  917. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  918. if(!track)
  919. return;
  920. const handler = (track.getType() === "audio")?
  921. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  922. let id;
  923. const mute = track.isMuted();
  924. if(track.isLocal()){
  925. id = APP.conference.getMyUserId();
  926. if(track.getType() === "audio") {
  927. this.audioMuted = mute;
  928. } else {
  929. this.videoMuted = mute;
  930. }
  931. } else {
  932. id = track.getParticipantId();
  933. }
  934. handler(id , mute);
  935. });
  936. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  937. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  938. lvl = 0;
  939. }
  940. if(config.debug)
  941. {
  942. this.audioLevelsMap[id] = lvl;
  943. if(config.debugAudioLevels)
  944. console.log("AudioLevel:" + id + "/" + lvl);
  945. }
  946. APP.UI.setAudioLevel(id, lvl);
  947. });
  948. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  949. //FIXME
  950. if (config.muteLocalVideoIfNotInLastN) {
  951. // TODO mute or unmute if required
  952. // mark video on UI
  953. // APP.UI.markVideoMuted(true/false);
  954. }
  955. });
  956. room.on(
  957. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  958. APP.UI.handleLastNEndpoints(ids, enteringIds);
  959. });
  960. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  961. if (this.isLocalId(id)) {
  962. this.isDominantSpeaker = true;
  963. this.setRaisedHand(false);
  964. } else {
  965. this.isDominantSpeaker = false;
  966. var participant = room.getParticipantById(id);
  967. if (participant) {
  968. APP.UI.setRaisedHandStatus(participant, false);
  969. }
  970. }
  971. APP.UI.markDominantSpeaker(id);
  972. });
  973. if (!interfaceConfig.filmStripOnly) {
  974. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  975. APP.UI.markVideoInterrupted(true);
  976. });
  977. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  978. APP.UI.markVideoInterrupted(false);
  979. });
  980. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  981. let nick = getDisplayName(id);
  982. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  983. APP.UI.addMessage(id, nick, text, ts);
  984. });
  985. }
  986. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  987. connectionIsInterrupted = true;
  988. ConnectionQuality.updateLocalConnectionQuality(0);
  989. });
  990. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  991. connectionIsInterrupted = false;
  992. });
  993. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  994. APP.API.notifyDisplayNameChanged(id, displayName);
  995. APP.UI.changeDisplayName(id, displayName);
  996. });
  997. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  998. (participant, name, oldValue, newValue) => {
  999. if (name === "raisedHand") {
  1000. APP.UI.setRaisedHandStatus(participant, newValue);
  1001. }
  1002. });
  1003. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1004. console.log("Received recorder status change: ", status, error);
  1005. APP.UI.updateRecordingState(status);
  1006. });
  1007. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  1008. APP.UI.updateUserStatus(id, status);
  1009. });
  1010. room.on(ConferenceEvents.KICKED, () => {
  1011. APP.UI.hideStats();
  1012. APP.UI.notifyKicked();
  1013. // FIXME close
  1014. });
  1015. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1016. APP.UI.updateDTMFSupport(isDTMFSupported);
  1017. });
  1018. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  1019. if (room.isModerator()) {
  1020. let promise = roomLocker.isLocked
  1021. ? roomLocker.askToUnlock()
  1022. : roomLocker.askToLock();
  1023. promise.then(() => {
  1024. APP.UI.markRoomLocked(roomLocker.isLocked);
  1025. });
  1026. } else {
  1027. roomLocker.notifyModeratorRequired();
  1028. }
  1029. });
  1030. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1031. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1032. if (!interfaceConfig.filmStripOnly) {
  1033. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1034. APP.API.notifySendingChatMessage(message);
  1035. room.sendTextMessage(message);
  1036. });
  1037. }
  1038. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1039. ConnectionQuality.updateLocalStats(stats, connectionIsInterrupted);
  1040. });
  1041. ConnectionQuality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1042. (percent, stats) => {
  1043. APP.UI.updateLocalStats(percent, stats);
  1044. // Send only the data that remote participants care about.
  1045. let data = {
  1046. bitrate: stats.bitrate,
  1047. packetLoss: stats.packetLoss};
  1048. try {
  1049. room.broadcastEndpointMessage({
  1050. type: this.commands.defaults.CONNECTION_QUALITY,
  1051. values: data });
  1052. } catch (e) {
  1053. reportError(e);
  1054. }
  1055. });
  1056. room.on(ConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1057. (participant, payload) => {
  1058. switch(payload.type) {
  1059. case this.commands.defaults.CONNECTION_QUALITY:
  1060. ConnectionQuality.updateRemoteStats(participant.getId(),
  1061. payload.values);
  1062. break;
  1063. default:
  1064. console.warn("Unknown datachannel message", payload);
  1065. }
  1066. });
  1067. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1068. (id, percent, stats) => {
  1069. APP.UI.updateRemoteStats(id, percent, stats);
  1070. });
  1071. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1072. APP.UI.initEtherpad(value);
  1073. });
  1074. APP.UI.addListener(UIEvents.EMAIL_CHANGED, changeLocalEmail);
  1075. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1076. APP.UI.setUserEmail(from, data.value);
  1077. });
  1078. APP.UI.addListener(UIEvents.AVATAR_URL_CHANGED, changeLocalAvatarUrl);
  1079. room.addCommandListener(this.commands.defaults.AVATAR_URL,
  1080. (data, from) => {
  1081. APP.UI.setUserAvatarUrl(from, data.value);
  1082. });
  1083. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1084. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1085. (startAudioMuted, startVideoMuted) => {
  1086. room.setStartMutedPolicy({
  1087. audio: startAudioMuted,
  1088. video: startVideoMuted
  1089. });
  1090. }
  1091. );
  1092. room.on(
  1093. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1094. ({ audio, video }) => {
  1095. APP.UI.onStartMutedChanged(audio, video);
  1096. }
  1097. );
  1098. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1099. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1100. && APP.UI.notifyInitiallyMuted();
  1101. });
  1102. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  1103. APP.UI.inviteParticipants(
  1104. roomUrl,
  1105. APP.conference.roomName,
  1106. roomLocker.password,
  1107. APP.settings.getDisplayName()
  1108. );
  1109. });
  1110. room.on(
  1111. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1112. APP.UI.updateDevicesAvailability(id, devices);
  1113. }
  1114. );
  1115. // call hangup
  1116. APP.UI.addListener(UIEvents.HANGUP, () => {
  1117. hangup(true);
  1118. });
  1119. // logout
  1120. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1121. AuthHandler.logout(room).then(function (url) {
  1122. if (url) {
  1123. window.location.href = url;
  1124. } else {
  1125. hangup(true);
  1126. }
  1127. });
  1128. });
  1129. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1130. room.dial(sipNumber);
  1131. });
  1132. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1133. (id, oldResolution, newResolution, delay) => {
  1134. room.sendApplicationLog("Resolution change id=" + id
  1135. + " old=" + oldResolution + " new=" + newResolution
  1136. + " delay=" + delay);
  1137. });
  1138. // Starts or stops the recording for the conference.
  1139. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1140. room.toggleRecording(options);
  1141. });
  1142. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1143. room.setSubject(topic);
  1144. });
  1145. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1146. APP.UI.setSubject(subject);
  1147. });
  1148. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1149. room.kickParticipant(id);
  1150. });
  1151. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1152. room.muteParticipant(id);
  1153. });
  1154. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1155. AuthHandler.authenticate(room);
  1156. });
  1157. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1158. try {
  1159. room.selectParticipant(id);
  1160. } catch (e) {
  1161. AnalyticsAdapter.sendEvent('selectParticipant.failed');
  1162. reportError(e);
  1163. }
  1164. });
  1165. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1166. var smallVideoId = smallVideo.getId();
  1167. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1168. && !APP.conference.isLocalId(smallVideoId)) {
  1169. // When the library starts supporting multiple pins we would
  1170. // pass the isPinned parameter together with the identifier,
  1171. // but currently we send null to indicate that we unpin the
  1172. // last pinned.
  1173. try {
  1174. room.pinParticipant(isPinned ? smallVideoId : null);
  1175. } catch (e) {
  1176. reportError(e);
  1177. }
  1178. }
  1179. });
  1180. APP.UI.addListener(
  1181. UIEvents.VIDEO_DEVICE_CHANGED,
  1182. (cameraDeviceId) => {
  1183. AnalyticsAdapter.sendEvent('settings.changeDevice.video');
  1184. createLocalTracks({
  1185. devices: ['video'],
  1186. cameraDeviceId: cameraDeviceId,
  1187. micDeviceId: null
  1188. })
  1189. .then(([stream]) => {
  1190. this.useVideoStream(stream);
  1191. console.log('switched local video device');
  1192. APP.settings.setCameraDeviceId(cameraDeviceId);
  1193. })
  1194. .catch((err) => {
  1195. APP.UI.showDeviceErrorDialog(null, err);
  1196. APP.UI.setSelectedCameraFromSettings();
  1197. });
  1198. }
  1199. );
  1200. APP.UI.addListener(
  1201. UIEvents.AUDIO_DEVICE_CHANGED,
  1202. (micDeviceId) => {
  1203. AnalyticsAdapter.sendEvent('settings.changeDevice.audioIn');
  1204. createLocalTracks({
  1205. devices: ['audio'],
  1206. cameraDeviceId: null,
  1207. micDeviceId: micDeviceId
  1208. })
  1209. .then(([stream]) => {
  1210. this.useAudioStream(stream);
  1211. console.log('switched local audio device');
  1212. APP.settings.setMicDeviceId(micDeviceId);
  1213. })
  1214. .catch((err) => {
  1215. APP.UI.showDeviceErrorDialog(err, null);
  1216. APP.UI.setSelectedMicFromSettings();
  1217. });
  1218. }
  1219. );
  1220. APP.UI.addListener(
  1221. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1222. (audioOutputDeviceId) => {
  1223. AnalyticsAdapter.sendEvent('settings.changeDevice.audioOut');
  1224. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1225. .then(() => console.log('changed audio output device'))
  1226. .catch((err) => {
  1227. console.warn('Failed to change audio output device. ' +
  1228. 'Default or previously set audio output device ' +
  1229. 'will be used instead.', err);
  1230. APP.UI.setSelectedAudioOutputFromSettings();
  1231. });
  1232. }
  1233. );
  1234. APP.UI.addListener(
  1235. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1236. );
  1237. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1238. (url, state, time, isMuted, volume) => {
  1239. // send start and stop commands once, and remove any updates
  1240. // that had left
  1241. if (state === 'stop' || state === 'start' || state === 'playing') {
  1242. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1243. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1244. value: url,
  1245. attributes: {
  1246. state: state,
  1247. time: time,
  1248. muted: isMuted,
  1249. volume: volume
  1250. }
  1251. });
  1252. }
  1253. else {
  1254. // in case of paused, in order to allow late users to join
  1255. // paused
  1256. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1257. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1258. value: url,
  1259. attributes: {
  1260. state: state,
  1261. time: time,
  1262. muted: isMuted,
  1263. volume: volume
  1264. }
  1265. });
  1266. }
  1267. });
  1268. room.addCommandListener(
  1269. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1270. if (attributes.state === 'stop') {
  1271. APP.UI.onSharedVideoStop(id, attributes);
  1272. }
  1273. else if (attributes.state === 'start') {
  1274. APP.UI.onSharedVideoStart(id, value, attributes);
  1275. }
  1276. else if (attributes.state === 'playing'
  1277. || attributes.state === 'pause') {
  1278. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1279. }
  1280. });
  1281. },
  1282. /**
  1283. * Adds any room listener.
  1284. * @param eventName one of the ConferenceEvents
  1285. * @param callBack the function to be called when the event occurs
  1286. */
  1287. addConferenceListener(eventName, callBack) {
  1288. room.on(eventName, callBack);
  1289. },
  1290. /**
  1291. * Inits list of current devices and event listener for device change.
  1292. * @private
  1293. */
  1294. _initDeviceList() {
  1295. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1296. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1297. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1298. // Ugly way to synchronize real device IDs with local
  1299. // storage and settings menu. This is a workaround until
  1300. // getConstraints() method will be implemented in browsers.
  1301. if (localAudio) {
  1302. localAudio._setRealDeviceIdFromDeviceList(devices);
  1303. APP.settings.setMicDeviceId(localAudio.getDeviceId());
  1304. }
  1305. if (localVideo) {
  1306. localVideo._setRealDeviceIdFromDeviceList(devices);
  1307. APP.settings.setCameraDeviceId(localVideo.getDeviceId());
  1308. }
  1309. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1310. APP.UI.onAvailableDevicesChanged(devices);
  1311. });
  1312. JitsiMeetJS.mediaDevices.addEventListener(
  1313. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1314. (devices) =>
  1315. window.setTimeout(
  1316. () => this._onDeviceListChanged(devices), 0));
  1317. }
  1318. },
  1319. /**
  1320. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1321. * handle change of available media devices.
  1322. * @private
  1323. * @param {MediaDeviceInfo[]} devices
  1324. * @returns {Promise}
  1325. */
  1326. _onDeviceListChanged(devices) {
  1327. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1328. // Event handler can be fired before direct
  1329. // enumerateDevices() call, so handle this situation here.
  1330. if (!currentDevices.audioinput &&
  1331. !currentDevices.videoinput &&
  1332. !currentDevices.audiooutput) {
  1333. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1334. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1335. }
  1336. let newDevices =
  1337. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1338. devices, this.isSharingScreen, localVideo, localAudio);
  1339. let promises = [];
  1340. let audioWasMuted = this.audioMuted;
  1341. let videoWasMuted = this.videoMuted;
  1342. let availableAudioInputDevices =
  1343. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1344. let availableVideoInputDevices =
  1345. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1346. if (typeof newDevices.audiooutput !== 'undefined') {
  1347. // Just ignore any errors in catch block.
  1348. promises.push(APP.settings
  1349. .setAudioOutputDeviceId(newDevices.audiooutput)
  1350. .catch());
  1351. }
  1352. promises.push(
  1353. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1354. createLocalTracks,
  1355. newDevices.videoinput,
  1356. newDevices.audioinput)
  1357. .then(tracks =>
  1358. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1359. .then(() => {
  1360. // If audio was muted before, or we unplugged current device
  1361. // and selected new one, then mute new audio track.
  1362. if (audioWasMuted ||
  1363. currentDevices.audioinput.length >
  1364. availableAudioInputDevices.length) {
  1365. muteLocalAudio(true);
  1366. }
  1367. // If video was muted before, or we unplugged current device
  1368. // and selected new one, then mute new video track.
  1369. if (videoWasMuted ||
  1370. currentDevices.videoinput.length >
  1371. availableVideoInputDevices.length) {
  1372. muteLocalVideo(true);
  1373. }
  1374. }));
  1375. return Promise.all(promises)
  1376. .then(() => {
  1377. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1378. APP.UI.onAvailableDevicesChanged(devices);
  1379. });
  1380. },
  1381. /**
  1382. * Toggles the local "raised hand" status, if the current state allows
  1383. * toggling.
  1384. */
  1385. maybeToggleRaisedHand() {
  1386. // If we are the dominant speaker, we don't enable "raise hand".
  1387. if (this.isHandRaised || !this.isDominantSpeaker) {
  1388. this.setRaisedHand(!this.isHandRaised);
  1389. }
  1390. },
  1391. /**
  1392. * Sets the local "raised hand" status to a particular value.
  1393. */
  1394. setRaisedHand(raisedHand) {
  1395. if (raisedHand !== this.isHandRaised)
  1396. {
  1397. this.isHandRaised = raisedHand;
  1398. // Advertise the updated status
  1399. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1400. // Update the view
  1401. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1402. }
  1403. }
  1404. };