backup.handlers.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { ipcMain, BrowserWindow } from 'electron'
  2. import * as fs from 'fs'
  3. import { IpcChannels } from '@shared/ipc-channels'
  4. import * as backup from '../services/backup.service'
  5. import * as library from '../services/library.service'
  6. import * as steam from '../services/steam.service'
  7. import { getAutoUnsubscribeAfterBackup } from '../services/config.service'
  8. async function backupOne(id: string, win: BrowserWindow): Promise<{ ok: boolean; unsubscribed: boolean }> {
  9. const wallpaper = library.getWallpaper(id)
  10. if (!wallpaper?.localPath) throw new Error(`Wallpaper ${id} has no local files to back up`)
  11. await backup.backupWallpaper(id, wallpaper.localPath, win)
  12. library.updateWallpaper(id, { backedUp: true })
  13. let unsubscribed = false
  14. if (getAutoUnsubscribeAfterBackup()) {
  15. await steam.unsubscribeFromItem(BigInt(id))
  16. try {
  17. fs.rmSync(wallpaper.localPath, { recursive: true, force: true })
  18. } catch {
  19. /* ignore */
  20. }
  21. library.updateWallpaper(id, {
  22. source: 'backup',
  23. localPath: backup.getBackupDir(id),
  24. subscribed: false
  25. })
  26. unsubscribed = true
  27. }
  28. return { ok: true, unsubscribed }
  29. }
  30. export function registerBackupHandlers(win: BrowserWindow): void {
  31. ipcMain.handle(IpcChannels.BACKUP_ITEM, async (_e, itemId: string) => {
  32. return backupOne(itemId, win)
  33. })
  34. ipcMain.handle(IpcChannels.BACKUP_SELECTION, async (_e, itemIds: string[]) => {
  35. let backedUp = 0
  36. let failed = 0
  37. let unsubscribed = 0
  38. for (const id of itemIds) {
  39. try {
  40. const result = await backupOne(id, win)
  41. backedUp++
  42. if (result.unsubscribed) unsubscribed++
  43. } catch {
  44. failed++
  45. }
  46. }
  47. return { backedUp, failed, unsubscribed }
  48. })
  49. ipcMain.handle(IpcChannels.BACKUP_SCAN, () => {
  50. return backup.scanBackupFolder()
  51. })
  52. }