main.js 2.8 KB

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