js
复制代码
// electron/ipc/api/updater.js
const { autoUpdater } = require('electron-updater')
const { dialog, BrowserWindow } = require('electron')
const log = require('electron-log')
// 配置日志
autoUpdater.logger = log
autoUpdater.logger.transports.file.level = 'info'
// 自动更新状态
let updateState = {
isChecking: false, // 标记是否正在检查更新
isDownloading: false, // 标记是否正在下载更新包
downloadProgress: 0, // 记录下载进度百分比 (0-100)
lastError: null, // 记录最后一次错误
updateAvailable: false, // 标记是否有可用更新
updateDownloaded: false // 标记更新是否已下载完成
}
// 主窗口引用
let mainWindow = null
/**
* 设置主窗口引用
*/
function setMainWindow(window) {
mainWindow = window
}
/**
* 检查更新
*/
async function checkForUpdates(event, options = {}) {
if (updateState.isChecking) {
return { success: false, message: '正在检查更新中...' }
}
try {
updateState.isChecking = true
updateState.lastError = null
console.log('开始检查更新...')
// 发送检查开始消息
if (mainWindow) {
mainWindow.webContents.send('updater:updateMessage', '正在检查更新...')
}
const result = await autoUpdater.checkForUpdates()
// 如果没有找到更新,autoUpdater 会触发 'update-not-available' 事件
if (result) {
console.log('发现更新:', result.updateInfo.version)
return {
success: true,
message: `发现新版本 v${result.updateInfo.version}`,
version: result.updateInfo.version
}
}
return { success: true, message: '正在检查更新...' }
} catch (error) {
console.error('检查更新失败:', error)
updateState.lastError = error.message
// 发送错误消息
if (mainWindow) {
mainWindow.webContents.send('updater:updateError', error.message)
}
return {
success: false,
message: `检查更新失败: ${error.message}`
}
} finally {
updateState.isChecking = false
}
}
/**
* 退出并安装更新
*/
async function quitAndInstall(event) {
try {
console.log('准备退出并安装更新...')
autoUpdater.quitAndInstall()
return { success: true }
} catch (error) {
console.error('安装更新失败:', error)
return {
success: false,
message: `安装更新失败: ${error.message}`
}
}
}
/**
* 获取更新状态
*/
async function getUpdateStatus(event) {
return {
...updateState,
currentVersion: require('../../package.json').version
}
}
/**
* 初始化自动更新监听器
*/
function initializeAutoUpdater() {
// 检查更新中
autoUpdater.on('checking-for-update', () => {
console.log('正在检查更新...')
updateState.isChecking = true
if (mainWindow) {
mainWindow.webContents.send('updater:updateMessage', '正在检查更新...')
}
})
// 发现新版本
autoUpdater.on('update-available', (info) => {
console.log('发现新版本:', info.version)
updateState.updateAvailable = true
updateState.isChecking = false
if (mainWindow) {
mainWindow.webContents.send('updater:updateAvailable', info)
mainWindow.webContents.send('updater:updateMessage', `发现新版本 v${info.version},正在下载...`)
}
// 可选:显示更新提示对话框
if (mainWindow && process.env.NODE_ENV !== 'development') {
dialog.showMessageBox(mainWindow, {
type: 'info',
title: '发现新版本',
message: `发现新版本 v${info.version}`,
detail: '新版本正在后台下载,下载完成后将提示您安装。',
buttons: ['确定']
})
}
})
// 没有新版本
autoUpdater.on('update-not-available', (info) => {
console.log('当前已是最新版本')
updateState.isChecking = false
updateState.updateAvailable = false
if (mainWindow) {
mainWindow.webContents.send('updater:updateNotAvailable', info)
mainWindow.webContents.send('updater:updateMessage', '当前已是最新版本')
}
})
// 下载进度
autoUpdater.on('download-progress', (progressObj) => {
updateState.isDownloading = true
updateState.downloadProgress = Math.floor(progressObj.percent)
const progressMessage = `下载进度: ${progressObj.percent}% (${progressObj.transferred}/${progressObj.total})`
console.log(progressMessage)
if (mainWindow) {
mainWindow.webContents.send('updater:downloadProgress', progressObj)
mainWindow.webContents.send('updater:updateMessage', progressMessage)
}
})
// 下载完成
autoUpdater.on('update-downloaded', (info) => {
console.log('更新下载完成,准备安装')
updateState.isDownloading = false
updateState.updateDownloaded = true
updateState.downloadProgress = 100
if (mainWindow) {
mainWindow.webContents.send('updater:updateDownloaded', info)
mainWindow.webContents.send('updater:updateMessage', '更新下载完成,准备安装')
}
// 提示用户安装更新
if (mainWindow && process.env.NODE_ENV !== 'development') {
dialog.showMessageBox(mainWindow, {
type: 'info',
title: '更新就绪',
message: `新版本 v${info.version} 已下载完成`,
detail: '应用将在关闭后自动安装更新。',
buttons: ['立即重启', '稍后重启']
}).then((result) => {
if (result.response === 0) {
autoUpdater.quitAndInstall()
}
})
}
})
// 更新错误
autoUpdater.on('error', (err) => {
console.error('更新错误:', err)
updateState.isChecking = false
updateState.isDownloading = false
updateState.lastError = err.message
if (mainWindow) {
mainWindow.webContents.send('updater:updateError', err.message)
mainWindow.webContents.send('updater:updateMessage', `更新错误: ${err.message}`)
}
})
console.log('自动更新监听器初始化完成')
}
module.exports = {
checkForUpdates,
quitAndInstall,
getUpdateStatus,
initializeAutoUpdater,
setMainWindow
}