798 lines
37 KiB
JavaScript
798 lines
37 KiB
JavaScript
// Local project dashboard - scans every folder in ROOT_DIR, reads an
|
||
// optional .dashboard.json per project for status/priority/notes/tasks, and
|
||
// serves a small Kanban UI to view/edit them. No accounts, no database -
|
||
// state lives as a JSON file inside each project folder.
|
||
//
|
||
// Also shows git/backup status, detected tech, disk usage (via
|
||
// _Tools\Cleanup\cleanup.ps1), generator usage and app icons, and can start
|
||
// predefined actions in a visible console window.
|
||
//
|
||
// 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')
|
||
const { pool, openConsole, openDetached, run } = require('./lib/proc')
|
||
const { gitInfo, setRemote, initRepo, sshKey } = require('./lib/git')
|
||
const tech = require('./lib/tech')
|
||
const { toolInfo } = require('./lib/tools')
|
||
const icons = require('./lib/icons')
|
||
const storage = require('./lib/storage')
|
||
const backup = require('./lib/backup')
|
||
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 itchpack = require('./lib/itchpack')
|
||
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.
|
||
let ROOT_DIR = ''
|
||
const STATUS_FILE = '.dashboard.json'
|
||
const HOST = '127.0.0.1'
|
||
const PORT = Number(process.env.DASHBOARD_PORT) || 4848
|
||
const ALLOWED_HOSTS = new Set([`localhost:${PORT}`, `127.0.0.1:${PORT}`])
|
||
|
||
const STATUSES = ['idea', 'active', 'paused', 'done', 'archived']
|
||
const PRIORITIES = ['low', 'medium', 'high']
|
||
|
||
// Thumbnail discovery: every project folder is scanned (shallow, breadth-first)
|
||
// for a representative image. A project can override the pick by setting
|
||
// "thumbnail": "relative/path.png" in its .dashboard.json. A real app icon
|
||
// (lib/icons.js) wins over a generic image.
|
||
const IMAGE_EXT = { '.png': 3, '.jpg': 3, '.jpeg': 3, '.webp': 3, '.gif': 2, '.bmp': 2, '.svg': 2, '.ico': 1 }
|
||
const SKIP_DIRS = new Set([
|
||
'node_modules', '.git', '.svn', 'dist', 'build', 'out', 'bin', 'obj', 'target',
|
||
'venv', '.venv', 'env', '__pycache__', '.gradle', '.idea', '.vscode', 'Library',
|
||
'Temp', 'Logs', 'coverage', 'vendor', '.next', '.cache',
|
||
])
|
||
const PREFERRED_NAMES = ['icon', 'logo', 'thumb', 'thumbnail', 'preview', 'screenshot', 'cover', 'banner', 'splash', 'title', 'header', 'app_icon', 'appicon']
|
||
const MAX_DEPTH = 3
|
||
const MAX_ENTRIES = 3000
|
||
const THUMB_TTL_MS = 5 * 60 * 1000
|
||
const thumbCache = new Map() // project name -> { file: string|null, at: number }
|
||
|
||
function scoreImage(fileName, depth) {
|
||
const lower = fileName.toLowerCase()
|
||
const ext = path.extname(lower)
|
||
const base = path.basename(lower, ext)
|
||
let score = IMAGE_EXT[ext] ?? 0
|
||
if (PREFERRED_NAMES.includes(base)) score += 20
|
||
else if (PREFERRED_NAMES.some((n) => base.includes(n))) score += 12
|
||
score += Math.max(0, 6 - depth * 2) // shallower files win
|
||
return score
|
||
}
|
||
|
||
function sanitizeTasks(tasks) {
|
||
if (!Array.isArray(tasks)) return []
|
||
return tasks.slice(0, 200).map((t) => ({
|
||
id: String(t?.id ?? Date.now() + Math.random().toString(36).slice(2)),
|
||
text: String(t?.text ?? '').slice(0, 500),
|
||
done: !!t?.done,
|
||
})).filter((t) => t.text.length > 0)
|
||
}
|
||
|
||
function readStatusFile(projectPath) {
|
||
const file = path.join(projectPath, STATUS_FILE)
|
||
try {
|
||
const raw = fs.readFileSync(file, 'utf-8')
|
||
const data = JSON.parse(raw)
|
||
return {
|
||
status: STATUSES.includes(data.status) ? data.status : 'idea',
|
||
priority: PRIORITIES.includes(data.priority) ? data.priority : 'medium',
|
||
notes: typeof data.notes === 'string' ? data.notes : '',
|
||
tags: Array.isArray(data.tags) ? data.tags.map(String).slice(0, 10) : [],
|
||
tasks: sanitizeTasks(data.tasks),
|
||
thumbnail: typeof data.thumbnail === 'string' ? data.thumbnail.slice(0, 300) : '',
|
||
start: typeof data.start === 'string' ? data.start.slice(0, 300) : '',
|
||
program: typeof data.program === 'string' ? data.program.slice(0, 300) : '',
|
||
itch: typeof data.itch === 'string' ? data.itch.slice(0, 300) : '',
|
||
updatedAt: data.updatedAt ?? null,
|
||
}
|
||
} catch {
|
||
return { status: 'idea', priority: 'medium', notes: '', tags: [], tasks: [], thumbnail: '', start: '', program: '', itch: '', updatedAt: null }
|
||
}
|
||
}
|
||
|
||
// Breadth-first walk of the project folder, returning the best-scoring image
|
||
// path (absolute) or null. Bounded by depth and total entries so a huge folder
|
||
// can't stall the request.
|
||
function scanForImage(projectPath) {
|
||
let queue = [{ dir: projectPath, depth: 0 }]
|
||
let seen = 0
|
||
let best = null
|
||
let bestScore = -1
|
||
while (queue.length) {
|
||
const { dir, depth } = queue.shift()
|
||
let entries
|
||
try {
|
||
entries = fs.readdirSync(dir, { withFileTypes: true })
|
||
} catch {
|
||
continue
|
||
}
|
||
for (const e of entries) {
|
||
if (++seen > MAX_ENTRIES) return best
|
||
if (e.isDirectory()) {
|
||
if (depth >= MAX_DEPTH || e.name.startsWith('.') || SKIP_DIRS.has(e.name)) continue
|
||
queue.push({ dir: path.join(dir, e.name), depth: depth + 1 })
|
||
continue
|
||
}
|
||
if (!e.isFile()) continue
|
||
const ext = path.extname(e.name).toLowerCase()
|
||
if (!(ext in IMAGE_EXT)) continue
|
||
const score = scoreImage(e.name, depth)
|
||
if (score > bestScore) {
|
||
bestScore = score
|
||
best = path.join(dir, e.name)
|
||
}
|
||
}
|
||
}
|
||
return best
|
||
}
|
||
|
||
function findThumbnail(name, projectPath) {
|
||
const cached = thumbCache.get(name)
|
||
if (cached && Date.now() - cached.at < THUMB_TTL_MS) return cached.file
|
||
|
||
let file = null
|
||
const override = readStatusFile(projectPath).thumbnail
|
||
if (override) {
|
||
const candidate = path.resolve(projectPath, override)
|
||
if (candidate.startsWith(projectPath + path.sep) && fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
|
||
file = candidate
|
||
}
|
||
}
|
||
if (!file) file = icons.findIcon(projectPath)
|
||
if (!file) file = scanForImage(projectPath)
|
||
|
||
thumbCache.set(name, { file, at: Date.now() })
|
||
return file
|
||
}
|
||
|
||
// Several projects folders can be shown at once (ROOTS). A project is named in
|
||
// the API by its key: the folder name, or "Folder (Projects folder)" when the
|
||
// same folder name exists in more than one shown projects folder.
|
||
let ROOTS = [] // [{ id, name, path }] shown, path resolved
|
||
let projMap = new Map() // key -> { key, folder, root }
|
||
|
||
// Folders that are never projects (drive roots of a friend's PC may contain these)
|
||
const NOT_PROJECTS = new Set(['project-dashboard', '$recycle.bin', 'system volume information', 'recovery', 'config.msi'])
|
||
|
||
function projectList() {
|
||
const raw = []
|
||
for (const root of ROOTS) {
|
||
let entries
|
||
try { entries = fs.readdirSync(root.path, { withFileTypes: true }) } catch { continue }
|
||
for (const e of entries) {
|
||
if (e.isDirectory() && !e.name.startsWith('.') && !NOT_PROJECTS.has(e.name.toLowerCase())) raw.push({ folder: e.name, root })
|
||
}
|
||
}
|
||
const count = new Map()
|
||
for (const p of raw) count.set(p.folder.toLowerCase(), (count.get(p.folder.toLowerCase()) ?? 0) + 1)
|
||
const used = new Set()
|
||
const list = raw.map((p) => {
|
||
let key = count.get(p.folder.toLowerCase()) > 1 ? `${p.folder} (${p.root.name})` : p.folder
|
||
while (used.has(key.toLowerCase())) key += ` [${p.root.id}]`
|
||
used.add(key.toLowerCase())
|
||
return { key, folder: p.folder, root: p.root }
|
||
})
|
||
projMap = new Map(list.map((p) => [p.key, p]))
|
||
return list
|
||
}
|
||
|
||
function projectNames() { return projectList().map((p) => p.key) }
|
||
|
||
// key -> { key, folder, root, path } or null
|
||
function projectRef(key) {
|
||
if (typeof key !== 'string' || !key) return null
|
||
const p = projMap.get(key) ?? (projectList(), projMap.get(key))
|
||
return p ? { ...p, path: path.join(p.root.path, p.folder) } : null
|
||
}
|
||
// key of a project folder (for lib/backup.js)
|
||
function keyOf(rootPath, folder) {
|
||
for (const p of projMap.values()) if (p.folder === folder && p.root.path.toLowerCase() === rootPath.toLowerCase()) return p.key
|
||
return folder
|
||
}
|
||
|
||
// Resolves a project key to its directory, or null if it isn't an existing
|
||
// direct child of a shown projects folder (guards the write/open endpoints
|
||
// against path traversal).
|
||
function resolveProject(key) {
|
||
const p = projectRef(key)
|
||
if (!p) return null
|
||
if (!fs.existsSync(p.path) || !fs.statSync(p.path).isDirectory() || path.dirname(p.path) !== p.root.path) return null
|
||
return p.path
|
||
}
|
||
|
||
// Applies the current settings: projects folders, backup target, caches.
|
||
function applySettings() {
|
||
const s = settings.get()
|
||
ROOTS = settings.configured()
|
||
? settings.activeRootList(s).map((r) => ({ ...r, path: path.resolve(r.path) })).filter((r) => fs.existsSync(r.path))
|
||
: []
|
||
ROOT_DIR = ROOTS[0]?.path ?? ''
|
||
projectList()
|
||
storage.init(ROOTS.map((r) => r.path), s.roots.map((r) => r.path))
|
||
backup.init(ROOTS.map((r) => r.path), keyOf)
|
||
thumbCache.clear()
|
||
quickCache.clear()
|
||
icons.clear()
|
||
activity.clear()
|
||
activity.warm([...projMap.values()].map((p) => path.join(p.root.path, p.folder)))
|
||
}
|
||
|
||
function storageSummary(p) {
|
||
const s = storage.get(p.root.path, p.folder)
|
||
if (!s) return null
|
||
return { at: s.at, sizeMB: s.sizeMB, deletable: s.deletable }
|
||
}
|
||
|
||
// target = backup target id whose "last backup" the cards show (default: the first)
|
||
async function describeProject(p, target) {
|
||
const projectPath = path.join(p.root.path, p.folder)
|
||
const stat = fs.statSync(projectPath)
|
||
const meta = readStatusFile(projectPath)
|
||
const found = tech.detect(projectPath)
|
||
const tools = toolInfo(projectPath)
|
||
const git = await gitInfo(projectPath)
|
||
return {
|
||
name: p.key,
|
||
folder: p.folder,
|
||
root: p.root.id,
|
||
rootName: p.root.name,
|
||
mtime: stat.mtime.toISOString(),
|
||
lastCommit: git.lastCommit,
|
||
git,
|
||
tech: tech.summary(found),
|
||
tools,
|
||
hasIcon: !!icons.findIcon(projectPath),
|
||
quickStart: quickStartFor(p.key, projectPath),
|
||
lastChange: activity.lastChange(projectPath),
|
||
lastBackup: backup.lastFor(p.root.path, p.folder, target),
|
||
storage: storageSummary(p),
|
||
...meta,
|
||
published: itch.forProject(p.folder, meta.itch),
|
||
}
|
||
}
|
||
|
||
async function listProjects(target) {
|
||
await itch.ensure()
|
||
const list = await pool(projectList(), 8, (p) => describeProject(p, target))
|
||
return list.sort((a, b) => new Date(b.mtime) - new Date(a.mtime))
|
||
}
|
||
|
||
// tech.actions matches programs against the folder name; the key names the console windows
|
||
function actionsFor(key, projectPath) {
|
||
const found = tech.detect(projectPath)
|
||
return tech.actions(path.basename(projectPath), projectPath, found, readStatusFile(projectPath), toolInfo(projectPath))
|
||
}
|
||
|
||
// The ▶ button on cards: the program chosen in "Aktionen", else own start command, else the main program (exe/html),
|
||
// else a start script of the project ("Soundclick starten.bat", run.bat, ...),
|
||
// else the first "Starten" action (Unity, npm run dev, Python, ...).
|
||
// Finding programs walks the project folder, so the pick is cached a while.
|
||
const QUICK_TTL_MS = 3 * 60 * 1000
|
||
const quickCache = new Map() // name -> { value, at }
|
||
function quickStartFor(name, projectPath) {
|
||
const c = quickCache.get(name)
|
||
if (c && Date.now() - c.at < QUICK_TTL_MS) return c.value
|
||
let value = null
|
||
try {
|
||
const list = actionsFor(name, projectPath)
|
||
const startScript = (a) => a.group === 'Starten' && a.id.startsWith('bat:') && /(start|run|launch|spiel|play|öffne|open)/i.test(a.label)
|
||
const pick = list.find((a) => a.id === 'program') ?? list.find((a) => a.id === 'custom') ?? list.find((a) => a.group === 'Programm')
|
||
?? list.find(startScript) ?? list.find((a) => a.group === 'Starten')
|
||
if (pick) value = { id: pick.id, label: pick.label, detail: pick.detail ?? '', kind: pick.kind === 'console' ? 'cmd' : 'exe' }
|
||
} catch {}
|
||
quickCache.set(name, { value, at: Date.now() })
|
||
return value
|
||
}
|
||
|
||
// Wraps async handlers so a thrown error becomes a 500 instead of a crash.
|
||
const handle = (fn) => async (req, res) => {
|
||
try { await fn(req, res) } catch (e) { if (!res.headersSent) res.status(500).json({ error: String(e.message ?? e) }) }
|
||
}
|
||
|
||
const app = express()
|
||
|
||
// Blocks other web pages (CSRF) and DNS rebinding: Host must be local, and
|
||
// writes must come from this dashboard's own origin.
|
||
app.use((req, res, next) => {
|
||
if (!ALLOWED_HOSTS.has(req.headers.host)) return res.status(403).send('forbidden host')
|
||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||
const origin = req.headers.origin
|
||
if (!origin || !ALLOWED_HOSTS.has(origin.replace(/^https?:\/\//, ''))) return res.status(403).json({ error: 'forbidden origin' })
|
||
}
|
||
next()
|
||
})
|
||
app.use(express.json())
|
||
app.use(express.static(path.join(__dirname, 'public')))
|
||
|
||
// Lucide icon sprite (ISC license), used as <svg><use href="/icons.svg#name"/></svg>
|
||
const ICON_SPRITE = path.join(__dirname, 'node_modules', 'lucide-static', 'sprite.svg')
|
||
app.get('/icons.svg', (req, res) => {
|
||
res.setHeader('Cache-Control', 'public, max-age=86400')
|
||
res.sendFile(ICON_SPRITE, (err) => { if (err && !res.headersSent) res.status(404).end() })
|
||
})
|
||
|
||
app.get('/api/projects', handle(async (req, res) => {
|
||
const list = await listProjects(String(req.query.target ?? '') || null)
|
||
const s = settings.get()
|
||
res.json({
|
||
root: ROOT_DIR,
|
||
rootPaths: ROOTS.map((r) => r.path),
|
||
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(),
|
||
})
|
||
}))
|
||
|
||
// itch.io profile: games found + which project claims them (lib/itch.js)
|
||
async function itchStatus() {
|
||
const s = itch.state
|
||
const claimed = projectList().map((p) => itch.forProject(p.folder, readStatusFile(path.join(p.root.path, p.folder)).itch)?.url).filter(Boolean)
|
||
return { profile: s.profile, at: s.at, error: s.error, games: s.games, unmatched: itch.unmatched(claimed) }
|
||
}
|
||
app.get('/api/itch', handle(async (req, res) => { await itch.ensure(); res.json(await itchStatus()) }))
|
||
app.post('/api/itch/refresh', handle(async (req, res) => { await itch.refresh(); res.json(await itchStatus()) }))
|
||
|
||
// Settings: projects folder, backup target, excludes (lib/settings.js)
|
||
app.get('/api/settings', (req, res) => {
|
||
res.json({ ...settings.get(), configured: !!ROOT_DIR, dataDir: settings.DATA_DIR })
|
||
})
|
||
app.post('/api/settings', (req, res) => {
|
||
if (storage.busy() || backup.busy() || create.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' })
|
||
try {
|
||
settings.save(req.body ?? {})
|
||
applySettings()
|
||
res.json({ ...settings.get(), configured: !!ROOT_DIR, dataDir: settings.DATA_DIR })
|
||
} catch (e) {
|
||
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.' })
|
||
try {
|
||
settings.setActive(Array.isArray(req.body?.ids) ? req.body.ids : String(req.body?.id ?? ''))
|
||
applySettings()
|
||
res.json({ ...settings.get(), configured: !!ROOT_DIR, dataDir: settings.DATA_DIR })
|
||
} catch (e) {
|
||
res.status(400).json({ error: String(e.message ?? e) })
|
||
}
|
||
})
|
||
// New project (empty) or clone of a project of the active folder (lib/create.js).
|
||
// body: { name, root (folder id, default: active), from (project name), withGit, skipBuild }
|
||
app.post('/api/projects/new', handle(async (req, res) => {
|
||
const s = settings.get()
|
||
const b = req.body ?? {}
|
||
const root = s.roots.find((r) => r.id === (b.root || s.activeRoot))
|
||
if (!root || !fs.existsSync(root.path)) return res.status(400).json({ error: 'Projektordner nicht gefunden.' })
|
||
let from = null
|
||
if (b.from) {
|
||
from = resolveProject(String(b.from))
|
||
if (!from) return res.status(404).json({ error: 'Vorlage nicht gefunden.' })
|
||
}
|
||
try {
|
||
const r = await create.create({ rootPath: path.resolve(root.path), name: b.name, from, withGit: !!b.withGit, skipBuild: b.skipBuild !== false })
|
||
const shown = ROOTS.some((x) => x.id === root.id)
|
||
if (shown) { activity.warm([r.path]); projectList() }
|
||
// key: the name the UI knows it by (may get "(Ordner)" when the name exists in another shown folder)
|
||
res.json({ ...r, root: root.id, shown, key: shown ? keyOf(path.resolve(root.path), r.name) : r.name })
|
||
} catch (e) {
|
||
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 })
|
||
})
|
||
// itch.io package (<project>\docs\itchio, lib/itchpack.js): read for the copy
|
||
// view, its images, open in Explorer, and Claude Code with the itchiocreater skill.
|
||
app.get('/api/projects/:name/itch', (req, res) => {
|
||
const projectPath = resolveProject(req.params.name)
|
||
if (!projectPath) return res.status(404).json({ error: 'unknown project' })
|
||
res.json(itchpack.read(projectPath))
|
||
})
|
||
app.get('/api/projects/:name/itch/file', (req, res) => {
|
||
const projectPath = resolveProject(req.params.name)
|
||
const f = projectPath && itchpack.file(projectPath, String(req.query.f ?? ''))
|
||
if (!f || !/\.(png|jpe?g|gif|webp)$/i.test(f)) return res.status(404).end()
|
||
res.setHeader('Cache-Control', 'no-cache')
|
||
res.sendFile(f, (err) => { if (err && !res.headersSent) res.status(404).end() })
|
||
})
|
||
app.post('/api/projects/:name/itch/open', (req, res) => {
|
||
const projectPath = resolveProject(req.params.name)
|
||
if (!projectPath) return res.status(404).json({ error: 'unknown project' })
|
||
const d = itchpack.dir(projectPath)
|
||
if (!d) return res.status(404).json({ error: 'Kein itch.io-Ordner im Projekt' })
|
||
const f = req.body?.f ? itchpack.file(projectPath, String(req.body.f)) : null
|
||
// explorer wants "/select,<path>" as one argument
|
||
openDetached('explorer.exe', f ? [`/select,${f}`] : [d])
|
||
res.json({ ok: true })
|
||
})
|
||
app.post('/api/projects/:name/itch/generate', handle(async (req, res) => {
|
||
const projectPath = resolveProject(req.params.name)
|
||
if (!projectPath) return res.status(404).json({ error: 'unknown project' })
|
||
try { res.json(await itchpack.launch(projectPath, req.params.name)) } catch (e) { res.status(400).json({ error: String(e.message ?? e) }) }
|
||
}))
|
||
// 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.' })
|
||
try {
|
||
const before = settings.get().activeRoots.join('|')
|
||
const { settings: s, added } = settings.addRoots(req.body?.paths, !!req.body?.activate)
|
||
if (s.activeRoots.join('|') !== before) applySettings()
|
||
res.json({ ...s, added, configured: !!ROOT_DIR, dataDir: settings.DATA_DIR })
|
||
} catch (e) {
|
||
res.status(400).json({ error: String(e.message ?? e) })
|
||
}
|
||
})
|
||
// Subfolders of a folder, for adding several projects folders at once
|
||
app.get('/api/subfolders', (req, res) => {
|
||
try { res.json(settings.subfolders(String(req.query.path ?? ''))) } catch (e) { res.status(400).json({ error: String(e.message ?? e) }) }
|
||
})
|
||
|
||
app.patch('/api/projects/:name', (req, res) => {
|
||
const projectPath = resolveProject(req.params.name)
|
||
if (!projectPath) return res.status(404).json({ error: 'unknown project' })
|
||
const current = readStatusFile(projectPath)
|
||
const { status, priority, notes, tags, tasks, thumbnail, start, program, itch: itchLink } = req.body ?? {}
|
||
// itch: '' = automatic, '-' = not published, otherwise the game's page
|
||
let nextItch = current.itch
|
||
if (typeof itchLink === 'string') {
|
||
const v = itchLink.trim()
|
||
if (v && v !== '-' && !/^https:\/\/[a-z0-9-]+\.itch\.io\/[^\s"<>]+$/i.test(v)) return res.status(400).json({ error: 'itch.io-Link: z. B. https://name.itch.io/spiel – oder „-“ für „nicht veröffentlicht“' })
|
||
nextItch = v.slice(0, 300)
|
||
}
|
||
// program: absolute path (file dialog) or relative; stored relative, must lie inside the project
|
||
let nextProgram = current.program
|
||
if (typeof program === 'string') {
|
||
const p = program.trim().replace(/^"|"$/g, '')
|
||
if (!p) nextProgram = ''
|
||
else {
|
||
const abs = path.resolve(projectPath, p)
|
||
if (!abs.startsWith(projectPath + path.sep)) return res.status(400).json({ error: 'Die Datei muss im Projektordner liegen.' })
|
||
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) return res.status(400).json({ error: `Datei nicht gefunden: ${p}` })
|
||
nextProgram = path.relative(projectPath, abs).slice(0, 300)
|
||
}
|
||
}
|
||
const next = {
|
||
status: STATUSES.includes(status) ? status : current.status,
|
||
priority: PRIORITIES.includes(priority) ? priority : current.priority,
|
||
notes: typeof notes === 'string' ? notes : current.notes,
|
||
tags: Array.isArray(tags) ? tags.map(String).slice(0, 10) : current.tags,
|
||
tasks: tasks !== undefined ? sanitizeTasks(tasks) : current.tasks,
|
||
thumbnail: typeof thumbnail === 'string' ? thumbnail.slice(0, 300) : current.thumbnail,
|
||
start: typeof start === 'string' ? start.replace(/[\r\n]+/g, ' ').slice(0, 300) : current.start,
|
||
program: nextProgram,
|
||
itch: nextItch,
|
||
updatedAt: new Date().toISOString(),
|
||
}
|
||
fs.writeFileSync(path.join(projectPath, STATUS_FILE), JSON.stringify(next, null, 2))
|
||
thumbCache.delete(req.params.name)
|
||
icons.forget(projectPath)
|
||
quickCache.delete(req.params.name)
|
||
res.json(next)
|
||
})
|
||
|
||
// Serves the project's thumbnail image; 404 when the folder has no usable
|
||
// image (the UI then falls back to a generated letter tile).
|
||
app.get('/api/projects/:name/thumb', (req, res) => {
|
||
const projectPath = resolveProject(req.params.name)
|
||
if (!projectPath) return res.status(404).end()
|
||
const file = findThumbnail(req.params.name, projectPath)
|
||
if (!file) return res.status(404).end()
|
||
res.setHeader('Cache-Control', 'public, max-age=300')
|
||
res.sendFile(file, (err) => { if (err && !res.headersSent) res.status(404).end() })
|
||
})
|
||
|
||
// The program chosen for ▶ ({ rel, missing }) or null.
|
||
function programInfo(projectPath) {
|
||
const rel = readStatusFile(projectPath).program
|
||
if (!rel) return null
|
||
const r = tech.resolveProgram(projectPath, rel)
|
||
return { rel, missing: !r?.exists }
|
||
}
|
||
|
||
// Everything the editor's Info/Aktionen tabs need.
|
||
app.get('/api/projects/:name/details', handle(async (req, res) => {
|
||
const name = req.params.name
|
||
const projectPath = resolveProject(name)
|
||
if (!projectPath) return res.status(404).json({ error: 'unknown project' })
|
||
const icon = icons.findIcon(projectPath)
|
||
const p = projectRef(name)
|
||
res.json({
|
||
git: await gitInfo(projectPath),
|
||
tech: tech.summary(tech.detect(projectPath)),
|
||
tools: toolInfo(projectPath),
|
||
icon: icon ? path.relative(projectPath, icon) : null,
|
||
storage: storage.get(p.root.path, p.folder),
|
||
lastBackup: backup.lastFor(p.root.path, p.folder, String(req.query.target ?? '') || null),
|
||
backupTargets: backup.lastOnAllTargets(p.root.path, p.folder),
|
||
actions: actionsFor(name, projectPath).map(({ id, label, group, detail, rel }) => ({ id, label, group, detail, rel })),
|
||
program: programInfo(projectPath),
|
||
path: projectPath,
|
||
sshKey: sshKey(),
|
||
releaseDirs: archive.findReleaseDirs(projectPath),
|
||
archives: archive.listArchives(projectPath),
|
||
itchPack: itchpack.summary(projectPath),
|
||
})
|
||
}))
|
||
|
||
// Opens the project folder in Windows Explorer.
|
||
app.post('/api/projects/:name/open', (req, res) => {
|
||
const projectPath = resolveProject(req.params.name)
|
||
if (!projectPath) return res.status(404).json({ error: 'unknown project' })
|
||
try {
|
||
openDetached('explorer.exe', [projectPath])
|
||
res.json({ ok: true })
|
||
} catch (e) {
|
||
res.status(500).json({ error: String(e) })
|
||
}
|
||
})
|
||
|
||
// Runs one of the server-built actions; the body only names its id.
|
||
app.post('/api/projects/:name/run', handle(async (req, res) => {
|
||
const name = req.params.name
|
||
const projectPath = resolveProject(name)
|
||
if (!projectPath) return res.status(404).json({ error: 'unknown project' })
|
||
const action = actionsFor(name, projectPath).find((a) => a.id === req.body?.id)
|
||
if (!action) return res.status(400).json({ error: 'unknown action' })
|
||
const target = action.kind === 'exe' ? action.exe : action.kind === 'open' ? action.file : null
|
||
if (target && !fs.existsSync(target)) {
|
||
quickCache.delete(name)
|
||
return res.status(400).json({ error: `Nicht gefunden: ${path.relative(projectPath, target) || target}` })
|
||
}
|
||
switch (action.kind) {
|
||
case 'console': openConsole(`${name} ${action.id}`, action.cwd, action.command, { raw: action.id === 'custom' }); break
|
||
case 'exe': openDetached(action.exe, action.args, action.cwd); break
|
||
case 'open': openDetached('explorer.exe', [action.file]); break
|
||
case 'vscode': {
|
||
// code is a .cmd shim, so go through cmd; the path was checked by resolveProject
|
||
const r = await run('cmd.exe', ['/c', 'code', projectPath], { timeout: 15000 })
|
||
if (!r.ok) return res.status(500).json({ error: 'VS Code (code) nicht gefunden' })
|
||
break
|
||
}
|
||
}
|
||
res.json({ ok: true, label: action.label })
|
||
}))
|
||
|
||
// git push in a visible console, so SSH/credential prompts and errors are seen.
|
||
// body.message: commit all changes with this message first ("Commit & Push").
|
||
app.post('/api/projects/:name/push', handle(async (req, res) => {
|
||
const name = req.params.name
|
||
const projectPath = resolveProject(name)
|
||
if (!projectPath) return res.status(404).json({ error: 'unknown project' })
|
||
const git = await gitInfo(projectPath)
|
||
if (!git.remote) return res.status(400).json({ error: 'kein Remote eingerichtet' })
|
||
if (!/^[\w./-]+$/.test(git.branch)) return res.status(400).json({ error: `Branch-Name nicht unterstützt: ${git.branch || '(keiner)'}` })
|
||
const steps = []
|
||
if (typeof req.body?.message === 'string' && req.body.message.trim()) {
|
||
// the message sits in "..." in a .cmd file: no quotes, no line breaks
|
||
const msg = req.body.message.replace(/["\r\n]+/g, ' ').trim().slice(0, 200)
|
||
steps.push('git add -A', `git commit -m "${msg}"`)
|
||
}
|
||
steps.push(git.upstream ? 'git push' : `git push -u origin ${git.branch}`)
|
||
openConsole(`${name} push`, projectPath, steps.join(' && '))
|
||
res.json({ ok: true })
|
||
}))
|
||
|
||
// Sets the "origin" remote (SSH or https URL; '' removes it).
|
||
app.post('/api/projects/:name/remote', handle(async (req, res) => {
|
||
const projectPath = resolveProject(req.params.name)
|
||
if (!projectPath) return res.status(404).json({ error: 'unknown project' })
|
||
try { await setRemote(projectPath, req.body?.url) } catch (e) { return res.status(400).json({ error: String(e.message ?? e) }) }
|
||
res.json({ ok: true, git: await gitInfo(projectPath) })
|
||
}))
|
||
|
||
// git init for a project without repository.
|
||
app.post('/api/projects/:name/git-init', handle(async (req, res) => {
|
||
const projectPath = resolveProject(req.params.name)
|
||
if (!projectPath) return res.status(404).json({ error: 'unknown project' })
|
||
try { await initRepo(projectPath) } catch (e) { return res.status(400).json({ error: String(e.message ?? e) }) }
|
||
res.json({ ok: true, git: await gitInfo(projectPath) })
|
||
}))
|
||
|
||
// Background disk scan: one project ({name}) or all (empty body).
|
||
app.post('/api/scan', (req, res) => {
|
||
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' })
|
||
if (!storage.startScan(refs.map((p) => ({ root: p.root.path, folder: p.folder, key: p.key })))) return res.status(409).json({ error: 'Scan läuft schon' })
|
||
res.json({ ok: true, state: storage.state })
|
||
})
|
||
|
||
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)
|
||
if (!ref) return res.status(404).json({ error: 'unknown project' })
|
||
if (ref.folder === '_Tools') return res.status(400).json({ error: '_Tools wird nie aufgeräumt' })
|
||
// paths are relative to the projects folder, as cleanup.ps1 listed them ("<folder>\...")
|
||
const paths = (Array.isArray(req.body?.paths) ? req.body.paths : [])
|
||
.filter((p) => typeof p === 'string' && p.startsWith(ref.folder + path.sep))
|
||
if (!paths.length) return res.status(400).json({ error: 'nichts ausgewählt' })
|
||
const result = await storage.clean(ref.root.path, ref.folder, paths)
|
||
res.json(result)
|
||
}))
|
||
|
||
// NAS backup (lib/backup.js): check → copy, never deletes in the backup.
|
||
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
|
||
const ref = project && resolveProject(project) ? projectRef(project) : null
|
||
if (project && (!ref || ref.folder === '_Tools')) return res.status(404).json({ error: 'unknown project' })
|
||
const target = String(req.body?.target ?? '') || null
|
||
if (target && !settings.get().backup.targets.some((t) => t.id === target)) return res.status(404).json({ error: 'Backup-Ziel nicht gefunden' })
|
||
if (!ROOTS.length) return res.status(400).json({ error: 'Kein Projektordner gewählt' })
|
||
if (!backup.check(ref ? { root: ref.root.path, folder: ref.folder } : null, !!req.body?.autoCopy, target)) return res.status(409).json({ error: 'Es läuft schon ein Backup' })
|
||
res.json(backup.getState())
|
||
}))
|
||
app.post('/api/backup/copy', handle(async (req, res) => {
|
||
if (!backup.copy()) return res.status(409).json({ error: 'Erst prüfen (oder läuft schon)' })
|
||
res.json(backup.getState())
|
||
}))
|
||
app.post('/api/backup/cancel', (req, res) => {
|
||
backup.cancel()
|
||
res.json(backup.getState())
|
||
})
|
||
|
||
applySettings()
|
||
scheduler.start()
|
||
|
||
app.listen(PORT, HOST, () => {
|
||
console.log(`Project dashboard running at http://${HOST}:${PORT}`)
|
||
console.log(`Scanning: ${ROOT_DIR}`)
|
||
})
|