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

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