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.

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