update.service.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import { execFile } from 'child_process'
  2. import { promisify } from 'util'
  3. import * as fs from 'fs'
  4. import * as os from 'os'
  5. import * as path from 'path'
  6. import { app, type BrowserWindow } from 'electron'
  7. import { IpcChannels } from '@shared/ipc-channels'
  8. import { APP_RELEASE_REPO, LWE_RELEASE_REPO } from '@shared/constants'
  9. import { compareVersions, isNewerVersion, parseVersion } from '@shared/updates'
  10. import type {
  11. AppInstallKind,
  12. AppUpdateProgress,
  13. AvailableUpdate,
  14. EngineInstallKind,
  15. ReleaseChoice,
  16. UpdateChecks,
  17. UpdateStatus,
  18. UpdateTarget
  19. } from '@shared/types'
  20. import { isFlatpak } from '../utils/flatpak'
  21. import { download, fetchLatestRelease, fetchReleaseByTag, fetchReleases, isVersionTag, verifyAsset, type GithubRelease } from '../utils/github'
  22. import { owningPackage, packageVersion } from '../utils/packages'
  23. import { isCommandAvailable, runningAppImage } from '../utils/platform'
  24. import { relaunchApp } from '../utils/relaunch'
  25. import { getDismissedUpdates, getUpdateChecks, setDismissedUpdates, setUpdateChecks } from './config.service'
  26. import { getLweStatus } from './lwe.service'
  27. const execFileAsync = promisify(execFile)
  28. const FIRST_CHECK_DELAY_MS = 15_000
  29. const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000
  30. const TICK_MS = 30 * 60 * 1000
  31. let win: BrowserWindow | null = null
  32. let appInstall: AppInstallKind | undefined
  33. let appRelease: GithubRelease | null = null
  34. let engineRelease: GithubRelease | null = null
  35. let checking = false
  36. let snoozed: Partial<Record<UpdateTarget, string>> = {}
  37. let checkedAt: number | null = null
  38. let checked: UpdateChecks = { app: false, engine: false }
  39. let lastError: string | null = null
  40. let appProgress: AppUpdateProgress | null = null
  41. let installingVersion: string | undefined
  42. let engine: { install: EngineInstallKind | null; managedBy?: string; version: string | null; update: AvailableUpdate | null } | null = null
  43. function detectAppInstall(): AppInstallKind {
  44. if (isFlatpak()) return 'flatpak'
  45. if (runningAppImage()) return 'appimage'
  46. if (!app.isPackaged) return 'source'
  47. const pkg = owningPackage(process.execPath)
  48. if (pkg?.manager === 'dpkg') return 'deb'
  49. return pkg?.manager ?? 'unknown'
  50. }
  51. function releaseInfo(release: GithubRelease, current: string | null): AvailableUpdate {
  52. return {
  53. version: release.tag_name,
  54. current,
  55. notes: release.body ?? '',
  56. url: release.html_url,
  57. publishedAt: release.published_at
  58. }
  59. }
  60. function appUpdate(): AvailableUpdate | null {
  61. if (!appRelease || !isNewerVersion(appRelease.tag_name, app.getVersion())) return null
  62. return releaseInfo(appRelease, app.getVersion())
  63. }
  64. /** /nix/store/<hash>-linux-wallpaperengine-kde-0.8.0/bin/... */
  65. function nixVersion(real: string): string | undefined {
  66. return /^\/nix\/store\/[^/]*?-(\d+(?:\.\d+)+)\//.exec(real)?.[1]
  67. }
  68. /** Unversioned engines are outdated when the binary is older than the release */
  69. function evaluateEngine(): void {
  70. const status = getLweStatus()
  71. if (!status.installed || !status.path) {
  72. engine = { install: null, version: null, update: null }
  73. return
  74. }
  75. if (isFlatpak()) {
  76. engine = { install: 'bundled', version: null, update: null }
  77. return
  78. }
  79. let install: EngineInstallKind = 'build'
  80. let version: string | null = status.version ?? null
  81. let managedBy: string | undefined
  82. let real = status.path
  83. try { real = fs.realpathSync(status.path) } catch { }
  84. if (status.version) {
  85. install = 'prebuilt'
  86. } else if (status.managedBy) {
  87. install = 'package'
  88. managedBy = status.managedBy
  89. const pkg = owningPackage(real)
  90. const pkgVersion = real.startsWith('/nix/store/') ? nixVersion(real) : pkg && packageVersion(pkg)
  91. version = pkgVersion && parseVersion(pkgVersion) ? pkgVersion : null
  92. }
  93. let update: AvailableUpdate | null = null
  94. if (engineRelease) {
  95. if (version) {
  96. if (isNewerVersion(engineRelease.tag_name, version)) update = releaseInfo(engineRelease, version)
  97. } else {
  98. let builtAt = 0
  99. try { builtAt = fs.statSync(real).mtimeMs } catch { /* treat as old */ }
  100. if (builtAt < Date.parse(engineRelease.published_at)) update = releaseInfo(engineRelease, null)
  101. }
  102. }
  103. engine = { install, managedBy, version, update }
  104. }
  105. export function getUpdateStatus(): UpdateStatus {
  106. appInstall ??= detectAppInstall()
  107. // needed before any check ran (setup screen, checks off)
  108. if (!engine) evaluateEngine()
  109. const { install, managedBy, version, update } = engine!
  110. return {
  111. checks: getUpdateChecks(),
  112. checking,
  113. checkedAt,
  114. checked,
  115. error: lastError,
  116. appVersion: app.getVersion(),
  117. appInstall,
  118. app: appUpdate(),
  119. appProgress,
  120. engineInstall: install,
  121. ...(managedBy ? { engineManagedBy: managedBy } : {}),
  122. engineVersion: version,
  123. engine: update,
  124. dismissed: getDismissedUpdates(),
  125. snoozed
  126. }
  127. }
  128. function push(): void {
  129. if (win && !win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_UPDATE_STATUS, getUpdateStatus())
  130. }
  131. /** manual: look at everything whatever the automatic checks are set to */
  132. export async function checkForUpdates(manual = false): Promise<UpdateStatus> {
  133. const checks: UpdateChecks | null = manual ? { app: true, engine: true } : getUpdateChecks()
  134. if (checking || !checks) return getUpdateStatus()
  135. checking = true
  136. lastError = null
  137. push()
  138. const errors: string[] = []
  139. const done: UpdateChecks = { app: false, engine: false }
  140. try {
  141. if (checks.app) {
  142. try {
  143. appRelease = await fetchLatestRelease(APP_RELEASE_REPO)
  144. done.app = true
  145. } catch (err) {
  146. errors.push((err as Error).message)
  147. }
  148. } else {
  149. appRelease = null
  150. }
  151. if (checks.engine && !isFlatpak()) {
  152. try {
  153. engineRelease = await fetchLatestRelease(LWE_RELEASE_REPO)
  154. done.engine = true
  155. } catch (err) {
  156. errors.push((err as Error).message)
  157. }
  158. } else {
  159. engineRelease = null
  160. }
  161. evaluateEngine()
  162. checkedAt = Date.now()
  163. checked = done
  164. } finally {
  165. checking = false
  166. lastError = errors.length > 0 ? errors.join(' ') : null
  167. push()
  168. }
  169. return getUpdateStatus()
  170. }
  171. /** After an engine install, build or removal, without asking GitHub again */
  172. export function refreshEngineUpdate(): void {
  173. evaluateEngine()
  174. push()
  175. }
  176. export function setUpdateChecksAndCheck(checks: UpdateChecks): UpdateStatus {
  177. setUpdateChecks(checks)
  178. void checkForUpdates()
  179. return getUpdateStatus()
  180. }
  181. /** Brings dismissed notices back */
  182. export function checkNow(): Promise<UpdateStatus> {
  183. snoozed = {}
  184. setDismissedUpdates({})
  185. return checkForUpdates(true)
  186. }
  187. /** forever: kept in the config, otherwise hidden until the app starts again */
  188. export function dismissUpdate(target: UpdateTarget, version: string, forever: boolean): UpdateStatus {
  189. if (forever) setDismissedUpdates({ ...getDismissedUpdates(), [target]: version })
  190. else snoozed = { ...snoozed, [target]: version }
  191. push()
  192. return getUpdateStatus()
  193. }
  194. function setAppProgress(progress: AppUpdateProgress | null): void {
  195. appProgress = progress && installingVersion ? { ...progress, version: installingVersion } : progress
  196. push()
  197. }
  198. async function installAppImage(release: GithubRelease, target: string): Promise<void> {
  199. const asset = release.assets.find((a) => a.name.endsWith('.AppImage'))
  200. if (!asset) throw new Error(`Release ${release.tag_name} has no AppImage.`)
  201. // next to the old file so the rename stays on one filesystem
  202. const staged = `${target}.download`
  203. try {
  204. await download(asset.browser_download_url, staged, asset.size, (fraction) => {
  205. setAppProgress({ stage: 'downloading', percentage: Math.round(fraction * 90) })
  206. })
  207. setAppProgress({ stage: 'installing', percentage: 92 })
  208. await verifyAsset(staged, asset)
  209. fs.chmodSync(staged, 0o755)
  210. fs.renameSync(staged, target)
  211. } finally {
  212. fs.rmSync(staged, { force: true })
  213. }
  214. }
  215. async function installDeb(release: GithubRelease): Promise<void> {
  216. const asset = release.assets.find((a) => a.name.endsWith('_amd64.deb')) ?? release.assets.find((a) => a.name.endsWith('.deb'))
  217. if (!asset) throw new Error(`Release ${release.tag_name} has no .deb package.`)
  218. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'we-manager-update-'))
  219. const file = path.join(dir, asset.name)
  220. try {
  221. await download(asset.browser_download_url, file, asset.size, (fraction) => {
  222. setAppProgress({ stage: 'downloading', percentage: Math.round(fraction * 80) })
  223. })
  224. await verifyAsset(file, asset)
  225. setAppProgress({ stage: 'installing', percentage: 85 })
  226. // dpkg alone wouldn't resolve new dependencies
  227. // apt refuses to go back to an older version unless told to, but only for a deliberate downgrade
  228. const downgrade = (compareVersions(release.tag_name, app.getVersion()) ?? 0) < 0
  229. const command = isCommandAvailable('apt-get')
  230. ? ['apt-get', 'install', '-y', ...(downgrade ? ['--allow-downgrades'] : []), file]
  231. : ['dpkg', '-i', file]
  232. const elevate = isCommandAvailable('pkexec') ? 'pkexec' : 'sudo'
  233. try {
  234. await execFileAsync(elevate, command, { timeout: 600_000, maxBuffer: 10 * 1024 * 1024 })
  235. } catch (err) {
  236. const code = (err as { code?: number }).code
  237. // pkexec: 126 = the password dialog was dismissed, 127 = not authorized
  238. if (code === 126 || code === 127) throw new Error('The installation was not authorized.', { cause: err })
  239. throw err
  240. }
  241. } finally {
  242. fs.rmSync(dir, { recursive: true, force: true })
  243. }
  244. }
  245. function hasAppAsset(release: GithubRelease): boolean {
  246. appInstall ??= detectAppInstall()
  247. const suffix = appInstall === 'deb' ? '.deb' : '.AppImage'
  248. return release.assets.some((a) => a.name.endsWith(suffix))
  249. }
  250. /** usable: the engine's check for an asset that fits this system, the app's follows from how it was installed */
  251. export async function listVersions(target: UpdateTarget, usable?: (release: GithubRelease) => boolean): Promise<ReleaseChoice[]> {
  252. const releases = await fetchReleases(target === 'app' ? APP_RELEASE_REPO : LWE_RELEASE_REPO)
  253. const fits = target === 'app' ? hasAppAsset : usable
  254. return releases
  255. .filter((r) => !fits || fits(r))
  256. .map((r) => ({ tag: r.tag_name, publishedAt: r.published_at, prerelease: r.prerelease === true }))
  257. .sort((a, b) => Date.parse(b.publishedAt) - Date.parse(a.publishedAt))
  258. }
  259. /** Without a tag: the pending update. With one: that release, newer or older than the running version */
  260. export async function installAppUpdate(tag?: string): Promise<UpdateStatus> {
  261. if (appProgress?.stage === 'downloading' || appProgress?.stage === 'installing') return getUpdateStatus()
  262. if (tag !== undefined && (typeof tag !== 'string' || !isVersionTag(tag))) {
  263. installingVersion = undefined
  264. setAppProgress({ stage: 'error', percentage: 0, message: `${String(tag)} is not a version of WE Manager.` })
  265. return getUpdateStatus()
  266. }
  267. if (!tag && !appUpdate()) return getUpdateStatus()
  268. appInstall ??= detectAppInstall()
  269. installingVersion = tag ?? appRelease?.tag_name
  270. setAppProgress({ stage: 'downloading', percentage: 0 })
  271. try {
  272. const release = tag ? await fetchReleaseByTag(APP_RELEASE_REPO, tag) : appRelease
  273. if (!release) throw new Error(`${APP_RELEASE_REPO} has no ${tag} release.`)
  274. const appImage = runningAppImage()
  275. if (appInstall === 'appimage' && appImage) {
  276. await installAppImage(release, appImage)
  277. } else if (appInstall === 'deb') {
  278. await installDeb(release)
  279. } else {
  280. throw new Error(`A ${appInstall} install updates outside WE Manager.`)
  281. }
  282. setAppProgress({ stage: 'ready', percentage: 100 })
  283. } catch (err) {
  284. setAppProgress({ stage: 'error', percentage: 0, message: (err as Error).message })
  285. }
  286. return getUpdateStatus()
  287. }
  288. export function restartApp(): void {
  289. relaunchApp()
  290. }
  291. function checkDue(): boolean {
  292. const checks = getUpdateChecks()
  293. return !!checks && (checks.app || checks.engine) && (checkedAt === null || Date.now() - checkedAt >= CHECK_INTERVAL_MS)
  294. }
  295. export function initUpdates(window: BrowserWindow): void {
  296. win = window
  297. setTimeout(() => {
  298. if (checkDue()) void checkForUpdates()
  299. }, FIRST_CHECK_DELAY_MS)
  300. setInterval(() => {
  301. if (checkDue()) void checkForUpdates()
  302. }, TICK_MS)
  303. }