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

conference.js 58KB

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