-
Notifications
You must be signed in to change notification settings - Fork 129
/
index.ts
285 lines (248 loc) · 8.81 KB
/
index.ts
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import assert from 'assert';
import isURL from 'is-url';
import ms from 'ms';
import gh from 'github-url-to-object';
import path from 'path';
import fs from 'fs';
import os from 'os';
import { format } from 'util';
import { app } from 'electron';
export interface ILogger {
log(message: string): void;
info(message: string): void;
error(message: string): void;
warn(message: string): void;
}
export enum UpdateSourceType {
ElectronPublicUpdateService,
StaticStorage,
}
export interface IElectronUpdateServiceSource {
type: UpdateSourceType.ElectronPublicUpdateService;
/**
* @param {String} repo A GitHub repository in the format `owner/repo`.
* Defaults to your `package.json`'s `"repository"` field
*/
repo?: string;
/**
* @param {String} host Defaults to `https://update.electronjs.org`
*/
host?: string;
}
export interface IStaticUpdateSource {
type: UpdateSourceType.StaticStorage;
/**
* @param {String} baseUrl Base URL for your static storage provider where your
* updates are stored
*/
baseUrl: string;
}
export type IUpdateSource = IElectronUpdateServiceSource | IStaticUpdateSource;
export interface IDialogMessages {
/**
* @param {String} title The title of the dialog box.
* Defaults to `Application Update`
*/
title: string;
/**
* @param {String} detail The text of the dialog box.
* Defaults to `A new version has been downloaded. Restart the application to apply the updates.`
*/
detail: string;
/**
* @param {String} restartButtonText The text of the restart button.
* Defaults to `Restart`
*/
restartButtonText: string;
/**
* @param {String} laterButtonText The text of the later button.
* Defaults to `Later`
*/
laterButtonText: string;
}
export interface IUpdateElectronAppOptions<L = ILogger> {
/**
* @param {String} repo A GitHub repository in the format `owner/repo`.
* Defaults to your `package.json`'s `"repository"` field
* @deprecated Use the new `updateSource` option
*/
readonly repo?: string;
/**
* @param {String} host Defaults to `https://update.electronjs.org`
* @deprecated Use the new `updateSource` option
*/
readonly host?: string;
readonly updateSource?: IUpdateSource;
/**
* @param {String} updateInterval How frequently to check for updates. Defaults to `10 minutes`.
* Minimum allowed interval is `5 minutes`.
*/
readonly updateInterval?: string;
/**
* @param {Object} logger A custom logger object that defines a `log` function.
* Defaults to `console`. See electron-log, a module
* that aggregates logs from main and renderer processes into a single file.
*/
readonly logger?: L;
/**
* @param {Boolean} notifyUser Defaults to `true`. When enabled the user will be
* prompted to apply the update immediately after download.
*/
readonly notifyUser?: boolean;
readonly dialog?: IDialogMessages;
}
const pkg = require('../package.json');
const userAgent = format('%s/%s (%s: %s)', pkg.name, pkg.version, os.platform(), os.arch());
const supportedPlatforms = ['darwin', 'win32'];
export function updateElectronApp(opts: IUpdateElectronAppOptions = {}) {
// check for bad input early, so it will be logged during development
const safeOpts = validateInput(opts);
// don't attempt to update during development
if (!app.isPackaged) {
const message =
'update-electron-app config looks good; aborting updates since app is in development mode';
opts.logger ? opts.logger.log(message) : console.log(message);
return;
}
if (safeOpts.electron.app.isReady()) initUpdater(safeOpts);
else app.on('ready', () => initUpdater(safeOpts));
}
function initUpdater(opts: ReturnType<typeof validateInput>) {
const { updateSource, updateInterval, logger, electron } = opts;
// exit early on unsupported platforms, e.g. `linux`
if (!supportedPlatforms.includes(process?.platform)) {
log(`Electron's autoUpdater does not support the '${process.platform}' platform. Ref: https://www.electronjs.org/docs/latest/api/auto-updater#platform-notices`);
return;
}
const { app, autoUpdater, dialog } = electron;
let feedURL: string;
let serverType: 'default' | 'json' = 'default';
switch (updateSource.type) {
case UpdateSourceType.ElectronPublicUpdateService: {
feedURL = `${updateSource.host}/${updateSource.repo}/${process.platform}-${
process.arch
}/${app.getVersion()}`;
break;
}
case UpdateSourceType.StaticStorage: {
feedURL = updateSource.baseUrl;
if (process.platform === 'darwin') {
feedURL += '/RELEASES.json';
serverType = 'json';
}
break;
}
}
const requestHeaders = { 'User-Agent': userAgent };
function log(...args: any[]) {
logger.log(...args);
}
log('feedURL', feedURL);
log('requestHeaders', requestHeaders);
autoUpdater.setFeedURL({
url: feedURL,
headers: requestHeaders,
serverType,
});
autoUpdater.on('error', (err) => {
log('updater error');
log(err);
});
autoUpdater.on('checking-for-update', () => {
log('checking-for-update');
});
autoUpdater.on('update-available', () => {
log('update-available; downloading...');
});
autoUpdater.on('update-not-available', () => {
log('update-not-available');
});
if (opts.notifyUser) {
autoUpdater.on(
'update-downloaded',
(event, releaseNotes, releaseName, releaseDate, updateURL) => {
log('update-downloaded', [event, releaseNotes, releaseName, releaseDate, updateURL]);
const { title, restartButtonText, laterButtonText, detail } = opts.dialog;
const dialogOpts = {
type: 'info',
buttons: [restartButtonText, laterButtonText],
title,
message: process.platform === 'win32' ? releaseNotes : releaseName,
detail,
};
dialog.showMessageBox(dialogOpts).then(({ response }) => {
if (response === 0) autoUpdater.quitAndInstall();
});
},
);
}
// check for updates right away and keep checking later
autoUpdater.checkForUpdates();
setInterval(() => {
autoUpdater.checkForUpdates();
}, ms(updateInterval));
}
function guessRepo(electron: typeof Electron.Main) {
const pkgBuf = fs.readFileSync(path.join(electron.app.getAppPath(), 'package.json'));
const pkg = JSON.parse(pkgBuf.toString());
const repoString = pkg.repository?.url || pkg.repository;
const repoObject = gh(repoString);
assert(repoObject, "repo not found. Add repository string to your app's package.json file");
return `${repoObject.user}/${repoObject.repo}`;
}
function validateInput(opts: IUpdateElectronAppOptions) {
const defaults = {
host: 'https://update.electronjs.org',
updateInterval: '10 minutes',
logger: console,
notifyUser: true,
dialog: {
title: 'Application Update',
detail: 'A new version has been downloaded. Restart the application to apply the updates.',
restartButtonText: 'Restart',
laterButtonText: 'Later'
}
};
const { host, updateInterval, logger, notifyUser } = Object.assign({}, defaults, opts);
const assignedDialog = Object.assign({}, defaults.dialog, opts.dialog);
// allows electron to be mocked in tests
const electron: typeof Electron.Main = (opts as any).electron || require('electron');
let updateSource = opts.updateSource;
// Handle migration from old properties + default to update service
if (!updateSource) {
updateSource = {
type: UpdateSourceType.ElectronPublicUpdateService,
repo: opts.repo || guessRepo(electron),
host,
};
}
switch (updateSource.type) {
case UpdateSourceType.ElectronPublicUpdateService: {
assert(
updateSource.repo?.includes('/'),
'repo is required and should be in the format `owner/repo`',
);
assert(
updateSource.host && isURL(updateSource.host) && updateSource.host.startsWith('https:'),
'host must be a valid HTTPS URL',
);
break;
}
case UpdateSourceType.StaticStorage: {
assert(
updateSource.baseUrl &&
isURL(updateSource.baseUrl) &&
updateSource.baseUrl.startsWith('https:'),
'baseUrl must be a valid HTTPS URL',
);
break;
}
}
assert(
typeof updateInterval === 'string' && updateInterval.match(/^\d+/),
'updateInterval must be a human-friendly string interval like `20 minutes`',
);
assert(ms(updateInterval) >= 5 * 60 * 1000, 'updateInterval must be `5 minutes` or more');
assert(logger && typeof logger.log, 'function');
return { updateSource, updateInterval, logger, electron, notifyUser, dialog: assignedDialog };
}