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

conference.js 57KB

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