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

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