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

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