-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoUpdater.js
More file actions
265 lines (237 loc) · 8.16 KB
/
Copy pathautoUpdater.js
File metadata and controls
265 lines (237 loc) · 8.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/**
* guIDE — Auto-Updater
*
* Wraps electron-updater for automatic update checking, downloading,
* and installation. Falls back gracefully when electron-updater is
* not installed (dev mode, web-only mode).
*/
'use strict';
const EventEmitter = require('events');
const {
getInstallVariant,
getUpdateChannel,
getGithubFeedConfig,
isUpdateArtifactCompatible,
} = require('./updateVariant');
class AutoUpdater extends EventEmitter {
/**
* @param {Electron.BrowserWindow | null} mainWindow
* @param {{ feedUrl?: object, autoDownload?: boolean, autoInstallOnAppQuit?: boolean, channel?: string|null }} opts
*/
constructor(mainWindow, opts) {
super();
this._mainWindow = mainWindow;
this._autoUpdater = null;
this._available = false;
this._status = 'idle'; // idle | checking | available | downloading | downloaded | error
this._updateInfo = null;
this._progress = null;
this._error = null;
this._periodicTimer = null;
this._periodicHours = 0;
this._autoDownload = opts.autoDownload !== undefined ? opts.autoDownload : true;
this._channel = opts.channel !== undefined ? opts.channel : getUpdateChannel();
this._installVariant = getInstallVariant();
this._init(opts || {});
}
_init(opts) {
try {
const { autoUpdater } = require('electron-updater');
this._autoUpdater = autoUpdater;
this._available = true;
autoUpdater.autoDownload = this._autoDownload;
autoUpdater.autoInstallOnAppQuit = opts.autoInstallOnAppQuit !== undefined ? opts.autoInstallOnAppQuit : false;
autoUpdater.allowDowngrade = false;
if (this._channel) {
autoUpdater.channel = this._channel;
}
const feed = opts.feedUrl || getGithubFeedConfig();
autoUpdater.setFeedURL(feed);
autoUpdater.on('checking-for-update', () => {
this._status = 'checking';
this._error = null;
this._sendStatus();
this.emit('checking');
});
autoUpdater.on('update-available', (info) => {
if (!isUpdateArtifactCompatible(info, this._installVariant)) {
const msg = `Refusing ${this._installVariant} install update: feed returned wrong variant artifact (${info?.version || 'unknown'}). Reinstall the matching installer from GitHub Releases.`;
console.warn(`[AutoUpdater] ${msg}`);
this._handleError(msg);
return;
}
this._status = 'available';
this._updateInfo = info;
this._sendStatus();
this.emit('available', info);
if (this._autoDownload) {
this.downloadUpdate();
}
});
autoUpdater.on('update-not-available', (info) => {
this._status = 'idle';
this._updateInfo = info;
this._sendStatus({ status: 'up-to-date' });
this.emit('up-to-date', info);
});
autoUpdater.on('download-progress', (progress) => {
this._status = 'downloading';
this._progress = progress;
this._sendStatus({
progress: {
percent: Math.round(progress.percent),
transferred: progress.transferred,
total: progress.total,
bytesPerSecond: progress.bytesPerSecond,
},
});
this.emit('progress', progress);
});
autoUpdater.on('update-downloaded', (info) => {
if (!isUpdateArtifactCompatible(info, this._installVariant)) {
const msg = `Downloaded update does not match ${this._installVariant} install — not installing. Use the correct variant from GitHub Releases.`;
console.warn(`[AutoUpdater] ${msg}`);
this._handleError(msg);
return;
}
this._status = 'downloaded';
this._updateInfo = info;
this._progress = null;
this._sendStatus();
this.emit('downloaded', info);
});
autoUpdater.on('error', (err) => {
this._handleError(err?.message || String(err));
});
console.log(`[AutoUpdater] ready variant=${this._installVariant} channel=${this._channel || 'default'}`);
} catch (err) {
this._available = false;
const msg = err?.message || String(err);
console.warn(`[AutoUpdater] init failed — updates disabled: ${msg}`);
}
}
_handleError(message) {
this._status = 'error';
this._error = message;
this._sendStatus({ error: message });
this.emit('error', new Error(message));
}
_sendStatus(overrides = {}) {
const payload = {
status: overrides.status || this._status,
info: overrides.info !== undefined ? overrides.info : this._updateInfo,
progress: overrides.progress !== undefined ? overrides.progress : (
this._progress ? {
percent: Math.round(this._progress.percent),
transferred: this._progress.transferred,
total: this._progress.total,
bytesPerSecond: this._progress.bytesPerSecond,
} : null
),
error: overrides.error !== undefined ? overrides.error : this._error,
available: this._available,
channel: this._channel,
installVariant: this._installVariant,
};
this._sendToRenderer('update-status', payload);
}
_sendToRenderer(channel, data) {
try {
if (this._mainWindow && !this._mainWindow.isDestroyed()) {
this._mainWindow.webContents.send(channel, data);
}
} catch {
// Window may have been closed
}
}
/** Check for updates. No-op if electron-updater is not available. */
checkForUpdates() {
if (!this._available || !this._autoUpdater) return;
this._autoUpdater.checkForUpdates().catch((err) => {
this._handleError(err.message);
});
}
/** Download an available update. */
downloadUpdate() {
if (!this._available || !this._autoUpdater) return;
this._autoUpdater.downloadUpdate().catch((err) => {
this._handleError(err.message);
});
}
/** Quit and install the downloaded update. */
quitAndInstall() {
if (!this._available || !this._autoUpdater) return;
this._autoUpdater.quitAndInstall();
}
/** Get current updater state. */
getStatus() {
return {
available: this._available,
status: this._status,
updateInfo: this._updateInfo,
progress: this._progress ? {
percent: Math.round(this._progress.percent),
transferred: this._progress.transferred,
total: this._progress.total,
bytesPerSecond: this._progress.bytesPerSecond,
} : null,
error: this._error,
periodicCheckHours: this._periodicHours,
channel: this._channel,
installVariant: this._installVariant,
};
}
/**
* Schedule a periodic background check.
* @param {number} hours - check interval in hours. 0 disables.
*/
startPeriodicCheck(hours) {
this.stopPeriodicCheck();
const h = Number(hours);
if (!Number.isFinite(h) || h <= 0) {
this._periodicHours = 0;
return;
}
this._periodicHours = Math.max(1, Math.floor(h));
const intervalMs = this._periodicHours * 60 * 60 * 1000;
this._periodicTimer = setInterval(() => {
try { this.checkForUpdates(); }
catch (e) { console.warn('[AutoUpdater] periodic check failed:', e.message); }
}, intervalMs);
if (this._periodicTimer && typeof this._periodicTimer.unref === 'function') {
this._periodicTimer.unref();
}
console.log(`[AutoUpdater] periodic check scheduled every ${this._periodicHours}h`);
}
/** Cancel the periodic background check. */
stopPeriodicCheck() {
if (this._periodicTimer) {
clearInterval(this._periodicTimer);
this._periodicTimer = null;
console.log('[AutoUpdater] periodic check cancelled');
}
this._periodicHours = 0;
}
/**
* Register Electron IPC handlers.
* @param {Electron.IpcMain} ipcMain
*/
registerIPC(ipcMain) {
ipcMain.handle('updater-check', () => {
this.checkForUpdates();
return this.getStatus();
});
ipcMain.handle('updater-download', () => {
this.downloadUpdate();
return { ok: true };
});
ipcMain.handle('updater-install', () => {
this.quitAndInstall();
return { ok: true };
});
ipcMain.handle('updater-status', () => {
return this.getStatus();
});
}
}
module.exports = { AutoUpdater };