This repository has been archived by the owner on Dec 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 972
/
Copy pathupdater.js
297 lines (262 loc) · 9.61 KB
/
updater.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
'strict mode'
const fs = require('fs')
const path = require('path')
const os = require('os')
const assert = require('assert')
const electron = require('electron')
const querystring = require('querystring')
const Immutable = require('immutable')
const autoUpdater = electron.autoUpdater
const app = electron.app
// Actions
const appActions = require('../js/actions/appActions')
// State
const AppStore = require('../js/stores/appStore')
const updateState = require('./common/state/updateState')
// Constants
const appConfig = require('../js/constants/appConfig')
const messages = require('../js/constants/messages')
const UpdateStatus = require('../js/constants/updateStatus')
// Utils
const request = require('../js/lib/request').request
const ledgerUtil = require('./common/lib/ledgerUtil')
const dates = require('./dates')
const Channel = require('./channel')
// in built mode console.log output is not emitted to the terminal
// in prod mode we pipe to a file
var debug = function (contents) {
const updateLogPath = path.join(app.getPath('userData'), 'updateLog.log')
fs.appendFile(updateLogPath, new Date().toISOString() + ' - ' + contents + os.EOL, (err) => {
if (err) console.error(err)
})
}
// this maps the result of a call to process.platform to an update API identifier
var platforms = {
'darwin': 'osx',
'win32x64': 'winx64',
'win32ia32': 'winia32',
'linux': 'linux'
}
// We are storing this as a package variable because a number of functions need access
// It is set in the init function
var platformBaseUrl = null
var version = null
var updateToPreviewReleases = false
// build the complete update url from the base, platform and version
exports.updateUrl = function (updates, platform, arch) {
// For windows we need to separate x64 and ia32 for update purposes
if (platform === 'win32') {
platform = platform + arch
}
platformBaseUrl = `${updates.baseUrl}/${Channel.channel()}/${version}/${platforms[platform]}`
debug(`platformBaseUrl = ${platformBaseUrl}`)
if (platform === 'darwin' || platform === 'linux') {
return platformBaseUrl
} else {
if (platform.match(/^win32/)) {
var windowsUpdateUrlWithArch = updates.winBaseUrl.replace('CHANNEL', Channel.channel()) + platforms[platform]
return windowsUpdateUrlWithArch
} else {
// Unsupport platform for automatic updates
return null
}
}
}
// Setup schedule for periodic and startup update checks
var scheduleUpdates = () => {
// Periodic check
if (appConfig.updates.appUpdateCheckFrequency) {
setInterval(() => {
exports.checkForUpdate()
}, appConfig.updates.appUpdateCheckFrequency)
}
// Startup check
if (appConfig.updates.runtimeUpdateCheckDelay) {
setTimeout(() => {
exports.checkForUpdate()
}, appConfig.updates.runtimeUpdateCheckDelay)
}
}
// set the feed url for the auto-update system
exports.init = (platform, arch, ver, updateToPreview) => {
// When starting up we should not expect an update to be available
appActions.setUpdateStatus(UpdateStatus.UPDATE_NONE)
// Browser version X.X.X
version = ver
// Flag controlling whether preview releases are accepted
updateToPreviewReleases = updateToPreview
var baseUrl = exports.updateUrl(appConfig.updates, platform, arch)
var query = { accept_preview: updateToPreviewReleases ? 'true' : 'false' }
if (baseUrl) {
debug(`updateUrl = ${baseUrl}`)
scheduleUpdates()
// This will fail if we are in dev
try {
// add the preview flag to the base feed url
autoUpdater.setFeedURL(`${baseUrl}?${querystring.stringify(query)}`)
} catch (err) {
console.error(err)
}
} else {
debug('No updateUrl, not scheduling updates.')
}
}
// Build a set of three params providing flags determining when the last update occurred
// This is a privacy preserving policy. Instead of passing personally identifying
// information, the browser will pass thefour boolean values indicating when the last
// update check occurred.
var paramsFromLastCheckDelta = (lastCheckYMD, lastCheckWOY, lastCheckMonth, firstCheckMade, weekOfInstallation, ref) => {
return {
daily: !lastCheckYMD || (dates.todayYMD() > lastCheckYMD),
weekly: !lastCheckWOY || (dates.todayWOY() !== lastCheckWOY),
monthly: !lastCheckMonth || (dates.todayMonth() !== lastCheckMonth),
first: !firstCheckMade,
woi: weekOfInstallation,
ref: ref || null
}
}
// Make a request to the update server to retrieve meta data
var requestVersionInfo = (done, pingOnly) => {
if (!platformBaseUrl) throw new Error('platformBaseUrl not set')
// Get the daily, week of year and month update checks
const state = AppStore.getState()
const lastCheckYMD = state.getIn(['updates', 'lastCheckYMD'], null)
debug(`lastCheckYMD = ${lastCheckYMD}`)
const lastCheckWOY = state.getIn(['updates', 'lastCheckWOY'], null)
debug(`lastCheckWOY = ${lastCheckWOY}`)
const lastCheckMonth = state.getIn(['updates', 'lastCheckMonth'], null)
debug(`lastCheckMonth = ${lastCheckMonth}`)
// Has the browser ever asked for an update
const firstCheckMade = state.getIn(['updates', 'firstCheckMade'], false)
debug(`firstCheckMade = ${firstCheckMade}`)
// The previous Monday from the installation date
const weekOfInstallation = state.getIn(['updates', 'weekOfInstallation'], null)
debug(`weekOfInstallation= ${weekOfInstallation}`)
// The installation promoCode from buildConfig
const promoCode = updateState.getUpdateProp(state, 'referralPromoCode') || 'none'
debug(`promoCode = ${promoCode}`)
// Build query string based on the last date an update request was made
const query = paramsFromLastCheckDelta(
lastCheckYMD,
lastCheckWOY,
lastCheckMonth,
firstCheckMade,
weekOfInstallation,
promoCode
)
query.accept_preview = updateToPreviewReleases ? 'true' : 'false'
const queryString = `${platformBaseUrl}?${querystring.stringify(query)}`
debug(queryString)
request(queryString, (err, response, body) => {
var statusCode = response.statusCode
appActions.setUpdateLastCheck()
if (pingOnly) {
return
}
if (!err && statusCode === 204) {
autoUpdater.emit(messages.UPDATE_NOT_AVAILABLE)
} else if (!err && (statusCode === 200)) {
if (body) {
try {
body = JSON.parse(body)
} catch (error) {
autoUpdater.emit('error', error)
}
}
// This should be handled by a UI component for the update toolbar
process.emit(messages.UPDATE_META_DATA_RETRIEVED, body)
done(null, body)
} else {
// Network error or mis-configuration
autoUpdater.emit('error', err)
}
})
}
var downloadHandler = (err, metadata) => {
assert.equal(err, null)
debug(`Metadata: ${JSON.stringify(metadata)}`)
appActions.setUpdateStatus(undefined, undefined, Immutable.fromJS(metadata))
if (process.platform === 'win32') {
// check versions to see if an update is required
if (metadata) {
if (metadata.braveURL) {
autoUpdater.setFeedURL(metadata.braveURL)
}
autoUpdater.checkForUpdates()
} else {
autoUpdater.emit(messages.UPDATE_NOT_AVAILABLE)
}
} else {
autoUpdater.checkForUpdates()
}
}
// Make network request to check for an available update
exports.checkForUpdate = (verbose, skipReferral = false) => {
const state = AppStore.getState()
// check for referral 30 days
if (
!skipReferral &&
!updateState.getUpdateProp(state, 'referralTimestamp') &&
updateState.getUpdateProp(state, 'referralDownloadId')
) {
const installTime = state.get('firstRunTimestamp')
const month = parseInt(process.env.LEDGER_REFERRAL_CHECK_TIME || (ledgerUtil.milliseconds.day * 30))
if (installTime + month < new Date().getTime()) {
appActions.checkReferralActivity()
return
}
}
const updateStatus = state.getIn(['updates', 'status'])
if (updateStatus !== UpdateStatus.UPDATE_ERROR &&
updateStatus !== UpdateStatus.UPDATE_NOT_AVAILABLE &&
updateStatus !== UpdateStatus.UPDATE_NONE) {
debug('Already checking for updates...')
requestVersionInfo(undefined, true)
appActions.setUpdateStatus(undefined, verbose)
return
}
// Force falsy or truthy here so session store will write out a value
// and it won't auto make updater UI appear periodically.
appActions.setUpdateStatus(UpdateStatus.UPDATE_CHECKING, !!verbose)
debug('checkForUpdates')
try {
requestVersionInfo(downloadHandler, false)
} catch (err) {
debug(err)
}
}
exports.quitAndInstall = () => {
autoUpdater.quitAndInstall()
}
// The download is complete, we send a signal and await UI
autoUpdater.on('update-downloaded', (evt, releaseNotes, releaseDate, updateURL) => {
debug('update downloaded')
if (releaseNotes) {
debug(`Release notes : ${releaseNotes}`)
}
if (releaseDate) {
debug(`Release date: ${releaseDate}`)
}
if (updateURL) {
debug(`Update URL: ${updateURL}`)
}
appActions.setUpdateStatus(UpdateStatus.UPDATE_AVAILABLE)
})
// Download has started
autoUpdater.on(messages.UPDATE_AVAILABLE, (evt) => {
debug('update downloading')
appActions.setUpdateStatus(UpdateStatus.UPDATE_DOWNLOADING)
})
// The current version of the software is up to date
autoUpdater.on(messages.UPDATE_NOT_AVAILABLE, (evt) => {
debug('update not available')
appActions.setUpdateStatus(UpdateStatus.UPDATE_NOT_AVAILABLE)
})
// Handle autoUpdater errors (Network, permissions etc...)
autoUpdater.on('error', (err) => {
appActions.setUpdateStatus(UpdateStatus.UPDATE_ERROR)
debug(err)
})