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

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