70 lines
2.4 KiB
JavaScript
70 lines
2.4 KiB
JavaScript
|
|
// main/updater.js
|
|||
|
|
const { app, BrowserWindow, ipcMain } = require('electron')
|
|||
|
|
const { autoUpdater } = require('electron-updater')
|
|||
|
|
const log = require('electron-log')
|
|||
|
|
Object.assign(console, log.functions)
|
|||
|
|
|
|||
|
|
const updaterState = {
|
|||
|
|
updateInProgress: false,
|
|||
|
|
updateDownloaded: false,
|
|||
|
|
pendingNavs: [],
|
|||
|
|
}
|
|||
|
|
function flushPendingNavs() {
|
|||
|
|
const fns = updaterState.pendingNavs.slice()
|
|||
|
|
updaterState.pendingNavs = []
|
|||
|
|
for (const fn of fns) try { fn() } catch (e) { console.warn('[Nav defer err]', e) }
|
|||
|
|
}
|
|||
|
|
function broadcast(channel, payload) {
|
|||
|
|
BrowserWindow.getAllWindows().forEach(w => !w.isDestroyed() && w.webContents.send(channel, payload))
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function registerUpdater() {
|
|||
|
|
autoUpdater.logger = log
|
|||
|
|
autoUpdater.logger.transports.file.level = 'info'
|
|||
|
|
autoUpdater.autoDownload = true
|
|||
|
|
autoUpdater.autoInstallOnAppQuit = false
|
|||
|
|
|
|||
|
|
autoUpdater.on('checking-for-update', () => console.log('[updater] checking...'))
|
|||
|
|
autoUpdater.on('update-available', (info) => {
|
|||
|
|
updaterState.updateInProgress = true
|
|||
|
|
console.log('[updater] available', info.version)
|
|||
|
|
broadcast('update:available', info)
|
|||
|
|
})
|
|||
|
|
autoUpdater.on('update-not-available', () => {
|
|||
|
|
console.log('[updater] not-available')
|
|||
|
|
updaterState.updateInProgress = false
|
|||
|
|
flushPendingNavs()
|
|||
|
|
})
|
|||
|
|
let lastSend = 0
|
|||
|
|
autoUpdater.on('download-progress', (p) => {
|
|||
|
|
updaterState.updateInProgress = true
|
|||
|
|
const now = Date.now()
|
|||
|
|
if (now - lastSend > 150) {
|
|||
|
|
lastSend = now
|
|||
|
|
broadcast('update:progress', p)
|
|||
|
|
}
|
|||
|
|
const win = BrowserWindow.getAllWindows()[0]
|
|||
|
|
if (win) win.setProgressBar(p.percent / 100)
|
|||
|
|
})
|
|||
|
|
autoUpdater.on('update-downloaded', (info) => {
|
|||
|
|
console.log('[updater] downloaded')
|
|||
|
|
updaterState.updateInProgress = true
|
|||
|
|
updaterState.updateDownloaded = true
|
|||
|
|
broadcast('update:downloaded', info)
|
|||
|
|
// 想要自动安装:autoUpdater.quitAndInstall(false, true)
|
|||
|
|
})
|
|||
|
|
autoUpdater.on('error', (err) => {
|
|||
|
|
console.error('[updater] error', err)
|
|||
|
|
broadcast('update:error', { message: String(err) })
|
|||
|
|
updaterState.updateInProgress = false
|
|||
|
|
flushPendingNavs()
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
ipcMain.handle('update:quitAndInstall', () => autoUpdater.quitAndInstall(false, true))
|
|||
|
|
ipcMain.handle('update:checkNow', () => autoUpdater.checkForUpdates())
|
|||
|
|
|
|||
|
|
autoUpdater.checkForUpdates()
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
module.exports = { registerUpdater, updaterState }
|