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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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.PASSWORD_REQUIRED, function () {
  301. // FIXME handle
  302. });
  303. room.on(ConferenceErrors.CONNECTION_ERROR, function () {
  304. // FIXME handle
  305. });
  306. APP.UI.addListener(
  307. UIEvents.START_MUTED_CHANGED,
  308. function (startAudioMuted, startVideoMuted) {
  309. // FIXME start muted
  310. }
  311. );
  312. APP.UI.addListener(UIEvents.USER_INVITED, function (roomUrl) {
  313. inviteParticipants(
  314. roomUrl,
  315. APP.conference.roomName,
  316. roomLocker.password,
  317. APP.settings.getDisplayName()
  318. );
  319. });
  320. return new Promise(function (resolve, reject) {
  321. room.on(ConferenceEvents.CONFERENCE_JOINED, resolve);
  322. room.on(ConferenceErrors.ROOM_PASSWORD_REQUIRED, function () {
  323. APP.UI.markRoomLocked(true);
  324. roomLocker.requirePassword().then(function () {
  325. room.join(roomLocker.password);
  326. });
  327. });
  328. APP.UI.closeAuthenticationDialog();
  329. room.join();
  330. }).catch(function (err) {
  331. if (err[0] === ConferenceErrors.PASSWORD_REQUIRED) {
  332. // FIXME ask for password and try again
  333. return initConference(localTracks, connection);
  334. }
  335. // FIXME else notify that we cannot conenct to the room
  336. throw new Error(err[0]);
  337. });
  338. }
  339. function createLocalTracks () {
  340. return JitsiMeetJS.createLocalTracks({
  341. devices: ['audio', 'video']
  342. }).catch(function (err) {
  343. console.error('failed to create local tracks', err);
  344. return [];
  345. });
  346. }
  347. function init() {
  348. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  349. JitsiMeetJS.init().then(function () {
  350. return Promise.all([createLocalTracks(), connect()]);
  351. }).then(function ([tracks, connection]) {
  352. console.log('initialized with %s local tracks', tracks.length);
  353. return initConference(tracks, connection);
  354. }).then(function () {
  355. APP.UI.start();
  356. APP.UI.initConference();
  357. APP.UI.addListener(UIEvents.LANG_CHANGED, function (language) {
  358. APP.translation.setLanguage(language);
  359. APP.settings.setLanguage(language);
  360. });
  361. APP.desktopsharing.init();
  362. APP.statistics.start();
  363. APP.connectionquality.init();
  364. APP.keyboardshortcut.init();
  365. });
  366. }
  367. /**
  368. * If we have an HTTP endpoint for getting config.json configured we're going to
  369. * read it and override properties from config.js and interfaceConfig.js.
  370. * If there is no endpoint we'll just continue with initialization.
  371. * Keep in mind that if the endpoint has been configured and we fail to obtain
  372. * the config for any reason then the conference won't start and error message
  373. * will be displayed to the user.
  374. */
  375. function obtainConfigAndInit() {
  376. let roomName = APP.conference.roomName;
  377. if (config.configLocation) {
  378. APP.configFetch.obtainConfig(
  379. config.configLocation, roomName,
  380. // Get config result callback
  381. function(success, error) {
  382. if (success) {
  383. console.log("(TIME) configuration fetched:\t",
  384. window.performance.now());
  385. init();
  386. } else {
  387. // Show obtain config error,
  388. // pass the error object for report
  389. APP.UI.messageHandler.openReportDialog(
  390. null, "dialog.connectError", error);
  391. }
  392. });
  393. } else {
  394. require("./modules/config/BoshAddressChoice").chooseAddress(
  395. config, roomName);
  396. init();
  397. }
  398. }
  399. $(document).ready(function () {
  400. console.log("(TIME) document ready:\t", window.performance.now());
  401. var URLProcessor = require("./modules/config/URLProcessor");
  402. URLProcessor.setConfigParametersFromUrl();
  403. APP.init();
  404. APP.translation.init();
  405. if (APP.API.isEnabled()) {
  406. APP.API.init();
  407. }
  408. obtainConfigAndInit();
  409. });
  410. $(window).bind('beforeunload', function () {
  411. if (APP.API.isEnabled()) {
  412. APP.API.dispose();
  413. }
  414. });
  415. /**
  416. * Invite participants to conference.
  417. */
  418. function inviteParticipants(roomUrl, conferenceName, key, nick) {
  419. let keyText = "";
  420. if (key) {
  421. keyText = APP.translation.translateString(
  422. "email.sharedKey", {sharedKey: key}
  423. );
  424. }
  425. let and = APP.translation.translateString("email.and");
  426. let supportedBrowsers = `Chromium, Google Chrome ${and} Opera`;
  427. let subject = APP.translation.translateString(
  428. "email.subject", {appName:interfaceConfig.APP_NAME, conferenceName}
  429. );
  430. let body = APP.translation.translateString(
  431. "email.body", {
  432. appName:interfaceConfig.APP_NAME,
  433. sharedKeyText: keyText,
  434. roomUrl,
  435. supportedBrowsers
  436. }
  437. );
  438. body = body.replace(/\n/g, "%0D%0A");
  439. if (nick) {
  440. body += "%0D%0A%0D%0A" + nick;
  441. }
  442. if (interfaceConfig.INVITATION_POWERED_BY) {
  443. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  444. }
  445. window.open(`mailto:?subject=${subject}&body=${body}`, '_blank');
  446. }
  447. export default APP;