electron-updater#autoUpdater TypeScript Examples

The following examples show how to use electron-updater#autoUpdater. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From angular-sqlite-app-starter with MIT License 6 votes vote down vote up
// Run Application
(async () => {
  // Wait for electron app to be ready.
  await app.whenReady();
  // Security - Set Content-Security-Policy based on whether or not we are in dev mode.
  setupContentSecurityPolicy(myCapacitorApp.getCustomURLScheme());
  // Initialize our app, build windows, and load content.
  await myCapacitorApp.init();
  // Check for updates if we are in a packaged app.
  autoUpdater.checkForUpdatesAndNotify();
})();
Example #2
Source File: UpdateHandler.ipc.ts    From Bridge with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Begins the process of downloading the latest update.
   */
  handler() {
    if (this.downloading) { return }
    this.downloading = true

    autoUpdater.on('download-progress', (updateProgress: UpdateProgress) => {
      emitIPCEvent('update-progress', updateProgress)
    })

    autoUpdater.on('update-downloaded', () => {
      emitIPCEvent('update-downloaded', undefined)
    })

    autoUpdater.downloadUpdate()
  }
Example #3
Source File: updater.ts    From SpaceEye with MIT License 6 votes vote down vote up
/**
 * Do a full auto update if enabled, one is available, and the app window is
 * closed.
 */
function tryUpdating() {
    if (isUpdateDownloaded && !isWindowVisible && AppConfigStore.autoUpdate) {
        log.info('Doing full-auto update in background')
        autoUpdater.quitAndInstall()
    } else {
        log.info(
            'Unable to do full-auto update. Is downloaded:',
            isUpdateDownloaded,
            'Is window visible:',
            isWindowVisible,
            'Is auto update enabled:',
            AppConfigStore.autoUpdate
        )
    }
}
Example #4
Source File: main.dev.ts    From ow-mod-manager with MIT License 6 votes vote down vote up
autoUpdater.signals.updateDownloaded(({ version }) => {
  log.info('CALLED update-available');

  const response = dialog.showMessageBoxSync({
    type: 'info',
    buttons: [updateText.dialogYes, updateText.dialogNo],
    title: updateText.dialogTitle,
    message: updateText.dialogMessage,
    detail: updateText.dialogDetail(version),
  });

  if (response === 0) autoUpdater.quitAndInstall();
});
Example #5
Source File: updates.ts    From awakened-poe-trade with MIT License 6 votes vote down vote up
// on('download-progress') https://github.com/electron-userland/electron-builder/issues/2521

export async function checkForUpdates () {
  autoUpdater.logger = logger
  autoUpdater.autoDownload = (
    !process.env.PORTABLE_EXECUTABLE_DIR && // https://www.electron.build/configuration/nsis.html#portable
    !config.get('disableUpdateDownload')
  )

  UpdateState.canCheck = false
  UpdateState.status = 'Checking for update...'
  rebuildTrayMenu()

  try {
    await autoUpdater.checkForUpdates()
  } catch {
    // handled by event
  }
}
Example #6
Source File: app-updater.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
private initIpcHandlers() {
    ipcMain.on(IPC_APP_CHECK_UPDATE, () => {
      this.checkForUpdates().catch((e) => console.error(e));
    });

    // Used this solution for Mac support
    // https://github.com/electron-userland/electron-builder/issues/1604#issuecomment-372091881
    ipcMain.on(IPC_APP_INSTALL_UPDATE, () => {
      app.removeAllListeners("window-all-closed");
      const browserWindows = BrowserWindow.getAllWindows();
      browserWindows.forEach(function (browserWindow) {
        browserWindow.removeAllListeners("close");
      });
      autoUpdater.quitAndInstall();
    });

    ipcMain.handle("set-release-channel", (evt, channel: WowUpReleaseChannelType) => {
      autoUpdater.allowPrerelease = channel === WowUpReleaseChannelType.Beta;
      log.info(`set-release-channel: allowPreRelease = ${autoUpdater.allowPrerelease.toString()}`);
    });
  }
Example #7
Source File: index.ts    From bluebubbles-server with Apache License 2.0 6 votes vote down vote up
constructor(window: BrowserWindow) {
        // This won't work in dev-mode because it checks Electron's Version
        this.currentVersion = app.getVersion();
        this.isOpen = false;
        this.window = window;

        // Correct current version if needed
        if (this.currentVersion.split(".").length > 3) {
            this.currentVersion = semver.coerce(this.currentVersion).format();
        }

        const autoUpdate = Server().repo.getConfig("auto_install_updates") as boolean;
        if (autoUpdate) {
            autoUpdater.autoDownload = true;
            autoUpdater.autoInstallOnAppQuit = true;
        } else {
            autoUpdater.autoDownload = false;
            autoUpdater.autoInstallOnAppQuit = false;
        }

        autoUpdater.on("update-downloaded", info => {
            Server().log("Installing update...");
            autoUpdater.quitAndInstall(false, true);
        });

        ipcMain.handle("install-update", async (_, __) => {
            Server().log("Downloading update...");
            await autoUpdater.downloadUpdate();
            Server().log("Finished downloading update...");
        });
    }
Example #8
Source File: index.ts    From react-sqlite-app-starter with MIT License 6 votes vote down vote up
// Run Application
(async () => {
  // Wait for electron app to be ready.
  await app.whenReady();
  // Security - Set Content-Security-Policy based on whether or not we are in dev mode.
  setupContentSecurityPolicy(myCapacitorApp.getCustomURLScheme());
  // Initialize our app, build windows, and load content.
  await myCapacitorApp.init();
  // Check for updates if we are in a packaged app.
  autoUpdater.checkForUpdatesAndNotify();
})();
Example #9
Source File: AutoUpdate.ts    From yana with MIT License 6 votes vote down vote up
async prepareDownloadUpdate() {
    autoUpdater.once('update-available', async () => {
      logger.log('Update is available. Initiate update.');

      if (this.shouldBackupBefore) {
        for (const ws of this.appData.workspaces) {
          const dest = path.join(
            this.appData.settings.autoBackupLocation,
            `backup_before_update__${ws.name.toLowerCase().replace(/\s/g, '-')}__${Date.now()}.zip`
          );
          logger.log(`Backing up ${ws.name} to ${dest}`);
          await AppDataExportService.exportTo(dest, ws, logger.log);
          logger.log('Finished backing up ', [ws.name]);
        }
      }

      logger.log('Starting update.');
      autoUpdater.logger = {
        info: msg => logger.log(JSON.stringify(msg)),
        warn: msg => logger.warn(JSON.stringify(msg)),
        error: msg => logger.error(JSON.stringify(msg)),
        debug: msg => logger.debug(JSON.stringify(msg)),
      };
      await autoUpdater.downloadUpdate();
      logger.log('Done with checkForUpdatesAndNotify().');
    });

    autoUpdater.once('update-not-available', async () => {
      logger.log('No update available');
    });

    autoUpdater.on('update-downloaded', () => {
      // Do nothing for now
      // autoUpdater.quitAndInstall();
    });
  }
Example #10
Source File: electron.ts    From shadowsocks-electron with GNU General Public License v3.0 6 votes vote down vote up
/* -------------- electron life cycle -------------- */

app.on("ready", async () => {
  let mainProfiler: any;

  electronApp.afterReady(app, (err, app) => { if (err) console.log(err); });
  electronApp.ready(app);
  isInspect && (mainProfiler = await startProfiler('main', 5222));
  ipcMainProcess = new IpcMainProcess(ipcMain);
  await setupAfterInstall(true);

  ipcMainWindow = new IpcMainWindow({
    width: 460,
    height: 540
  });

  ipcMainWindow.create().then((win: BrowserWindow) => {
    (global as any).win = win;
    if (isDev) {
      win.webContents.openDevTools({ mode: 'undocked' });
      ProcessManager.openWindow();
    }
    setMainWindow(win);
  });

  ipcMainWindow.createTray();

  !isDev && autoUpdater.checkForUpdatesAndNotify();
  isInspect && setTimeout(() => { mainProfiler?.stop(); }, 5e3);

  electronApp.registryHooksSync('beforeQuit', 'ipcMainWindowActions', () => {
    ipcMainWindow.beforeQuitting();
  });

});
Example #11
Source File: index.ts    From CrewLink with GNU General Public License v3.0 6 votes vote down vote up
function createOverlay() {
	const window = new BrowserWindow({
		width: 400,
		height: 300,
		webPreferences: {
			nodeIntegration: true,
			webSecurity: false,
		},
		...electronOverlayWindow.WINDOW_OPTS,
	});

	if (isDevelopment) {
		window.loadURL(
			`http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}?version=${autoUpdater.currentVersion.version}&view=overlay`
		);
	} else {
		window.loadURL(
			formatUrl({
				pathname: joinPath(__dirname, 'index.html'),
				protocol: 'file',
				query: {
					version: autoUpdater.currentVersion.version,
					view: 'overlay',
				},
				slashes: true,
			})
		);
	}
	window.setIgnoreMouseEvents(true);
	electronOverlayWindow.attachTo(window, 'Among Us');

	if (isDevelopment) {
		// Force devtools into detached mode otherwise they are unusable
		window.webContents.openDevTools({
			mode: 'detach',
		});
	}
	return window;
}
Example #12
Source File: updater.ts    From desktop with GNU Affero General Public License v3.0 6 votes vote down vote up
export function autoUpdate() {
    if (process.platform === "win32") {
        if (process.windowsStore) {
            return;
        }
    }

    if (process.platform === "linux") {
        if (typeof process.env.APP_IMAGE === "undefined") {
            return;
        }
    }

    autoUpdater.checkForUpdatesAndNotify();
}
Example #13
Source File: index.ts    From electron-playground with MIT License 6 votes vote down vote up
private async onUpdateAvailable(info: UpdateInfo) {
    this.log('有可用更新:', info)
    this.setStatus(UpdateStatus.Available)
    this.updateInfo = info
    if (!this.silent) {
      const { response } = await messageBox.info({
        message: '有可用更新',
        detail: this.updateInfoMessage,
        buttons: ['取消', '下载更新'],
      })
      if (response === 1) {
        autoUpdater.downloadUpdate()
      }
    } else {
      autoUpdater.downloadUpdate()
    }
  }
Example #14
Source File: index.ts    From bluebubbles-server with Apache License 2.0 6 votes vote down vote up
async checkForUpdate({ showNoUpdateDialog = false, showUpdateDialog = true } = {}): Promise<boolean> {
        const res = await autoUpdater.checkForUpdates();
        this.hasUpdate = !!res?.updateInfo && semver.lt(this.currentVersion, res.updateInfo.version);
        this.updateInfo = res;

        if (this.hasUpdate) {
            Server().emitMessage("server-update", res.updateInfo.version);
            Server().emitToUI("update-available", res.updateInfo.version);

            if (showUpdateDialog) {
                const notification = {
                    title: "BlueBubbles Update Available!",
                    body: `BlueBubbles macOS Server v${res.updateInfo.version} is now available to be installed!`
                };
                new Notification(notification).show();
            }
        }

        if (!this.hasUpdate && showNoUpdateDialog) {
            const dialogOpts = {
                type: "info",
                title: "BlueBubbles Update",
                message: "You have the latest version installed!",
                detail: `You are running the latest version of BlueBubbles! v${this.currentVersion}`
            };

            dialog.showMessageBox(this.window, dialogOpts);
        }

        return this.hasUpdate;
    }
Example #15
Source File: main.dev.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 6 votes vote down vote up
autoUpdater.on('update-available', async () => {
  const response = await dialog.showMessageBox(mainWindow!, {
    type: 'info',
    title: 'Found Updates',
    message: 'Found updates, do you want update now?',
    buttons: ['Sure', 'Later'],
  });

  if (response.response === 0) {
    logger.log('Downloading Update');
    autoUpdater.downloadUpdate();
    await dialog.showMessageBox(mainWindow!, {
      type: 'info',
      title: 'Update Downloading',
      message:
        'Update is being downloaded, you will be notified when it is ready to install',
      buttons: [],
    });
  }
});
Example #16
Source File: UpdateHandler.ipc.ts    From Bridge with GNU General Public License v3.0 6 votes vote down vote up
private registerUpdaterListeners() {
    autoUpdater.on('error', (err: Error) => {
      updateAvailable = null
      emitIPCEvent('update-error', err)
    })

    autoUpdater.on('update-available', (info: UpdateInfo) => {
      updateAvailable = true
      emitIPCEvent('update-available', info)
    })

    autoUpdater.on('update-not-available', (info: UpdateInfo) => {
      updateAvailable = false
      emitIPCEvent('update-available', null)
    })
  }
Example #17
Source File: update.ts    From dbm with Apache License 2.0 5 votes vote down vote up
function handlerUpdater(mainWindow: BrowserWindow) {
  console.log(platform(), arch());
  console.log(process.env.NODE_ENV);
  let uploadUrl = 'https://downloads.edurt.io/dbm/releases/' + platform() + '/' + arch() + '/';
  if (process.env.NODE_ENV === 'development') {
    uploadUrl = 'http://localhost:7777/release/';
  }
  console.log(uploadUrl);
  autoUpdater.setFeedURL(uploadUrl)
  autoUpdater.autoDownload = false

  let cancellationToken = new CancellationToken();;

  autoUpdater.on('error', (err) => {
    if (err.message.includes('sha512 checksum mismatch')) {
      handlerMessage(mainWindow, UpdateEnum.error, 'sha512 checksum mismatch')
    }
  })

  ipcMain.on('checking-for-update', (event, arg) => {
    console.log('checking-for-update')
    handlerMessage(mainWindow, UpdateEnum.checking)
  })

  autoUpdater.on('update-available', (info) => {
    console.log('update-available')
    handlerMessage(mainWindow, UpdateEnum.hasversion, info)
  })

  autoUpdater.on('update-not-available', (event, arg) => {
    console.log('update-not-available')
    handlerMessage(mainWindow, UpdateEnum.noversion, arg)
  })

  autoUpdater.on('download-progress', (progressObj) => {
    console.log('download-progress')
    handlerMessage(mainWindow, UpdateEnum.downloading, progressObj)
  })

  autoUpdater.on('update-downloaded', () => {
    console.log('update-downloaded')
    handlerMessage(mainWindow, UpdateEnum.completed)
  })

  ipcMain.on('check-update', () => {
    console.log('update-not-available')
    autoUpdater.checkForUpdates().catch(err => {
      handlerMessage(mainWindow, UpdateEnum.failed, err)
    })
  })

  ipcMain.on('confirm-update', () => {
    console.log('quit install')
    try {
      autoUpdater.quitAndInstall(true, true);
    } catch (e) {
      console.log('Error', 'Failed to install updates', e);
      handlerMessage(mainWindow, UpdateEnum.failed, e);
    }
  })

  ipcMain.on('confirm-downloadUpdate', () => {
    autoUpdater.downloadUpdate(cancellationToken).catch(err => {
      handlerMessage(mainWindow, UpdateEnum.failed, err)
    })
  })

  ipcMain.on('confirm-downloadCancel', () => {
    cancellationToken.cancel();
    cancellationToken = new CancellationToken();
    handlerMessage(mainWindow, UpdateEnum.cancel, 'Cancel');
  })
}
Example #18
Source File: main.ts    From Creators.TF-Community-Launcher with MIT License 5 votes vote down vote up
ipcMain.on("restart_app", () => {
    autoUpdater.quitAndInstall();
    log.info("Restarting program to install an update");
});
Example #19
Source File: updater.ts    From kaiheila-universal with MIT License 5 votes vote down vote up
public initialize(): void {
    autoUpdater.checkForUpdatesAndNotify()
  }
Example #20
Source File: main.ts    From blockcore-hub with MIT License 5 votes vote down vote up
autoUpdater.on('update-downloaded', (info) => {
    contents.send('update-downloaded', info);
});
Example #21
Source File: AutoUpdate.ts    From yana with MIT License 5 votes vote down vote up
async runAutoUpdateIfSettingsSet() {
    if (this.shouldAutoUpdate) {
      await this.prepareDownloadUpdate();
      await autoUpdater.checkForUpdates();
    }
  }
Example #22
Source File: main.ts    From rocketredis with MIT License 5 votes vote down vote up
app.on('ready', () => {
  createWindow()
  autoUpdater.checkForUpdatesAndNotify()
  createMenu()
})
Example #23
Source File: main.ts    From Creators.TF-Community-Launcher with MIT License 5 votes vote down vote up
autoUpdater.on("error", (err) => {
    Main.mainWindow.webContents.send("update_error");
    log.error("Error in auto-updater: " + err);
});
Example #24
Source File: AutoUpdate.ts    From yana with MIT License 5 votes vote down vote up
constructor() {
    autoUpdater.autoInstallOnAppQuit = true;
    autoUpdater.autoDownload = false;
  }
Example #25
Source File: index.tsx    From mysterium-vpn-desktop with MIT License 5 votes vote down vote up
autoUpdater.logger = log
Example #26
Source File: main.ts    From Creators.TF-Community-Launcher with MIT License 5 votes vote down vote up
autoUpdater.on("update-downloaded", () => {
    Main.mainWindow.webContents.send("update_downloaded");
    log.info("Update downloaded");
});
Example #27
Source File: index.ts    From CrewLink with GNU General Public License v3.0 5 votes vote down vote up
function createMainWindow() {
	const mainWindowState = windowStateKeeper({});

	const window = new BrowserWindow({
		width: 250,
		height: 350,
		maxWidth: 250,
		minWidth: 250,
		maxHeight: 350,
		minHeight: 350,
		x: mainWindowState.x,
		y: mainWindowState.y,

		resizable: false,
		frame: false,
		fullscreenable: false,
		maximizable: false,
		transparent: true,
		webPreferences: {
			nodeIntegration: true,
			webSecurity: false,
		},
	});

	mainWindowState.manage(window);
	if (isDevelopment) {
		// Force devtools into detached mode otherwise they are unusable
		window.webContents.openDevTools({
			mode: 'detach',
		});
	}

	let crewlinkVersion: string;
	if (isDevelopment) {
		crewlinkVersion = '0.0.0';
		window.loadURL(
			`http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}?version=DEV&view=app`
		);
	} else {
		crewlinkVersion = autoUpdater.currentVersion.version;
		window.loadURL(
			formatUrl({
				pathname: joinPath(__dirname, 'index.html'),
				protocol: 'file',
				query: {
					version: autoUpdater.currentVersion.version,
					view: 'app',
				},
				slashes: true,
			})
		);
	}
	window.webContents.userAgent = `CrewLink/${crewlinkVersion} (${process.platform})`;

	window.on('closed', () => {
		mainWindow = null;
		if (overlayWindow != null) {
			try {
				overlayWindow.close();
			} catch (_) {
				console.error(_);
			}
			overlayWindow = null;
		}
	});

	window.webContents.on('devtools-opened', () => {
		window.focus();
		setImmediate(() => {
			window.focus();
		});
	});

	return window;
}
Example #28
Source File: main.ts    From Creators.TF-Community-Launcher with MIT License 5 votes vote down vote up
ipcMain.on("download_update", () => {
    autoUpdater.downloadUpdate();
    Main.mainWindow.webContents.send("update_downloading");
    log.info("Downloading update");
});
Example #29
Source File: AppUpdater.ts    From deskreen with GNU Affero General Public License v3.0 5 votes vote down vote up
constructor() {
    log.transports.file.level = 'info';
    autoUpdater.logger = log;
    autoUpdater.checkForUpdatesAndNotify();
  }