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

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