watcher.service.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import * as fs from 'fs'
  2. import * as path from 'path'
  3. import { BrowserWindow } from 'electron'
  4. import { IpcChannels } from '@shared/ipc-channels'
  5. import { importWallpaperById } from './library.service'
  6. import { getWorkshopPath } from '../utils/paths'
  7. let activeWatcher: fs.FSWatcher | null = null
  8. let watcherWin: BrowserWindow | null = null
  9. export function startWatcher(win: BrowserWindow): void {
  10. watcherWin = win
  11. restartWatcher()
  12. }
  13. export function restartWatcher(): void {
  14. if (activeWatcher) {
  15. activeWatcher.close()
  16. activeWatcher = null
  17. }
  18. if (!watcherWin) return
  19. const watchPath = getWorkshopPath()
  20. if (!fs.existsSync(watchPath)) {
  21. console.warn(`[Watcher] Workshop path does not exist: ${watchPath}`)
  22. try {
  23. fs.mkdirSync(watchPath, { recursive: true })
  24. } catch {
  25. return
  26. }
  27. }
  28. console.log('[Watcher] Watching', watchPath)
  29. activeWatcher = fs.watch(watchPath, { persistent: false }, (event, filename) => {
  30. if (event === 'rename' && filename) {
  31. const fullPath = path.join(watchPath, filename)
  32. setTimeout(() => {
  33. if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
  34. console.log('[Watcher] New wallpaper detected:', filename)
  35. const meta = importWallpaperById(filename)
  36. if (meta && watcherWin) {
  37. watcherWin.webContents.send(IpcChannels.EVENT_WALLPAPER_IMPORTED, meta)
  38. }
  39. }
  40. }, 1000)
  41. }
  42. })
  43. }