- Einstellungen -> Allgemein: Akzentfarbe (8 Presets + eigener Farbwaehler), per color-mix theme-aware abgeleitet, in localStorage gespeichert - sanfter Fade + einmaliges Karten-Stagger beim View-Wechsel (Guard-Flag, respektiert prefers-reduced-motion) - Leerzustaende: "nichts passt zu deinen Filtern" + Filter zuruecksetzen, sonst "noch keine Projekte" + Neues Projekt (im Demo-Limit ausgeblendet) in Board/Galerie/Liste/Home - README als Markdown im Info-Panel (server: readmeFull-Feld) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1028 lines
50 KiB
JavaScript
1028 lines
50 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).
|
||
// A worker always has the IPC channel (process.send); the variable alone is not
|
||
// enough - it would be inherited by programs the dashboard starts (VS Code, consoles)
|
||
// and a dashboard started from there would then run without its supervisor.
|
||
if (!process.env.DASHBOARD_WORKER || !process.send) {
|
||
delete process.env.DASHBOARD_WORKER
|
||
require('./lib/supervisor').supervise(__filename)
|
||
return
|
||
}
|
||
delete process.env.DASHBOARD_WORKER // not passed on to anything started from here
|
||
// 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 nested = require('./lib/nested')
|
||
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}`])
|
||
|
||
// Edition is baked into the code, not a separate file (which anyone could delete). build.ps1 -Demo
|
||
// rewrites 'full' -> 'demo' in the staged copy only; the launcher re-checks the unpacked files on every
|
||
// start, so editing this back out doesn't stick. DASHBOARD_DEMO=1 tests the demo from the source folder.
|
||
// Keep the next line in this exact single-line form \u2013 the build's text replace matches it literally.
|
||
const BUILD_EDITION = 'full'
|
||
const DEMO = BUILD_EDITION === 'demo' || process.env.DASHBOARD_DEMO === '1'
|
||
const DEMO_LIMIT = 6
|
||
const BUY_URL = 'https://sn09.itch.io/project-dashboard'
|
||
let demoTotal = 0 // all project folders found (the demo shows DEMO_LIMIT of them)
|
||
|
||
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)
|
||
}
|
||
|
||
const MAX_DESCRIPTION = 4000
|
||
|
||
// First real paragraph(s) of the project's README - suggestion for the
|
||
// description in the Info tab. Skips headings, badges, images, tables, code.
|
||
function readmeIntro(projectPath) {
|
||
let text = ''
|
||
for (const f of ['README.md', 'readme.md', 'Readme.md', 'README.txt', 'README']) {
|
||
try { text = fs.readFileSync(path.join(projectPath, f), 'utf-8'); break } catch {}
|
||
}
|
||
if (!text) return ''
|
||
text = text.replace(/^---[\s\S]*?\n---\s*\n/, '').replace(/<!--[\s\S]*?-->/g, '').replace(/```[\s\S]*?```/g, '')
|
||
const paras = []
|
||
let cur = []
|
||
const flush = () => { if (cur.length) paras.push(cur.join(' ')); cur = [] }
|
||
for (const raw of text.split(/\r?\n/)) {
|
||
const line = raw.trim()
|
||
if (!line) { flush(); continue }
|
||
if (/^(#|\||!\[|\[!\[|<|>|---|===|\*\*\*)/.test(line)) { flush(); continue }
|
||
cur.push(line.replace(/^[-*]\s+/, '• '))
|
||
}
|
||
flush()
|
||
const clean = (p) => p.replace(/\*\*|__|`/g, '').replace(/\[([^\]]+)\]\([^)]+\)/g, '$1').trim()
|
||
let out = ''
|
||
for (const p of paras.map(clean).filter((p) => p.length > 20)) {
|
||
if (out && out.length + p.length > 600) break
|
||
out = out ? `${out}\n\n${p}` : p
|
||
if (out.length > 300) break
|
||
}
|
||
return out.length > 800 ? out.slice(0, 797).replace(/\s+\S*$/, '') + '…' : out
|
||
}
|
||
|
||
// Raw README text (first ~20 KB) for the client's markdown view. Path-confined to the project folder.
|
||
function readmeRaw(projectPath) {
|
||
for (const f of ['README.md', 'readme.md', 'Readme.md', 'README.txt', 'README']) {
|
||
try {
|
||
const text = fs.readFileSync(path.join(projectPath, f), 'utf-8').replace(/^/, '')
|
||
return text.length > 20000 ? text.slice(0, 20000) : text
|
||
} catch {}
|
||
}
|
||
return ''
|
||
}
|
||
|
||
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 : '',
|
||
description: typeof data.description === 'string' ? data.description.slice(0, MAX_DESCRIPTION) : '',
|
||
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) : '',
|
||
favorite: data.favorite === true,
|
||
updatedAt: data.updatedAt ?? null,
|
||
}
|
||
} catch {
|
||
return { status: 'idea', priority: 'medium', notes: '', description: '', tags: [], tasks: [], thumbnail: '', start: '', program: '', itch: '', favorite: false, 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 }
|
||
// projects in subfolders chosen in the scanner (lib/nested.js); a pure
|
||
// collection folder above them is hidden, a real project stays
|
||
const sub = (root.nested ?? []).filter((rel) => { try { return fs.statSync(path.join(root.path, rel)).isDirectory() } catch { return false } })
|
||
const hide = new Set()
|
||
for (const rel of sub) {
|
||
const top = rel.split(path.sep)[0]
|
||
if (!nested.isProject(path.join(root.path, top))) hide.add(top.toLowerCase())
|
||
}
|
||
for (const e of entries) {
|
||
if (e.isDirectory() && !e.name.startsWith('.') && !NOT_PROJECTS.has(e.name.toLowerCase()) && !hide.has(e.name.toLowerCase())) raw.push({ folder: e.name, root, parent: '' })
|
||
}
|
||
for (const rel of sub) raw.push({ folder: rel, root, parent: path.dirname(rel) })
|
||
}
|
||
// key: the folder's name; on a clash "(parent folder)" / "(projects folder)" is added
|
||
const base = (p) => path.basename(p.folder)
|
||
const count = new Map()
|
||
for (const p of raw) count.set(base(p).toLowerCase(), (count.get(base(p).toLowerCase()) ?? 0) + 1)
|
||
const used = new Set()
|
||
const list = raw.map((p) => {
|
||
const b = base(p)
|
||
let key = count.get(b.toLowerCase()) > 1 ? `${b} (${p.parent ? path.basename(p.parent) : p.root.name})` : b
|
||
if (used.has(key.toLowerCase())) key = `${b} (${p.root.name})`
|
||
while (used.has(key.toLowerCase())) key += ` [${p.root.id}]`
|
||
used.add(key.toLowerCase())
|
||
return { key, folder: p.folder, root: p.root, parent: p.parent }
|
||
})
|
||
demoTotal = list.length
|
||
// demo: a fixed set (by name, so touching a project doesn't swap it in) – every view,
|
||
// action and the backup only know these, since they all go through projMap
|
||
const shown = DEMO ? [...list].sort((a, b) => a.key.localeCompare(b.key, 'de', { sensitivity: 'base' })).slice(0, DEMO_LIMIT) : list
|
||
projMap = new Map(shown.map((p) => [p.key, p]))
|
||
backup.limitTo(DEMO ? shown.map((p) => ({ root: p.root.path, folder: p.folder })) : null)
|
||
return shown
|
||
}
|
||
|
||
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
|
||
// a direct child of a shown projects folder, or a chosen project in a subfolder (projMap)
|
||
const inside = p.path.toLowerCase().startsWith(p.root.path.toLowerCase() + path.sep)
|
||
if (!inside || !fs.existsSync(p.path) || !fs.statSync(p.path).isDirectory()) 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,
|
||
parent: p.parent ?? '',
|
||
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: settings.itchOn() ? itch.forProject(path.basename(p.folder), meta.itch) : null,
|
||
}
|
||
}
|
||
|
||
// progress of reading the projects (start screen: /api/progress)
|
||
const loadState = { running: 0, phase: '', done: 0, total: 0 }
|
||
async function listProjects(target) {
|
||
loadState.running++
|
||
try {
|
||
if (settings.itchOn()) { loadState.phase = 'itch'; await itch.ensure() } // switched off: no request to itch.io
|
||
const items = projectList()
|
||
Object.assign(loadState, { phase: 'projects', done: 0, total: items.length })
|
||
const list = await pool(items, 8, async (p) => { const d = await describeProject(p, target); loadState.done++; return d })
|
||
return list.sort((a, b) => new Date(b.mtime) - new Date(a.mtime))
|
||
} finally {
|
||
loadState.running--
|
||
if (!loadState.running) loadState.phase = ''
|
||
}
|
||
}
|
||
|
||
// 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() })
|
||
})
|
||
|
||
// Start screen: how far reading the projects (git, sizes ...) and the
|
||
// "last change" of every project (lib/activity.js, in the background) has come.
|
||
app.get('/api/progress', (req, res) => {
|
||
const total = projMap.size
|
||
res.json({
|
||
projects: { running: loadState.running > 0, phase: loadState.phase, done: loadState.done, total: loadState.total },
|
||
activity: { pending: activity.pending(), total },
|
||
})
|
||
})
|
||
|
||
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,
|
||
// first start: no usable projects folder registered at all (an empty selection is fine)
|
||
setupNeeded: !settings.get().roots.some((r) => fs.existsSync(r.path)),
|
||
noneShown: !ROOTS.length && !!settings.get().noneShown,
|
||
projects: list,
|
||
demo: DEMO ? { limit: DEMO_LIMIT, total: demoTotal, buyUrl: BUY_URL } : null,
|
||
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(),
|
||
// projects in subfolders found but not yet chosen/dismissed (lib/nested.js)
|
||
features: s.features ?? { itch: false },
|
||
nestedHint: ROOTS.length ? nested.hint(s.roots.filter((r) => fs.existsSync(r.path))) : 0,
|
||
})
|
||
}))
|
||
|
||
// 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(path.basename(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) }
|
||
}
|
||
// everything itch.io only works while it is switched on (Einstellungen → Allgemein)
|
||
const itchOnly = (req, res, next) => (settings.itchOn() ? next() : res.status(404).json({ error: 'itch.io ist in den Einstellungen ausgeschaltet' }))
|
||
app.use(['/api/itch', '/api/projects/:name/itch'], itchOnly)
|
||
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) })
|
||
}
|
||
})
|
||
// Export the settings as JSON (client offers it as a download).
|
||
app.get('/api/settings/export', (req, res) => {
|
||
res.json(settings.exportData())
|
||
})
|
||
// Import a settings object (from a previously exported file) and apply it.
|
||
app.post('/api/settings/import', (req, res) => {
|
||
if (storage.busy() || backup.busy() || create.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' })
|
||
try {
|
||
settings.importData(req.body?.data ?? 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) })
|
||
}
|
||
})
|
||
// Reset to a fresh "new user" state. Backs up settings.json first, then starts over.
|
||
app.post('/api/settings/reset', (req, res) => {
|
||
if (storage.busy() || backup.busy() || create.busy() || archive.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' })
|
||
try {
|
||
const r = settings.reset()
|
||
applySettings()
|
||
res.json({ ok: true, backupFile: r.backupFile })
|
||
} 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, version: require('./package.json').version, 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 ?? {}
|
||
projectList()
|
||
if (DEMO && demoTotal >= DEMO_LIMIT) return res.status(403).json({ error: `Demo: maximal ${DEMO_LIMIT} Projekte – für mehr die Vollversion holen: ${BUY_URL}` })
|
||
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.' })
|
||
// a project in a subfolder is renamed where it is (same projects folder);
|
||
// moved to another projects folder it lands at the top there
|
||
const stay = ref.parent && root.id === ref.root.id
|
||
let r
|
||
try {
|
||
r = await create.move({ from: ref.path, rootPath: stay ? path.join(root.path, ref.parent) : root.path, name: req.body?.name })
|
||
} catch (e) {
|
||
return res.status(400).json({ error: String(e.message ?? e) })
|
||
}
|
||
const newRoot = path.resolve(root.path)
|
||
const newFolder = stay ? path.join(ref.parent, r.name) : r.name
|
||
if (ref.parent) {
|
||
const old = settings.get().roots.find((x) => x.id === ref.root.id)
|
||
if (old) {
|
||
const keep = (old.nested ?? []).filter((x) => x.toLowerCase() !== ref.folder.toLowerCase())
|
||
settings.setNested(old.id, stay ? [...keep, newFolder] : keep, old.nestedIgnored ?? [])
|
||
nested.forgetHint()
|
||
applySettings()
|
||
}
|
||
}
|
||
storage.rename(ref.root.path, ref.folder, newRoot, newFolder)
|
||
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, newFolder) : 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) })
|
||
}
|
||
})
|
||
// Projects in subfolders (lib/nested.js): scan every registered projects folder.
|
||
// ?deep=1 also lists sub-projects inside real projects.
|
||
app.get('/api/nested/scan', (req, res) => {
|
||
const deep = req.query.deep === '1'
|
||
const out = settings.get().roots.filter((r) => fs.existsSync(r.path)).map((r) => {
|
||
const chosen = new Set((r.nested ?? []).map((x) => x.toLowerCase()))
|
||
const ignored = new Set((r.nestedIgnored ?? []).map((x) => x.toLowerCase()))
|
||
const flag = (x) => ({ ...x, chosen: chosen.has(x.rel.toLowerCase()), ignored: ignored.has(x.rel.toLowerCase()) })
|
||
const sc = nested.scan(r.path, { deep })
|
||
// chosen entries the scan doesn't show any more (e.g. inside a real project, scanned without deep)
|
||
const seen = new Set([...sc.containers.flatMap((c) => c.projects), ...sc.inProjects].map((x) => x.rel.toLowerCase()))
|
||
const extra = (r.nested ?? []).filter((x) => !seen.has(x.toLowerCase()) && fs.existsSync(path.join(r.path, x)))
|
||
.map((rel) => ({ rel, markers: nested.markers(path.join(r.path, rel)), parent: rel.split(path.sep)[0] }))
|
||
return {
|
||
id: r.id, name: r.name, path: r.path,
|
||
containers: sc.containers.map((c) => ({ rel: c.rel, projects: c.projects.map(flag) })),
|
||
inProjects: [...sc.inProjects, ...extra].map(flag),
|
||
}
|
||
})
|
||
res.json({ roots: out, deep })
|
||
})
|
||
// Stores the choice. body: { roots: { <rootId>: { chosen: [rel], ignored: [rel] } } }
|
||
app.post('/api/nested', (req, res) => {
|
||
if (storage.busy() || backup.busy() || create.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' })
|
||
const input = req.body?.roots
|
||
if (!input || typeof input !== 'object') return res.status(400).json({ error: 'roots fehlt' })
|
||
let chosenCount = 0
|
||
for (const r of settings.get().roots) {
|
||
const v = input[r.id]
|
||
if (!v) continue
|
||
const ok = (list) => (Array.isArray(list) ? list : []).map((x) => nested.cleanRel(r.path, x))
|
||
.filter((x) => x && fs.existsSync(path.join(r.path, x)) && fs.statSync(path.join(r.path, x)).isDirectory())
|
||
const chosen = ok(v.chosen)
|
||
settings.setNested(r.id, chosen, ok(v.ignored).filter((x) => !chosen.includes(x)))
|
||
chosenCount += chosen.length
|
||
}
|
||
nested.forgetHint()
|
||
applySettings()
|
||
res.json({ ok: true, chosen: chosenCount, projects: projectList().length })
|
||
})
|
||
// 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, description, tags, tasks, thumbnail, start, program, itch: itchLink, favorite } = 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,
|
||
description: typeof description === 'string' ? description.trim().slice(0, MAX_DESCRIPTION) : current.description,
|
||
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,
|
||
favorite: typeof favorite === 'boolean' ? favorite : current.favorite,
|
||
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: settings.itchOn() ? itchpack.summary(projectPath) : null,
|
||
readme: readmeIntro(projectPath),
|
||
readmeFull: readmeRaw(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)
|
||
}))
|
||
|
||
// Permanently deletes the whole project folder from disk (not from any backup).
|
||
// Guarded: only a real subfolder of a shown projects folder, never a root or _Tools.
|
||
app.post('/api/projects/:name/delete', handle(async (req, res) => {
|
||
if (storage.busy() || backup.busy() || create.busy() || archive.busy()) return res.status(409).json({ error: 'Erst warten, bis Scan/Backup fertig ist.' })
|
||
const key = req.params.name
|
||
const dir = resolveProject(key)
|
||
const ref = dir && projectRef(key)
|
||
if (!ref || !dir) return res.status(404).json({ error: 'unknown project' })
|
||
if (ref.folder === '_Tools') return res.status(400).json({ error: '_Tools wird nie gelöscht' })
|
||
const root = path.resolve(ref.root.path)
|
||
const target = path.resolve(dir)
|
||
// never the projects folder itself, never a drive root – only a subfolder of a registered root
|
||
if (target.toLowerCase() === root.toLowerCase() || !target.toLowerCase().startsWith(root.toLowerCase() + path.sep) || path.dirname(target) === target) {
|
||
return res.status(400).json({ error: 'Ordner nicht löschbar.' })
|
||
}
|
||
try {
|
||
fs.rmSync(target, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 })
|
||
} catch (e) {
|
||
return res.status(400).json({ error: `Löschen fehlgeschlagen (Datei gesperrt? Programm offen?): ${String(e.message ?? e)}` })
|
||
}
|
||
// drop it from the subfolder-scanner lists if it was listed there
|
||
const rSet = settings.get().roots.find((x) => x.id === ref.root.id)
|
||
if (rSet) {
|
||
const low = ref.folder.toLowerCase()
|
||
const nn = (rSet.nested ?? []).filter((x) => x.toLowerCase() !== low)
|
||
const ni = (rSet.nestedIgnored ?? []).filter((x) => x.toLowerCase() !== low)
|
||
if (nn.length !== (rSet.nested ?? []).length || ni.length !== (rSet.nestedIgnored ?? []).length) {
|
||
settings.setNested(rSet.id, nn, ni); nested.forgetHint(); applySettings()
|
||
}
|
||
}
|
||
thumbCache.delete(key); quickCache.delete(key); icons.forget(target)
|
||
projectList()
|
||
res.json({ ok: true, name: ref.name })
|
||
}))
|
||
|
||
// 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}`)
|
||
})
|