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

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