464 lines
19 KiB
JavaScript
464 lines
19 KiB
JavaScript
'use strict';
|
|
|
|
// Update service of the main process. Finds the newest eligible published release (update-source.js),
|
|
// lets electron-updater read that release's feed, download and verify the package, and installs ONLY after
|
|
// an explicit user action. It never quits or restarts the app on its own.
|
|
//
|
|
// Every check uses a NEW electron-updater instance. electron-updater keeps the last checked feed inside the
|
|
// instance and cannot cancel a running check, so a check that timed out (or a check for another channel) can
|
|
// still finish later; with one instance per check, such a late result can only touch an abandoned instance.
|
|
// Download and install always use the exact instance that checked the offered release.
|
|
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { app, net, shell } = require('electron');
|
|
const source = require('./update-source');
|
|
const { logsDir } = require('./paths');
|
|
|
|
const STARTUP_DELAY_MS = 15 * 1000;
|
|
const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
|
const DEFERRED_POLL_MS = 60 * 1000;
|
|
const FEED_TIMEOUT_MS = 60 * 1000;
|
|
const LOG_LIMIT_BYTES = 1024 * 1024;
|
|
const CHANNELS = ['preview', 'stable'];
|
|
|
|
function fileLogger(file) {
|
|
const write = (level, parts) => {
|
|
const line = `${new Date().toISOString()} ${level} ${parts.map((p) => (p instanceof Error ? p.stack || p.message : String(p))).join(' ')}`;
|
|
try {
|
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
try {
|
|
if (fs.statSync(file).size > LOG_LIMIT_BYTES) fs.renameSync(file, `${file}.1`);
|
|
} catch {
|
|
// no log yet
|
|
}
|
|
fs.appendFileSync(file, `${line.replace(/[\r\n]+/g, ' ')}\n`);
|
|
} catch {
|
|
// logging must never break updating
|
|
}
|
|
};
|
|
return {
|
|
info: (...p) => write('info', p),
|
|
warn: (...p) => write('warn', p),
|
|
error: (...p) => write('error', p),
|
|
debug: () => {},
|
|
};
|
|
}
|
|
|
|
/** electron-updater instance for this target, configured so that nothing happens without our call. */
|
|
function defaultCreateUpdater(target, logger, channel) {
|
|
const { NsisUpdater, AppImageUpdater } = require('electron-updater');
|
|
const instance = target.kind === 'nsis' ? new NsisUpdater() : new AppImageUpdater();
|
|
instance.logger = logger;
|
|
instance.autoDownload = false;
|
|
instance.autoInstallOnAppQuit = false;
|
|
instance.allowDowngrade = false;
|
|
// Only the GitHub providers read allowPrerelease; with the generic provider the channel policy is applied
|
|
// by update-source before a feed is chosen. Kept consistent with the selected channel anyway.
|
|
instance.allowPrerelease = channel === 'preview';
|
|
instance.disableWebInstaller = true;
|
|
return instance;
|
|
}
|
|
|
|
const CHECKSUM_FAILURE = /checksum mismatch/i;
|
|
const NETWORK_FAILURE = /net::ERR_|ENOTFOUND|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|socket hang up/i;
|
|
|
|
/** Maps electron-updater / network failures to stable codes; `detail` keeps the technical text. */
|
|
function classify(err, fallback, tag) {
|
|
if (err instanceof source.UpdateError) return err;
|
|
const detail = (err && err.message ? err.message : String(err)).split('\n')[0].slice(0, 300);
|
|
const code = err && err.code;
|
|
if (code === 'ERR_CHECKSUM_MISMATCH' || CHECKSUM_FAILURE.test(detail)) return new source.UpdateError('checksum', { tag, detail }, detail);
|
|
if (code === 'ERR_UPDATER_CHANNEL_FILE_NOT_FOUND' || (err && err.statusCode === 404)) {
|
|
return new source.UpdateError('incomplete-release', { tag, file: null, detail }, detail);
|
|
}
|
|
if (err && Number.isInteger(err.statusCode)) return new source.UpdateError('http', { status: err.statusCode }, detail);
|
|
if (NETWORK_FAILURE.test(detail)) {
|
|
return new source.UpdateError('network', { detail }, detail);
|
|
}
|
|
return new source.UpdateError(fallback, { tag, detail }, detail);
|
|
}
|
|
|
|
function withTimeout(promise, ms, tag) {
|
|
let timer;
|
|
const seconds = Math.round(ms / 1000);
|
|
return Promise.race([
|
|
promise,
|
|
new Promise((_, reject) => {
|
|
timer = setTimeout(() => reject(new source.UpdateError('timeout', { seconds, tag }, `feed of ${tag}: no answer in ${seconds} s`)), ms);
|
|
}),
|
|
]).finally(() => clearTimeout(timer));
|
|
}
|
|
|
|
/**
|
|
* @param {object} o
|
|
* @param {{ get(): object, set(partial: object): object }} o.prefs holds `updateChannel`
|
|
* @param {() => boolean} o.isSessionActive true while connected to a server (voice / stream viewing)
|
|
* @param {(state: object) => void} o.send pushes the state to the renderer
|
|
* Remaining options exist for the Electron behaviour harness; the release host is not configurable.
|
|
*/
|
|
function createUpdateService({
|
|
prefs,
|
|
isSessionActive,
|
|
send,
|
|
electronApp = app,
|
|
fetchImpl = (url, init) => net.fetch(url, init),
|
|
target = source.detectTarget({
|
|
platform: process.platform,
|
|
arch: process.arch,
|
|
packaged: electronApp.isPackaged,
|
|
env: process.env,
|
|
execPath: process.execPath,
|
|
exists: fs.existsSync,
|
|
}),
|
|
createUpdater = defaultCreateUpdater,
|
|
openExternal = (url) => shell.openExternal(url),
|
|
logger = fileLogger(path.join(logsDir(), 'updater.log')),
|
|
appImagePath = () => process.env.APPIMAGE,
|
|
argv = process.argv,
|
|
feedTimeoutMs = FEED_TIMEOUT_MS,
|
|
profileOverride = process.env.TEAMSPEACH_PROFILE_DIR,
|
|
}) {
|
|
const currentVersion = electronApp.getVersion();
|
|
// The NSIS installer restarts the app through Explorer (StdUtils.ExecShellAsUser), which does not pass this
|
|
// process's environment on: an app running on a TEAMSPEACH_PROFILE_DIR profile would come back on the
|
|
// default profile. Such a run is offered the release page (manual install) instead of an automatic install.
|
|
// AppImage relaunch (app.relaunch) keeps the environment and is not affected.
|
|
const installBlock = target.kind === 'nsis' && profileOverride ? 'custom-profile' : null;
|
|
const autoInstall = target.mode === 'auto' && !installBlock;
|
|
let offered = null; // { candidate, updater } — release in state.available and the instance that checked it
|
|
let downloaded = null; // { candidate, updater } — verified package ready to install
|
|
let downloading = null; // { updater, token }
|
|
let busy = null; // in-flight check/download promise
|
|
let timers = [];
|
|
let deferredTimer = null;
|
|
let lastProgressSent = 0;
|
|
|
|
const state = {
|
|
currentVersion,
|
|
channel: 'preview',
|
|
mode: installBlock ? 'manual' : target.mode,
|
|
manualReason: installBlock, // null | 'custom-profile'
|
|
target: target.id,
|
|
phase: target.mode === 'none' ? 'disabled' : 'idle',
|
|
lastCheckedAt: null,
|
|
available: null,
|
|
progress: null,
|
|
newerWithoutBuild: [],
|
|
newerPreview: null,
|
|
error: null, // { code, params } — localized by the renderer; params.detail is technical text
|
|
disabledCode: target.disabledCode,
|
|
disabledParams: target.mode === 'none' ? { platform: target.platform, arch: target.arch } : null,
|
|
};
|
|
|
|
logger.info(`updater: version ${currentVersion} pid ${process.pid} target ${target.id} mode ${state.mode}${installBlock ? ` (${installBlock})` : ''}`);
|
|
|
|
function channel() {
|
|
const value = prefs.get().updateChannel;
|
|
return CHANNELS.includes(value) ? value : 'preview';
|
|
}
|
|
|
|
function snapshot() {
|
|
return {
|
|
...state,
|
|
channel: channel(),
|
|
available: state.available ? { ...state.available } : null,
|
|
progress: state.progress ? { ...state.progress } : null,
|
|
newerWithoutBuild: state.newerWithoutBuild.map((x) => ({ ...x, params: { ...x.params } })),
|
|
error: state.error ? { code: state.error.code, params: { ...state.error.params } } : null,
|
|
disabledParams: state.disabledParams ? { ...state.disabledParams } : null,
|
|
sessionActive: Boolean(isSessionActive()),
|
|
};
|
|
}
|
|
|
|
function emit() {
|
|
try {
|
|
send(snapshot());
|
|
} catch (err) {
|
|
logger.warn('updater: state push failed', err);
|
|
}
|
|
}
|
|
|
|
function setPhase(phase, extra = {}) {
|
|
Object.assign(state, { phase }, extra);
|
|
emit();
|
|
}
|
|
|
|
function fail(err, fallback, tag) {
|
|
const e = classify(err, fallback, tag);
|
|
logger.error(`updater: ${e.code}: ${e.message}`);
|
|
setPhase('error', { error: { code: e.code, params: e.params || {} }, progress: null });
|
|
return e;
|
|
}
|
|
|
|
function newUpdater(selectedChannel) {
|
|
const u = createUpdater(target, logger, selectedChannel);
|
|
// Failures are handled where the promises reject; the listener keeps EventEmitter from throwing.
|
|
u.on('error', (err) => logger.warn('updater: electron-updater error event', err));
|
|
u.on('download-progress', (p) => {
|
|
if (!downloading || downloading.updater !== u) return;
|
|
state.progress = { percent: Math.max(0, Math.min(100, Number(p.percent) || 0)), transferred: p.transferred, total: p.total };
|
|
const now = Date.now();
|
|
if (now - lastProgressSent >= 250) {
|
|
lastProgressSent = now;
|
|
emit();
|
|
}
|
|
});
|
|
return u;
|
|
}
|
|
|
|
/** Reads the candidate's feed through electron-updater and checks it against the release assets. */
|
|
async function readFeed(u, candidate) {
|
|
u.setFeedURL({ provider: 'generic', url: candidate.downloadBase, channel: candidate.feedChannel });
|
|
const result = await withTimeout(u.checkForUpdates(), feedTimeoutMs, candidate.tag);
|
|
if (!result) throw new source.UpdateError('feed-mismatch', { tag: candidate.tag, detail: 'updater inactive' }, 'electron-updater inactive');
|
|
source.verifyFeed(candidate, target, result.updateInfo);
|
|
if (!result.isUpdateAvailable) {
|
|
const detail = 'electron-updater: not applicable to this system';
|
|
throw new source.UpdateError('feed-mismatch', { tag: candidate.tag, detail }, detail);
|
|
}
|
|
}
|
|
|
|
async function runCheck() {
|
|
const selectedChannel = channel();
|
|
setPhase('checking', { error: null });
|
|
let selection;
|
|
try {
|
|
const releases = await source.fetchReleases({ fetchImpl });
|
|
selection = source.selectReleases(releases, { currentVersion, channel: selectedChannel, target });
|
|
} catch (err) {
|
|
fail(err, 'bad-response');
|
|
return;
|
|
}
|
|
const skipped = [...selection.withoutBuild];
|
|
let chosen = null;
|
|
if (target.mode === 'manual') {
|
|
if (selection.candidates[0]) chosen = { candidate: selection.candidates[0], updater: null };
|
|
} else {
|
|
for (const candidate of selection.candidates) {
|
|
const u = newUpdater(selectedChannel);
|
|
try {
|
|
await readFeed(u, candidate);
|
|
chosen = { candidate, updater: u };
|
|
break;
|
|
} catch (err) {
|
|
const e = classify(err, 'feed-mismatch', candidate.tag);
|
|
// A broken or incomplete release is skipped in favour of an older complete one; a network failure or
|
|
// timeout ends the check with an error, so "no update" is never reported without a full answer.
|
|
if (e.code !== 'feed-mismatch' && e.code !== 'incomplete-release') {
|
|
fail(e, 'network');
|
|
return;
|
|
}
|
|
logger.warn(`updater: skip ${candidate.tag}: ${e.message}`);
|
|
skipped.push({ version: candidate.version, code: e.code, params: { version: candidate.version, ...e.params } });
|
|
}
|
|
}
|
|
}
|
|
offered = chosen;
|
|
state.lastCheckedAt = new Date().toISOString();
|
|
state.newerWithoutBuild = skipped;
|
|
state.newerPreview = selection.newestPreview;
|
|
if (!chosen) {
|
|
downloaded = null;
|
|
logger.info(`updater: up to date (${selectedChannel}), ${skipped.length} newer release(s) without a usable build`);
|
|
setPhase('up-to-date', { available: null, progress: null, error: null });
|
|
return;
|
|
}
|
|
const c = chosen.candidate;
|
|
logger.info(`updater: ${c.tag} available (${selectedChannel})`);
|
|
const available = { version: c.version, tag: c.tag, preview: c.preview, publishedAt: c.publishedAt, assetName: c.manualAsset || c.packageFile };
|
|
if (downloaded && downloaded.candidate.tag === c.tag) {
|
|
offered = downloaded;
|
|
setPhase('downloaded', { available, error: null });
|
|
return;
|
|
}
|
|
downloaded = null;
|
|
setPhase('available', { available, progress: null, error: null });
|
|
}
|
|
|
|
async function runDownload() {
|
|
const job = offered;
|
|
const { CancellationToken } = require('electron-updater');
|
|
downloading = { updater: job.updater, token: new CancellationToken() };
|
|
const { token } = downloading;
|
|
setPhase('downloading', { progress: { percent: 0, transferred: 0, total: 0 }, error: null });
|
|
try {
|
|
await job.updater.downloadUpdate(token);
|
|
if (offered !== job) {
|
|
logger.info(`updater: ${job.candidate.tag} downloaded but no longer offered`);
|
|
return;
|
|
}
|
|
downloaded = job;
|
|
logger.info(`updater: ${job.candidate.tag} downloaded and verified`);
|
|
setPhase('downloaded', { progress: null });
|
|
} catch (err) {
|
|
if (token.cancelled) {
|
|
logger.info('updater: download cancelled');
|
|
if (offered === job) setPhase('available', { progress: null });
|
|
} else {
|
|
fail(err, 'download', job.candidate.tag);
|
|
}
|
|
} finally {
|
|
downloading = null;
|
|
}
|
|
}
|
|
|
|
function exclusive(fn) {
|
|
if (busy) return busy.then(snapshot);
|
|
busy = fn().finally(() => {
|
|
busy = null;
|
|
});
|
|
return busy.then(snapshot);
|
|
}
|
|
|
|
function scheduleDeferredPoll() {
|
|
if (deferredTimer) return;
|
|
deferredTimer = setInterval(() => {
|
|
if (state.phase !== 'deferred') {
|
|
clearInterval(deferredTimer);
|
|
deferredTimer = null;
|
|
} else if (!isSessionActive()) {
|
|
download({ manual: false });
|
|
}
|
|
}, DEFERRED_POLL_MS);
|
|
}
|
|
|
|
/** Background downloads wait while the user is connected; a manual request downloads now. */
|
|
function download({ manual }) {
|
|
if (busy) return busy.then(snapshot);
|
|
if (!autoInstall || !offered || (state.phase !== 'available' && state.phase !== 'deferred')) return Promise.resolve(snapshot());
|
|
if (!manual && isSessionActive()) {
|
|
if (state.phase !== 'deferred') {
|
|
logger.info('updater: download deferred until the session ends');
|
|
setPhase('deferred');
|
|
}
|
|
scheduleDeferredPoll();
|
|
return Promise.resolve(snapshot());
|
|
}
|
|
return exclusive(runDownload);
|
|
}
|
|
|
|
function check({ manual }) {
|
|
if (target.mode === 'none' || state.phase === 'installing') return Promise.resolve(snapshot());
|
|
return exclusive(runCheck)
|
|
.then((s) => (s.phase === 'available' && autoInstall ? download({ manual: false }) : s))
|
|
.then((s) => {
|
|
if (manual) logger.info(`updater: manual check → ${s.phase}`);
|
|
return s;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Installs the downloaded, verified package after an explicit user action. Uses electron-updater's
|
|
* quitAndInstall; its install step is synchronous and reports failures through the 'error' event.
|
|
* NSIS: silent update of the existing installation, the installer starts the new version. Whether the
|
|
* installer then succeeds happens after this process quits and is not claimed here.
|
|
* AppImage: the file is replaced, then app.relaunch() starts the new AppImage only after this process
|
|
* has exited (the single-instance lock and the core's data-dir lock are free by then).
|
|
*/
|
|
function install(options) {
|
|
const confirmInterrupt = Boolean(options && options.confirmInterrupt === true);
|
|
if (installBlock) return { ok: false, code: installBlock };
|
|
if (target.mode !== 'auto' || state.phase !== 'downloaded' || !downloaded || offered !== downloaded) {
|
|
return { ok: false, code: 'not-ready' };
|
|
}
|
|
if (isSessionActive() && !confirmInterrupt) return { ok: false, code: 'session-active' };
|
|
const u = downloaded.updater;
|
|
const tag = downloaded.candidate.tag;
|
|
setPhase('installing');
|
|
let installError = null;
|
|
let destination = appImagePath();
|
|
const onError = (err) => {
|
|
installError = err;
|
|
};
|
|
const onRename = (file) => {
|
|
destination = file;
|
|
};
|
|
u.on('error', onError);
|
|
u.on('appimage-filename-updated', onRename);
|
|
try {
|
|
if (target.kind === 'appimage') u.quitAndInstall(true, false);
|
|
else u.quitAndInstall(true, true);
|
|
} catch (err) {
|
|
installError = err;
|
|
} finally {
|
|
u.removeListener('error', onError);
|
|
u.removeListener('appimage-filename-updated', onRename);
|
|
}
|
|
if (installError) {
|
|
const e = fail(installError, 'install', tag);
|
|
return { ok: false, code: 'install-failed', params: e.params };
|
|
}
|
|
if (target.kind === 'appimage') {
|
|
// quitAndInstall quits on the next tick; the relaunch is registered before that.
|
|
electronApp.relaunch({ execPath: destination, args: argv.slice(1) });
|
|
logger.info(`updater: AppImage replaced by ${tag} at ${destination}; relaunch after exit`);
|
|
} else {
|
|
logger.info(`updater: NSIS installer for ${tag} started; app quits`);
|
|
}
|
|
return { ok: true };
|
|
}
|
|
|
|
async function setChannel(value) {
|
|
if (!CHANNELS.includes(value)) return snapshot();
|
|
if (value !== channel()) {
|
|
prefs.set({ updateChannel: value });
|
|
logger.info(`updater: channel → ${value}`);
|
|
if (downloading) downloading.token.cancel();
|
|
if (busy) await busy;
|
|
offered = null;
|
|
downloaded = null;
|
|
Object.assign(state, { available: null, progress: null, newerWithoutBuild: [], newerPreview: null });
|
|
if (state.phase !== 'disabled') setPhase('idle');
|
|
}
|
|
return check({ manual: true });
|
|
}
|
|
|
|
async function openRelease() {
|
|
if (!offered) return { ok: false };
|
|
try {
|
|
await openExternal(source.releasePageUrl(offered.candidate.tag));
|
|
return { ok: true };
|
|
} catch (err) {
|
|
logger.warn('updater: cannot open release page', err);
|
|
return { ok: false };
|
|
}
|
|
}
|
|
|
|
function start() {
|
|
if (target.mode === 'none') {
|
|
logger.info(`updater: disabled: ${target.disabledCode}`);
|
|
return;
|
|
}
|
|
timers.push(setTimeout(() => check({ manual: false }), STARTUP_DELAY_MS));
|
|
timers.push(setInterval(() => check({ manual: false }), CHECK_INTERVAL_MS));
|
|
}
|
|
|
|
function stop() {
|
|
for (const t of timers) clearTimeout(t);
|
|
timers = [];
|
|
clearInterval(deferredTimer);
|
|
deferredTimer = null;
|
|
if (downloading) downloading.token.cancel();
|
|
}
|
|
|
|
function registerIpc(ipcMain, trustedSender) {
|
|
ipcMain.handle('update:get-state', (event) => (trustedSender(event) ? snapshot() : null));
|
|
ipcMain.handle('update:check', (event) => (trustedSender(event) ? check({ manual: true }) : null));
|
|
ipcMain.handle('update:download', (event) => (trustedSender(event) ? download({ manual: true }) : null));
|
|
ipcMain.handle('update:install', (event, options) => {
|
|
if (!trustedSender(event)) return { ok: false, code: 'forbidden' };
|
|
if (options !== undefined && (options === null || typeof options !== 'object' || Array.isArray(options))) {
|
|
return { ok: false, code: 'bad-request' };
|
|
}
|
|
return install(options);
|
|
});
|
|
ipcMain.handle('update:open-release', (event) => (trustedSender(event) ? openRelease() : { ok: false }));
|
|
ipcMain.handle('update:set-channel', (event, value) => (trustedSender(event) && typeof value === 'string' ? setChannel(value) : null));
|
|
}
|
|
|
|
return { start, stop, check, download, install, setChannel, openRelease, getState: snapshot, registerIpc };
|
|
}
|
|
|
|
module.exports = { createUpdateService, createElectronUpdater: defaultCreateUpdater };
|