forked from yansenlei/electron-asar-hot-updater
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
414 lines (372 loc) · 11.9 KB
/
index.js
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
const { app } = require('electron')
const FileSystem = require('original-fs')
const Utils = require('util')
const request = require('request')
const progress = require('request-progress')
const admZip = require('adm-zip')
// Yes, it's weird, but we need the trailing slash after the .asar
// so we can read paths "inside" it, e.g. the package.json, where we look
// for our current version
const AppPath = app.getAppPath() + '\\'
const AppPathFolder = AppPath.slice(0, AppPath.indexOf('app.asar')) + '\\'
const AppAsar = AppPath.slice(0, -1)
const WindowsUpdater =
AppPath.slice(0, AppPath.indexOf('resources')) + '\\updater.exe'
const errors = [
'version_not_specified',
'cannot_connect_to_api',
'no_update_available',
'api_response_not_valid',
'update_file_not_found',
'failed_to_download_update',
'failed_to_apply_update'
]
/**
* */
var Updater = {
/**
* The setup
* */
setup: {
api: null,
token: null,
server: true,
logFile: 'updater-log.txt',
requestOptions: {},
callback: false,
progresscallback: false
},
/**
* The new update information
* */
update: {
last: null,
source: null,
file: null
},
/**
* Init the module
* */
init: function (setup) {
this.setup = Utils._extend(this.setup, setup)
this.log('AppPath: ' + AppPath)
this.log('AppPathFolder: ' + AppPathFolder)
},
/**
* Logging
* */
log: function (line) {
// Log it
console.log('Updater: ', line)
// Put it into a file
if (this.setup.logFile) {
console.log('%s + %s + %s', AppPathFolder + "\\", this.setup.logFile, line)
FileSystem.appendFileSync(AppPathFolder + "\\" + this.setup.logFile, line + '\n')
}
},
/**
* Compare Versions
* @param {new version} v1
* @param {old version} v2
* */
compareVersions: function (v1, v2) {
v1 = v1.split(".");
v2 = v2.split(".");
var longestLength = v1.length > v2.length ? v1.length : v2.length;
for (var i = 0; i < longestLength; i++) {
if (v1[i] != v2[i]) {
return v1 > v2 ? 1 : -1;
}
}
return 0;
},
/**
* Triggers the callback you set to receive the result of the update
* */
end: function (error, body) {
if (typeof this.setup.callback !== 'function') return false
this.setup.callback.call(
this,
error != 'undefined' ? errors[error] : false,
this.update.last,
body
)
},
/**
* Make the check for the update
* */
check: function (callback) {
if (callback) {
this.setup.callback = callback
}
// Get the current version
debugger
// Error FIX: Cannot find module 'F:\Path\package.json'
var packageInfo = require('../../dist_electron/package.json')
this.log("Current Version: "+ packageInfo.version)
// If the version property not specified
if (!packageInfo.version) {
this.log(
'The "version" property not specified inside the application package.json'
)
this.end(0)
return false
}
var that = this
request(
{
url: this.setup.api,
method: 'post',
json: true,
body: {
name: packageInfo.name,
current: packageInfo.version
},
headers: this.setup.headers || {}
},
function (error, res, body) {
if (!error) {
try {
let response = {}
if (Updater.setup.server) {
response = body
} else {
response = { last: body.version }
if (body.version !== packageInfo.version) {
response.source = body.asar
}
}
// If the "last" property is not defined
if (!response.last) {
throw false
}
if (that.compareVersions(response.last, packageInfo.version) === 1) {
Updater.log('Update available: ' + response.last)
// Store the response
Updater.update = response
// Ask user for confirmation
Updater.end(undefined, body)
} else {
Updater.log('No updates available: '+ response.last)
Updater.end(2)
return false
}
} catch (error) {
Updater.log(error)
Updater.log('API response is not valid')
Updater.end(3)
}
} else {
Updater.log(error)
Updater.log('Could not connect')
Updater.end(1)
}
}
)
},
/**
* Download the update file
* */
download: function (callback) {
if (callback) {
this.setup.callback = callback
}
var url = this.update.source, fileName = 'update.asar'
this.log('Downloading Asar File: ' + url)
progress(
request(
{
uri: url,
encoding: null
},
function (error, response, body) {
if (error) {
return console.error('err')
}
var updateFile = AppPathFolder + fileName
if (response.headers['content-type'].indexOf('zip') > -1) {
Updater.log('ZipFilePath: ' + AppPathFolder)
try {
const zip = new admZip(body)
zip.extractAllTo(AppPathFolder, true)
// Store the update file path
Updater.update.file = updateFile
Updater.log('Updater.update.file: ' + updateFile)
// Success
Updater.log('Update Zip downloaded: ' + AppPathFolder)
// Apply the update
if (process.platform === 'darwin') {
Updater.apply()
} else {
Updater.mvOrMove()
}
} catch (error) {
Updater.log('unzip error: ' + error)
}
} else {
console.log('Upload successful! Server responded with:')
Updater.log('updateFile: ' + updateFile)
// Create the file
FileSystem.writeFile(updateFile, body, null, function (error) {
if (error) {
Updater.log(
error + '\n Failed to download the update to a local file.'
)
Updater.end(5)
return false
}
// Store the update file path
Updater.update.file = updateFile
Updater.log('Updater.update.file: ' + updateFile)
// Success
Updater.log('Update downloaded: ' + updateFile)
// Apply the update
if (process.platform === 'darwin') {
Updater.apply()
} else {
Updater.mvOrMove()
}
})
}
}
),
{
throttle: 500 // Throttle the progress event to 500ms, defaults to 1000ms
// delay: 1000, // Only start to emit after 1000ms delay, defaults to 0ms
// lengthHeader: 'x-transfer-length' // Length header to use, defaults to content-length
}
)
.on('progress', function (state) {
// The state is an object that looks like this:
// {
// percent: 0.5, // Overall percent (between 0 to 1)
// speed: 554732, // The download speed in bytes/sec
// size: {
// total: 90044871, // The total payload size in bytes
// transferred: 27610959 // The transferred payload size in bytes
// },
// time: {
// elapsed: 36.235, // The total elapsed seconds since the start (3 decimals)
// remaining: 81.403 // The remaining seconds to finish (3 decimals)
// }
// }
if (Updater.setup.progresscallback) {
Updater.setup.progresscallback(state)
}
})
.on('error', function (err) {
// Do something with err
console.log('Do something with err', err)
})
.on('end', function (d) {
// Do something after request finishes
console.log('Do something after request finishes', d)
})
},
progress: function (callback) {
if (callback) {
this.setup.progresscallback = callback
}
},
/**
* Apply the update, remove app.asar and rename update.zip to app.asar
* */
apply: function () {
try {
this.log('Going to unlink: ' + AppPath.slice(0, -1))
FileSystem.unlink(AppPath.slice(0, -1), function (err) {
if (err) {
Updater.log("Couldn't unlink: " + AppPath.slice(0, -1))
return console.error(err)
}
Updater.log('Asar deleted successfully.')
})
} catch (error) {
this.log('Delete error: ' + error)
// Failure
this.end(6)
}
try {
this.log(
'Going to rename: ' + this.update.file + ' to: ' + AppPath.slice(0, -1)
)
FileSystem.rename(this.update.file, AppPath.slice(0, -1), function (err) {
if (err) {
Updater.log(
"Couldn't rename: " +
Updater.update.file +
' to: ' +
AppPath.slice(0, -1)
)
return console.error(err)
}
Updater.log('Update applied.')
})
this.log('End of update.')
// Success
this.end()
} catch (error) {
this.log('Rename error: ' + error)
// Failure
this.end(6)
}
},
// app.asar is always EBUSY on Windows, so we need to try another
// way of replacing it. This should get called after the main Electron
// process has quit. Win32 calls 'move' and other platforms call 'mv'
mvOrMove: function (child) {
var updateAsar = AppPathFolder + 'update.asar'
var appAsar = AppPathFolder + 'app.asar'
var winArgs = ''
Updater.log('Checking for ' + updateAsar)
try {
FileSystem.accessSync(updateAsar)
try {
Updater.log(
'Going to shell out to move: ' + updateAsar + ' to: ' + AppAsar
)
if (process.platform === 'win32') {
Updater.log(
'Going to start the windows updater:' +
WindowsUpdater +
' ' +
updateAsar +
' ' +
appAsar
)
const fs = require('fs')
fs.writeFileSync(
WindowsUpdater,
fs.readFileSync(
`${AppPathFolder}app.asar/node_modules/${require('./package.json').name}/updater.exe`
)
)
// JSON.stringify() calls mean we're correctly quoting paths with spaces
winArgs = `${JSON.stringify(WindowsUpdater)} ${JSON.stringify(updateAsar)} ${JSON.stringify(appAsar)}`
Updater.log(winArgs)
// and the windowsVerbatimArguments options argument, in combination with the /s switch, stops windows stripping quotes from our commandline
// This doesn't work:
const { spawn } = require('child_process')
// spawn(`${JSON.stringify(WindowsUpdater)}`,[`${JSON.stringify(updateAsar)}`,`${JSON.stringify(appAsar)}`], {detached: true, windowsVerbatimArguments: true, stdio: 'ignore'});
// so we have to spawn a cmd shell, which then runs the updater, and leaves a visible window whilst running
spawn('cmd', ['/s', '/c', '"' + winArgs + '"'], {
detached: true,
windowsVerbatimArguments: true,
stdio: 'ignore'
})
app.quit()
} else {
// here's how we'd do this on Mac/Linux, but on Mac at least, the .asar isn't marked as busy, so the update process above
// is able to overwrite it.
//
child.spawn('bash', ['-c', ['cd ' + JSON.stringify(AppPathFolder), 'mv -f update.asar app.asar'].join(' && ')], {detached: true});
}
} catch (error) {
Updater.log('Shelling out to move failed: ' + error)
}
} catch (error) {
Updater.log("Couldn't see an " + updateAsar + ' error was: ' + error)
}
}
}
module.exports = Updater