-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoUpdater.js
More file actions
245 lines (216 loc) · 7.34 KB
/
autoUpdater.js
File metadata and controls
245 lines (216 loc) · 7.34 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
/**
* guIDE 2.0 — 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).
*
* Usage:
* const updater = new AutoUpdater(mainWindow);
* updater.checkForUpdates();
* updater.registerIPC(); // Electron IPC handlers
* updater.registerRoutes(app); // Express API for web UI fallback
*/
'use strict';
const EventEmitter = require('events');
class AutoUpdater extends EventEmitter {
/**
* @param {Electron.BrowserWindow | null} mainWindow
* @param {{ feedUrl?: string, autoDownload?: boolean, autoInstallOnAppQuit?: boolean }} 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._init(opts || {});
}
_init(opts) {
try {
const { autoUpdater } = require('electron-updater');
this._autoUpdater = autoUpdater;
this._available = true;
// Configure
autoUpdater.autoDownload = opts.autoDownload !== undefined ? opts.autoDownload : false;
autoUpdater.autoInstallOnAppQuit = opts.autoInstallOnAppQuit !== undefined ? opts.autoInstallOnAppQuit : true;
autoUpdater.allowDowngrade = false;
if (opts.feedUrl) {
autoUpdater.setFeedURL(opts.feedUrl);
}
// Wire events
autoUpdater.on('checking-for-update', () => {
this._status = 'checking';
this._sendToRenderer('update-status', { status: 'checking' });
this.emit('checking');
});
autoUpdater.on('update-available', (info) => {
this._status = 'available';
this._updateInfo = info;
this._sendToRenderer('update-status', { status: 'available', info });
this.emit('available', info);
});
autoUpdater.on('update-not-available', (info) => {
this._status = 'idle';
this._updateInfo = null;
this._sendToRenderer('update-status', { status: 'up-to-date', info });
this.emit('up-to-date', info);
});
autoUpdater.on('download-progress', (progress) => {
this._status = 'downloading';
this._progress = progress;
this._sendToRenderer('update-status', {
status: 'downloading',
progress: {
percent: Math.round(progress.percent),
transferred: progress.transferred,
total: progress.total,
bytesPerSecond: progress.bytesPerSecond,
},
});
this.emit('progress', progress);
});
autoUpdater.on('update-downloaded', (info) => {
this._status = 'downloaded';
this._updateInfo = info;
this._progress = null;
this._sendToRenderer('update-status', { status: 'downloaded', info });
this.emit('downloaded', info);
});
autoUpdater.on('error', (err) => {
this._status = 'error';
this._error = err.message;
this._sendToRenderer('update-status', { status: 'error', error: err.message });
this.emit('error', err);
});
} catch {
// electron-updater not installed (dev mode or web-only)
this._available = false;
console.log('[AutoUpdater] electron-updater not available — updates disabled');
}
}
_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._status = 'error';
this._error = err.message;
});
}
/** Download an available update. */
downloadUpdate() {
if (!this._available || !this._autoUpdater) return;
this._autoUpdater.downloadUpdate().catch((err) => {
this._status = 'error';
this._error = 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,
error: this._error,
periodicCheckHours: this._periodicHours,
};
}
/**
* Schedule a periodic background check.
* Setting hours <= 0 cancels any existing schedule. Calling with a new positive
* value replaces the existing schedule. The check is fire-and-forget; status
* still flows through the same renderer events as a manual checkForUpdates().
* @param {number} hours - check interval in hours. 0 disables. Values below 1 are clamped to 1.
*/
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);
// Allow the Node process to exit even if this timer is alive.
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. No-op if none is scheduled. */
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();
});
}
/**
* Register Express API routes (fallback for web UI when not running in Electron).
* @param {import('express').Application} app
*/
registerRoutes(app) {
app.get('/api/updater/status', (req, res) => {
res.json(this.getStatus());
});
app.post('/api/updater/check', (req, res) => {
this.checkForUpdates();
res.json({ triggered: true, status: this._status });
});
app.post('/api/updater/download', (req, res) => {
this.downloadUpdate();
res.json({ triggered: true });
});
app.post('/api/updater/install', (req, res) => {
this.quitAndInstall();
res.json({ triggered: true });
});
}
}
module.exports = { AutoUpdater };