add dashboard

This commit is contained in:
2026-11-12 14:03:53 +01:00
parent 53f1896d05
commit 68bb7ff810
14 changed files with 2037 additions and 280 deletions

152
server.js
View File

@@ -9,6 +9,15 @@
//
// Security: listens on 127.0.0.1 only, and every request must carry a local
// Host header and (for writes) a local Origin, so other web pages can't drive it.
// The process started by the launcher/console only supervises; the real server
// runs as its worker so it can be restarted after an update (lib/supervisor.js).
if (!process.env.DASHBOARD_WORKER) {
require('./lib/supervisor').supervise(__filename)
return
}
// supervisor gone (window closed, killed) → stop too, never left behind
process.on('disconnect', () => process.exit(0))
const express = require('express')
const fs = require('fs')
const path = require('path')
@@ -23,6 +32,8 @@ const settings = require('./lib/settings')
const activity = require('./lib/activity')
const itch = require('./lib/itch')
const create = require('./lib/create')
const archive = require('./lib/archive')
const scheduler = require('./lib/scheduler')
// The projects folder comes from the settings (lib/settings.js) and can be
// changed at runtime; '' until it is set up. DASHBOARD_PORT allows a test instance.
@@ -323,11 +334,13 @@ app.get('/api/projects', handle(async (req, res) => {
roots: s.roots,
activeRoot: s.activeRoot,
activeRoots: s.activeRoots,
remindDays: s.backup.remindDays ?? 7,
setupNeeded: !ROOT_DIR,
projects: list,
totals: { ...storage.totals(list.map((p) => ({ root: ROOTS.find((r) => r.id === p.root)?.path, folder: p.folder }))), noBackup: list.filter((p) => p.git.level === 'red').length },
scan: storage.state,
cleanupAvailable: storage.available(),
cleanAvailable: storage.cleanupAvailable(),
activityPending: activity.pending(),
})
}))
@@ -355,6 +368,35 @@ app.post('/api/settings', (req, res) => {
res.status(400).json({ error: String(e.message ?? e) })
}
})
// Update detection: newest change of the server code (server.js, lib\*.js) and
// of the page (public\*). The server code is only read at start, so a newer
// file means "restart needed"; the page only needs a reload.
function newestMtime(files) {
let t = 0
for (const f of files) { try { t = Math.max(t, fs.statSync(f).mtimeMs) } catch {} }
return t
}
const filesIn = (dir, re) => { try { return fs.readdirSync(dir).filter((n) => re.test(n)).map((n) => path.join(dir, n)) } catch { return [] } }
const codeFiles = () => [__filename, ...filesIn(path.join(__dirname, 'lib'), /\.js$/i)]
const uiFiles = () => filesIn(path.join(__dirname, 'public'), /\.(js|html|css)$/i)
const CODE_STAMP = newestMtime(codeFiles())
const STARTED_AT = new Date().toISOString()
app.get('/api/version', (req, res) => {
res.json({ startedAt: STARTED_AT, pid: process.pid, stale: newestMtime(codeFiles()) > CODE_STAMP, uiStamp: newestMtime(uiFiles()) })
})
// Restart the server (lib/supervisor.js starts it again).
app.post('/api/restart', (req, res) => {
if (storage.busy() || backup.busy() || create.busy() || archive.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' })
res.json({ ok: true })
setTimeout(() => process.exit(require('./lib/supervisor').RESTART_CODE), 200)
})
// Opens the dashboard's data folder (settings, scan.json, backup.json) in Explorer.
app.post('/api/datadir/open', (req, res) => {
fs.mkdirSync(settings.DATA_DIR, { recursive: true })
openDetached('explorer.exe', [settings.DATA_DIR])
res.json({ ok: true })
})
// Which registered projects folders are shown (dropdown next to the logo). body: { ids: [...] } or { id }
app.post('/api/roots/active', (req, res) => {
if (storage.busy() || backup.busy() || create.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' })
@@ -388,6 +430,61 @@ app.post('/api/projects/new', handle(async (req, res) => {
res.status(400).json({ error: String(e.message ?? e) })
}
}))
// ZIP a build folder or the whole project into <project>\releases (lib/archive.js).
// body: { what: relative folder | 'project', deleteAfter } - deleteAfter only for
// folders the cleanup lists as "Release" (finished builds), via cleanup.ps1.
app.post('/api/projects/:name/archive', handle(async (req, res) => {
const key = req.params.name
const ref = resolveProject(key) && projectRef(key)
if (!ref) return res.status(404).json({ error: 'unknown project' })
const what = String(req.body?.what ?? '')
if (!what) return res.status(400).json({ error: 'Was soll archiviert werden?' })
let r
try { r = await archive.zip(ref.path, what) } catch (e) { return res.status(400).json({ error: String(e.message ?? e) }) }
let deleted = false
if (req.body?.deleteAfter && what !== 'project') {
const rel = `${ref.folder}${path.sep}${path.normalize(what)}`
const cand = storage.get(ref.root.path, ref.folder)?.candidates?.find((c) => c.Path.toLowerCase() === rel.toLowerCase() && c.Tier === 'Release' && !c.Skip)
if (cand && !storage.busy()) {
try { await storage.clean(ref.root.path, ref.folder, [cand.Path]); deleted = true } catch {}
}
}
res.json({ ok: true, ...r, deleted, archives: archive.listArchives(ref.path) })
}))
// Opens <project>\releases in Explorer.
app.post('/api/projects/:name/archive/open', (req, res) => {
const projectPath = resolveProject(req.params.name)
if (!projectPath) return res.status(404).json({ error: 'unknown project' })
const dir = path.join(projectPath, archive.ARCHIVE_DIR)
fs.mkdirSync(dir, { recursive: true })
openDetached('explorer.exe', [dir])
res.json({ ok: true })
})
// Rename a project and/or move it into another projects folder (lib/create.js).
// body: { name, root (folder id, default: its own) }
app.post('/api/projects/:name/move', handle(async (req, res) => {
if (storage.busy() || backup.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' })
const key = req.params.name
const ref = resolveProject(key) && projectRef(key)
if (!ref) return res.status(404).json({ error: 'unknown project' })
const root = settings.get().roots.find((r) => r.id === (req.body?.root || ref.root.id))
if (!root || !fs.existsSync(root.path)) return res.status(400).json({ error: 'Projektordner nicht gefunden.' })
let r
try {
r = await create.move({ from: ref.path, rootPath: root.path, name: req.body?.name })
} catch (e) {
return res.status(400).json({ error: String(e.message ?? e) })
}
const newRoot = path.resolve(root.path)
storage.rename(ref.root.path, ref.folder, newRoot, r.name)
thumbCache.delete(key)
quickCache.delete(key)
icons.forget(ref.path)
projectList()
const shown = ROOTS.some((x) => x.id === root.id)
if (shown) activity.warm([r.path])
res.json({ ok: true, name: r.name, root: root.id, rootName: root.name, shown, key: shown ? keyOf(newRoot, r.name) : r.name })
}))
// Adds projects folders from the dropdown. body: { paths: [...], activate }
app.post('/api/roots/add', (req, res) => {
if (storage.busy() || backup.busy() || create.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' })
@@ -486,6 +583,8 @@ app.get('/api/projects/:name/details', handle(async (req, res) => {
program: programInfo(projectPath),
path: projectPath,
sshKey: sshKey(),
releaseDirs: archive.findReleaseDirs(projectPath),
archives: archive.listArchives(projectPath),
})
}))
@@ -565,7 +664,6 @@ app.post('/api/projects/:name/git-init', handle(async (req, res) => {
// Background disk scan: one project ({name}) or all (empty body).
app.post('/api/scan', (req, res) => {
if (!storage.available()) return res.status(400).json({ error: 'cleanup.ps1 nicht gefunden' })
const name = req.body?.name
const refs = name ? [name].filter((n) => resolveProject(n)).map(projectRef) : projectList().filter((p) => p.folder !== '_Tools')
if (!refs.length) return res.status(404).json({ error: 'unknown project' })
@@ -575,6 +673,55 @@ app.post('/api/scan', (req, res) => {
app.get('/api/scan', (req, res) => res.json(storage.state))
// Activity heatmap: per day which projects changed (files by last-change date,
// plus git commits). -> { days: { 'YYYY-MM-DD': { files, commits, projects: [{ name, files, commits }] } }, pending }
async function projectActivity(p) {
const dir = path.join(p.root.path, p.folder)
return { files: activity.filesPerDay(dir), commits: await activity.gitDays(dir) }
}
app.get('/api/activity', handle(async (req, res) => {
const list = projectList()
const acts = await pool(list, 8, projectActivity)
const days = {}
let pending = 0
list.forEach((p, i) => {
const a = acts[i]
if (a.files === undefined) pending++
for (const [d, n] of Object.entries(a.files ?? {})) {
const e = (days[d] ??= { files: 0, commits: 0, projects: {} })
e.files += n
;(e.projects[p.key] ??= { name: p.key, files: 0, commits: 0 }).files += n
}
for (const [d, n] of Object.entries(a.commits)) {
const e = (days[d] ??= { files: 0, commits: 0, projects: {} })
e.commits += n
;(e.projects[p.key] ??= { name: p.key, files: 0, commits: 0 }).commits += n
}
})
for (const e of Object.values(days)) e.projects = Object.values(e.projects).sort((a, b) => (b.files + b.commits * 5) - (a.files + a.commits * 5))
res.json({ days, pending, today: activity.dayOf(Date.now()) })
}))
app.get('/api/projects/:name/activity', handle(async (req, res) => {
const ref = resolveProject(req.params.name) && projectRef(req.params.name)
if (!ref) return res.status(404).json({ error: 'unknown project' })
const a = await projectActivity(ref)
res.json({ files: a.files ?? null, commits: a.commits, today: activity.dayOf(Date.now()) })
}))
// Storage page: every shown project with its scan result (size, split, cleanup candidates).
app.get('/api/storage', (req, res) => {
const list = projectList().map((p) => {
const d = storage.get(p.root.path, p.folder)
return {
name: p.key, folder: p.folder, root: p.root.id, rootName: p.root.name,
sizeMB: d?.sizeMB ?? null, at: d?.at ?? null, deletable: d?.deletable ?? null,
tree: d?.tree ?? null,
candidates: (d?.candidates ?? []).filter((c) => c.MB >= 1).map((c) => ({ path: c.Path, tier: c.Tier, mb: c.MB, skip: !!c.Skip })),
}
})
res.json({ projects: list, scan: storage.state, cleanupAvailable: storage.cleanupAvailable() })
})
// Deletes selected cleanup candidates of one project (cleanup.ps1 re-checks them).
app.post('/api/projects/:name/clean', handle(async (req, res) => {
const ref = resolveProject(req.params.name) && projectRef(req.params.name)
@@ -589,7 +736,7 @@ app.post('/api/projects/:name/clean', handle(async (req, res) => {
}))
// NAS backup (lib/backup.js): check → copy, never deletes in the backup.
app.get('/api/backup', (req, res) => res.json(backup.getState()))
app.get('/api/backup', (req, res) => res.json({ ...backup.getState(), schedule: scheduler.status() }))
// body: { target } = check everything · { target, project, autoCopy: true } = "Sichern" of one project
app.post('/api/backup/check', handle(async (req, res) => {
const project = req.body?.project ?? null
@@ -611,6 +758,7 @@ app.post('/api/backup/cancel', (req, res) => {
})
applySettings()
scheduler.start()
app.listen(PORT, HOST, () => {
console.log(`Project dashboard running at http://${HOST}:${PORT}`)