Changes of Linux canary v0.0.68
This commit is contained in:
parent
e018d704db
commit
1f1a9df8e9
28 changed files with 709 additions and 1115 deletions
|
@ -4,28 +4,25 @@
|
|||
// after startup, these constants will be merged into core module constants
|
||||
// since they are used in both locations (see app/Constants.js)
|
||||
|
||||
var _require = require('./buildInfo'),
|
||||
releaseChannel = _require.releaseChannel;
|
||||
const { releaseChannel } = require('./buildInfo');
|
||||
const { getSettings } = require('./appSettings');
|
||||
|
||||
var _require2 = require('./appSettings'),
|
||||
getSettings = _require2.getSettings;
|
||||
|
||||
var settings = getSettings();
|
||||
const settings = getSettings();
|
||||
|
||||
function capitalizeFirstLetter(s) {
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
}
|
||||
|
||||
var APP_NAME = 'Discord' + (releaseChannel === 'stable' ? '' : capitalizeFirstLetter(releaseChannel));
|
||||
var APP_ID_BASE = 'com.squirrel';
|
||||
var APP_ID = APP_ID_BASE + '.' + APP_NAME + '.' + APP_NAME;
|
||||
const APP_NAME = 'Discord' + (releaseChannel === 'stable' ? '' : capitalizeFirstLetter(releaseChannel));
|
||||
const APP_ID_BASE = 'com.squirrel';
|
||||
const APP_ID = `${APP_ID_BASE}.${APP_NAME}.${APP_NAME}`;
|
||||
|
||||
var API_ENDPOINT = settings.get('API_ENDPOINT') || 'https://discordapp.com/api';
|
||||
var UPDATE_ENDPOINT = settings.get('UPDATE_ENDPOINT') || API_ENDPOINT;
|
||||
const API_ENDPOINT = settings.get('API_ENDPOINT') || 'https://discordapp.com/api';
|
||||
const UPDATE_ENDPOINT = settings.get('UPDATE_ENDPOINT') || API_ENDPOINT;
|
||||
|
||||
module.exports = {
|
||||
APP_NAME: APP_NAME,
|
||||
APP_ID: APP_ID,
|
||||
API_ENDPOINT: API_ENDPOINT,
|
||||
UPDATE_ENDPOINT: UPDATE_ENDPOINT
|
||||
APP_NAME,
|
||||
APP_ID,
|
||||
API_ENDPOINT,
|
||||
UPDATE_ENDPOINT
|
||||
};
|
|
@ -11,28 +11,7 @@
|
|||
exports.replace = function (GPUSettings) {
|
||||
// replacing module.exports directly would have no effect, since requires are cached
|
||||
// so we mutate the existing object
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = Object.keys(GPUSettings)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var name = _step.value;
|
||||
|
||||
exports[name] = GPUSettings[name];
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
for (const name of Object.keys(GPUSettings)) {
|
||||
exports[name] = GPUSettings[name];
|
||||
}
|
||||
};
|
|
@ -18,7 +18,7 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj;
|
|||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
var settings = void 0;
|
||||
let settings;
|
||||
|
||||
function init() {
|
||||
settings = new _Settings2.default(paths.getUserData());
|
||||
|
|
|
@ -27,7 +27,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
|
|||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function update(startMinimized, doneCallback, showCallback) {
|
||||
var settings = (0, _appSettings.getSettings)();
|
||||
const settings = (0, _appSettings.getSettings)();
|
||||
moduleUpdater.init(_Constants.UPDATE_ENDPOINT, settings, _buildInfo2.default);
|
||||
|
||||
splashScreen.initSplash(startMinimized);
|
||||
|
|
|
@ -26,13 +26,22 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
|
|||
|
||||
// TODO: We should use Constant's APP_NAME, but only once
|
||||
// we set up backwards compat with this.
|
||||
var appName = _path2.default.basename(process.execPath, '.exe');
|
||||
var exePath = _electron.app.getPath('exe');
|
||||
var exeDir = _path2.default.dirname(exePath);
|
||||
var iconPath = _path2.default.join(exeDir, 'discord.png');
|
||||
var autostartDir = _path2.default.join(_electron.app.getPath('appData'), 'autostart');
|
||||
var autostartFileName = _path2.default.join(autostartDir, _electron.app.getName() + '-' + _buildInfo2.default.releaseChannel + '.desktop');
|
||||
var desktopFile = '[Desktop Entry]\nType=Application\nExec=' + exePath + '\nHidden=false\nNoDisplay=false\nName=' + appName + '\nIcon=' + iconPath + '\nComment=Text and voice chat for gamers.\nX-GNOME-Autostart-enabled=true\n';
|
||||
const appName = _path2.default.basename(process.execPath, '.exe');
|
||||
const exePath = _electron.app.getPath('exe');
|
||||
const exeDir = _path2.default.dirname(exePath);
|
||||
const iconPath = _path2.default.join(exeDir, 'discord.png');
|
||||
const autostartDir = _path2.default.join(_electron.app.getPath('appData'), 'autostart');
|
||||
const autostartFileName = _path2.default.join(autostartDir, _electron.app.getName() + '-' + _buildInfo2.default.releaseChannel + '.desktop');
|
||||
const desktopFile = `[Desktop Entry]
|
||||
Type=Application
|
||||
Exec=${exePath}
|
||||
Hidden=false
|
||||
NoDisplay=false
|
||||
Name=${appName}
|
||||
Icon=${iconPath}
|
||||
Comment=Text and voice chat for gamers.
|
||||
X-GNOME-Autostart-enabled=true
|
||||
`;
|
||||
|
||||
function ensureDir() {
|
||||
try {
|
||||
|
@ -62,7 +71,7 @@ function update(callback) {
|
|||
|
||||
function isInstalled(callback) {
|
||||
try {
|
||||
_fs2.default.stat(autostartFileName, function (err, stats) {
|
||||
_fs2.default.stat(autostartFileName, (err, stats) => {
|
||||
if (err) {
|
||||
return callback(false);
|
||||
}
|
||||
|
|
|
@ -22,27 +22,25 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj;
|
|||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
var settings = (0, _appSettings.getSettings)();
|
||||
const settings = (0, _appSettings.getSettings)();
|
||||
|
||||
// TODO: We should use Constant's APP_NAME, but only once
|
||||
// we set up backwards compat with this.
|
||||
var appName = _path2.default.basename(process.execPath, '.exe');
|
||||
const appName = _path2.default.basename(process.execPath, '.exe');
|
||||
|
||||
function install(callback) {
|
||||
var startMinimized = settings.get('START_MINIMIZED', false);
|
||||
var _process = process,
|
||||
execPath = _process.execPath;
|
||||
|
||||
const startMinimized = settings.get('START_MINIMIZED', false);
|
||||
let { execPath } = process;
|
||||
if (startMinimized) {
|
||||
execPath = execPath + ' --start-minimized';
|
||||
execPath = `${execPath} --start-minimized`;
|
||||
}
|
||||
var queue = [['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName, '/d', execPath]];
|
||||
const queue = [['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName, '/d', execPath]];
|
||||
|
||||
windowsUtils.addToRegistry(queue, callback);
|
||||
}
|
||||
|
||||
function update(callback) {
|
||||
isInstalled(function (installed) {
|
||||
isInstalled(installed => {
|
||||
if (installed) {
|
||||
install(callback);
|
||||
} else {
|
||||
|
@ -52,18 +50,18 @@ function update(callback) {
|
|||
}
|
||||
|
||||
function isInstalled(callback) {
|
||||
var queryValue = ['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName];
|
||||
const queryValue = ['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName];
|
||||
queryValue.unshift('query');
|
||||
windowsUtils.spawnReg(queryValue, function (error, stdout) {
|
||||
var doesOldKeyExist = stdout.indexOf(appName) >= 0;
|
||||
windowsUtils.spawnReg(queryValue, (error, stdout) => {
|
||||
const doesOldKeyExist = stdout.indexOf(appName) >= 0;
|
||||
callback(doesOldKeyExist);
|
||||
});
|
||||
}
|
||||
|
||||
function uninstall(callback) {
|
||||
var queryValue = ['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName, '/f'];
|
||||
const queryValue = ['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName, '/f'];
|
||||
queryValue.unshift('delete');
|
||||
windowsUtils.spawnReg(queryValue, function (error, stdout) {
|
||||
windowsUtils.spawnReg(queryValue, (error, stdout) => {
|
||||
callback();
|
||||
});
|
||||
}
|
71
appasar/canary/app_bootstrap/bootstrap.js
vendored
71
appasar/canary/app_bootstrap/bootstrap.js
vendored
|
@ -13,31 +13,29 @@ if (process.platform === 'linux') {
|
|||
}
|
||||
}
|
||||
|
||||
var _require = require('electron'),
|
||||
app = _require.app,
|
||||
Menu = _require.Menu;
|
||||
const { app, Menu } = require('electron');
|
||||
|
||||
var buildInfo = require('./buildInfo');
|
||||
const buildInfo = require('./buildInfo');
|
||||
app.setVersion(buildInfo.version);
|
||||
|
||||
// expose releaseChannel to a global, since it's used by splash screen
|
||||
global.releaseChannel = buildInfo.releaseChannel;
|
||||
|
||||
var errorHandler = require('./errorHandler');
|
||||
const errorHandler = require('./errorHandler');
|
||||
errorHandler.init();
|
||||
|
||||
var paths = require('../common/paths');
|
||||
const paths = require('../common/paths');
|
||||
paths.init(buildInfo);
|
||||
|
||||
global.modulePath = paths.getModulePath();
|
||||
|
||||
var appSettings = require('./appSettings');
|
||||
const appSettings = require('./appSettings');
|
||||
appSettings.init();
|
||||
|
||||
var Constants = require('./Constants');
|
||||
var GPUSettings = require('./GPUSettings');
|
||||
const Constants = require('./Constants');
|
||||
const GPUSettings = require('./GPUSettings');
|
||||
|
||||
var settings = appSettings.getSettings();
|
||||
const settings = appSettings.getSettings();
|
||||
// TODO: this is a copy of gpuSettings.getEnableHardwareAcceleration
|
||||
if (!settings.get('enableHardwareAcceleration', true)) {
|
||||
app.disableHardwareAcceleration();
|
||||
|
@ -53,20 +51,17 @@ function hasArgvFlag(flag) {
|
|||
return (process.argv || []).slice(1).includes(flag);
|
||||
}
|
||||
|
||||
console.log(Constants.APP_NAME + ' ' + app.getVersion());
|
||||
console.log(`${Constants.APP_NAME} ${app.getVersion()}`);
|
||||
|
||||
var preventStartup = false;
|
||||
let preventStartup = false;
|
||||
if (process.platform === 'win32') {
|
||||
// this tells Windows (in particular Windows 10) which icon to associate your app with, important for correctly
|
||||
// pinning app to task bar.
|
||||
app.setAppUserModelId(Constants.APP_ID);
|
||||
|
||||
var _require2 = require('./squirrelUpdate'),
|
||||
handleStartupEvent = _require2.handleStartupEvent;
|
||||
const { handleStartupEvent } = require('./squirrelUpdate');
|
||||
// TODO: Isn't using argv[1] fragile?
|
||||
|
||||
|
||||
var squirrelCommand = process.argv[1];
|
||||
const squirrelCommand = process.argv[1];
|
||||
// TODO: Should `Discord` be a constant in this case? It's a protocol.
|
||||
// TODO: Is protocol case sensitive?
|
||||
if (handleStartupEvent('Discord', app, squirrelCommand)) {
|
||||
|
@ -74,49 +69,49 @@ if (process.platform === 'win32') {
|
|||
}
|
||||
}
|
||||
|
||||
var singleInstance = require('./singleInstance');
|
||||
var appUpdater = require('./appUpdater');
|
||||
var moduleUpdater = require('../common/moduleUpdater');
|
||||
var splashScreen = require('./splashScreen');
|
||||
var autoStart = require('./autoStart');
|
||||
var requireNative = require('./requireNative');
|
||||
var coreModule = void 0;
|
||||
const singleInstance = require('./singleInstance');
|
||||
const appUpdater = require('./appUpdater');
|
||||
const moduleUpdater = require('../common/moduleUpdater');
|
||||
const splashScreen = require('./splashScreen');
|
||||
const autoStart = require('./autoStart');
|
||||
const requireNative = require('./requireNative');
|
||||
let coreModule;
|
||||
|
||||
function startUpdate() {
|
||||
var startMinimized = hasArgvFlag('--start-minimized');
|
||||
const startMinimized = hasArgvFlag('--start-minimized');
|
||||
|
||||
appUpdater.update(startMinimized, function () {
|
||||
appUpdater.update(startMinimized, () => {
|
||||
try {
|
||||
coreModule = requireNative('discord_desktop_core');
|
||||
coreModule.startup({
|
||||
paths: paths,
|
||||
splashScreen: splashScreen,
|
||||
moduleUpdater: moduleUpdater,
|
||||
autoStart: autoStart,
|
||||
buildInfo: buildInfo,
|
||||
appSettings: appSettings,
|
||||
Constants: Constants,
|
||||
GPUSettings: GPUSettings
|
||||
paths,
|
||||
splashScreen,
|
||||
moduleUpdater,
|
||||
autoStart,
|
||||
buildInfo,
|
||||
appSettings,
|
||||
Constants,
|
||||
GPUSettings
|
||||
});
|
||||
} catch (err) {
|
||||
return errorHandler.fatal(err);
|
||||
}
|
||||
}, function () {
|
||||
}, () => {
|
||||
coreModule.setMainWindowVisible(!startMinimized);
|
||||
});
|
||||
}
|
||||
|
||||
function startApp() {
|
||||
paths.cleanOldVersions(buildInfo);
|
||||
var startupMenu = require('./startupMenu');
|
||||
const startupMenu = require('./startupMenu');
|
||||
Menu.setApplicationMenu(startupMenu);
|
||||
|
||||
var multiInstance = hasArgvFlag('--multi-instance');
|
||||
const multiInstance = hasArgvFlag('--multi-instance');
|
||||
|
||||
if (multiInstance) {
|
||||
startUpdate();
|
||||
} else {
|
||||
singleInstance.create(startUpdate, function (args) {
|
||||
singleInstance.create(startUpdate, args => {
|
||||
// TODO: isn't relying on index 0 awfully fragile?
|
||||
if (args != null && args.length > 0 && args[0] === '--squirrel-uninstall') {
|
||||
app.quit();
|
||||
|
|
|
@ -10,7 +10,7 @@ var _path2 = _interopRequireDefault(_path);
|
|||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
var buildInfo = require(_path2.default.join(process.resourcesPath, 'build_info.json'));
|
||||
const buildInfo = require(_path2.default.join(process.resourcesPath, 'build_info.json'));
|
||||
|
||||
exports.default = buildInfo;
|
||||
module.exports = exports['default'];
|
|
@ -14,9 +14,9 @@ function isErrorSafeToSuppress(error) {
|
|||
}
|
||||
|
||||
function init() {
|
||||
process.on('uncaughtException', function (error) {
|
||||
var stack = error.stack ? error.stack : String(error);
|
||||
var message = 'Uncaught exception:\n ' + stack;
|
||||
process.on('uncaughtException', error => {
|
||||
const stack = error.stack ? error.stack : String(error);
|
||||
const message = `Uncaught exception:\n ${stack}`;
|
||||
console.warn(message);
|
||||
|
||||
if (!isErrorSafeToSuppress(error)) {
|
||||
|
@ -32,7 +32,7 @@ function fatal(err) {
|
|||
type: 'error',
|
||||
message: 'A fatal Javascript error occured',
|
||||
detail: err && err.stack ? err.stack : String(err)
|
||||
}, function () {
|
||||
}, () => {
|
||||
_electron.app.quit();
|
||||
});
|
||||
}
|
|
@ -4,8 +4,6 @@ Object.defineProperty(exports, "__esModule", {
|
|||
value: true
|
||||
});
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
|
||||
|
||||
var _events = require('events');
|
||||
|
||||
var _squirrelUpdate = require('./squirrelUpdate');
|
||||
|
@ -22,23 +20,15 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
|
|||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
|
||||
|
||||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
|
||||
|
||||
function versionParse(verString) {
|
||||
return verString.split('.').map(function (i) {
|
||||
return parseInt(i);
|
||||
});
|
||||
return verString.split('.').map(i => parseInt(i));
|
||||
}
|
||||
|
||||
function versionNewer(verA, verB) {
|
||||
var i = 0;
|
||||
let i = 0;
|
||||
while (true) {
|
||||
var a = verA[i];
|
||||
var b = verB[i];
|
||||
const a = verA[i];
|
||||
const b = verB[i];
|
||||
i++;
|
||||
if (a === undefined) {
|
||||
return false;
|
||||
|
@ -53,168 +43,131 @@ function versionNewer(verA, verB) {
|
|||
}
|
||||
}
|
||||
|
||||
var AutoUpdaterWin32 = function (_EventEmitter) {
|
||||
_inherits(AutoUpdaterWin32, _EventEmitter);
|
||||
class AutoUpdaterWin32 extends _events.EventEmitter {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
function AutoUpdaterWin32() {
|
||||
_classCallCheck(this, AutoUpdaterWin32);
|
||||
|
||||
var _this = _possibleConstructorReturn(this, (AutoUpdaterWin32.__proto__ || Object.getPrototypeOf(AutoUpdaterWin32)).call(this));
|
||||
|
||||
_this.updateUrl = null;
|
||||
_this.updateVersion = null;
|
||||
return _this;
|
||||
this.updateUrl = null;
|
||||
this.updateVersion = null;
|
||||
}
|
||||
|
||||
_createClass(AutoUpdaterWin32, [{
|
||||
key: 'setFeedURL',
|
||||
value: function setFeedURL(updateUrl) {
|
||||
this.updateUrl = updateUrl;
|
||||
setFeedURL(updateUrl) {
|
||||
this.updateUrl = updateUrl;
|
||||
}
|
||||
|
||||
quitAndInstall() {
|
||||
if (squirrelUpdate.updateExistsSync()) {
|
||||
squirrelUpdate.restart(_electron.app, this.updateVersion || _electron.app.getVersion());
|
||||
} else {
|
||||
require('auto-updater').quitAndInstall();
|
||||
}
|
||||
}, {
|
||||
key: 'quitAndInstall',
|
||||
value: function quitAndInstall() {
|
||||
if (squirrelUpdate.updateExistsSync()) {
|
||||
squirrelUpdate.restart(_electron.app, this.updateVersion || _electron.app.getVersion());
|
||||
} else {
|
||||
require('auto-updater').quitAndInstall();
|
||||
}
|
||||
}
|
||||
|
||||
downloadAndInstallUpdate(callback) {
|
||||
squirrelUpdate.spawnUpdateInstall(this.updateUrl, progress => {
|
||||
this.emit('update-progress', progress);
|
||||
}).catch(err => callback(err)).then(() => callback());
|
||||
}
|
||||
|
||||
checkForUpdates() {
|
||||
if (this.updateUrl == null) {
|
||||
throw new Error('Update URL is not set');
|
||||
}
|
||||
}, {
|
||||
key: 'downloadAndInstallUpdate',
|
||||
value: function downloadAndInstallUpdate(callback) {
|
||||
var _this2 = this;
|
||||
|
||||
squirrelUpdate.spawnUpdateInstall(this.updateUrl, function (progress) {
|
||||
_this2.emit('update-progress', progress);
|
||||
}).catch(function (err) {
|
||||
return callback(err);
|
||||
}).then(function () {
|
||||
return callback();
|
||||
});
|
||||
this.emit('checking-for-update');
|
||||
|
||||
if (!squirrelUpdate.updateExistsSync()) {
|
||||
this.emit('update-not-available');
|
||||
return;
|
||||
}
|
||||
}, {
|
||||
key: 'checkForUpdates',
|
||||
value: function checkForUpdates() {
|
||||
var _this3 = this;
|
||||
|
||||
if (this.updateUrl == null) {
|
||||
throw new Error('Update URL is not set');
|
||||
}
|
||||
|
||||
this.emit('checking-for-update');
|
||||
|
||||
if (!squirrelUpdate.updateExistsSync()) {
|
||||
this.emit('update-not-available');
|
||||
squirrelUpdate.spawnUpdate(['--check', this.updateUrl], (error, stdout) => {
|
||||
if (error != null) {
|
||||
this.emit('error', error);
|
||||
return;
|
||||
}
|
||||
|
||||
squirrelUpdate.spawnUpdate(['--check', this.updateUrl], function (error, stdout) {
|
||||
if (error != null) {
|
||||
_this3.emit('error', error);
|
||||
try {
|
||||
// Last line of the output is JSON details about the releases
|
||||
const json = stdout.trim().split('\n').pop();
|
||||
const releasesFound = JSON.parse(json).releasesToApply;
|
||||
if (releasesFound == null || releasesFound.length == 0) {
|
||||
this.emit('update-not-available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Last line of the output is JSON details about the releases
|
||||
var json = stdout.trim().split('\n').pop();
|
||||
var releasesFound = JSON.parse(json).releasesToApply;
|
||||
if (releasesFound == null || releasesFound.length == 0) {
|
||||
_this3.emit('update-not-available');
|
||||
const update = releasesFound.pop();
|
||||
this.emit('update-available');
|
||||
this.downloadAndInstallUpdate(error => {
|
||||
if (error != null) {
|
||||
this.emit('error', error);
|
||||
return;
|
||||
}
|
||||
|
||||
var update = releasesFound.pop();
|
||||
_this3.emit('update-available');
|
||||
_this3.downloadAndInstallUpdate(function (error) {
|
||||
if (error != null) {
|
||||
_this3.emit('error', error);
|
||||
return;
|
||||
}
|
||||
this.updateVersion = update.version;
|
||||
|
||||
_this3.updateVersion = update.version;
|
||||
|
||||
_this3.emit('update-downloaded', {}, update.release, update.version, new Date(), _this3.updateUrl, _this3.quitAndInstall.bind(_this3));
|
||||
});
|
||||
} catch (error) {
|
||||
error.stdout = stdout;
|
||||
_this3.emit('error', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}]);
|
||||
|
||||
return AutoUpdaterWin32;
|
||||
}(_events.EventEmitter);
|
||||
this.emit('update-downloaded', {}, update.release, update.version, new Date(), this.updateUrl, this.quitAndInstall.bind(this));
|
||||
});
|
||||
} catch (error) {
|
||||
error.stdout = stdout;
|
||||
this.emit('error', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// todo
|
||||
|
||||
|
||||
var AutoUpdaterLinux = function (_EventEmitter2) {
|
||||
_inherits(AutoUpdaterLinux, _EventEmitter2);
|
||||
|
||||
function AutoUpdaterLinux() {
|
||||
_classCallCheck(this, AutoUpdaterLinux);
|
||||
|
||||
var _this4 = _possibleConstructorReturn(this, (AutoUpdaterLinux.__proto__ || Object.getPrototypeOf(AutoUpdaterLinux)).call(this));
|
||||
|
||||
_this4.updateUrl = null;
|
||||
return _this4;
|
||||
class AutoUpdaterLinux extends _events.EventEmitter {
|
||||
constructor() {
|
||||
super();
|
||||
this.updateUrl = null;
|
||||
}
|
||||
|
||||
_createClass(AutoUpdaterLinux, [{
|
||||
key: 'setFeedURL',
|
||||
value: function setFeedURL(url) {
|
||||
this.updateUrl = url;
|
||||
}
|
||||
}, {
|
||||
key: 'checkForUpdates',
|
||||
value: function checkForUpdates() {
|
||||
var _this5 = this;
|
||||
setFeedURL(url) {
|
||||
this.updateUrl = url;
|
||||
}
|
||||
|
||||
var currVersion = versionParse(_electron.app.getVersion());
|
||||
this.emit('checking-for-update');
|
||||
checkForUpdates() {
|
||||
const currVersion = versionParse(_electron.app.getVersion());
|
||||
this.emit('checking-for-update');
|
||||
|
||||
_request2.default.get({ url: this.updateUrl, encoding: null }, function (error, response, body) {
|
||||
if (error) {
|
||||
console.error('[Updates] Error fetching ' + _this5.updateUrl + ': ' + error);
|
||||
_this5.emit('error', error);
|
||||
return;
|
||||
}
|
||||
_request2.default.get({ url: this.updateUrl, encoding: null }, (error, response, body) => {
|
||||
if (error) {
|
||||
console.error('[Updates] Error fetching ' + this.updateUrl + ': ' + error);
|
||||
this.emit('error', error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.statusCode === 204) {
|
||||
// you are up to date
|
||||
_this5.emit('update-not-available');
|
||||
} else if (response.statusCode === 200) {
|
||||
var latestVerStr = '';
|
||||
var latestVersion = [];
|
||||
try {
|
||||
var latestMetadata = JSON.parse(body);
|
||||
latestVerStr = latestMetadata.name;
|
||||
latestVersion = versionParse(latestVerStr);
|
||||
} catch (e) {}
|
||||
if (response.statusCode === 204) {
|
||||
// you are up to date
|
||||
this.emit('update-not-available');
|
||||
} else if (response.statusCode === 200) {
|
||||
let latestVerStr = '';
|
||||
let latestVersion = [];
|
||||
try {
|
||||
const latestMetadata = JSON.parse(body);
|
||||
latestVerStr = latestMetadata.name;
|
||||
latestVersion = versionParse(latestVerStr);
|
||||
} catch (e) {}
|
||||
|
||||
if (versionNewer(latestVersion, currVersion)) {
|
||||
console.log('[Updates] You are out of date!');
|
||||
// you need to update
|
||||
_this5.emit('update-manually', latestVerStr);
|
||||
} else {
|
||||
console.log('[Updates] You are living in the future!');
|
||||
_this5.emit('update-not-available');
|
||||
}
|
||||
if (versionNewer(latestVersion, currVersion)) {
|
||||
console.log('[Updates] You are out of date!');
|
||||
// you need to update
|
||||
this.emit('update-manually', latestVerStr);
|
||||
} else {
|
||||
// something is wrong
|
||||
console.error('[Updates] Error: fetch returned: ' + response.statusCode);
|
||||
_this5.emit('update-not-available');
|
||||
console.log('[Updates] You are living in the future!');
|
||||
this.emit('update-not-available');
|
||||
}
|
||||
});
|
||||
}
|
||||
}]);
|
||||
} else {
|
||||
// something is wrong
|
||||
console.error(`[Updates] Error: fetch returned: ${response.statusCode}`);
|
||||
this.emit('update-not-available');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return AutoUpdaterLinux;
|
||||
}(_events.EventEmitter);
|
||||
|
||||
var autoUpdater = void 0;
|
||||
let autoUpdater;
|
||||
|
||||
// TODO
|
||||
// events: checking-for-update, update-available, update-not-available, update-manually, update-downloaded, error
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
'use strict';
|
||||
|
||||
var buildInfo = require('./buildInfo');
|
||||
var paths = require('../common/paths');
|
||||
const buildInfo = require('./buildInfo');
|
||||
const paths = require('../common/paths');
|
||||
paths.init(buildInfo);
|
||||
var moduleUpdater = require('../common/moduleUpdater');
|
||||
const moduleUpdater = require('../common/moduleUpdater');
|
||||
moduleUpdater.initPathsOnly(buildInfo);
|
||||
var requireNative = require('./requireNative');
|
||||
const requireNative = require('./requireNative');
|
||||
|
||||
function getAppMode() {
|
||||
if (process.argv && process.argv.includes('--overlay-host')) {
|
||||
|
@ -15,7 +15,7 @@ function getAppMode() {
|
|||
return 'app';
|
||||
}
|
||||
|
||||
var mode = getAppMode();
|
||||
const mode = getAppMode();
|
||||
if (mode === 'app') {
|
||||
require('./bootstrap');
|
||||
} else if (mode === 'overlay-host') {
|
||||
|
|
|
@ -7,11 +7,11 @@ Object.defineProperty(exports, "__esModule", {
|
|||
// require('electron').remote.require('./installDevTools')()
|
||||
|
||||
function installDevTools() {
|
||||
console.log('Installing Devtron');
|
||||
var devtron = require('devtron');
|
||||
console.log(`Installing Devtron`);
|
||||
const devtron = require('devtron');
|
||||
devtron.uninstall();
|
||||
devtron.install();
|
||||
console.log('Installed Devtron');
|
||||
console.log(`Installed Devtron`);
|
||||
}
|
||||
|
||||
exports.default = installDevTools;
|
||||
|
|
|
@ -7,11 +7,7 @@ Object.defineProperty(exports, "__esModule", {
|
|||
var _electron = require('electron');
|
||||
|
||||
exports.default = {
|
||||
on: function on(event, callback) {
|
||||
return _electron.ipcMain.on('DISCORD_' + event, callback);
|
||||
},
|
||||
removeListener: function removeListener(event, callback) {
|
||||
return _electron.ipcMain.removeListener('DISCORD_' + event, callback);
|
||||
}
|
||||
on: (event, callback) => _electron.ipcMain.on(`DISCORD_${event}`, callback),
|
||||
removeListener: (event, callback) => _electron.ipcMain.removeListener(`DISCORD_${event}`, callback)
|
||||
};
|
||||
module.exports = exports['default'];
|
|
@ -27,88 +27,75 @@ function _log(_msg) {
|
|||
}
|
||||
|
||||
function requestWithMethod(method, origOpts, origCallback) {
|
||||
var _this = this;
|
||||
|
||||
if (typeof origOpts == 'string') {
|
||||
origOpts = { url: origOpts };
|
||||
}
|
||||
|
||||
var opts = _extends({}, origOpts, { method: method });
|
||||
const opts = _extends({}, origOpts, { method });
|
||||
|
||||
var callback = void 0;
|
||||
let callback;
|
||||
if (origCallback || opts.callback) {
|
||||
var origOptsCallback = opts.callback;
|
||||
const origOptsCallback = opts.callback;
|
||||
delete opts.callback;
|
||||
callback = function callback() {
|
||||
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
callback = (...args) => {
|
||||
if (origCallback) {
|
||||
origCallback.apply(_this, args);
|
||||
origCallback.apply(this, args);
|
||||
}
|
||||
if (origOptsCallback) {
|
||||
origOptsCallback.apply(_this, args);
|
||||
origOptsCallback.apply(this, args);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var strictOpts = _extends({}, opts, { strictSSL: true });
|
||||
var laxOpts = _extends({}, opts, { strictSSL: false });
|
||||
const strictOpts = _extends({}, opts, { strictSSL: true });
|
||||
const laxOpts = _extends({}, opts, { strictSSL: false });
|
||||
|
||||
var rv = new _events2.default();
|
||||
const rv = new _events2.default();
|
||||
|
||||
if (callback) {
|
||||
_log('have callback, so wrapping');
|
||||
rv.on('response', function (response) {
|
||||
var chunks = [];
|
||||
response.on('data', function (chunk) {
|
||||
return chunks.push(chunk);
|
||||
});
|
||||
response.on('end', function () {
|
||||
rv.on('response', response => {
|
||||
const chunks = [];
|
||||
response.on('data', chunk => chunks.push(chunk));
|
||||
response.on('end', () => {
|
||||
callback(null, response, Buffer.concat(chunks));
|
||||
});
|
||||
});
|
||||
rv.on('error', function (error) {
|
||||
return callback(error);
|
||||
});
|
||||
rv.on('error', error => callback(error));
|
||||
}
|
||||
|
||||
var requestTypes = [{
|
||||
factory: function factory() {
|
||||
const requestTypes = [{
|
||||
factory: function () {
|
||||
return (0, _request2.default)(strictOpts);
|
||||
},
|
||||
method: 'node_request_strict'
|
||||
}, {
|
||||
factory: function factory() {
|
||||
var qs = _querystring2.default.stringify(strictOpts.qs);
|
||||
var nr = _electron.net.request(_extends({}, strictOpts, { url: strictOpts.url + '?' + qs }));
|
||||
factory: function () {
|
||||
const qs = _querystring2.default.stringify(strictOpts.qs);
|
||||
const nr = _electron.net.request(_extends({}, strictOpts, { url: `${strictOpts.url}?${qs}` }));
|
||||
nr.end();
|
||||
return nr;
|
||||
},
|
||||
method: 'electron_net_request_strict'
|
||||
}, {
|
||||
factory: function factory() {
|
||||
factory: function () {
|
||||
return (0, _request2.default)(laxOpts);
|
||||
},
|
||||
method: 'node_request_lax'
|
||||
}];
|
||||
|
||||
function attempt(index) {
|
||||
var _requestTypes$index = requestTypes[index],
|
||||
factory = _requestTypes$index.factory,
|
||||
method = _requestTypes$index.method;
|
||||
|
||||
_log('Attempt #' + (index + 1) + ': ' + method);
|
||||
factory().on('response', function (response) {
|
||||
_log(method + ' success! emitting response ' + response);
|
||||
const { factory, method } = requestTypes[index];
|
||||
_log(`Attempt #${index + 1}: ${method}`);
|
||||
factory().on('response', response => {
|
||||
_log(`${method} success! emitting response ${response}`);
|
||||
rv.emit('response', response);
|
||||
}).on('error', function (error) {
|
||||
}).on('error', error => {
|
||||
if (index + 1 < requestTypes.length) {
|
||||
_log(method + ' failure, trying next option');
|
||||
_log(`${method} failure, trying next option`);
|
||||
attempt(index + 1);
|
||||
} else {
|
||||
_log(method + ' failure, out of options');
|
||||
_log(`${method} failure, out of options`);
|
||||
rv.emit('error', error);
|
||||
}
|
||||
});
|
||||
|
@ -121,9 +108,7 @@ function requestWithMethod(method, origOpts, origCallback) {
|
|||
|
||||
// only supports get for now, since retrying is non-idempotent and
|
||||
// we'd want to grovel the errors to make sure it's safe to retry
|
||||
var _arr = ['get'];
|
||||
for (var _i = 0; _i < _arr.length; _i++) {
|
||||
var method = _arr[_i];
|
||||
for (const method of ['get']) {
|
||||
requestWithMethod[method] = requestWithMethod.bind(null, method);
|
||||
}
|
||||
|
||||
|
|
|
@ -59,16 +59,14 @@ function deleteSocketFile(socketPath) {
|
|||
function listenForArgumentsFromNewProcess(socketPath, callback) {
|
||||
deleteSocketFile(socketPath);
|
||||
|
||||
var server = _net2.default.createServer(function (connection) {
|
||||
connection.on('data', function (data) {
|
||||
var args = JSON.parse(data);
|
||||
const server = _net2.default.createServer(connection => {
|
||||
connection.on('data', data => {
|
||||
const args = JSON.parse(data);
|
||||
callback(args);
|
||||
});
|
||||
});
|
||||
server.listen(socketPath);
|
||||
server.on('error', function (error) {
|
||||
return console.error('Application server failed', error);
|
||||
});
|
||||
server.on('error', error => console.error('Application server failed', error));
|
||||
return server;
|
||||
}
|
||||
|
||||
|
@ -82,8 +80,8 @@ function tryStart(socketPath, callback, otherAppFound) {
|
|||
return;
|
||||
}
|
||||
|
||||
var client = _net2.default.connect({ path: socketPath }, function () {
|
||||
client.write(JSON.stringify(process.argv.slice(1)), function () {
|
||||
const client = _net2.default.connect({ path: socketPath }, () => {
|
||||
client.write(JSON.stringify(process.argv.slice(1)), () => {
|
||||
client.end();
|
||||
otherAppFound();
|
||||
});
|
||||
|
@ -92,7 +90,7 @@ function tryStart(socketPath, callback, otherAppFound) {
|
|||
}
|
||||
|
||||
function makeSocketPath() {
|
||||
var name = _electron.app.getName();
|
||||
let name = _electron.app.getName();
|
||||
if (_buildInfo2.default.releaseChannel !== 'stable') {
|
||||
name = _electron.app.getName() + _buildInfo2.default.releaseChannel;
|
||||
}
|
||||
|
@ -105,23 +103,23 @@ function makeSocketPath() {
|
|||
}
|
||||
|
||||
function create(startCallback, newProcessCallback) {
|
||||
var socketPath = makeSocketPath();
|
||||
const socketPath = makeSocketPath();
|
||||
|
||||
tryStart(socketPath, function () {
|
||||
var server = listenForArgumentsFromNewProcess(socketPath, newProcessCallback);
|
||||
tryStart(socketPath, () => {
|
||||
const server = listenForArgumentsFromNewProcess(socketPath, newProcessCallback);
|
||||
|
||||
_electron.app.on('will-quit', function () {
|
||||
_electron.app.on('will-quit', () => {
|
||||
server.close();
|
||||
deleteSocketFile(socketPath);
|
||||
});
|
||||
|
||||
_electron.app.on('will-exit', function () {
|
||||
_electron.app.on('will-exit', () => {
|
||||
server.close();
|
||||
deleteSocketFile(socketPath);
|
||||
});
|
||||
|
||||
startCallback();
|
||||
}, function () {
|
||||
}, () => {
|
||||
_electron.app.exit(0);
|
||||
});
|
||||
}
|
||||
|
|
|
@ -22507,44 +22507,38 @@ var _Progress2 = _interopRequireDefault(_Progress);
|
|||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
var VIDEO_REF = 'video';
|
||||
var DOWNLOAD_OPTIONS = [{ value: 'deb', label: 'Ubuntu (deb)' }, { value: 'tar.gz', label: 'Linux (tar.gz)' }, { value: 'nope', label: 'I\'ll figure it out' }];
|
||||
var RELEASE_CHANNEL = _electron.remote.getGlobal('releaseChannel');
|
||||
var LINUX_DOWNLOAD_URL_BASE = 'https://discordapp.com/api/download/' + RELEASE_CHANNEL + '?platform=linux&format=';
|
||||
const VIDEO_REF = 'video';
|
||||
const DOWNLOAD_OPTIONS = [{ value: 'deb', label: `Ubuntu (deb)` }, { value: 'tar.gz', label: `Linux (tar.gz)` }, { value: 'nope', label: `I'll figure it out` }];
|
||||
const RELEASE_CHANNEL = _electron.remote.getGlobal('releaseChannel');
|
||||
const LINUX_DOWNLOAD_URL_BASE = `https://discordapp.com/api/download/${RELEASE_CHANNEL}?platform=linux&format=`;
|
||||
|
||||
var ipcRenderer = {
|
||||
send: function send(event) {
|
||||
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
||||
args[_key - 1] = arguments[_key];
|
||||
}
|
||||
|
||||
return _electron.ipcRenderer.send.apply(_electron.ipcRenderer, ['DISCORD_' + event].concat(args));
|
||||
},
|
||||
on: function on(event, callback) {
|
||||
return _electron.ipcRenderer.on('DISCORD_' + event, callback);
|
||||
},
|
||||
removeListener: function removeListener(event, callback) {
|
||||
return _electron.ipcRenderer.removeListener('DISCORD_' + event, callback);
|
||||
}
|
||||
const ipcRenderer = {
|
||||
send: (event, ...args) => _electron.ipcRenderer.send(`DISCORD_${event}`, ...args),
|
||||
on: (event, callback) => _electron.ipcRenderer.on(`DISCORD_${event}`, callback),
|
||||
removeListener: (event, callback) => _electron.ipcRenderer.removeListener(`DISCORD_${event}`, callback)
|
||||
};
|
||||
|
||||
var Splash = _react2.default.createClass({
|
||||
const Splash = _react2.default.createClass({
|
||||
displayName: 'Splash',
|
||||
setInterval: function setInterval(interval, callback) {
|
||||
|
||||
setInterval(interval, callback) {
|
||||
this.clearInterval();
|
||||
|
||||
this._interval = window.setInterval(callback, interval);
|
||||
},
|
||||
clearInterval: function clearInterval() {
|
||||
|
||||
clearInterval() {
|
||||
if (this._interval) {
|
||||
window.clearInterval(this._interval);
|
||||
this._interval = null;
|
||||
}
|
||||
},
|
||||
componentWillUnmount: function componentWillUnmount() {
|
||||
|
||||
componentWillUnmount() {
|
||||
this.clearInterval();
|
||||
},
|
||||
getInitialState: function getInitialState() {
|
||||
|
||||
getInitialState() {
|
||||
return {
|
||||
quote: _quotes_copy2.default[Math.floor(Math.random() * _quotes_copy2.default.length)],
|
||||
videoLoaded: false,
|
||||
|
@ -22553,39 +22547,43 @@ var Splash = _react2.default.createClass({
|
|||
selectedDownload: 'deb'
|
||||
};
|
||||
},
|
||||
componentDidMount: function componentDidMount() {
|
||||
var _this = this;
|
||||
|
||||
componentDidMount() {
|
||||
_reactDom2.default.findDOMNode(this.refs[VIDEO_REF]).addEventListener('loadeddata', this.handleVideoLoaded);
|
||||
this.setInterval(1000, this.updateCountdownSeconds);
|
||||
ipcRenderer.on('SPLASH_UPDATE_STATE', function (_e, state) {
|
||||
_this.setState({ update: state });
|
||||
ipcRenderer.on('SPLASH_UPDATE_STATE', (_e, state) => {
|
||||
this.setState({ update: state });
|
||||
});
|
||||
ipcRenderer.send('SPLASH_SCREEN_READY');
|
||||
},
|
||||
updateCountdownSeconds: function updateCountdownSeconds() {
|
||||
|
||||
updateCountdownSeconds() {
|
||||
if (this.state.update.seconds > 0) {
|
||||
var newUpdateState = this.state.update;
|
||||
const newUpdateState = this.state.update;
|
||||
newUpdateState.seconds -= 1;
|
||||
this.setState({ update: newUpdateState });
|
||||
}
|
||||
},
|
||||
handleVideoLoaded: function handleVideoLoaded() {
|
||||
|
||||
handleVideoLoaded() {
|
||||
this.setState({ videoLoaded: true });
|
||||
},
|
||||
handleDownloadChanged: function handleDownloadChanged(selection) {
|
||||
|
||||
handleDownloadChanged(selection) {
|
||||
this.setState({ selectedDownload: selection.value });
|
||||
},
|
||||
handleDownload: function handleDownload() {
|
||||
|
||||
handleDownload() {
|
||||
if (this.state.selectedDownload != 'nope') {
|
||||
var url = LINUX_DOWNLOAD_URL_BASE + this.state.selectedDownload;
|
||||
const url = LINUX_DOWNLOAD_URL_BASE + this.state.selectedDownload;
|
||||
_electron.shell.openExternal(url, { activate: true });
|
||||
}
|
||||
_electron.remote.app.quit();
|
||||
},
|
||||
render: function render() {
|
||||
var statusText = void 0;
|
||||
var progress = _react2.default.createElement(
|
||||
|
||||
render() {
|
||||
let statusText;
|
||||
let progress = _react2.default.createElement(
|
||||
'div',
|
||||
{ className: 'progress-placeholder' },
|
||||
'\xA0'
|
||||
|
@ -22634,7 +22632,7 @@ var Splash = _react2.default.createClass({
|
|||
);
|
||||
break;
|
||||
case 'update-manually':
|
||||
var buttonText = this.state.selectedDownload != 'nope' ? 'Download' : 'Okay';
|
||||
const buttonText = this.state.selectedDownload != 'nope' ? 'Download' : 'Okay';
|
||||
return _react2.default.createElement(
|
||||
'div',
|
||||
{ id: 'splash' },
|
||||
|
@ -25724,19 +25722,15 @@ var _react2 = _interopRequireDefault(_react);
|
|||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
var Progress = function Progress(_ref) {
|
||||
var _ref$percent = _ref.percent,
|
||||
percent = _ref$percent === undefined ? 0 : _ref$percent;
|
||||
return _react2.default.createElement(
|
||||
const Progress = ({ percent = 0 }) => _react2.default.createElement(
|
||||
"div",
|
||||
{ className: "progress" },
|
||||
_react2.default.createElement(
|
||||
"div",
|
||||
{ className: "progress" },
|
||||
_react2.default.createElement(
|
||||
"div",
|
||||
{ className: "progress-bar" },
|
||||
_react2.default.createElement("div", { className: "complete", style: { width: percent + "%" } })
|
||||
)
|
||||
);
|
||||
};
|
||||
{ className: "progress-bar" },
|
||||
_react2.default.createElement("div", { className: "complete", style: { width: `${percent}%` } })
|
||||
)
|
||||
);
|
||||
|
||||
exports.default = Progress;
|
||||
module.exports = exports["default"];
|
||||
|
|
|
@ -35,69 +35,61 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj;
|
|||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
var UPDATE_TIMEOUT_WAIT = 10000;
|
||||
var RETRY_CAP_SECONDS = 60;
|
||||
const UPDATE_TIMEOUT_WAIT = 10000;
|
||||
const RETRY_CAP_SECONDS = 60;
|
||||
// citron note: atom seems to add about 50px height to the frame on mac but not windows
|
||||
// TODO: see if we can eliminate fudge by using useContentSize BrowserWindow option
|
||||
var LOADING_WINDOW_WIDTH = 300;
|
||||
var LOADING_WINDOW_HEIGHT = process.platform == 'darwin' ? 300 : 350;
|
||||
const LOADING_WINDOW_WIDTH = 300;
|
||||
const LOADING_WINDOW_HEIGHT = process.platform == 'darwin' ? 300 : 350;
|
||||
|
||||
// TODO: addModulesListener events should use Module's constants
|
||||
var CHECKING_FOR_UPDATES = 'checking-for-updates';
|
||||
var UPDATE_CHECK_FINISHED = 'update-check-finished';
|
||||
var UPDATE_FAILURE = 'update-failure';
|
||||
var LAUNCHING = 'launching';
|
||||
var DOWNLOADING_MODULE = 'downloading-module';
|
||||
var DOWNLOADING_UPDATES = 'downloading-updates';
|
||||
var DOWNLOADING_MODULES_FINISHED = 'downloading-modules-finished';
|
||||
var DOWNLOADING_MODULE_PROGRESS = 'downloading-module-progress';
|
||||
var DOWNLOADED_MODULE = 'downloaded-module';
|
||||
var NO_PENDING_UPDATES = 'no-pending-updates';
|
||||
var INSTALLING_MODULE = 'installing-module';
|
||||
var INSTALLING_UPDATES = 'installing-updates';
|
||||
var INSTALLED_MODULE = 'installed-module';
|
||||
var INSTALLING_MODULE_PROGRESS = 'installing-module-progress';
|
||||
var INSTALLING_MODULES_FINISHED = 'installing-modules-finished';
|
||||
var UPDATE_MANUALLY = 'update-manually';
|
||||
const CHECKING_FOR_UPDATES = 'checking-for-updates';
|
||||
const UPDATE_CHECK_FINISHED = 'update-check-finished';
|
||||
const UPDATE_FAILURE = 'update-failure';
|
||||
const LAUNCHING = 'launching';
|
||||
const DOWNLOADING_MODULE = 'downloading-module';
|
||||
const DOWNLOADING_UPDATES = 'downloading-updates';
|
||||
const DOWNLOADING_MODULES_FINISHED = 'downloading-modules-finished';
|
||||
const DOWNLOADING_MODULE_PROGRESS = 'downloading-module-progress';
|
||||
const DOWNLOADED_MODULE = 'downloaded-module';
|
||||
const NO_PENDING_UPDATES = 'no-pending-updates';
|
||||
const INSTALLING_MODULE = 'installing-module';
|
||||
const INSTALLING_UPDATES = 'installing-updates';
|
||||
const INSTALLED_MODULE = 'installed-module';
|
||||
const INSTALLING_MODULE_PROGRESS = 'installing-module-progress';
|
||||
const INSTALLING_MODULES_FINISHED = 'installing-modules-finished';
|
||||
const UPDATE_MANUALLY = 'update-manually';
|
||||
|
||||
var APP_SHOULD_LAUNCH = exports.APP_SHOULD_LAUNCH = 'APP_SHOULD_LAUNCH';
|
||||
var APP_SHOULD_SHOW = exports.APP_SHOULD_SHOW = 'APP_SHOULD_SHOW';
|
||||
const APP_SHOULD_LAUNCH = exports.APP_SHOULD_LAUNCH = 'APP_SHOULD_LAUNCH';
|
||||
const APP_SHOULD_SHOW = exports.APP_SHOULD_SHOW = 'APP_SHOULD_SHOW';
|
||||
|
||||
var events = exports.events = new _events.EventEmitter();
|
||||
const events = exports.events = new _events.EventEmitter();
|
||||
|
||||
function webContentsSend(win, event) {
|
||||
function webContentsSend(win, event, ...args) {
|
||||
if (win != null && win.webContents != null) {
|
||||
var _win$webContents;
|
||||
|
||||
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
|
||||
args[_key - 2] = arguments[_key];
|
||||
}
|
||||
|
||||
(_win$webContents = win.webContents).send.apply(_win$webContents, ['DISCORD_' + event].concat(args));
|
||||
win.webContents.send(`DISCORD_${event}`, ...args);
|
||||
}
|
||||
}
|
||||
|
||||
var splashWindow = void 0;
|
||||
var modulesListeners = void 0;
|
||||
var updateTimeout = void 0;
|
||||
var updateAttempt = void 0;
|
||||
var splashState = void 0;
|
||||
var launchedMainWindow = void 0;
|
||||
|
||||
function initSplash() {
|
||||
var startMinimized = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
|
||||
let splashWindow;
|
||||
let modulesListeners;
|
||||
let updateTimeout;
|
||||
let updateAttempt;
|
||||
let splashState;
|
||||
let launchedMainWindow;
|
||||
|
||||
function initSplash(startMinimized = false) {
|
||||
modulesListeners = {};
|
||||
splashState = {};
|
||||
launchedMainWindow = false;
|
||||
updateAttempt = 0;
|
||||
|
||||
addModulesListener(CHECKING_FOR_UPDATES, function () {
|
||||
addModulesListener(CHECKING_FOR_UPDATES, () => {
|
||||
startUpdateTimeout();
|
||||
updateSplashState(CHECKING_FOR_UPDATES);
|
||||
});
|
||||
|
||||
addModulesListener(UPDATE_CHECK_FINISHED, function (succeeded, updateCount, manualRequired) {
|
||||
addModulesListener(UPDATE_CHECK_FINISHED, (succeeded, updateCount, manualRequired) => {
|
||||
stopUpdateTimeout();
|
||||
if (!succeeded) {
|
||||
scheduleUpdateCheck();
|
||||
|
@ -108,55 +100,45 @@ function initSplash() {
|
|||
}
|
||||
});
|
||||
|
||||
addModulesListener(DOWNLOADING_MODULE, function (name, current, total) {
|
||||
addModulesListener(DOWNLOADING_MODULE, (name, current, total) => {
|
||||
stopUpdateTimeout();
|
||||
splashState = { current: current, total: total };
|
||||
splashState = { current, total };
|
||||
updateSplashState(DOWNLOADING_UPDATES);
|
||||
});
|
||||
|
||||
addModulesListener(DOWNLOADING_MODULE_PROGRESS, function (name, progress) {
|
||||
addModulesListener(DOWNLOADING_MODULE_PROGRESS, (name, progress) => {
|
||||
splashState.progress = progress;
|
||||
updateSplashState(DOWNLOADING_UPDATES);
|
||||
});
|
||||
|
||||
addModulesListener(DOWNLOADED_MODULE, function (name, current, total, succeeded) {
|
||||
return delete splashState.progress;
|
||||
});
|
||||
addModulesListener(DOWNLOADED_MODULE, (name, current, total, succeeded) => delete splashState.progress);
|
||||
|
||||
addModulesListener(DOWNLOADING_MODULES_FINISHED, function (succeeded, failed) {
|
||||
addModulesListener(DOWNLOADING_MODULES_FINISHED, (succeeded, failed) => {
|
||||
if (failed > 0) {
|
||||
scheduleUpdateCheck();
|
||||
updateSplashState(UPDATE_FAILURE);
|
||||
} else {
|
||||
process.nextTick(function () {
|
||||
return moduleUpdater.quitAndInstallUpdates();
|
||||
});
|
||||
process.nextTick(() => moduleUpdater.quitAndInstallUpdates());
|
||||
}
|
||||
});
|
||||
|
||||
addModulesListener(NO_PENDING_UPDATES, function () {
|
||||
return moduleUpdater.checkForUpdates();
|
||||
});
|
||||
addModulesListener(NO_PENDING_UPDATES, () => moduleUpdater.checkForUpdates());
|
||||
|
||||
addModulesListener(INSTALLING_MODULE, function (name, current, total) {
|
||||
splashState = { current: current, total: total };
|
||||
addModulesListener(INSTALLING_MODULE, (name, current, total) => {
|
||||
splashState = { current, total };
|
||||
updateSplashState(INSTALLING_UPDATES);
|
||||
});
|
||||
|
||||
addModulesListener(INSTALLED_MODULE, function (name, current, total, succeeded) {
|
||||
return delete splashState.progress;
|
||||
});
|
||||
addModulesListener(INSTALLED_MODULE, (name, current, total, succeeded) => delete splashState.progress);
|
||||
|
||||
addModulesListener(INSTALLING_MODULE_PROGRESS, function (name, progress) {
|
||||
addModulesListener(INSTALLING_MODULE_PROGRESS, (name, progress) => {
|
||||
splashState.progress = progress;
|
||||
updateSplashState(INSTALLING_UPDATES);
|
||||
});
|
||||
|
||||
addModulesListener(INSTALLING_MODULES_FINISHED, function (succeeded, failed) {
|
||||
return moduleUpdater.checkForUpdates();
|
||||
});
|
||||
addModulesListener(INSTALLING_MODULES_FINISHED, (succeeded, failed) => moduleUpdater.checkForUpdates());
|
||||
|
||||
addModulesListener(UPDATE_MANUALLY, function (newVersion) {
|
||||
addModulesListener(UPDATE_MANUALLY, newVersion => {
|
||||
splashState.newVersion = newVersion;
|
||||
updateSplashState(UPDATE_MANUALLY);
|
||||
});
|
||||
|
@ -171,7 +153,7 @@ function destroySplash() {
|
|||
if (splashWindow) {
|
||||
splashWindow.setSkipTaskbar(true);
|
||||
// defer the window hiding for a short moment so it gets covered by the main window
|
||||
var _nukeWindow = function _nukeWindow() {
|
||||
const _nukeWindow = () => {
|
||||
splashWindow.hide();
|
||||
splashWindow.close();
|
||||
splashWindow = null;
|
||||
|
@ -186,37 +168,14 @@ function addModulesListener(event, listener) {
|
|||
}
|
||||
|
||||
function removeModulesListeners() {
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = Object.keys(modulesListeners)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var event = _step.value;
|
||||
|
||||
moduleUpdater.events.removeListener(event, modulesListeners[event]);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
for (const event of Object.keys(modulesListeners)) {
|
||||
moduleUpdater.events.removeListener(event, modulesListeners[event]);
|
||||
}
|
||||
}
|
||||
|
||||
function startUpdateTimeout() {
|
||||
if (!updateTimeout) {
|
||||
updateTimeout = setTimeout(function () {
|
||||
return scheduleUpdateCheck();
|
||||
}, UPDATE_TIMEOUT_WAIT);
|
||||
updateTimeout = setTimeout(() => scheduleUpdateCheck(), UPDATE_TIMEOUT_WAIT);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -234,7 +193,7 @@ function updateSplashState(event) {
|
|||
}
|
||||
|
||||
function launchSplashWindow(startMinimized) {
|
||||
var windowConfig = {
|
||||
const windowConfig = {
|
||||
width: LOADING_WINDOW_WIDTH,
|
||||
height: LOADING_WINDOW_HEIGHT,
|
||||
transparent: false,
|
||||
|
@ -247,11 +206,9 @@ function launchSplashWindow(startMinimized) {
|
|||
splashWindow = new _electron.BrowserWindow(windowConfig);
|
||||
|
||||
// prevent users from dropping links to navigate in splash window
|
||||
splashWindow.webContents.on('will-navigate', function (e) {
|
||||
return e.preventDefault();
|
||||
});
|
||||
splashWindow.webContents.on('will-navigate', e => e.preventDefault());
|
||||
|
||||
splashWindow.webContents.on('new-window', function (e, windowURL) {
|
||||
splashWindow.webContents.on('new-window', (e, windowURL) => {
|
||||
e.preventDefault();
|
||||
_electron.shell.openExternal(windowURL);
|
||||
// exit, but delay half a second because openExternal is about to fire
|
||||
|
@ -261,7 +218,7 @@ function launchSplashWindow(startMinimized) {
|
|||
|
||||
if (process.platform !== 'darwin') {
|
||||
// citron note: this causes a crash on quit while the window is open on osx
|
||||
splashWindow.on('closed', function () {
|
||||
splashWindow.on('closed', () => {
|
||||
splashWindow = null;
|
||||
if (!launchedMainWindow) {
|
||||
// user has closed this window before we launched the app, so let's quit
|
||||
|
@ -270,7 +227,7 @@ function launchSplashWindow(startMinimized) {
|
|||
});
|
||||
}
|
||||
|
||||
_ipcMain2.default.on('SPLASH_SCREEN_READY', function () {
|
||||
_ipcMain2.default.on('SPLASH_SCREEN_READY', () => {
|
||||
if (splashWindow && !startMinimized) {
|
||||
splashWindow.show();
|
||||
}
|
||||
|
@ -278,7 +235,7 @@ function launchSplashWindow(startMinimized) {
|
|||
moduleUpdater.installPendingUpdates();
|
||||
});
|
||||
|
||||
var splashUrl = _url2.default.format({
|
||||
const splashUrl = _url2.default.format({
|
||||
protocol: 'file',
|
||||
slashes: true,
|
||||
pathname: _path2.default.join(__dirname, 'splash', 'index.html')
|
||||
|
@ -297,11 +254,9 @@ function launchMainWindow() {
|
|||
function scheduleUpdateCheck() {
|
||||
// TODO: can we use backoff here?
|
||||
updateAttempt += 1;
|
||||
var retryInSeconds = Math.min(updateAttempt * 10, RETRY_CAP_SECONDS);
|
||||
const retryInSeconds = Math.min(updateAttempt * 10, RETRY_CAP_SECONDS);
|
||||
splashState.seconds = retryInSeconds;
|
||||
setTimeout(function () {
|
||||
return moduleUpdater.checkForUpdates();
|
||||
}, retryInSeconds * 1000);
|
||||
setTimeout(() => moduleUpdater.checkForUpdates(), retryInSeconds * 1000);
|
||||
}
|
||||
|
||||
function focusWindow() {
|
||||
|
@ -312,7 +267,5 @@ function focusWindow() {
|
|||
|
||||
function pageReady() {
|
||||
destroySplash();
|
||||
process.nextTick(function () {
|
||||
return events.emit(APP_SHOULD_SHOW);
|
||||
});
|
||||
process.nextTick(() => events.emit(APP_SHOULD_SHOW));
|
||||
}
|
|
@ -38,68 +38,46 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj;
|
|||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
// citron note: this assumes the execPath is in the format Discord/someVersion/Discord.exe
|
||||
var appFolder = _path2.default.resolve(process.execPath, '..');
|
||||
var rootFolder = _path2.default.resolve(appFolder, '..');
|
||||
var exeName = _path2.default.basename(process.execPath);
|
||||
var updateExe = _path2.default.join(rootFolder, 'Update.exe');
|
||||
const appFolder = _path2.default.resolve(process.execPath, '..');
|
||||
const rootFolder = _path2.default.resolve(appFolder, '..');
|
||||
const exeName = _path2.default.basename(process.execPath);
|
||||
const updateExe = _path2.default.join(rootFolder, 'Update.exe');
|
||||
|
||||
// Specialized spawn function specifically used for spawning the updater in
|
||||
// update mode. Calls back with progress percentages.
|
||||
// Returns Promise.
|
||||
function spawnUpdateInstall(updateUrl, progressCallback) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
var proc = _child_process2.default.spawn(updateExe, ['--update', updateUrl]);
|
||||
return new Promise((resolve, reject) => {
|
||||
const proc = _child_process2.default.spawn(updateExe, ['--update', updateUrl]);
|
||||
proc.on('error', reject);
|
||||
proc.on('exit', function (code) {
|
||||
proc.on('exit', code => {
|
||||
if (code !== 0) {
|
||||
return reject(new Error('Update failed with exit code ' + code));
|
||||
return reject(new Error(`Update failed with exit code ${code}`));
|
||||
}
|
||||
return resolve();
|
||||
});
|
||||
|
||||
var lastProgress = -1;
|
||||
let lastProgress = -1;
|
||||
function parseProgress() {
|
||||
var lines = stdout.split(/\r?\n/);
|
||||
const lines = stdout.split(/\r?\n/);
|
||||
if (lines.length === 1) return;
|
||||
// return the last (possibly incomplete) line to stdout for parsing again
|
||||
stdout = lines.pop();
|
||||
var currentProgress = void 0;
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = lines[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var line = _step.value;
|
||||
|
||||
if (!/^\d\d?$/.test(line)) continue;
|
||||
var progress = Number(line);
|
||||
// make sure that this number is steadily increasing
|
||||
if (lastProgress > progress) continue;
|
||||
currentProgress = progress;
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
let currentProgress;
|
||||
for (const line of lines) {
|
||||
if (!/^\d\d?$/.test(line)) continue;
|
||||
const progress = Number(line);
|
||||
// make sure that this number is steadily increasing
|
||||
if (lastProgress > progress) continue;
|
||||
currentProgress = progress;
|
||||
}
|
||||
|
||||
if (currentProgress == null) return;
|
||||
lastProgress = currentProgress;
|
||||
progressCallback(Math.min(currentProgress, 100));
|
||||
}
|
||||
|
||||
var stdout = '';
|
||||
proc.stdout.on('data', function (chunk) {
|
||||
let stdout = '';
|
||||
proc.stdout.on('data', chunk => {
|
||||
stdout += String(chunk);
|
||||
parseProgress();
|
||||
});
|
||||
|
@ -116,17 +94,17 @@ function spawnUpdate(args, callback) {
|
|||
// provided by Squirrel's Update.exe
|
||||
function createShortcuts(callback, updateOnly) {
|
||||
// move icon out to a more stable location, to keep shortcuts from breaking as much
|
||||
var icoSrc = _path2.default.join(appFolder, 'app.ico');
|
||||
var icoDest = _path2.default.join(rootFolder, 'app.ico');
|
||||
var icoForTarget = icoDest;
|
||||
const icoSrc = _path2.default.join(appFolder, 'app.ico');
|
||||
const icoDest = _path2.default.join(rootFolder, 'app.ico');
|
||||
let icoForTarget = icoDest;
|
||||
try {
|
||||
var ico = _fs2.default.readFileSync(icoSrc);
|
||||
const ico = _fs2.default.readFileSync(icoSrc);
|
||||
_fs2.default.writeFileSync(icoDest, ico);
|
||||
} catch (e) {
|
||||
// if we can't write there for some reason, just use the source.
|
||||
icoForTarget = icoSrc;
|
||||
}
|
||||
var createShortcutArgs = ['--createShortcut', exeName, '--setupIcon', icoForTarget];
|
||||
const createShortcutArgs = ['--createShortcut', exeName, '--setupIcon', icoForTarget];
|
||||
if (updateOnly) {
|
||||
createShortcutArgs.push('--updateOnly');
|
||||
}
|
||||
|
@ -135,7 +113,7 @@ function createShortcuts(callback, updateOnly) {
|
|||
|
||||
// Add a protocol registration for this application.
|
||||
function installProtocol(protocol, callback) {
|
||||
var queue = [['HKCU\\Software\\Classes\\' + protocol, '/ve', '/d', 'URL:' + protocol + ' Protocol'], ['HKCU\\Software\\Classes\\' + protocol, '/v', 'URL Protocol'], ['HKCU\\Software\\Classes\\' + protocol + '\\DefaultIcon', '/ve', '/d', '"' + process.execPath + '",-1'], ['HKCU\\Software\\Classes\\' + protocol + '\\shell\\open\\command', '/ve', '/d', '"' + process.execPath + '" --url -- "%1"']];
|
||||
const queue = [['HKCU\\Software\\Classes\\' + protocol, '/ve', '/d', `URL:${protocol} Protocol`], ['HKCU\\Software\\Classes\\' + protocol, '/v', 'URL Protocol'], ['HKCU\\Software\\Classes\\' + protocol + '\\DefaultIcon', '/ve', '/d', '"' + process.execPath + '",-1'], ['HKCU\\Software\\Classes\\' + protocol + '\\shell\\open\\command', '/ve', '/d', `"${process.execPath}" --url -- "%1"`]];
|
||||
|
||||
windowsUtils.addToRegistry(queue, callback);
|
||||
}
|
||||
|
@ -167,9 +145,9 @@ function uninstallProtocol(protocol, callback) {
|
|||
function handleStartupEvent(protocol, app, squirrelCommand) {
|
||||
switch (squirrelCommand) {
|
||||
case '--squirrel-install':
|
||||
createShortcuts(function () {
|
||||
autoStart.install(function () {
|
||||
installProtocol(protocol, function () {
|
||||
createShortcuts(() => {
|
||||
autoStart.install(() => {
|
||||
installProtocol(protocol, () => {
|
||||
terminate(app);
|
||||
});
|
||||
});
|
||||
|
@ -177,9 +155,9 @@ function handleStartupEvent(protocol, app, squirrelCommand) {
|
|||
return true;
|
||||
|
||||
case '--squirrel-updated':
|
||||
updateShortcuts(function () {
|
||||
autoStart.update(function () {
|
||||
installProtocol(protocol, function () {
|
||||
updateShortcuts(() => {
|
||||
autoStart.update(() => {
|
||||
installProtocol(protocol, () => {
|
||||
terminate(app);
|
||||
});
|
||||
});
|
||||
|
@ -187,14 +165,10 @@ function handleStartupEvent(protocol, app, squirrelCommand) {
|
|||
return true;
|
||||
|
||||
case '--squirrel-uninstall':
|
||||
removeShortcuts(function () {
|
||||
autoStart.uninstall(function () {
|
||||
uninstallProtocol(protocol, function () {
|
||||
singleInstance.pipeCommandLineArgs(function () {
|
||||
return terminate(app);
|
||||
}, function () {
|
||||
return terminate(app);
|
||||
});
|
||||
removeShortcuts(() => {
|
||||
autoStart.uninstall(() => {
|
||||
uninstallProtocol(protocol, () => {
|
||||
singleInstance.pipeCommandLineArgs(() => terminate(app), () => terminate(app));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -216,8 +190,8 @@ function updateExistsSync() {
|
|||
|
||||
// Restart app as the new version
|
||||
function restart(app, newVersion) {
|
||||
app.once('will-quit', function () {
|
||||
var execPath = _path2.default.resolve(rootFolder, 'app-' + newVersion + '/' + exeName);
|
||||
app.once('will-quit', () => {
|
||||
const execPath = _path2.default.resolve(rootFolder, `app-${newVersion}/${exeName}`);
|
||||
_child_process2.default.spawn(execPath, [], { detached: true });
|
||||
});
|
||||
app.quit();
|
||||
|
|
|
@ -10,9 +10,7 @@ exports.default = [{
|
|||
label: 'Discord',
|
||||
submenu: [{
|
||||
label: 'Quit',
|
||||
click: function click() {
|
||||
return _electron.app.quit();
|
||||
},
|
||||
click: () => _electron.app.quit(),
|
||||
accelerator: 'Command+Q'
|
||||
}]
|
||||
}];
|
||||
|
|
|
@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", {
|
|||
|
||||
var _electron = require('electron');
|
||||
|
||||
var menu = require('./' + process.platform);
|
||||
const menu = require('./' + process.platform);
|
||||
|
||||
exports.default = _electron.Menu.buildFromTemplate(menu);
|
||||
module.exports = exports['default'];
|
|
@ -10,9 +10,7 @@ exports.default = [{
|
|||
label: '&File',
|
||||
submenu: [{
|
||||
label: '&Exit',
|
||||
click: function click() {
|
||||
return _electron.app.quit();
|
||||
},
|
||||
click: () => _electron.app.quit(),
|
||||
accelerator: 'Control+Q'
|
||||
}]
|
||||
}];
|
||||
|
|
|
@ -10,9 +10,7 @@ exports.default = [{
|
|||
label: '&File',
|
||||
submenu: [{
|
||||
label: '&Exit',
|
||||
click: function click() {
|
||||
return _electron.app.quit();
|
||||
},
|
||||
click: () => _electron.app.quit(),
|
||||
accelerator: 'Alt+F4'
|
||||
}]
|
||||
}];
|
||||
|
|
|
@ -17,20 +17,20 @@ var _path2 = _interopRequireDefault(_path);
|
|||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
var regExe = process.env.SystemRoot ? _path2.default.join(process.env.SystemRoot, 'System32', 'reg.exe') : 'reg.exe';
|
||||
const regExe = process.env.SystemRoot ? _path2.default.join(process.env.SystemRoot, 'System32', 'reg.exe') : 'reg.exe';
|
||||
|
||||
// Spawn a command and invoke the callback when it completes with an error
|
||||
// and the output from standard out.
|
||||
function spawn(command, args, callback) {
|
||||
var stdout = '';
|
||||
let stdout = '';
|
||||
|
||||
var spawnedProcess = void 0;
|
||||
let spawnedProcess;
|
||||
try {
|
||||
// TODO: contrary to below, it should not throw any error
|
||||
spawnedProcess = _child_process2.default.spawn(command, args);
|
||||
} catch (err) {
|
||||
// Spawn can throw an error
|
||||
process.nextTick(function () {
|
||||
process.nextTick(() => {
|
||||
if (callback != null) {
|
||||
callback(err, stdout);
|
||||
}
|
||||
|
@ -39,14 +39,14 @@ function spawn(command, args, callback) {
|
|||
}
|
||||
|
||||
// TODO: we need to specify the encoding for the data if we're going to concat it as a string
|
||||
spawnedProcess.stdout.on('data', function (data) {
|
||||
spawnedProcess.stdout.on('data', data => {
|
||||
stdout += data;
|
||||
});
|
||||
|
||||
var err = null;
|
||||
let err = null;
|
||||
// TODO: close event might not get called, we should
|
||||
// callback on error https://nodejs.org/api/child_process.html#child_process_event_error
|
||||
spawnedProcess.on('error', function (err) {
|
||||
spawnedProcess.on('error', err => {
|
||||
// TODO: there should always be an error
|
||||
if (err != null) {
|
||||
err = err;
|
||||
|
@ -54,7 +54,7 @@ function spawn(command, args, callback) {
|
|||
});
|
||||
|
||||
// TODO: don't listen to close, but listen to exit instead
|
||||
spawnedProcess.on('close', function (code, signal) {
|
||||
spawnedProcess.on('close', (code, signal) => {
|
||||
if (err === null && code !== 0) {
|
||||
err = new Error('Command failed: ' + (signal || code));
|
||||
}
|
||||
|
@ -80,10 +80,8 @@ function addToRegistry(queue, callback) {
|
|||
return callback && callback();
|
||||
}
|
||||
|
||||
var args = queue.shift();
|
||||
const args = queue.shift();
|
||||
args.unshift('add');
|
||||
args.push('/f');
|
||||
return spawnReg(args, function () {
|
||||
return addToRegistry(queue, callback);
|
||||
});
|
||||
return spawnReg(args, () => addToRegistry(queue, callback));
|
||||
}
|
|
@ -4,24 +4,15 @@ Object.defineProperty(exports, "__esModule", {
|
|||
value: true
|
||||
});
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
// copied from discord_app/lib because including from there is broken.
|
||||
|
||||
var Backoff = function () {
|
||||
class Backoff {
|
||||
|
||||
/**
|
||||
* Create a backoff instance can automatically backoff retries.
|
||||
*/
|
||||
function Backoff() {
|
||||
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 500;
|
||||
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
|
||||
var jitter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
|
||||
|
||||
_classCallCheck(this, Backoff);
|
||||
|
||||
constructor(min = 500, max = null, jitter = true) {
|
||||
this.min = min;
|
||||
this.max = max != null ? max : min * 10;
|
||||
this.jitter = jitter;
|
||||
|
@ -34,94 +25,69 @@ var Backoff = function () {
|
|||
/**
|
||||
* Return the number of failures.
|
||||
*/
|
||||
get fails() {
|
||||
return this._fails;
|
||||
}
|
||||
|
||||
/**
|
||||
* Current backoff value in milliseconds.
|
||||
*/
|
||||
get current() {
|
||||
return this._current;
|
||||
}
|
||||
|
||||
_createClass(Backoff, [{
|
||||
key: 'succeed',
|
||||
/**
|
||||
* A callback is going to fire.
|
||||
*/
|
||||
get pending() {
|
||||
return this._timeoutId != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear any pending callbacks and reset the backoff.
|
||||
*/
|
||||
succeed() {
|
||||
this.cancel();
|
||||
this._fails = 0;
|
||||
this._current = this.min;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear any pending callbacks and reset the backoff.
|
||||
*/
|
||||
value: function succeed() {
|
||||
this.cancel();
|
||||
this._fails = 0;
|
||||
this._current = this.min;
|
||||
/**
|
||||
* Increment the backoff and schedule a callback if provided.
|
||||
*/
|
||||
fail(callback) {
|
||||
this._fails += 1;
|
||||
let delay = this._current * 2;
|
||||
if (this.jitter) {
|
||||
delay *= Math.random();
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment the backoff and schedule a callback if provided.
|
||||
*/
|
||||
|
||||
}, {
|
||||
key: 'fail',
|
||||
value: function fail(callback) {
|
||||
var _this = this;
|
||||
|
||||
this._fails += 1;
|
||||
var delay = this._current * 2;
|
||||
if (this.jitter) {
|
||||
delay *= Math.random();
|
||||
}
|
||||
this._current = Math.min(this._current + delay, this.max);
|
||||
if (callback != null) {
|
||||
if (this._timeoutId != null) {
|
||||
throw new Error('callback already pending');
|
||||
}
|
||||
this._timeoutId = setTimeout(function () {
|
||||
try {
|
||||
if (callback != null) {
|
||||
callback();
|
||||
}
|
||||
} finally {
|
||||
_this._timeoutId = null;
|
||||
}
|
||||
}, this._current);
|
||||
}
|
||||
return this._current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear any pending callbacks.
|
||||
*/
|
||||
|
||||
}, {
|
||||
key: 'cancel',
|
||||
value: function cancel() {
|
||||
this._current = Math.min(this._current + delay, this.max);
|
||||
if (callback != null) {
|
||||
if (this._timeoutId != null) {
|
||||
clearTimeout(this._timeoutId);
|
||||
this._timeoutId = null;
|
||||
throw new Error('callback already pending');
|
||||
}
|
||||
this._timeoutId = setTimeout(() => {
|
||||
try {
|
||||
if (callback != null) {
|
||||
callback();
|
||||
}
|
||||
} finally {
|
||||
this._timeoutId = null;
|
||||
}
|
||||
}, this._current);
|
||||
}
|
||||
}, {
|
||||
key: 'fails',
|
||||
get: function get() {
|
||||
return this._fails;
|
||||
return this._current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear any pending callbacks.
|
||||
*/
|
||||
cancel() {
|
||||
if (this._timeoutId != null) {
|
||||
clearTimeout(this._timeoutId);
|
||||
this._timeoutId = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Current backoff value in milliseconds.
|
||||
*/
|
||||
|
||||
}, {
|
||||
key: 'current',
|
||||
get: function get() {
|
||||
return this._current;
|
||||
}
|
||||
|
||||
/**
|
||||
* A callback is going to fire.
|
||||
*/
|
||||
|
||||
}, {
|
||||
key: 'pending',
|
||||
get: function get() {
|
||||
return this._timeoutId != null;
|
||||
}
|
||||
}]);
|
||||
|
||||
return Backoff;
|
||||
}();
|
||||
|
||||
}
|
||||
}
|
||||
exports.default = Backoff;
|
||||
module.exports = exports['default'];
|
|
@ -3,42 +3,27 @@
|
|||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
var FeatureFlags = function () {
|
||||
function FeatureFlags() {
|
||||
_classCallCheck(this, FeatureFlags);
|
||||
|
||||
class FeatureFlags {
|
||||
constructor() {
|
||||
this.flags = new Set();
|
||||
}
|
||||
|
||||
_createClass(FeatureFlags, [{
|
||||
key: 'getSupported',
|
||||
value: function getSupported() {
|
||||
return Array.from(this.flags);
|
||||
}
|
||||
}, {
|
||||
key: 'supports',
|
||||
value: function supports(feature) {
|
||||
return this.flags.has(feature);
|
||||
}
|
||||
}, {
|
||||
key: 'declareSupported',
|
||||
value: function declareSupported(feature) {
|
||||
if (this.supports(feature)) {
|
||||
console.error('Feature redeclared; is this a duplicate flag? ', feature);
|
||||
return;
|
||||
}
|
||||
getSupported() {
|
||||
return Array.from(this.flags);
|
||||
}
|
||||
|
||||
this.flags.add(feature);
|
||||
supports(feature) {
|
||||
return this.flags.has(feature);
|
||||
}
|
||||
|
||||
declareSupported(feature) {
|
||||
if (this.supports(feature)) {
|
||||
console.error('Feature redeclared; is this a duplicate flag? ', feature);
|
||||
return;
|
||||
}
|
||||
}]);
|
||||
|
||||
return FeatureFlags;
|
||||
}();
|
||||
|
||||
this.flags.add(feature);
|
||||
}
|
||||
}
|
||||
exports.default = FeatureFlags;
|
||||
module.exports = exports['default'];
|
|
@ -4,8 +4,6 @@ Object.defineProperty(exports, "__esModule", {
|
|||
value: true
|
||||
});
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
|
||||
|
||||
var _fs = require('fs');
|
||||
|
||||
var _fs2 = _interopRequireDefault(_fs);
|
||||
|
@ -16,14 +14,10 @@ var _path2 = _interopRequireDefault(_path);
|
|||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
// TODO: sync fs operations could cause slowdown and/or freezes, depending on usage
|
||||
// if this is fine, remove this todo
|
||||
var Settings = function () {
|
||||
function Settings(root) {
|
||||
_classCallCheck(this, Settings);
|
||||
|
||||
class Settings {
|
||||
constructor(root) {
|
||||
this.path = _path2.default.join(root, 'settings.json');
|
||||
try {
|
||||
this.lastSaved = _fs2.default.readFileSync(this.path);
|
||||
|
@ -35,54 +29,43 @@ var Settings = function () {
|
|||
this.lastModified = this._lastModified();
|
||||
}
|
||||
|
||||
_createClass(Settings, [{
|
||||
key: '_lastModified',
|
||||
value: function _lastModified() {
|
||||
try {
|
||||
return _fs2.default.statSync(this.path).mtime.getTime();
|
||||
} catch (e) {
|
||||
return 0;
|
||||
}
|
||||
_lastModified() {
|
||||
try {
|
||||
return _fs2.default.statSync(this.path).mtime.getTime();
|
||||
} catch (e) {
|
||||
return 0;
|
||||
}
|
||||
}, {
|
||||
key: 'get',
|
||||
value: function get(key) {
|
||||
var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
|
||||
}
|
||||
|
||||
if (this.settings.hasOwnProperty(key)) {
|
||||
return this.settings[key];
|
||||
}
|
||||
|
||||
return defaultValue;
|
||||
get(key, defaultValue = false) {
|
||||
if (this.settings.hasOwnProperty(key)) {
|
||||
return this.settings[key];
|
||||
}
|
||||
}, {
|
||||
key: 'set',
|
||||
value: function set(key, value) {
|
||||
this.settings[key] = value;
|
||||
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
set(key, value) {
|
||||
this.settings[key] = value;
|
||||
}
|
||||
|
||||
save() {
|
||||
if (this.lastModified && this.lastModified !== this._lastModified()) {
|
||||
console.warn('Not saving settings, it has been externally modified.');
|
||||
return;
|
||||
}
|
||||
}, {
|
||||
key: 'save',
|
||||
value: function save() {
|
||||
if (this.lastModified && this.lastModified !== this._lastModified()) {
|
||||
console.warn('Not saving settings, it has been externally modified.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
var toSave = JSON.stringify(this.settings, null, 2);
|
||||
if (this.lastSaved != toSave) {
|
||||
this.lastSaved = toSave;
|
||||
_fs2.default.writeFileSync(this.path, toSave);
|
||||
this.lastModified = this._lastModified();
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Failed saving settings with error: ', err);
|
||||
try {
|
||||
const toSave = JSON.stringify(this.settings, null, 2);
|
||||
if (this.lastSaved != toSave) {
|
||||
this.lastSaved = toSave;
|
||||
_fs2.default.writeFileSync(this.path, toSave);
|
||||
this.lastModified = this._lastModified();
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Failed saving settings with error: ', err);
|
||||
}
|
||||
}]);
|
||||
|
||||
return Settings;
|
||||
}();
|
||||
|
||||
}
|
||||
}
|
||||
exports.default = Settings;
|
||||
module.exports = exports['default'];
|
|
@ -5,11 +5,11 @@ Object.defineProperty(exports, "__esModule", {
|
|||
});
|
||||
exports.events = exports.NO_PENDING_UPDATES = exports.INSTALLING_MODULE_PROGRESS = exports.INSTALLING_MODULE = exports.INSTALLING_MODULES_FINISHED = exports.DOWNLOADED_MODULE = exports.UPDATE_MANUALLY = exports.DOWNLOADING_MODULES_FINISHED = exports.DOWNLOADING_MODULE_PROGRESS = exports.DOWNLOADING_MODULE = exports.UPDATE_CHECK_FINISHED = exports.INSTALLED_MODULE = exports.CHECKING_FOR_UPDATES = undefined;
|
||||
|
||||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
|
||||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; // Manages additional module installation and management.
|
||||
// We add the module folder path to require() lookup paths here.
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
|
||||
// undocumented node API
|
||||
|
||||
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
|
||||
|
||||
exports.initPathsOnly = initPathsOnly;
|
||||
exports.init = init;
|
||||
|
@ -54,129 +54,88 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj;
|
|||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
const originalFs = require('original-fs');
|
||||
|
||||
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
|
||||
|
||||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // Manages additional module installation and management.
|
||||
// We add the module folder path to require() lookup paths here.
|
||||
|
||||
// undocumented node API
|
||||
|
||||
|
||||
var originalFs = require('original-fs');
|
||||
|
||||
var Events = function (_EventEmitter) {
|
||||
_inherits(Events, _EventEmitter);
|
||||
|
||||
function Events() {
|
||||
_classCallCheck(this, Events);
|
||||
|
||||
return _possibleConstructorReturn(this, (Events.__proto__ || Object.getPrototypeOf(Events)).apply(this, arguments));
|
||||
class Events extends _events.EventEmitter {
|
||||
emit(...args) {
|
||||
process.nextTick(() => super.emit.apply(this, args));
|
||||
}
|
||||
}
|
||||
|
||||
_createClass(Events, [{
|
||||
key: 'emit',
|
||||
value: function emit() {
|
||||
var _this2 = this;
|
||||
|
||||
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
process.nextTick(function () {
|
||||
return _get(Events.prototype.__proto__ || Object.getPrototypeOf(Events.prototype), 'emit', _this2).apply(_this2, args);
|
||||
});
|
||||
}
|
||||
}]);
|
||||
|
||||
return Events;
|
||||
}(_events.EventEmitter);
|
||||
|
||||
var LogStream = function () {
|
||||
function LogStream(logPath) {
|
||||
_classCallCheck(this, LogStream);
|
||||
|
||||
class LogStream {
|
||||
constructor(logPath) {
|
||||
try {
|
||||
this.logStream = _fs2.default.createWriteStream(logPath, { flags: 'a' });
|
||||
} catch (e) {
|
||||
console.error('Failed to create ' + logPath + ': ' + String(e));
|
||||
console.error(`Failed to create ${logPath}: ${String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
_createClass(LogStream, [{
|
||||
key: 'log',
|
||||
value: function log(message) {
|
||||
message = '[Modules] ' + message;
|
||||
console.log(message);
|
||||
if (this.logStream) {
|
||||
this.logStream.write(message);
|
||||
this.logStream.write('\r\n');
|
||||
}
|
||||
log(message) {
|
||||
message = `[Modules] ${message}`;
|
||||
console.log(message);
|
||||
if (this.logStream) {
|
||||
this.logStream.write(message);
|
||||
this.logStream.write('\r\n');
|
||||
}
|
||||
}, {
|
||||
key: 'end',
|
||||
value: function end() {
|
||||
if (this.logStream) {
|
||||
this.logStream.end();
|
||||
this.logStream = null;
|
||||
}
|
||||
}
|
||||
}]);
|
||||
}
|
||||
|
||||
return LogStream;
|
||||
}();
|
||||
end() {
|
||||
if (this.logStream) {
|
||||
this.logStream.end();
|
||||
this.logStream = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// events
|
||||
|
||||
|
||||
var CHECKING_FOR_UPDATES = exports.CHECKING_FOR_UPDATES = 'checking-for-updates';
|
||||
var INSTALLED_MODULE = exports.INSTALLED_MODULE = 'installed-module';
|
||||
var UPDATE_CHECK_FINISHED = exports.UPDATE_CHECK_FINISHED = 'update-check-finished';
|
||||
var DOWNLOADING_MODULE = exports.DOWNLOADING_MODULE = 'downloading-module';
|
||||
var DOWNLOADING_MODULE_PROGRESS = exports.DOWNLOADING_MODULE_PROGRESS = 'downloading-module-progress';
|
||||
var DOWNLOADING_MODULES_FINISHED = exports.DOWNLOADING_MODULES_FINISHED = 'downloading-modules-finished';
|
||||
var UPDATE_MANUALLY = exports.UPDATE_MANUALLY = 'update-manually';
|
||||
var DOWNLOADED_MODULE = exports.DOWNLOADED_MODULE = 'downloaded-module';
|
||||
var INSTALLING_MODULES_FINISHED = exports.INSTALLING_MODULES_FINISHED = 'installing-modules-finished';
|
||||
var INSTALLING_MODULE = exports.INSTALLING_MODULE = 'installing-module';
|
||||
var INSTALLING_MODULE_PROGRESS = exports.INSTALLING_MODULE_PROGRESS = 'installing-module-progress';
|
||||
var NO_PENDING_UPDATES = exports.NO_PENDING_UPDATES = 'no-pending-updates';
|
||||
const CHECKING_FOR_UPDATES = exports.CHECKING_FOR_UPDATES = 'checking-for-updates';
|
||||
const INSTALLED_MODULE = exports.INSTALLED_MODULE = 'installed-module';
|
||||
const UPDATE_CHECK_FINISHED = exports.UPDATE_CHECK_FINISHED = 'update-check-finished';
|
||||
const DOWNLOADING_MODULE = exports.DOWNLOADING_MODULE = 'downloading-module';
|
||||
const DOWNLOADING_MODULE_PROGRESS = exports.DOWNLOADING_MODULE_PROGRESS = 'downloading-module-progress';
|
||||
const DOWNLOADING_MODULES_FINISHED = exports.DOWNLOADING_MODULES_FINISHED = 'downloading-modules-finished';
|
||||
const UPDATE_MANUALLY = exports.UPDATE_MANUALLY = 'update-manually';
|
||||
const DOWNLOADED_MODULE = exports.DOWNLOADED_MODULE = 'downloaded-module';
|
||||
const INSTALLING_MODULES_FINISHED = exports.INSTALLING_MODULES_FINISHED = 'installing-modules-finished';
|
||||
const INSTALLING_MODULE = exports.INSTALLING_MODULE = 'installing-module';
|
||||
const INSTALLING_MODULE_PROGRESS = exports.INSTALLING_MODULE_PROGRESS = 'installing-module-progress';
|
||||
const NO_PENDING_UPDATES = exports.NO_PENDING_UPDATES = 'no-pending-updates';
|
||||
|
||||
// settings
|
||||
var ALWAYS_ALLOW_UPDATES = 'ALWAYS_ALLOW_UPDATES';
|
||||
var SKIP_HOST_UPDATE = 'SKIP_HOST_UPDATE';
|
||||
var SKIP_MODULE_UPDATE = 'SKIP_MODULE_UPDATE';
|
||||
var ALWAYS_BOOTSTRAP_MODULES = 'ALWAYS_BOOTSTRAP_MODULES';
|
||||
var USE_LOCAL_MODULE_VERSIONS = 'USE_LOCAL_MODULE_VERSIONS';
|
||||
const ALWAYS_ALLOW_UPDATES = 'ALWAYS_ALLOW_UPDATES';
|
||||
const SKIP_HOST_UPDATE = 'SKIP_HOST_UPDATE';
|
||||
const SKIP_MODULE_UPDATE = 'SKIP_MODULE_UPDATE';
|
||||
const ALWAYS_BOOTSTRAP_MODULES = 'ALWAYS_BOOTSTRAP_MODULES';
|
||||
const USE_LOCAL_MODULE_VERSIONS = 'USE_LOCAL_MODULE_VERSIONS';
|
||||
|
||||
var request = require('../app_bootstrap/request');
|
||||
var REQUEST_TIMEOUT = 15000;
|
||||
var backoff = new _Backoff2.default(1000, 20000);
|
||||
var events = exports.events = new Events();
|
||||
const request = require('../app_bootstrap/request');
|
||||
const REQUEST_TIMEOUT = 15000;
|
||||
const backoff = new _Backoff2.default(1000, 20000);
|
||||
const events = exports.events = new Events();
|
||||
|
||||
var logger = void 0;
|
||||
var locallyInstalledModules = void 0;
|
||||
var moduleInstallPath = void 0;
|
||||
var installedModulesFilePath = void 0;
|
||||
var moduleDownloadPath = void 0;
|
||||
var bootstrapping = void 0;
|
||||
var hostUpdater = void 0;
|
||||
var hostUpdateAvailable = void 0;
|
||||
var skipHostUpdate = void 0;
|
||||
var skipModuleUpdate = void 0;
|
||||
var checkingForUpdates = void 0;
|
||||
var remoteBaseURL = void 0;
|
||||
var remoteQuery = void 0;
|
||||
var settings = void 0;
|
||||
var remoteModuleVersions = void 0;
|
||||
var installedModules = void 0;
|
||||
var download = void 0;
|
||||
var unzip = void 0;
|
||||
var newInstallInProgress = void 0;
|
||||
var localModuleVersionsFilePath = void 0;
|
||||
var updatable = void 0;
|
||||
var bootstrapManifestFilePath = void 0;
|
||||
let logger;
|
||||
let locallyInstalledModules;
|
||||
let moduleInstallPath;
|
||||
let installedModulesFilePath;
|
||||
let moduleDownloadPath;
|
||||
let bootstrapping;
|
||||
let hostUpdater;
|
||||
let hostUpdateAvailable;
|
||||
let skipHostUpdate;
|
||||
let skipModuleUpdate;
|
||||
let checkingForUpdates;
|
||||
let remoteBaseURL;
|
||||
let remoteQuery;
|
||||
let settings;
|
||||
let remoteModuleVersions;
|
||||
let installedModules;
|
||||
let download;
|
||||
let unzip;
|
||||
let newInstallInProgress;
|
||||
let localModuleVersionsFilePath;
|
||||
let updatable;
|
||||
let bootstrapManifestFilePath;
|
||||
|
||||
function initPathsOnly(_buildInfo) {
|
||||
if (locallyInstalledModules || moduleInstallPath) {
|
||||
|
@ -201,9 +160,9 @@ function initPathsOnly(_buildInfo) {
|
|||
}
|
||||
|
||||
function init(_endpoint, _settings, _buildInfo) {
|
||||
var endpoint = _endpoint;
|
||||
const endpoint = _endpoint;
|
||||
settings = _settings;
|
||||
var buildInfo = _buildInfo;
|
||||
const buildInfo = _buildInfo;
|
||||
updatable = buildInfo.version != '0.0.0' && !buildInfo.debug || settings.get(ALWAYS_ALLOW_UPDATES);
|
||||
|
||||
initPathsOnly(buildInfo);
|
||||
|
@ -242,21 +201,21 @@ function init(_endpoint, _settings, _buildInfo) {
|
|||
failures: 0
|
||||
};
|
||||
|
||||
logger.log('Modules initializing');
|
||||
logger.log('Distribution: ' + (locallyInstalledModules ? 'local' : 'remote'));
|
||||
logger.log('Host updates: ' + (skipHostUpdate ? 'disabled' : 'enabled'));
|
||||
logger.log('Module updates: ' + (skipModuleUpdate ? 'disabled' : 'enabled'));
|
||||
logger.log(`Modules initializing`);
|
||||
logger.log(`Distribution: ${locallyInstalledModules ? 'local' : 'remote'}`);
|
||||
logger.log(`Host updates: ${skipHostUpdate ? 'disabled' : 'enabled'}`);
|
||||
logger.log(`Module updates: ${skipModuleUpdate ? 'disabled' : 'enabled'}`);
|
||||
|
||||
if (!locallyInstalledModules) {
|
||||
installedModulesFilePath = _path2.default.join(moduleInstallPath, 'installed.json');
|
||||
moduleDownloadPath = _path2.default.join(moduleInstallPath, 'pending');
|
||||
_mkdirp2.default.sync(moduleDownloadPath);
|
||||
|
||||
logger.log('Module install path: ' + moduleInstallPath);
|
||||
logger.log('Module installed file path: ' + installedModulesFilePath);
|
||||
logger.log('Module download path: ' + moduleDownloadPath);
|
||||
logger.log(`Module install path: ${moduleInstallPath}`);
|
||||
logger.log(`Module installed file path: ${installedModulesFilePath}`);
|
||||
logger.log(`Module download path: ${moduleDownloadPath}`);
|
||||
|
||||
var failedLoadingInstalledModules = false;
|
||||
let failedLoadingInstalledModules = false;
|
||||
try {
|
||||
installedModules = JSON.parse(_fs2.default.readFileSync(installedModulesFilePath));
|
||||
} catch (err) {
|
||||
|
@ -270,46 +229,32 @@ function init(_endpoint, _settings, _buildInfo) {
|
|||
|
||||
hostUpdater = require('../app_bootstrap/hostUpdater');
|
||||
// TODO: hostUpdater constants
|
||||
hostUpdater.on('checking-for-update', function () {
|
||||
return events.emit(CHECKING_FOR_UPDATES);
|
||||
});
|
||||
hostUpdater.on('update-available', function () {
|
||||
return hostOnUpdateAvailable();
|
||||
});
|
||||
hostUpdater.on('update-progress', function (progress) {
|
||||
return hostOnUpdateProgress(progress);
|
||||
});
|
||||
hostUpdater.on('update-not-available', function () {
|
||||
return hostOnUpdateNotAvailable();
|
||||
});
|
||||
hostUpdater.on('update-manually', function (newVersion) {
|
||||
return hostOnUpdateManually(newVersion);
|
||||
});
|
||||
hostUpdater.on('update-downloaded', function () {
|
||||
return hostOnUpdateDownloaded();
|
||||
});
|
||||
hostUpdater.on('error', function (err) {
|
||||
return hostOnError(err);
|
||||
});
|
||||
var setFeedURL = hostUpdater.setFeedURL.bind(hostUpdater);
|
||||
hostUpdater.on('checking-for-update', () => events.emit(CHECKING_FOR_UPDATES));
|
||||
hostUpdater.on('update-available', () => hostOnUpdateAvailable());
|
||||
hostUpdater.on('update-progress', progress => hostOnUpdateProgress(progress));
|
||||
hostUpdater.on('update-not-available', () => hostOnUpdateNotAvailable());
|
||||
hostUpdater.on('update-manually', newVersion => hostOnUpdateManually(newVersion));
|
||||
hostUpdater.on('update-downloaded', () => hostOnUpdateDownloaded());
|
||||
hostUpdater.on('error', err => hostOnError(err));
|
||||
let setFeedURL = hostUpdater.setFeedURL.bind(hostUpdater);
|
||||
|
||||
remoteBaseURL = endpoint + '/modules/' + buildInfo.releaseChannel;
|
||||
remoteBaseURL = `${endpoint}/modules/${buildInfo.releaseChannel}`;
|
||||
// eslint-disable-next-line camelcase
|
||||
remoteQuery = { host_version: buildInfo.version };
|
||||
|
||||
switch (process.platform) {
|
||||
case 'darwin':
|
||||
setFeedURL(endpoint + '/updates/' + buildInfo.releaseChannel + '?platform=osx&version=' + buildInfo.version);
|
||||
setFeedURL(`${endpoint}/updates/${buildInfo.releaseChannel}?platform=osx&version=${buildInfo.version}`);
|
||||
remoteQuery.platform = 'osx';
|
||||
break;
|
||||
case 'win32':
|
||||
// Squirrel for Windows can't handle query params
|
||||
// https://github.com/Squirrel/Squirrel.Windows/issues/132
|
||||
setFeedURL(endpoint + '/updates/' + buildInfo.releaseChannel);
|
||||
setFeedURL(`${endpoint}/updates/${buildInfo.releaseChannel}`);
|
||||
remoteQuery.platform = 'win';
|
||||
break;
|
||||
case 'linux':
|
||||
setFeedURL(endpoint + '/updates/' + buildInfo.releaseChannel + '?platform=linux&version=' + buildInfo.version);
|
||||
setFeedURL(`${endpoint}/updates/${buildInfo.releaseChannel}?platform=linux&version=${buildInfo.version}`);
|
||||
remoteQuery.platform = 'linux';
|
||||
break;
|
||||
}
|
||||
|
@ -317,35 +262,14 @@ function init(_endpoint, _settings, _buildInfo) {
|
|||
|
||||
function cleanDownloadedModules(installedModules) {
|
||||
try {
|
||||
var entries = _fs2.default.readdirSync(moduleDownloadPath) || [];
|
||||
entries.forEach(function (entry) {
|
||||
var entryPath = _path2.default.join(moduleDownloadPath, entry);
|
||||
var isStale = true;
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = Object.keys(installedModules)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var moduleName = _step.value;
|
||||
|
||||
if (entryPath === installedModules[moduleName].updateZipfile) {
|
||||
isStale = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
const entries = _fs2.default.readdirSync(moduleDownloadPath) || [];
|
||||
entries.forEach(entry => {
|
||||
const entryPath = _path2.default.join(moduleDownloadPath, entry);
|
||||
let isStale = true;
|
||||
for (const moduleName of Object.keys(installedModules)) {
|
||||
if (entryPath === installedModules[moduleName].updateZipfile) {
|
||||
isStale = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -360,19 +284,19 @@ function cleanDownloadedModules(installedModules) {
|
|||
}
|
||||
|
||||
function hostOnUpdateAvailable() {
|
||||
logger.log('Host update is available.');
|
||||
logger.log(`Host update is available.`);
|
||||
hostUpdateAvailable = true;
|
||||
events.emit(UPDATE_CHECK_FINISHED, true, 1, false);
|
||||
events.emit(DOWNLOADING_MODULE, 'host', 1, 1);
|
||||
}
|
||||
|
||||
function hostOnUpdateProgress(progress) {
|
||||
logger.log('Host update progress: ' + progress + '%');
|
||||
logger.log(`Host update progress: ${progress}%`);
|
||||
events.emit(DOWNLOADING_MODULE_PROGRESS, 'host', progress);
|
||||
}
|
||||
|
||||
function hostOnUpdateNotAvailable() {
|
||||
logger.log('Host is up to date.');
|
||||
logger.log(`Host is up to date.`);
|
||||
if (!skipModuleUpdate) {
|
||||
checkForModuleUpdates();
|
||||
} else {
|
||||
|
@ -381,7 +305,7 @@ function hostOnUpdateNotAvailable() {
|
|||
}
|
||||
|
||||
function hostOnUpdateManually(newVersion) {
|
||||
logger.log('Host update is available. Manual update required!');
|
||||
logger.log(`Host update is available. Manual update required!`);
|
||||
hostUpdateAvailable = true;
|
||||
checkingForUpdates = false;
|
||||
events.emit(UPDATE_MANUALLY, newVersion);
|
||||
|
@ -389,14 +313,14 @@ function hostOnUpdateManually(newVersion) {
|
|||
}
|
||||
|
||||
function hostOnUpdateDownloaded() {
|
||||
logger.log('Host update downloaded.');
|
||||
logger.log(`Host update downloaded.`);
|
||||
checkingForUpdates = false;
|
||||
events.emit(DOWNLOADED_MODULE, 'host', 1, 1, true);
|
||||
events.emit(DOWNLOADING_MODULES_FINISHED, 1, 0);
|
||||
}
|
||||
|
||||
function hostOnError(err) {
|
||||
logger.log('Host update failed: ' + err);
|
||||
logger.log(`Host update failed: ${err}`);
|
||||
|
||||
// [adill] osx unsigned builds will fire this code signing error inside setFeedURL and
|
||||
// if we don't do anything about it hostUpdater.checkForUpdates() will never respond.
|
||||
|
@ -430,33 +354,33 @@ function checkForUpdates() {
|
|||
|
||||
function getRemoteModuleName(name) {
|
||||
if (process.platform === 'win32' && process.arch === 'x64') {
|
||||
return name + '.x64';
|
||||
return `${name}.x64`;
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
function checkForModuleUpdates() {
|
||||
var query = _extends({}, remoteQuery, { _: Math.floor(Date.now() / 1000 / 60 / 5) });
|
||||
var url = remoteBaseURL + '/versions.json';
|
||||
logger.log('Checking for module updates at ' + url);
|
||||
const query = _extends({}, remoteQuery, { _: Math.floor(Date.now() / 1000 / 60 / 5) });
|
||||
const url = `${remoteBaseURL}/versions.json`;
|
||||
logger.log(`Checking for module updates at ${url}`);
|
||||
|
||||
request.get({
|
||||
url: url,
|
||||
url,
|
||||
agent: false,
|
||||
encoding: null,
|
||||
qs: query,
|
||||
timeout: REQUEST_TIMEOUT,
|
||||
strictSSL: false
|
||||
}, function (err, response, body) {
|
||||
}, (err, response, body) => {
|
||||
checkingForUpdates = false;
|
||||
|
||||
if (!err && response.statusCode !== 200) {
|
||||
err = new Error('Non-200 response code: ' + response.statusCode);
|
||||
err = new Error(`Non-200 response code: ${response.statusCode}`);
|
||||
}
|
||||
|
||||
if (err) {
|
||||
logger.log('Failed fetching module versions: ' + String(err));
|
||||
logger.log(`Failed fetching module versions: ${String(err)}`);
|
||||
events.emit(UPDATE_CHECK_FINISHED, false, 0, false);
|
||||
return;
|
||||
}
|
||||
|
@ -471,60 +395,35 @@ function checkForModuleUpdates() {
|
|||
}
|
||||
}
|
||||
|
||||
var updatesToDownload = [];
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = Object.keys(installedModules)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var moduleName = _step2.value;
|
||||
|
||||
var installedModule = installedModules[moduleName];
|
||||
var installed = installedModule.installedVersion;
|
||||
if (installed === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var update = installedModule.updateVersion || 0;
|
||||
var remote = remoteModuleVersions[getRemoteModuleName(moduleName)] || 0;
|
||||
// TODO: strict equality?
|
||||
if (installed != remote && update != remote) {
|
||||
logger.log('Module update available: ' + moduleName + '@' + remote + ' [installed: ' + installed + ']');
|
||||
updatesToDownload.push({ name: moduleName, version: remote });
|
||||
}
|
||||
const updatesToDownload = [];
|
||||
for (const moduleName of Object.keys(installedModules)) {
|
||||
const installedModule = installedModules[moduleName];
|
||||
const installed = installedModule.installedVersion;
|
||||
if (installed === null) {
|
||||
continue;
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
|
||||
const update = installedModule.updateVersion || 0;
|
||||
const remote = remoteModuleVersions[getRemoteModuleName(moduleName)] || 0;
|
||||
// TODO: strict equality?
|
||||
if (installed != remote && update != remote) {
|
||||
logger.log(`Module update available: ${moduleName}@${remote} [installed: ${installed}]`);
|
||||
updatesToDownload.push({ name: moduleName, version: remote });
|
||||
}
|
||||
}
|
||||
|
||||
events.emit(UPDATE_CHECK_FINISHED, true, updatesToDownload.length, false);
|
||||
if (updatesToDownload.length === 0) {
|
||||
logger.log('No module updates available.');
|
||||
logger.log(`No module updates available.`);
|
||||
} else {
|
||||
updatesToDownload.forEach(function (e) {
|
||||
return addModuleToDownloadQueue(e.name, e.version);
|
||||
});
|
||||
updatesToDownload.forEach(e => addModuleToDownloadQueue(e.name, e.version));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function addModuleToDownloadQueue(name, version, authToken) {
|
||||
download.queue.push({ name: name, version: version, authToken: authToken });
|
||||
process.nextTick(function () {
|
||||
return processDownloadQueue();
|
||||
});
|
||||
download.queue.push({ name, version, authToken });
|
||||
process.nextTick(() => processDownloadQueue());
|
||||
}
|
||||
|
||||
function processDownloadQueue() {
|
||||
|
@ -533,53 +432,51 @@ function processDownloadQueue() {
|
|||
|
||||
download.active = true;
|
||||
|
||||
var queuedModule = download.queue[download.next];
|
||||
const queuedModule = download.queue[download.next];
|
||||
download.next += 1;
|
||||
|
||||
events.emit(DOWNLOADING_MODULE, queuedModule.name, download.next, download.queue.length);
|
||||
|
||||
var totalBytes = 1;
|
||||
var receivedBytes = 0;
|
||||
var progress = 0;
|
||||
var hasErrored = false;
|
||||
let totalBytes = 1;
|
||||
let receivedBytes = 0;
|
||||
let progress = 0;
|
||||
let hasErrored = false;
|
||||
|
||||
var url = remoteBaseURL + '/' + getRemoteModuleName(queuedModule.name) + '/' + queuedModule.version;
|
||||
logger.log('Fetching ' + queuedModule.name + '@' + queuedModule.version + ' from ' + url);
|
||||
var headers = {};
|
||||
const url = `${remoteBaseURL}/${getRemoteModuleName(queuedModule.name)}/${queuedModule.version}`;
|
||||
logger.log(`Fetching ${queuedModule.name}@${queuedModule.version} from ${url}`);
|
||||
const headers = {};
|
||||
if (queuedModule.authToken) {
|
||||
headers['Authorization'] = queuedModule.authToken;
|
||||
}
|
||||
request.get({
|
||||
url: url,
|
||||
url,
|
||||
agent: false,
|
||||
encoding: null,
|
||||
followAllRedirects: true,
|
||||
qs: remoteQuery,
|
||||
timeout: REQUEST_TIMEOUT,
|
||||
strictSSL: false,
|
||||
headers: headers
|
||||
}).on('error', function (err) {
|
||||
headers
|
||||
}).on('error', err => {
|
||||
if (hasErrored) return;
|
||||
hasErrored = true;
|
||||
logger.log('Failed fetching ' + queuedModule.name + '@' + queuedModule.version + ': ' + String(err));
|
||||
logger.log(`Failed fetching ${queuedModule.name}@${queuedModule.version}: ${String(err)}`);
|
||||
finishModuleDownload(queuedModule.name, queuedModule.version, null, false);
|
||||
}).on('response', function (response) {
|
||||
}).on('response', response => {
|
||||
totalBytes = response.headers['content-length'] || 1;
|
||||
|
||||
var moduleZipPath = _path2.default.join(moduleDownloadPath, queuedModule.name + '-' + queuedModule.version + '.zip');
|
||||
logger.log('Streaming ' + queuedModule.name + '@' + queuedModule.version + ' [' + totalBytes + ' bytes] to ' + moduleZipPath);
|
||||
const moduleZipPath = _path2.default.join(moduleDownloadPath, `${queuedModule.name}-${queuedModule.version}.zip`);
|
||||
logger.log(`Streaming ${queuedModule.name}@${queuedModule.version} [${totalBytes} bytes] to ${moduleZipPath}`);
|
||||
|
||||
var stream = _fs2.default.createWriteStream(moduleZipPath);
|
||||
stream.on('finish', function () {
|
||||
return finishModuleDownload(queuedModule.name, queuedModule.version, moduleZipPath, response.statusCode === 200);
|
||||
});
|
||||
const stream = _fs2.default.createWriteStream(moduleZipPath);
|
||||
stream.on('finish', () => finishModuleDownload(queuedModule.name, queuedModule.version, moduleZipPath, response.statusCode === 200));
|
||||
|
||||
response.on('data', function (chunk) {
|
||||
response.on('data', chunk => {
|
||||
receivedBytes += chunk.length;
|
||||
stream.write(chunk);
|
||||
|
||||
var fraction = receivedBytes / totalBytes;
|
||||
var newProgress = Math.min(Math.floor(100 * fraction), 100);
|
||||
const fraction = receivedBytes / totalBytes;
|
||||
const newProgress = Math.min(Math.floor(100 * fraction), 100);
|
||||
if (progress != newProgress) {
|
||||
progress = newProgress;
|
||||
events.emit(DOWNLOADING_MODULE_PROGRESS, queuedModule.name, progress);
|
||||
|
@ -589,14 +486,12 @@ function processDownloadQueue() {
|
|||
// TODO: on response error
|
||||
// TODO: on stream error
|
||||
|
||||
response.on('end', function () {
|
||||
return stream.end();
|
||||
});
|
||||
response.on('end', () => stream.end());
|
||||
});
|
||||
}
|
||||
|
||||
function commitInstalledModules() {
|
||||
var data = JSON.stringify(installedModules, null, 2);
|
||||
const data = JSON.stringify(installedModules, null, 2);
|
||||
_fs2.default.writeFileSync(installedModulesFilePath, data);
|
||||
}
|
||||
|
||||
|
@ -616,15 +511,15 @@ function finishModuleDownload(name, version, zipfile, succeeded) {
|
|||
events.emit(DOWNLOADED_MODULE, name, download.next, download.queue.length, succeeded);
|
||||
|
||||
if (download.next >= download.queue.length) {
|
||||
var successes = download.queue.length - download.failures;
|
||||
logger.log('Finished module downloads. [success: ' + successes + '] [failure: ' + download.failures + ']');
|
||||
const successes = download.queue.length - download.failures;
|
||||
logger.log(`Finished module downloads. [success: ${successes}] [failure: ${download.failures}]`);
|
||||
events.emit(DOWNLOADING_MODULES_FINISHED, successes, download.failures);
|
||||
download.queue = [];
|
||||
download.next = 0;
|
||||
download.failures = 0;
|
||||
download.active = false;
|
||||
} else {
|
||||
var continueDownloads = function continueDownloads() {
|
||||
const continueDownloads = () => {
|
||||
download.active = false;
|
||||
processDownloadQueue();
|
||||
};
|
||||
|
@ -633,7 +528,7 @@ function finishModuleDownload(name, version, zipfile, succeeded) {
|
|||
backoff.succeed();
|
||||
process.nextTick(continueDownloads);
|
||||
} else {
|
||||
logger.log('Waiting ' + Math.floor(backoff.current) + 'ms before next download.');
|
||||
logger.log(`Waiting ${Math.floor(backoff.current)}ms before next download.`);
|
||||
backoff.fail(continueDownloads);
|
||||
}
|
||||
}
|
||||
|
@ -644,10 +539,8 @@ function finishModuleDownload(name, version, zipfile, succeeded) {
|
|||
}
|
||||
|
||||
function addModuleToUnzipQueue(name, version, zipfile) {
|
||||
unzip.queue.push({ name: name, version: version, zipfile: zipfile });
|
||||
process.nextTick(function () {
|
||||
return processUnzipQueue();
|
||||
});
|
||||
unzip.queue.push({ name, version, zipfile });
|
||||
process.nextTick(() => processUnzipQueue());
|
||||
}
|
||||
|
||||
function processUnzipQueue() {
|
||||
|
@ -656,17 +549,17 @@ function processUnzipQueue() {
|
|||
|
||||
unzip.active = true;
|
||||
|
||||
var queuedModule = unzip.queue[unzip.next];
|
||||
const queuedModule = unzip.queue[unzip.next];
|
||||
unzip.next += 1;
|
||||
|
||||
events.emit(INSTALLING_MODULE, queuedModule.name, unzip.next, unzip.queue.length);
|
||||
|
||||
var hasErrored = false;
|
||||
var onError = function onError(error, zipfile) {
|
||||
let hasErrored = false;
|
||||
const onError = (error, zipfile) => {
|
||||
if (hasErrored) return;
|
||||
hasErrored = true;
|
||||
|
||||
logger.log('Failed installing ' + queuedModule.name + '@' + queuedModule.version + ': ' + String(error));
|
||||
logger.log(`Failed installing ${queuedModule.name}@${queuedModule.version}: ${String(error)}`);
|
||||
succeeded = false;
|
||||
if (zipfile) {
|
||||
zipfile.close();
|
||||
|
@ -674,22 +567,22 @@ function processUnzipQueue() {
|
|||
finishModuleUnzip(queuedModule, succeeded);
|
||||
};
|
||||
|
||||
var succeeded = true;
|
||||
var extractRoot = _path2.default.join(moduleInstallPath, queuedModule.name);
|
||||
logger.log('Installing ' + queuedModule.name + '@' + queuedModule.version + ' from ' + queuedModule.zipfile);
|
||||
let succeeded = true;
|
||||
const extractRoot = _path2.default.join(moduleInstallPath, queuedModule.name);
|
||||
logger.log(`Installing ${queuedModule.name}@${queuedModule.version} from ${queuedModule.zipfile}`);
|
||||
|
||||
var processZipfile = function processZipfile(err, zipfile) {
|
||||
const processZipfile = (err, zipfile) => {
|
||||
if (err) {
|
||||
onError(err, null);
|
||||
return;
|
||||
}
|
||||
|
||||
var totalEntries = zipfile.entryCount;
|
||||
var processedEntries = 0;
|
||||
const totalEntries = zipfile.entryCount;
|
||||
let processedEntries = 0;
|
||||
|
||||
zipfile.on('entry', function (entry) {
|
||||
zipfile.on('entry', entry => {
|
||||
processedEntries += 1;
|
||||
var percent = Math.min(Math.floor(processedEntries / totalEntries * 100), 100);
|
||||
const percent = Math.min(Math.floor(processedEntries / totalEntries * 100), 100);
|
||||
events.emit(INSTALLING_MODULE_PROGRESS, queuedModule.name, percent);
|
||||
|
||||
// skip directories
|
||||
|
@ -698,17 +591,15 @@ function processUnzipQueue() {
|
|||
return;
|
||||
}
|
||||
|
||||
zipfile.openReadStream(entry, function (err, stream) {
|
||||
zipfile.openReadStream(entry, (err, stream) => {
|
||||
if (err) {
|
||||
onError(err, zipfile);
|
||||
return;
|
||||
}
|
||||
|
||||
stream.on('error', function (e) {
|
||||
return onError(e, zipfile);
|
||||
});
|
||||
stream.on('error', e => onError(e, zipfile));
|
||||
|
||||
(0, _mkdirp2.default)(_path2.default.join(extractRoot, _path2.default.dirname(entry.fileName)), function (err) {
|
||||
(0, _mkdirp2.default)(_path2.default.join(extractRoot, _path2.default.dirname(entry.fileName)), err => {
|
||||
if (err) {
|
||||
onError(err, zipfile);
|
||||
return;
|
||||
|
@ -716,11 +607,11 @@ function processUnzipQueue() {
|
|||
|
||||
// [adill] createWriteStream via original-fs is broken in Electron 4.0.0-beta.6 with .asar files
|
||||
// so we unzip to a temporary filename and rename it afterwards
|
||||
var tempFileName = _path2.default.join(extractRoot, entry.fileName + '.tmp');
|
||||
var finalFileName = _path2.default.join(extractRoot, entry.fileName);
|
||||
var writeStream = originalFs.createWriteStream(tempFileName);
|
||||
const tempFileName = _path2.default.join(extractRoot, entry.fileName + '.tmp');
|
||||
const finalFileName = _path2.default.join(extractRoot, entry.fileName);
|
||||
const writeStream = originalFs.createWriteStream(tempFileName);
|
||||
|
||||
writeStream.on('error', function (e) {
|
||||
writeStream.on('error', e => {
|
||||
stream.destroy();
|
||||
try {
|
||||
originalFs.unlinkSync(tempFileName);
|
||||
|
@ -728,7 +619,7 @@ function processUnzipQueue() {
|
|||
onError(e, zipfile);
|
||||
});
|
||||
|
||||
writeStream.on('finish', function () {
|
||||
writeStream.on('finish', () => {
|
||||
try {
|
||||
originalFs.unlinkSync(finalFileName);
|
||||
} catch (err) {}
|
||||
|
@ -746,11 +637,11 @@ function processUnzipQueue() {
|
|||
});
|
||||
});
|
||||
|
||||
zipfile.on('error', function (err) {
|
||||
zipfile.on('error', err => {
|
||||
onError(err, zipfile);
|
||||
});
|
||||
|
||||
zipfile.on('end', function () {
|
||||
zipfile.on('end', () => {
|
||||
if (!succeeded) return;
|
||||
|
||||
installedModules[queuedModule.name].installedVersion = queuedModule.version;
|
||||
|
@ -780,9 +671,9 @@ function finishModuleUnzip(unzippedModule, succeeded) {
|
|||
events.emit(INSTALLED_MODULE, unzippedModule.name, unzip.next, unzip.queue.length, succeeded);
|
||||
|
||||
if (unzip.next >= unzip.queue.length) {
|
||||
var successes = unzip.queue.length - unzip.failures;
|
||||
const successes = unzip.queue.length - unzip.failures;
|
||||
bootstrapping = false;
|
||||
logger.log('Finished module installations. [success: ' + successes + '] [failure: ' + unzip.failures + ']');
|
||||
logger.log(`Finished module installations. [success: ${successes}] [failure: ${unzip.failures}]`);
|
||||
unzip.queue = [];
|
||||
unzip.next = 0;
|
||||
unzip.failures = 0;
|
||||
|
@ -791,14 +682,14 @@ function finishModuleUnzip(unzippedModule, succeeded) {
|
|||
return;
|
||||
}
|
||||
|
||||
process.nextTick(function () {
|
||||
process.nextTick(() => {
|
||||
unzip.active = false;
|
||||
processUnzipQueue();
|
||||
});
|
||||
}
|
||||
|
||||
function quitAndInstallUpdates() {
|
||||
logger.log('Relaunching to install ' + (hostUpdateAvailable ? 'host' : 'module') + ' updates...');
|
||||
logger.log(`Relaunching to install ${hostUpdateAvailable ? 'host' : 'module'} updates...`);
|
||||
if (hostUpdateAvailable) {
|
||||
hostUpdater.quitAndInstall();
|
||||
} else {
|
||||
|
@ -808,16 +699,13 @@ function quitAndInstallUpdates() {
|
|||
|
||||
function relaunch() {
|
||||
logger.end();
|
||||
|
||||
var _require = require('electron'),
|
||||
app = _require.app;
|
||||
|
||||
const { app } = require('electron');
|
||||
app.relaunch();
|
||||
app.quit();
|
||||
}
|
||||
|
||||
function isInstalled(name, version) {
|
||||
var metadata = installedModules[name];
|
||||
const metadata = installedModules[name];
|
||||
if (locallyInstalledModules) return true;
|
||||
if (metadata && metadata.installedVersion > 0) {
|
||||
if (!version) return true;
|
||||
|
@ -831,10 +719,7 @@ function getInstalled() {
|
|||
}
|
||||
|
||||
function install(name, defer, options) {
|
||||
var _ref = options || {},
|
||||
version = _ref.version,
|
||||
authToken = _ref.authToken;
|
||||
|
||||
let { version, authToken } = options || {};
|
||||
if (isInstalled(name, version)) {
|
||||
if (!defer) {
|
||||
events.emit(INSTALLED_MODULE, name, 1, 1, true);
|
||||
|
@ -845,19 +730,19 @@ function install(name, defer, options) {
|
|||
if (newInstallInProgress[name]) return;
|
||||
|
||||
if (!updatable) {
|
||||
logger.log('Not updatable; ignoring request to install ' + name + '...');
|
||||
logger.log(`Not updatable; ignoring request to install ${name}...`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (defer) {
|
||||
if (version) {
|
||||
throw new Error('Cannot defer install for a specific version module (' + name + ', ' + version + ')');
|
||||
throw new Error(`Cannot defer install for a specific version module (${name}, ${version})`);
|
||||
}
|
||||
logger.log('Deferred install for ' + name + '...');
|
||||
logger.log(`Deferred install for ${name}...`);
|
||||
installedModules[name] = { installedVersion: 0 };
|
||||
commitInstalledModules();
|
||||
} else {
|
||||
logger.log('Starting to install ' + name + '...');
|
||||
logger.log(`Starting to install ${name}...`);
|
||||
if (!version) {
|
||||
version = remoteModuleVersions[name] || 0;
|
||||
}
|
||||
|
@ -867,76 +752,32 @@ function install(name, defer, options) {
|
|||
}
|
||||
|
||||
function installPendingUpdates() {
|
||||
var updatesToInstall = [];
|
||||
const updatesToInstall = [];
|
||||
|
||||
if (bootstrapping) {
|
||||
var modules = {};
|
||||
let modules = {};
|
||||
try {
|
||||
modules = JSON.parse(_fs2.default.readFileSync(bootstrapManifestFilePath));
|
||||
} catch (err) {}
|
||||
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = Object.keys(modules)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var moduleName = _step3.value;
|
||||
|
||||
installedModules[moduleName] = { installedVersion: 0 };
|
||||
var zipfile = _path2.default.join(paths.getResources(), 'bootstrap', moduleName + '.zip');
|
||||
updatesToInstall.push({ moduleName: moduleName, update: modules[moduleName], zipfile: zipfile });
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
for (const moduleName of Object.keys(modules)) {
|
||||
installedModules[moduleName] = { installedVersion: 0 };
|
||||
const zipfile = _path2.default.join(paths.getResources(), 'bootstrap', `${moduleName}.zip`);
|
||||
updatesToInstall.push({ moduleName, update: modules[moduleName], zipfile });
|
||||
}
|
||||
}
|
||||
|
||||
var _iteratorNormalCompletion4 = true;
|
||||
var _didIteratorError4 = false;
|
||||
var _iteratorError4 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator4 = Object.keys(installedModules)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
|
||||
var _moduleName = _step4.value;
|
||||
|
||||
var update = installedModules[_moduleName].updateVersion || 0;
|
||||
var _zipfile = installedModules[_moduleName].updateZipfile;
|
||||
if (update > 0 && _zipfile != null) {
|
||||
updatesToInstall.push({ moduleName: _moduleName, update: update, zipfile: _zipfile });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError4 = true;
|
||||
_iteratorError4 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion4 && _iterator4.return) {
|
||||
_iterator4.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError4) {
|
||||
throw _iteratorError4;
|
||||
}
|
||||
for (const moduleName of Object.keys(installedModules)) {
|
||||
const update = installedModules[moduleName].updateVersion || 0;
|
||||
const zipfile = installedModules[moduleName].updateZipfile;
|
||||
if (update > 0 && zipfile != null) {
|
||||
updatesToInstall.push({ moduleName, update, zipfile });
|
||||
}
|
||||
}
|
||||
|
||||
if (updatesToInstall.length > 0) {
|
||||
logger.log((bootstrapping ? 'Bootstrapping' : 'Installing updates') + '...');
|
||||
updatesToInstall.forEach(function (e) {
|
||||
return addModuleToUnzipQueue(e.moduleName, e.update, e.zipfile);
|
||||
});
|
||||
logger.log(`${bootstrapping ? 'Bootstrapping' : 'Installing updates'}...`);
|
||||
updatesToInstall.forEach(e => addModuleToUnzipQueue(e.moduleName, e.update, e.zipfile));
|
||||
} else {
|
||||
logger.log('No updates to install');
|
||||
events.emit(NO_PENDING_UPDATES);
|
||||
|
|
|
@ -29,17 +29,15 @@ var _rimraf2 = _interopRequireDefault(_rimraf);
|
|||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
// Determines environment-specific paths based on info provided
|
||||
var originalFs = require('original-fs');
|
||||
const originalFs = require('original-fs');
|
||||
|
||||
var userDataPath = null;
|
||||
var userDataVersionedPath = null;
|
||||
var resourcesPath = null;
|
||||
var modulePath = null;
|
||||
let userDataPath = null;
|
||||
let userDataVersionedPath = null;
|
||||
let resourcesPath = null;
|
||||
let modulePath = null;
|
||||
|
||||
function determineAppUserDataRoot() {
|
||||
var _require = require('electron'),
|
||||
app = _require.app;
|
||||
|
||||
const { app } = require('electron');
|
||||
return app.getPath('appData');
|
||||
}
|
||||
|
||||
|
@ -49,13 +47,13 @@ function determineUserData(userDataRoot, buildInfo) {
|
|||
|
||||
// cleans old version data in the background
|
||||
function cleanOldVersions(buildInfo) {
|
||||
var entries = _fs2.default.readdirSync(userDataPath) || [];
|
||||
entries.forEach(function (entry) {
|
||||
var fullPath = _path2.default.join(userDataPath, entry);
|
||||
const entries = _fs2.default.readdirSync(userDataPath) || [];
|
||||
entries.forEach(entry => {
|
||||
const fullPath = _path2.default.join(userDataPath, entry);
|
||||
if (_fs2.default.statSync(fullPath).isDirectory() && entry.indexOf(buildInfo.version) === -1) {
|
||||
if (entry.match('^[0-9]+.[0-9]+.[0-9]+') != null) {
|
||||
console.log('Removing old directory ', entry);
|
||||
(0, _rimraf2.default)(fullPath, originalFs, function (error) {
|
||||
(0, _rimraf2.default)(fullPath, originalFs, error => {
|
||||
if (error) {
|
||||
console.warn('...failed with error: ', error);
|
||||
}
|
||||
|
@ -68,13 +66,11 @@ function cleanOldVersions(buildInfo) {
|
|||
function init(buildInfo) {
|
||||
resourcesPath = _path2.default.join(require.main.filename, '..', '..', '..');
|
||||
|
||||
var userDataRoot = determineAppUserDataRoot();
|
||||
const userDataRoot = determineAppUserDataRoot();
|
||||
|
||||
userDataPath = determineUserData(userDataRoot, buildInfo);
|
||||
|
||||
var _require2 = require('electron'),
|
||||
app = _require2.app;
|
||||
|
||||
const { app } = require('electron');
|
||||
app.setPath('userData', userDataPath);
|
||||
|
||||
userDataVersionedPath = _path2.default.join(userDataPath, buildInfo.version);
|
||||
|
|
Loading…
Reference in a new issue