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 61KB

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