updater.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const { autoUpdater } = require("electron-updater");
  2. const ProgressBar = require('electron-progressbar');
  3. const { dialog } = require('electron');
  4. class Updater {
  5. run(mainWindow) {
  6. let progressBar = null;
  7. autoUpdater.autoDownload = false;
  8. autoUpdater.on('checking-for-update', () => {
  9. console.log('Checking for update...');
  10. });
  11. autoUpdater.on('update-available', (info) => {
  12. console.log('Update available:', info.version);
  13. dialog.showMessageBox(mainWindow, {
  14. type: 'question',
  15. buttons: ['Yes', 'No'],
  16. defaultId: 0,
  17. cancelId: 1,
  18. title: 'Update Available',
  19. message: `Version ${info.version} is available. Do you want to download it now?`
  20. }).then(result => {
  21. if (result.response === 0) {
  22. if (progressBar) {
  23. progressBar.close();
  24. progressBar = null;
  25. }
  26. progressBar = new ProgressBar({
  27. indeterminate: false,
  28. text: "Downloading update...",
  29. detail: "Please wait...",
  30. browserWindow: {
  31. parent: mainWindow,
  32. modal: true,
  33. closable: false,
  34. minimizable: false,
  35. maximizable: false,
  36. width: 400,
  37. height: 120
  38. }
  39. });
  40. autoUpdater.downloadUpdate();
  41. }
  42. });
  43. });
  44. autoUpdater.on('update-not-available', () => {
  45. console.log('No update available.');
  46. });
  47. autoUpdater.on("download-progress", (progress) => {
  48. console.log(`Downloaded ${Math.round(progress.percent)}%`);
  49. if (progressBar && !progressBar.isCompleted()) {
  50. progressBar.value = Math.floor(progress.percent);
  51. progressBar.detail = `Downloaded ${Math.round(progress.percent)}% (${(progress.transferred / 1024 / 1024).toFixed(2)} MB of ${(progress.total / 1024 / 1024).toFixed(2)} MB)`;
  52. }
  53. });
  54. autoUpdater.on("update-downloaded", (info) => {
  55. console.log("Update downloaded:", info.version);
  56. if (progressBar && !progressBar.isCompleted()) {
  57. progressBar.setCompleted();
  58. progressBar = null;
  59. }
  60. dialog.showMessageBox(mainWindow, {
  61. type: "info",
  62. buttons: ["Restart Now", "Later"],
  63. title: "Update Ready",
  64. message: "A new version has been downloaded. Restart the application to apply the updates?"
  65. }).then((result) => {
  66. if (result.response === 0) {
  67. autoUpdater.quitAndInstall();
  68. }
  69. });
  70. });
  71. autoUpdater.on("error", (err) => {
  72. console.error("Update error:", err);
  73. if (progressBar && !progressBar.isCompleted()) {
  74. progressBar.close();
  75. progressBar = null;
  76. }
  77. });
  78. autoUpdater.checkForUpdates();
  79. }
  80. }
  81. module.exports = Updater;