auto-updater-win.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import * as squirrelUpdate from '@electron/internal/browser/api/auto-updater/squirrel-update-win';
  2. import { app } from 'electron/main';
  3. import { EventEmitter } from 'events';
  4. class AutoUpdater extends EventEmitter implements Electron.AutoUpdater {
  5. updateAvailable: boolean = false;
  6. updateURL: string | null = null;
  7. quitAndInstall () {
  8. if (!this.updateAvailable) {
  9. return this.emitError(new Error('No update available, can\'t quit and install'));
  10. }
  11. squirrelUpdate.processStart();
  12. app.quit();
  13. }
  14. getFeedURL () {
  15. return this.updateURL ?? '';
  16. }
  17. setFeedURL (options: { url: string } | string) {
  18. let updateURL: string;
  19. if (typeof options === 'object') {
  20. if (typeof options.url === 'string') {
  21. updateURL = options.url;
  22. } else {
  23. throw new TypeError('Expected options object to contain a \'url\' string property in setFeedUrl call');
  24. }
  25. } else if (typeof options === 'string') {
  26. updateURL = options;
  27. } else {
  28. throw new TypeError('Expected an options object with a \'url\' property to be provided');
  29. }
  30. this.updateURL = updateURL;
  31. }
  32. async checkForUpdates () {
  33. const url = this.updateURL;
  34. if (!url) {
  35. return this.emitError(new Error('Update URL is not set'));
  36. }
  37. if (!squirrelUpdate.supported()) {
  38. return this.emitError(new Error('Can not find Squirrel'));
  39. }
  40. this.emit('checking-for-update');
  41. try {
  42. const update = await squirrelUpdate.checkForUpdate(url);
  43. if (update == null) {
  44. return this.emit('update-not-available');
  45. }
  46. this.updateAvailable = true;
  47. this.emit('update-available');
  48. await squirrelUpdate.update(url);
  49. const { releaseNotes, version } = update;
  50. // Date is not available on Windows, so fake it.
  51. const date = new Date();
  52. this.emit('update-downloaded', {}, releaseNotes, version, date, this.updateURL, () => {
  53. this.quitAndInstall();
  54. });
  55. } catch (error) {
  56. this.emitError(error as Error);
  57. }
  58. }
  59. // Private: Emit both error object and message, this is to keep compatibility
  60. // with Old APIs.
  61. emitError (error: Error) {
  62. this.emit('error', error, error.message);
  63. }
  64. }
  65. export default new AutoUpdater();