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.

app.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /* global $, JitsiMeetJS, config, interfaceConfig */
  2. /* application specific logic */
  3. import "babel-polyfill";
  4. import "jquery";
  5. import "jquery-ui";
  6. import "strophe";
  7. import "strophe-disco";
  8. import "strophe-caps";
  9. import "tooltip";
  10. import "popover";
  11. import "jQuery-Impromptu";
  12. import "autosize";
  13. window.toastr = require("toastr");
  14. import URLProcessor from "./modules/config/URLProcessor";
  15. import RoomnameGenerator from './modules/util/RoomnameGenerator';
  16. import CQEvents from './service/connectionquality/CQEvents';
  17. import UIEvents from './service/UI/UIEvents';
  18. import {openConnection} from './modules/connection';
  19. import AuthHandler from './modules/AuthHandler';
  20. import createRoomLocker from './modules/RoomLocker';
  21. const DesktopSharingEventTypes =
  22. require("./service/desktopsharing/DesktopSharingEventTypes");
  23. const ConnectionEvents = JitsiMeetJS.events.connection;
  24. const ConnectionErrors = JitsiMeetJS.errors.connection;
  25. const ConferenceEvents = JitsiMeetJS.events.conference;
  26. const ConferenceErrors = JitsiMeetJS.errors.conference;
  27. const TrackEvents = JitsiMeetJS.events.track;
  28. const TrackErrors = JitsiMeetJS.errors.track;
  29. let localVideo, localAudio;
  30. const Commands = {
  31. CONNECTION_QUALITY: "connectionQuality",
  32. EMAIL: "email",
  33. VIDEO_TYPE: "videoType"
  34. };
  35. function buildRoomName () {
  36. let path = window.location.pathname;
  37. let roomName;
  38. // determinde the room node from the url
  39. // TODO: just the roomnode or the whole bare jid?
  40. if (config.getroomnode && typeof config.getroomnode === 'function') {
  41. // custom function might be responsible for doing the pushstate
  42. roomName = config.getroomnode(path);
  43. } else {
  44. /* fall back to default strategy
  45. * this is making assumptions about how the URL->room mapping happens.
  46. * It currently assumes deployment at root, with a rewrite like the
  47. * following one (for nginx):
  48. location ~ ^/([a-zA-Z0-9]+)$ {
  49. rewrite ^/(.*)$ / break;
  50. }
  51. */
  52. if (path.length > 1) {
  53. roomName = path.substr(1).toLowerCase();
  54. } else {
  55. let word = RoomnameGenerator.generateRoomWithoutSeparator();
  56. roomName = word.toLowerCase();
  57. window.history.pushState(
  58. 'VideoChat', `Room: ${word}`, window.location.pathname + word
  59. );
  60. }
  61. }
  62. return roomName;
  63. }
  64. const APP = {
  65. init () {
  66. let roomName = buildRoomName();
  67. this.conference = {
  68. roomName,
  69. localId: undefined,
  70. isModerator: false,
  71. membersCount: 0,
  72. audioMuted: false,
  73. videoMuted: false,
  74. isLocalId (id) {
  75. return this.localId === id;
  76. },
  77. muteAudio (mute) {
  78. APP.UI.eventEmitter.emit(UIEvents.AUDIO_MUTED, mute);
  79. },
  80. toggleAudioMuted () {
  81. this.muteAudio(!this.audioMuted);
  82. },
  83. muteVideo (mute) {
  84. APP.UI.eventEmitter.emit(UIEvents.VIDEO_MUTED, mute);
  85. },
  86. toggleVideoMuted () {
  87. this.muteVideo(!this.videoMuted);
  88. }
  89. };
  90. this.UI = require("./modules/UI/UI");
  91. this.API = require("./modules/API/API");
  92. this.connectionquality =
  93. require("./modules/connectionquality/connectionquality");
  94. this.statistics = require("./modules/statistics/statistics");
  95. this.desktopsharing =
  96. require("./modules/desktopsharing/desktopsharing");
  97. this.keyboardshortcut =
  98. require("./modules/keyboardshortcut/keyboardshortcut");
  99. this.translation = require("./modules/translation/translation");
  100. this.settings = require("./modules/settings/Settings");
  101. this.configFetch = require("./modules/config/HttpConfigFetch");
  102. }
  103. };
  104. function initConference(localTracks, connection) {
  105. let room = connection.initJitsiConference(APP.conference.roomName, {
  106. openSctp: config.openSctp,
  107. disableAudioLevels: config.disableAudioLevels
  108. });
  109. const addTrack = (track) => {
  110. room.addTrack(track);
  111. if(track.getType() === "audio")
  112. return;
  113. room.removeCommand(Commands.VIDEO_TYPE);
  114. room.sendCommand(Commands.VIDEO_TYPE, {
  115. value: track.videoType,
  116. attributes: {
  117. xmlns: 'http://jitsi.org/jitmeet/video'
  118. }
  119. });
  120. };
  121. APP.conference.localId = room.myUserId();
  122. Object.defineProperty(APP.conference, "membersCount", {
  123. get: function () {
  124. return room.getParticipants().length; // FIXME maybe +1?
  125. }
  126. });
  127. APP.conference.listMembers = function () {
  128. return room.getParticipants();
  129. };
  130. APP.conference.listMembersIds = function () {
  131. return room.getParticipants().map(p => p.getId());
  132. };
  133. /**
  134. * Creates video track (desktop or camera).
  135. * @param type "camera" or "video"
  136. * @param endedHandler onended function
  137. * @returns Promise
  138. */
  139. APP.conference.createVideoTrack = (type, endedHandler) => {
  140. return JitsiMeetJS.createLocalTracks({
  141. devices: [type], resolution: config.resolution
  142. }).then((tracks) => {
  143. tracks[0].on(TrackEvents.TRACK_STOPPED, endedHandler);
  144. return tracks;
  145. });
  146. };
  147. APP.conference.changeLocalVideo = (track, callback) => {
  148. const localCallback = (newTrack) => {
  149. if (newTrack.isLocal() && newTrack === localVideo) {
  150. if(localVideo.isMuted() &&
  151. localVideo.videoType !== track.videoType) {
  152. localVideo.mute();
  153. }
  154. callback();
  155. room.off(ConferenceEvents.TRACK_ADDED, localCallback);
  156. }
  157. };
  158. room.on(ConferenceEvents.TRACK_ADDED, localCallback);
  159. localVideo.stop();
  160. localVideo = track;
  161. addTrack(track);
  162. APP.UI.addLocalStream(track);
  163. };
  164. APP.conference.sipGatewayEnabled = () => {
  165. return room.isSIPCallingSupported();
  166. };
  167. function getDisplayName(id) {
  168. if (APP.conference.isLocalId(id)) {
  169. return APP.settings.getDisplayName();
  170. }
  171. var participant = room.getParticipantById(id);
  172. if (participant && participant.getDisplayName()) {
  173. return participant.getDisplayName();
  174. }
  175. }
  176. // add local streams when joined to the conference
  177. room.on(ConferenceEvents.CONFERENCE_JOINED, function () {
  178. localTracks.forEach(function (track) {
  179. if(track.getType() === "audio") {
  180. localAudio = track;
  181. }
  182. else if (track.getType() === "video") {
  183. localVideo = track;
  184. }
  185. addTrack(track);
  186. APP.UI.addLocalStream(track);
  187. });
  188. APP.UI.updateAuthInfo(room.isAuthEnabled(), room.getAuthLogin());
  189. });
  190. room.on(ConferenceEvents.USER_JOINED, function (id, user) {
  191. if (APP.conference.isLocalId(id)) {
  192. return;
  193. }
  194. console.error('USER %s connnected', id);
  195. // FIXME email???
  196. APP.UI.addUser(id, user.getDisplayName());
  197. });
  198. room.on(ConferenceEvents.USER_LEFT, function (id, user) {
  199. console.error('USER LEFT', id);
  200. APP.UI.removeUser(id, user.getDisplayName());
  201. });
  202. room.on(ConferenceEvents.USER_ROLE_CHANGED, function (id, role) {
  203. if (APP.conference.isLocalId(id)) {
  204. console.info(`My role changed, new role: ${role}`);
  205. APP.conference.isModerator = room.isModerator();
  206. APP.UI.updateLocalRole(room.isModerator());
  207. } else {
  208. var user = room.getParticipantById(id);
  209. if (user) {
  210. APP.UI.updateUserRole(user);
  211. }
  212. }
  213. });
  214. let roomLocker = createRoomLocker(room);
  215. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, function () {
  216. if (room.isModerator()) {
  217. let promise = roomLocker.isLocked
  218. ? roomLocker.askToUnlock()
  219. : roomLocker.askToLock();
  220. promise.then(function () {
  221. APP.UI.markRoomLocked(roomLocker.isLocked);
  222. });
  223. } else {
  224. roomLocker.notifyModeratorRequired();
  225. }
  226. });
  227. room.on(ConferenceEvents.TRACK_ADDED, function (track) {
  228. if (track.isLocal()) { // skip local tracks
  229. return;
  230. }
  231. console.error(
  232. 'REMOTE %s TRACK', track.getType(), track.getParticipantId()
  233. );
  234. APP.UI.addRemoteStream(track);
  235. });
  236. room.on(ConferenceEvents.TRACK_REMOVED, function (track) {
  237. if (track.isLocal()) { // skip local tracks
  238. return;
  239. }
  240. console.error(
  241. 'REMOTE %s TRACK REMOVED', track.getType(), track.getParticipantId()
  242. );
  243. // FIXME handle
  244. });
  245. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, function (track) {
  246. // FIXME handle mute
  247. });
  248. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, function (id, lvl) {
  249. APP.UI.setAudioLevel(id, lvl);
  250. });
  251. APP.UI.addListener(UIEvents.AUDIO_MUTED, function (muted) {
  252. // FIXME mute or unmute
  253. APP.UI.setAudioMuted(muted);
  254. APP.conference.audioMuted = muted;
  255. });
  256. APP.UI.addListener(UIEvents.VIDEO_MUTED, function (muted) {
  257. // FIXME mute or unmute
  258. APP.UI.setVideoMuted(muted);
  259. APP.conference.videoMuted = muted;
  260. });
  261. room.on(ConferenceEvents.IN_LAST_N_CHANGED, function (inLastN) {
  262. if (config.muteLocalVideoIfNotInLastN) {
  263. // TODO mute or unmute if required
  264. // mark video on UI
  265. // APP.UI.markVideoMuted(true/false);
  266. }
  267. });
  268. room.on(ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, function (ids) {
  269. APP.UI.handleLastNEndpoints(ids);
  270. });
  271. room.on(ConferenceEvents.ACTIVE_SPEAKER_CHANGED, function (id) {
  272. APP.UI.markDominantSpiker(id);
  273. });
  274. if (!interfaceConfig.filmStripOnly) {
  275. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, function () {
  276. APP.UI.markVideoInterrupted(true);
  277. });
  278. room.on(ConferenceEvents.CONNECTION_RESTORED, function () {
  279. APP.UI.markVideoInterrupted(false);
  280. });
  281. APP.UI.addListener(UIEvents.MESSAGE_CREATED, function (message) {
  282. room.sendTextMessage(message);
  283. });
  284. room.on(ConferenceEvents.MESSAGE_RECEIVED, function (id, text, ts) {
  285. APP.UI.addMessage(id, getDisplayName(id), text, ts);
  286. });
  287. }
  288. APP.connectionquality.addListener(
  289. CQEvents.LOCALSTATS_UPDATED,
  290. function (percent, stats) {
  291. APP.UI.updateLocalStats(percent, stats);
  292. // send local stats to other users
  293. room.sendCommand(Commands.CONNECTION_QUALITY, {
  294. value: APP.connectionquality.convertToMUCStats(stats),
  295. attributes: {
  296. id: room.myUserId()
  297. }
  298. });
  299. }
  300. );
  301. APP.connectionquality.addListener(CQEvents.STOP, function () {
  302. APP.UI.hideStats();
  303. room.removeCommand(Commands.CONNECTION_QUALITY);
  304. });
  305. // listen to remote stats
  306. room.addCommandListener(Commands.CONNECTION_QUALITY, function (data) {
  307. APP.connectionquality.updateRemoteStats(data.attributes.id, data.value);
  308. });
  309. APP.connectionquality.addListener(
  310. CQEvents.REMOTESTATS_UPDATED,
  311. function (id, percent, stats) {
  312. APP.UI.updateRemoteStats(id, percent, stats);
  313. }
  314. );
  315. room.addCommandListener(Commands.VIDEO_TYPE, (data, from) => {
  316. APP.UI.onPeerVideoTypeChanged(from, data.value);
  317. });
  318. // share email with other users
  319. function sendEmail(email) {
  320. room.sendCommand(Commands.EMAIL, {
  321. value: email,
  322. attributes: {
  323. id: room.myUserId()
  324. }
  325. });
  326. }
  327. var email = APP.settings.getEmail();
  328. email && sendEmail(email);
  329. APP.UI.addListener(UIEvents.EMAIL_CHANGED, function (email) {
  330. APP.settings.setEmail(email);
  331. APP.UI.setUserAvatar(room.myUserId(), email);
  332. sendEmail(email);
  333. });
  334. room.addCommandListener(Commands.EMAIL, function (data) {
  335. APP.UI.setUserAvatar(data.attributes.id, data.value);
  336. });
  337. let nick = APP.settings.getDisplayName();
  338. if (config.useNicks && !nick) {
  339. nick = APP.UI.askForNickname();
  340. APP.settings.setDisplayName(nick);
  341. }
  342. if (nick) {
  343. room.setDisplayName(nick);
  344. }
  345. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, function (id, displayName) {
  346. APP.UI.changeDisplayName(id, displayName);
  347. });
  348. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  349. APP.settings.setDisplayName(nickname);
  350. room.setDisplayName(nickname);
  351. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  352. });
  353. APP.UI.addListener(
  354. UIEvents.START_MUTED_CHANGED,
  355. function (startAudioMuted, startVideoMuted) {
  356. // FIXME start muted
  357. }
  358. );
  359. APP.UI.addListener(UIEvents.USER_INVITED, function (roomUrl) {
  360. APP.UI.inviteParticipants(
  361. roomUrl,
  362. APP.conference.roomName,
  363. roomLocker.password,
  364. APP.settings.getDisplayName()
  365. );
  366. });
  367. // call hangup
  368. APP.UI.addListener(UIEvents.HANGUP, function () {
  369. APP.UI.requestFeedback().then(function () {
  370. connection.disconnect();
  371. if (config.enableWelcomePage) {
  372. setTimeout(function() {
  373. window.localStorage.welcomePageDisabled = false;
  374. window.location.pathname = "/";
  375. }, 3000);
  376. }
  377. });
  378. });
  379. // logout
  380. APP.UI.addListener(UIEvents.LOGOUT, function () {
  381. // FIXME handle logout
  382. // APP.xmpp.logout(function (url) {
  383. // if (url) {
  384. // window.location.href = url;
  385. // } else {
  386. // hangup();
  387. // }
  388. // });
  389. });
  390. APP.UI.addListener(UIEvents.SIP_DIAL, function (sipNumber) {
  391. room.dial(sipNumber);
  392. });
  393. // Starts or stops the recording for the conference.
  394. APP.UI.addListener(UIEvents.RECORDING_TOGGLE, function (predefinedToken) {
  395. // FIXME recording
  396. // APP.xmpp.toggleRecording(function (callback) {
  397. // if (predefinedToken) {
  398. // callback(predefinedToken);
  399. // return;
  400. // }
  401. // APP.UI.requestRecordingToken().then(callback);
  402. // }, APP.UI.updateRecordingState);
  403. });
  404. APP.UI.addListener(UIEvents.TOPIC_CHANGED, function (topic) {
  405. // FIXME handle topic change
  406. // APP.xmpp.setSubject(topic);
  407. // on SUBJECT_CHANGED UI.setSubject(topic);
  408. });
  409. APP.UI.addListener(UIEvents.USER_KICKED, function (id) {
  410. room.kickParticipant(id);
  411. });
  412. room.on(ConferenceEvents.KICKED, function () {
  413. APP.UI.notifyKicked();
  414. // FIXME close
  415. });
  416. APP.UI.addListener(UIEvents.AUTH_CLICKED, function () {
  417. AuthHandler.authenticate(room);
  418. });
  419. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, function (id) {
  420. room.selectParticipant(id);
  421. });
  422. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, function (isDTMFSupported) {
  423. APP.UI.updateDTMFSupport(isDTMFSupported);
  424. });
  425. $(window).bind('beforeunload', function () {
  426. room.leave();
  427. });
  428. return new Promise(function (resolve, reject) {
  429. room.on(ConferenceEvents.CONFERENCE_JOINED, handleConferenceJoined);
  430. room.on(ConferenceEvents.CONFERENCE_FAILED, onConferenceFailed);
  431. let password;
  432. let reconnectTimeout;
  433. function unsubscribe() {
  434. room.off(
  435. ConferenceEvents.CONFERENCE_JOINED, handleConferenceJoined
  436. );
  437. room.off(
  438. ConferenceEvents.CONFERENCE_FAILED, onConferenceFailed
  439. );
  440. if (reconnectTimeout) {
  441. clearTimeout(reconnectTimeout);
  442. }
  443. AuthHandler.closeAuth();
  444. }
  445. function handleConferenceJoined() {
  446. unsubscribe();
  447. resolve();
  448. }
  449. function handleConferenceFailed(err) {
  450. unsubscribe();
  451. reject(err);
  452. }
  453. function onConferenceFailed(err, msg = '') {
  454. console.error('CONFERENCE FAILED:', err, msg);
  455. switch (err) {
  456. // room is locked by the password
  457. case ConferenceErrors.PASSWORD_REQUIRED:
  458. APP.UI.markRoomLocked(true);
  459. roomLocker.requirePassword().then(function () {
  460. room.join(roomLocker.password);
  461. });
  462. break;
  463. case ConferenceErrors.CONNECTION_ERROR:
  464. APP.UI.notifyConnectionFailed(msg);
  465. break;
  466. // not enough rights to create conference
  467. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  468. // schedule reconnect to check if someone else created the room
  469. reconnectTimeout = setTimeout(function () {
  470. room.join(password);
  471. }, 5000);
  472. // notify user that auth is required
  473. AuthHandler.requireAuth(APP.conference.roomName);
  474. break;
  475. default:
  476. handleConferenceFailed(err);
  477. }
  478. }
  479. room.join(password);
  480. });
  481. }
  482. function createLocalTracks () {
  483. return JitsiMeetJS.createLocalTracks({
  484. devices: ['audio', 'video']
  485. }).catch(function (err) {
  486. console.error('failed to create local tracks', err);
  487. return [];
  488. });
  489. }
  490. function connect() {
  491. return openConnection({retry: true}).catch(function (err) {
  492. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  493. APP.UI.notifyTokenAuthFailed();
  494. } else {
  495. APP.UI.notifyConnectionFailed(err);
  496. }
  497. throw err;
  498. });
  499. }
  500. function init() {
  501. APP.UI.start();
  502. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  503. JitsiMeetJS.init(config).then(function () {
  504. return Promise.all([createLocalTracks(), connect()]);
  505. }).then(function ([tracks, connection]) {
  506. console.log('initialized with %s local tracks', tracks.length);
  507. return initConference(tracks, connection);
  508. }).then(function () {
  509. APP.UI.initConference();
  510. APP.UI.addListener(UIEvents.LANG_CHANGED, function (language) {
  511. APP.translation.setLanguage(language);
  512. APP.settings.setLanguage(language);
  513. });
  514. APP.desktopsharing.addListener(
  515. DesktopSharingEventTypes.NEW_STREAM_CREATED,
  516. (stream, callback) => {
  517. APP.conference.changeLocalVideo(stream,
  518. callback);
  519. });
  520. APP.desktopsharing.init(JitsiMeetJS.isDesktopSharingEnabled());
  521. APP.statistics.start();
  522. APP.connectionquality.init();
  523. APP.keyboardshortcut.init();
  524. }).catch(function (err) {
  525. console.error(err);
  526. });
  527. }
  528. /**
  529. * If we have an HTTP endpoint for getting config.json configured we're going to
  530. * read it and override properties from config.js and interfaceConfig.js.
  531. * If there is no endpoint we'll just continue with initialization.
  532. * Keep in mind that if the endpoint has been configured and we fail to obtain
  533. * the config for any reason then the conference won't start and error message
  534. * will be displayed to the user.
  535. */
  536. function obtainConfigAndInit() {
  537. let roomName = APP.conference.roomName;
  538. if (config.configLocation) {
  539. APP.configFetch.obtainConfig(
  540. config.configLocation, roomName,
  541. // Get config result callback
  542. function(success, error) {
  543. if (success) {
  544. console.log("(TIME) configuration fetched:\t",
  545. window.performance.now());
  546. init();
  547. } else {
  548. // Show obtain config error,
  549. // pass the error object for report
  550. APP.UI.messageHandler.openReportDialog(
  551. null, "dialog.connectError", error);
  552. }
  553. });
  554. } else {
  555. require("./modules/config/BoshAddressChoice").chooseAddress(
  556. config, roomName);
  557. init();
  558. }
  559. }
  560. $(document).ready(function () {
  561. console.log("(TIME) document ready:\t", window.performance.now());
  562. URLProcessor.setConfigParametersFromUrl();
  563. APP.init();
  564. APP.translation.init();
  565. if (APP.API.isEnabled()) {
  566. APP.API.init();
  567. }
  568. obtainConfigAndInit();
  569. });
  570. $(window).bind('beforeunload', function () {
  571. if (APP.API.isEnabled()) {
  572. APP.API.dispose();
  573. }
  574. });
  575. module.exports = APP;