[Chore] Remerge external commits

This commit is contained in:
Ducko 2022-03-24 22:26:50 +00:00
commit 185863400e
2 changed files with 43 additions and 83 deletions

View File

@ -101,14 +101,12 @@ const launchSplashWindow = (startMinimized) => {
if (process.platform !== 'darwin') win.on('closed', () => { if (!launchedMainWindow) app.quit(); }); if (process.platform !== 'darwin') win.on('closed', () => { if (!launchedMainWindow) app.quit(); });
wc.once('dom-ready', () => { wc.once('dom-ready', () => {
if (oaConfig.themeSync !== false) try { // Inject themesync CSS if (oaConfig.themeSync !== false) wc.insertCSS(JSON.parse(fs.readFileSync(join(paths.getUserData(), 'userDataCache.json'), 'utf8')).openasarSplashCSS);
wc.insertCSS(JSON.parse(fs.readFileSync(join(paths.getUserData(), 'userDataCache.json'), 'utf8')).openasarSplashCSS);
} catch (e) { }
if (oaConfig.splashText === true) try { if (oaConfig.splashText === true) {
const buildInfo = require('../utils/buildInfo.js'); const buildInfo = require('../utils/buildInfo.js');
wc.executeJavaScript(`debug.textContent = '${buildInfo.releaseChannel} ${buildInfo.version}\\nOpenAsar ${oaVersion}'`); wc.executeJavaScript(`debug.textContent = '${buildInfo.releaseChannel} ${buildInfo.version}\\nOpenAsar ${oaVersion}'`);
} catch (e) { } }
}); });
if (!startMinimized) win.once('ready-to-show', () => win.show()); if (!startMinimized) win.once('ready-to-show', () => win.show());
@ -201,7 +199,6 @@ const updateUntilCurrent = async () => {
if (!installedAnything) { if (!installedAnything) {
await newUpdater.startCurrentVersion(); await newUpdater.startCurrentVersion();
newUpdater.setRunningInBackground();
newUpdater.collectGarbage(); newUpdater.collectGarbage();
return launchMainWindow(); return launchMainWindow();

View File

@ -1,7 +1,7 @@
const { spawn } = require('child_process'); const { spawn } = require('child_process');
const { app } = require('electron'); const { app } = require('electron');
const { EventEmitter } = require('events'); const { EventEmitter } = require('events');
const NodeModule = require('module'); const Module = require('module');
const { join, resolve, basename } = require('path'); const { join, resolve, basename } = require('path');
const { hrtime } = require('process'); const { hrtime } = require('process');
@ -12,18 +12,15 @@ const TASK_STATE_COMPLETE = 'Complete';
const TASK_STATE_FAILED = 'Failed'; const TASK_STATE_FAILED = 'Failed';
const TASK_STATE_WAITING = 'Waiting'; const TASK_STATE_WAITING = 'Waiting';
const TASK_STATE_WORKING = 'Working'; const TASK_STATE_WORKING = 'Working';
const INCONSISTENT_INSTALLER_STATE_ERROR = 'InconsistentInstallerState';
const INVALID_UPDATER_ERROR = "Can't send request to updater because the native updater isn't loaded.";
class Updater extends EventEmitter { class Updater extends EventEmitter {
constructor(options) { constructor(options) {
super(); super();
let nativeUpdaterModule; let Native;
try { try {
nativeUpdaterModule = options.nativeUpdaterModule ?? require(paths.getExeDir() + '/updater'); Native = options.nativeUpdaterModule ?? require(paths.getExeDir() + '/updater');
} catch (e) { } catch (e) {
log('Updater', 'Require fail', e); log('Updater', 'Require fail', e);
@ -32,17 +29,15 @@ class Updater extends EventEmitter {
} }
this.committedHostVersion = null; this.committedHostVersion = null;
this.committedModules = new Set();
this.rootPath = options.root_path; this.rootPath = options.root_path;
this.nextRequestId = 0; this.nextRequestId = 0;
this.requests = new Map(); this.requests = new Map();
this.updateEventHistory = []; this.updateEventHistory = [];
this.isRunningInBackground = false;
this.currentlyDownloading = {}; this.currentlyDownloading = {};
this.currentlyInstalling = {}; this.currentlyInstalling = {};
this.hasEmittedUnhandledException = false; this.hasEmittedUnhandledException = false;
this.nativeUpdater = new nativeUpdaterModule.Updater({ this.nativeUpdater = new Native.Updater({
response_handler: this._handleResponse.bind(this), response_handler: this._handleResponse.bind(this),
...options ...options
}); });
@ -53,7 +48,7 @@ class Updater extends EventEmitter {
} }
_sendRequest(detail, progressCallback = null) { _sendRequest(detail, progressCallback = null) {
if (!this.valid) throw new Error(INVALID_UPDATER_ERROR); if (!this.valid) throw new Error('Native fail');
const requestId = this.nextRequestId++; const requestId = this.nextRequestId++;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -62,22 +57,20 @@ class Updater extends EventEmitter {
reject, reject,
progressCallback progressCallback
}); });
this.nativeUpdater.command(JSON.stringify([requestId, detail]));
this.nativeUpdater.command(JSON.stringify([ requestId, detail ]));
}); });
} }
_sendRequestSync(detail) { _sendRequestSync(detail) {
if (!this.valid) { if (!this.valid) throw new Error('Native fail');
throw new Error(INVALID_UPDATER_ERROR);
}
const requestId = this.nextRequestId++; return this.nativeUpdater.command_blocking(JSON.stringify([ this.nextRequestId++, detail ]));
return this.nativeUpdater.command_blocking(JSON.stringify([requestId, detail]));
} }
_handleResponse(response) { _handleResponse(response) {
try { try {
const [id, detail] = JSON.parse(response); const [ id, detail ] = JSON.parse(response);
const request = this.requests.get(id); const request = this.requests.get(id);
if (request == null) return log('Updater', 'Unknown resp', id, detail); if (request == null) return log('Updater', 'Unknown resp', id, detail);
@ -91,11 +84,7 @@ class Updater extends EventEmitter {
const e = new Error(`(${kind}) ${details}`); const e = new Error(`(${kind}) ${details}`);
if (severity === 'Fatal') { if (severity === 'Fatal') {
const handled = this.emit(kind, e); if (!this.emit(kind, e)) throw e;
if (!handled) {
throw e;
}
} else { } else {
this.emit('update-error', e); this.emit('update-error', e);
request.reject(e); request.reject(e);
@ -121,13 +110,9 @@ class Updater extends EventEmitter {
this._recordTaskProgress(progress); this._recordTaskProgress(progress);
if (request.progressCallback != null) { request.progressCallback?.(progress);
request.progressCallback(progress);
}
if (progress.task['HostInstall'] != null && progress.state === TASK_STATE_COMPLETE) { if (progress.task['HostInstall'] != null && progress.state === TASK_STATE_COMPLETE) this.emit('host-updated');
this.emit('host-updated');
}
} else { } else {
log('Updater', 'Unknown resp', id, detail); log('Updater', 'Unknown resp', id, detail);
} }
@ -144,13 +129,9 @@ class Updater extends EventEmitter {
_handleSyncResponse(response) { _handleSyncResponse(response) {
const detail = JSON.parse(response); const detail = JSON.parse(response);
if (detail['Error'] != null) { if (detail.Error != null) throw new Error(detail.Error);
throw new Error(detail['Error']); else if (detail === 'Ok') return;
} else if (detail === 'Ok') { else if (detail.VersionInfo != null) return detail.VersionInfo;
return;
} else if (detail['VersionInfo'] != null) {
return detail['VersionInfo'];
}
log('Updater', 'Unknown resp', detail); log('Updater', 'Unknown resp', detail);
} }
@ -162,19 +143,16 @@ class Updater extends EventEmitter {
_startCurrentVersionInner(options, versions) { _startCurrentVersionInner(options, versions) {
if (this.committedHostVersion == null) this.committedHostVersion = versions.current_host; if (this.committedHostVersion == null) this.committedHostVersion = versions.current_host;
const hostPath = this._getHostPath(); const latestPath = resolve(join(this._getHostPath(), basename(process.execPath)));
const currentPath = resolve(process.execPath);
if (latestPath != currentPath && !options?.allowObsoleteHost) {
app.once('will-quit', spawn(hostExePath, [], {
detached: true,
stdio: 'inherit'
}));
const hostExePath = join(hostPath, basename(process.execPath)); log('Updater', 'Restarting', currentPath, '->', latestPath);
if (resolve(hostExePath) != resolve(process.execPath) && !(options === null || options === void 0 ? void 0 : options.allowObsoleteHost)) {
app.once('will-quit', () => {
spawn(hostExePath, [], {
detached: true,
stdio: 'inherit'
});
});
log('Updater', 'Restarting', resolve(process.execPath), '->', resolve(hostExePath));
return app.quit(); return app.quit();
} }
@ -182,18 +160,12 @@ class Updater extends EventEmitter {
} }
_commitModulesInner(versions) { _commitModulesInner(versions) {
const hostPath = this._getHostPath(); const base = join(this._getHostPath(), 'modules');
const modulesPath = join(hostPath, 'modules'); for (const mod in versions.current_modules) {
const path = join(base, `${mod}-${versions.current_modules[mod]}`);
for (const module in versions.current_modules) { if (!Module.globalPaths.includes(path)) Module.globalPaths.push(path);
const moduleVersion = versions.current_modules[module];
const moduleSearchPath = join(modulesPath, `${module}-${moduleVersion}`);
if (!this.committedModules.has(module) && NodeModule.globalPaths.indexOf(moduleSearchPath) === -1) {
this.committedModules.add(module);
NodeModule.globalPaths.push(moduleSearchPath);
}
} }
} }
@ -204,15 +176,15 @@ class Updater extends EventEmitter {
this.currentlyDownloading[name] = true; this.currentlyDownloading[name] = true;
this.updateEventHistory.push({ this.updateEventHistory.push({
type: 'downloading-module', type: 'downloading-module',
name: name, name,
now: now now
}); });
} else if (progress.state === TASK_STATE_COMPLETE || progress.state === TASK_STATE_FAILED) { } else if (progress.state === TASK_STATE_COMPLETE || progress.state === TASK_STATE_FAILED) {
this.currentlyDownloading[name] = false; this.currentlyDownloading[name] = false;
this.updateEventHistory.push({ this.updateEventHistory.push({
type: 'downloaded-module', type: 'downloaded-module',
name: name, name,
now: now, now,
succeeded: progress.state === TASK_STATE_COMPLETE, succeeded: progress.state === TASK_STATE_COMPLETE,
receivedBytes: progress.bytesProcessed receivedBytes: progress.bytesProcessed
}); });
@ -228,8 +200,7 @@ class Updater extends EventEmitter {
type: 'installing-module', type: 'installing-module',
name, name,
now, now,
newVersion, newVersion
foreground: !this.isRunningInBackground
}); });
} else if (progress.state === TASK_STATE_COMPLETE || progress.state === TASK_STATE_FAILED) { } else if (progress.state === TASK_STATE_COMPLETE || progress.state === TASK_STATE_FAILED) {
this.currentlyInstalling[name] = false; this.currentlyInstalling[name] = false;
@ -239,8 +210,7 @@ class Updater extends EventEmitter {
now, now,
newVersion, newVersion,
succeeded: progress.state === TASK_STATE_COMPLETE, succeeded: progress.state === TASK_STATE_COMPLETE,
delta: isDelta, delta: isDelta
foreground: !this.isRunningInBackground
}); });
} }
} }
@ -330,15 +300,7 @@ class Updater extends EventEmitter {
async commitModules(versions) { async commitModules(versions) {
if (this.committedHostVersion == null) throw new Error('Cannot commit modules before host version.'); if (this.committedHostVersion == null) throw new Error('Cannot commit modules before host version.');
if (versions == null) { this._commitModulesInner(versions ?? await this.queryCurrentVersions());
versions = await this.queryCurrentVersions();
}
this._commitModulesInner(versions);
}
setRunningInBackground() {
this.isRunningInBackground = true;
} }
queryAndTruncateHistory() { queryAndTruncateHistory() {
@ -348,13 +310,13 @@ class Updater extends EventEmitter {
} }
getKnownFolder(name) { getKnownFolder(name) {
if (!this.valid) throw new Error(INVALID_UPDATER_ERROR); if (!this.valid) throw new Error('Native fail');
return this.nativeUpdater.known_folder(name); return this.nativeUpdater.known_folder(name);
} }
createShortcut(options) { createShortcut(options) {
if (!this.valid) throw new Error(INVALID_UPDATER_ERROR); if (!this.valid) throw new Error('Native fail');
return this.nativeUpdater.create_shortcut(options); return this.nativeUpdater.create_shortcut(options);
} }
@ -368,7 +330,8 @@ module.exports = {
TASK_STATE_FAILED, TASK_STATE_FAILED,
TASK_STATE_WAITING, TASK_STATE_WAITING,
TASK_STATE_WORKING, TASK_STATE_WORKING,
INCONSISTENT_INSTALLER_STATE_ERROR,
INCONSISTENT_INSTALLER_STATE_ERROR: 'InconsistentInstallerState',
tryInitUpdater: (buildInfo, repository_url) => { tryInitUpdater: (buildInfo, repository_url) => {
const root_path = paths.getInstallPath(); const root_path = paths.getInstallPath();