rule-actions.service.ts 4.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import type { Profile, ScheduleAction, ScreenAction, ScreenTarget } from '@shared/types'
  2. import { getWallpaper, updateWallpaper } from './library.service'
  3. import { getPlaylist } from './playlist.service'
  4. import { getSplitScreens } from './config.service'
  5. import { expandScreen, getDisplayTargets, isShownOn, showSplitScreen, showWallpaper, SplitUnavailableError, stopDisplay } from './display.service'
  6. import { startPlaylist, stopPlaylist } from './playlist-player.service'
  7. import { getProfile } from './profile.service'
  8. import { t } from '../i18n'
  9. const runningWallpapers = new Map<string, number>()
  10. /** Wallpapers a rule is in the middle of starting, so they are not optimized or deleted under it */
  11. export function runningWallpaperIds(): string[] {
  12. return [...runningWallpapers.keys()]
  13. }
  14. async function whileStarting<T>(ids: string[], work: () => Promise<T>): Promise<T> {
  15. for (const id of ids) runningWallpapers.set(id, (runningWallpapers.get(id) ?? 0) + 1)
  16. try {
  17. return await work()
  18. } finally {
  19. for (const id of ids) {
  20. const left = (runningWallpapers.get(id) ?? 1) - 1
  21. if (left > 0) runningWallpapers.set(id, left)
  22. else runningWallpapers.delete(id)
  23. }
  24. }
  25. }
  26. export async function runScreenAction(action: ScreenAction, screen: ScreenTarget): Promise<void> {
  27. if (action.type === 'wallpaper') {
  28. const wallpaper = getWallpaper(action.wallpaperId)
  29. if (!wallpaper) throw new Error(t('rules.wallpaperGone'))
  30. for (const s of expandScreen(screen)) stopPlaylist(s)
  31. await whileStarting([wallpaper.id], () => showWallpaper(wallpaper, screen, { dependencyPrompt: 'once' }))
  32. if (isShownOn(wallpaper.id, screen)) {
  33. updateWallpaper(wallpaper.id, { appliedCount: (wallpaper.appliedCount ?? 0) + 1, lastAppliedAt: Date.now() })
  34. }
  35. } else if (action.type === 'split') {
  36. const slotIds = (getSplitScreens()[screen]?.slots ?? []).map((slot) => slot.wallpaperId)
  37. try {
  38. // nobody is there to see a launch fail on a drive that is not mounted, so those slots are left out
  39. await whileStarting(slotIds, () => showSplitScreen(screen, () => { stopPlaylist(screen) }, 'once', true))
  40. } catch (err) {
  41. if (!(err instanceof SplitUnavailableError)) throw err
  42. console.error(`[Rules] the split on ${screen} can't be shown, going back to its first wallpaper:`, err)
  43. await runScreenAction({ type: 'wallpaper', wallpaperId: action.wallpaperId }, screen)
  44. }
  45. } else if (action.type === 'playlist') {
  46. if (!getPlaylist(action.playlistId)) throw new Error(t('rules.playlistGone'))
  47. startPlaylist(action.playlistId, screen)
  48. } else {
  49. stopPlaylist(screen)
  50. await stopDisplay(screen)
  51. }
  52. }
  53. /**
  54. * What a profile does on the screens there are now: a '*' entry goes first so an entry for one screen can follow it.
  55. * A profile from the other display mode or with a monitor that is gone is not lost: entries for screens that are
  56. * not there are skipped, and in shared mode (one '*' target) the first of them stands in for all screens
  57. */
  58. function profileEntries(profile: Profile, targets = getDisplayTargets()): [ScreenTarget, ScreenAction][] {
  59. const entries = Object.entries(profile.screens)
  60. const known = entries.filter(([screen]) => screen === '*' || targets.includes(screen))
  61. if (known.length === 0 && targets.includes('*') && entries.length > 0) known.push(['*', entries[0][1]])
  62. return known.sort(([a], [b]) => Number(b === '*') - Number(a === '*'))
  63. }
  64. /** The screens an action touches: a profile names its own, anything else the screen of the rule */
  65. export function actionScreens(action: ScheduleAction, screen: ScreenTarget, targets = getDisplayTargets()): ScreenTarget[] {
  66. if (action.type !== 'profile') return expandScreen(screen, targets)
  67. const profile = getProfile(action.profileId)
  68. return profile ? profileEntries(profile, targets).flatMap(([s]) => expandScreen(s, targets)) : []
  69. }
  70. export async function applyProfile(profileId: string): Promise<void> {
  71. const profile = getProfile(profileId)
  72. if (!profile) throw new Error(t('profiles.gone'))
  73. const failed: string[] = []
  74. for (const [screen, action] of profileEntries(profile)) {
  75. await runScreenAction(action, screen).catch((err: unknown) => {
  76. console.error(`[Profile] "${profile.name}" failed on ${screen}:`, err)
  77. failed.push(screen)
  78. })
  79. }
  80. if (failed.length > 0) throw new Error(t('profiles.failedOn', { name: profile.name, screens: failed.join(', ') }))
  81. }
  82. export async function runAction(action: ScheduleAction, screen: ScreenTarget): Promise<void> {
  83. if (action.type === 'profile') await applyProfile(action.profileId)
  84. else await runScreenAction(action, screen)
  85. }