main.js 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. const fs = require('fs')
  2. const path = require('path')
  3. const yaml = require('js-yaml')
  4. const { app, BrowserWindow, Menu, dialog } = require('electron')
  5. const { autoUpdater } = require('electron-updater')
  6. const updateHandle = (win) => {
  7. if (app.isPackaged) {
  8. const fileContents = fs.readFileSync('resources/app-update.yml', 'utf-8')
  9. const data = yaml.load(fileContents)
  10. if (data.url) {
  11. autoUpdater.autoDownload = false
  12. autoUpdater.autoInstallOnAppQuit = false
  13. autoUpdater.setFeedURL({
  14. provider: data.provider,
  15. url: data.url
  16. })
  17. // 检查更新出错
  18. autoUpdater.on('error', (err) => {
  19. dialog.showMessageBox({
  20. type: 'error',
  21. title: '错误',
  22. noLink: true,
  23. message: '更新发生错误',
  24. detail: err.message
  25. })
  26. })
  27. // 检测到有版本更新
  28. autoUpdater.on('update-available', (e) => {
  29. dialog.showMessageBox({
  30. type: 'info',
  31. title: '提示',
  32. noLink: true,
  33. message: e.version,
  34. detail: '发现新版本,是否现在下载?',
  35. buttons: ['取消', '下载']
  36. }).then((res) => {
  37. if (res.response === 1) {
  38. autoUpdater.downloadUpdate()
  39. }
  40. })
  41. })
  42. // 更新下载进度事件
  43. autoUpdater.on('download-progress', (progress) => {
  44. // https://www.electronjs.org/zh/docs/latest/tutorial/progress-bar
  45. win.setProgressBar(progress.percent / 100)
  46. })
  47. // 下载完成,询问用户是否更新
  48. autoUpdater.on('update-downloaded', (e) => {
  49. dialog.showMessageBox({
  50. type: 'info',
  51. title: '提示',
  52. noLink: true,
  53. message: e.version,
  54. detail: '已下载新版本,是否关闭应用更新?',
  55. buttons: ['取消', '安装']
  56. }).then((res) => {
  57. if (res.response === 1) {
  58. autoUpdater.quitAndInstall()
  59. } else {
  60. win.setProgressBar(-1)
  61. }
  62. })
  63. })
  64. autoUpdater.checkForUpdates()
  65. }
  66. }
  67. }
  68. const createWindow = () => {
  69. Menu.setApplicationMenu(null)
  70. const win = new BrowserWindow({
  71. center: true,
  72. minWidth: 1280,
  73. minHeight: 800,
  74. icon: path.resolve(__dirname, 'dist/favicon.ico')
  75. })
  76. win.maximize()
  77. win.loadFile(path.resolve(__dirname, 'dist/index.html'))
  78. win.on('ready-to-show', () => updateHandle(win))
  79. }
  80. app.whenReady().then(() => {
  81. createWindow()
  82. })