Files
ProjectDashboard/lib/backup.js

375 lines
18 KiB
JavaScript
Raw Normal View History

2026-11-12 09:32:23 +01:00
// Backup to one or more targets (folder / drive / NAS), in two steps like
// _Tools\Backup\backup-projekte.ps1:
// check: robocopy /L lists what is new/changed (missing in the backup) and
// what exists only in the backup
// copy: robocopy /E copies exactly that - nothing is ever deleted in the backup
// Scope: all shown projects folders (scope = null; several can be selected,
// see lib/settings.js) or one project (<root>\<folder> -> <dest>\<folder>).
// Each projects folder lands in its own place on the target (settings.backupSubdir):
// the first registered folder directly in the target, further ones in a subfolder.
// One job at a time (for one target), in the background; the UI polls getState().
// Excludes come from the settings, which also keep _Tools\Backup\backup-config.json
// in sync (backup-projekte.bat uses the first target). Every projects folder keeps
// its own "last backup" info per target.
const fs = require('fs')
const path = require('path')
const { spawn } = require('child_process')
const settings = require('./settings')
let roots = [] // selected projects folders (paths)
let keyOf = (root, folder) => folder // display name of a project (set by the server)
let logDir = null
const STATE_FILE = path.join(settings.DATA_DIR, 'backup.json')
// the running / last job
const state = {
phase: 'idle', // idle | checking | ready | copying | done | cancelled | error
target: null, // target id of the job
scope: null, // null = everything, else the project's display name
autoCopy: false, // copy right after the check (per-project "Sichern")
2026-11-12 14:03:53 +01:00
auto: false, // started by the automatic backup schedule
2026-11-12 09:32:23 +01:00
error: null,
check: null, // summary of the last check
progress: null, // { files, filesTotal, bytes, bytesTotal, current }
}
let job = null // { scope: {root, folder} | null, items: [{ root, source, target }] }
let all = {} // root (lower case) -> target id -> { path, last, lastByProject }
let child = null
const rootKey = (r) => (r ?? '').toLowerCase()
const targets = () => settings.get().backup.targets
const targetById = (id) => targets().find((t) => t.id === id) ?? null
// where a projects folder lands on a target
const destOf = (t, root) => path.join(t.path, settings.backupSubdir(root))
// per root and target; starts fresh when the destination changed
function dataFor(t, root) {
const r = (all[rootKey(root)] ??= {})
let d = r[t.id]
const dest = destOf(t, root)
if (!d || d.path.toLowerCase() !== dest.toLowerCase()) d = r[t.id] = { path: dest, last: null, lastByProject: {} }
return d
}
// (Re)initialise for the current settings. rootList: selected projects folders,
// key: (root, folder) -> name of the project in the UI.
function init(rootList, key) {
roots = (Array.isArray(rootList) ? rootList : [rootList]).filter(Boolean)
if (key) keyOf = key
const first = roots[0] ?? ''
const own = first ? path.join(first, '_Tools', 'Backup') : ''
logDir = own && fs.existsSync(own) ? path.join(own, 'logs') : path.join(settings.DATA_DIR, 'logs')
if (!busy()) Object.assign(state, { phase: 'idle', target: null, scope: null, error: null, check: null, progress: null })
all = {}
try {
const saved = JSON.parse(fs.readFileSync(STATE_FILE, 'utf-8'))
if (saved.roots && typeof saved.roots === 'object') all = saved.roots
else if (saved.targets) all[rootKey(saved.root ?? first)] = saved.targets
else {
// old format: one target
const t = targets().find((x) => !saved.target || x.path.toLowerCase() === saved.target.toLowerCase())
if (t) all[rootKey(first)] = { [t.id]: { path: t.path, last: saved.last ?? null, lastByProject: saved.lastByProject ?? {} } }
}
} catch {}
const ids = new Set(targets().map((t) => t.id))
for (const r of Object.values(all)) for (const id of Object.keys(r)) if (!ids.has(id)) delete r[id]
}
function save() {
fs.mkdirSync(path.dirname(STATE_FILE), { recursive: true })
fs.writeFileSync(STATE_FILE, JSON.stringify({ roots: all }, null, 1))
}
function config(targetId) {
const s = settings.get()
if (!s.backup.targets.length) throw new Error('Kein Backup-Ziel eingerichtet – in den Einstellungen (⚙) festlegen.')
const t = targetById(targetId) ?? s.backup.targets[0]
return { t, excludeDirs: s.backup.excludeDirs, excludeFiles: s.backup.excludeFiles }
}
// extraXd: full paths to skip as well (demo: the projects it doesn't show)
function baseArgs(cfg, extraXd = []) {
2026-11-12 09:32:23 +01:00
return ['/E', '/FFT', '/XJ', '/R:2', '/W:5', '/COPY:DAT', '/DCOPY:T',
'/XD', ...cfg.excludeDirs, ...extraXd, '/XF', ...cfg.excludeFiles]
}
// Demo edition: only these projects may be backed up. Map rootPath (lower) -> Set of
// allowed top-level folder names (lower); null = no limit (full version).
let allow = null
function limitTo(list) {
if (!list) { allow = null; return }
allow = new Map()
for (const p of list) {
const r = path.resolve(p.root).toLowerCase()
if (!allow.has(r)) allow.set(r, new Set())
allow.get(r).add(String(p.folder).split(/[\\/]/)[0].toLowerCase())
}
}
// top-level folders of a projects folder that the demo doesn't cover (full paths, for /XD)
function blockedIn(root) {
const ok = allow?.get(path.resolve(root).toLowerCase())
if (!ok) return []
try {
return fs.readdirSync(root, { withFileTypes: true })
.filter((e) => e.isDirectory() && !ok.has(e.name.toLowerCase()))
.map((e) => path.join(root, e.name))
} catch { return [] }
2026-11-12 09:32:23 +01:00
}
2026-11-12 14:03:53 +01:00
// robocopy runs of a job: one per projects folder (the shown ones, or `rootList`),
// or one for a single project
function itemsFor(t, scope, rootList = roots) {
2026-11-12 09:32:23 +01:00
if (scope) return [{ root: scope.root, source: path.join(scope.root, scope.folder), target: path.join(destOf(t, scope.root), scope.folder) }]
const list = allow ? rootList.filter((root) => allow.has(path.resolve(root).toLowerCase())) : rootList
return list.map((root) => ({ root, source: root, target: destOf(t, root), xd: allow ? blockedIn(root) : [] }))
2026-11-12 09:32:23 +01:00
}
const stamp = () => new Date().toISOString().slice(0, 16).replace('T', '_').replace(':', '-')
const slug = (s) => (s ? '-' + s.replace(/[^\w.-]+/g, '_').slice(0, 40) : '')
// Runs robocopy and calls onLine for every line it writes to `logFile`.
// robocopy's stdout uses the old OEM code page (umlauts break), but /UNILOG
// writes real UTF-16 - so the log file is tailed while robocopy runs.
function robocopy(args, logFile, onLine) {
return new Promise((resolve) => {
fs.mkdirSync(path.dirname(logFile), { recursive: true })
try { fs.unlinkSync(logFile) } catch {}
child = spawn('robocopy', [...args, `/UNILOG:${logFile}`], { windowsHide: true, stdio: 'ignore' })
const decoder = new TextDecoder('utf-16le')
let offset = 0
let rest = ''
const buf = Buffer.alloc(1 << 20)
const drain = (final) => {
let fd
try { fd = fs.openSync(logFile, 'r') } catch { return }
try {
for (;;) {
const n = fs.readSync(fd, buf, 0, buf.length, offset)
if (n <= 0) break
offset += n
const lines = (rest + decoder.decode(buf.subarray(0, n), { stream: true })).split(/\r?\n/)
rest = lines.pop()
for (const l of lines) onLine(l)
}
} finally { fs.closeSync(fd) }
if (final && rest) { onLine(rest); rest = '' }
}
const timer = setInterval(() => drain(false), 500)
const finish = (code) => { clearInterval(timer); drain(true); child = null; resolve(code ?? 16) }
child.on('close', finish)
child.on('error', () => finish(16))
})
}
// One file line of robocopy output: "<class>\t<size>\t<full path>"
function parseLine(line) {
const parts = line.split('\t').map((s) => s.trim()).filter(Boolean)
if (parts.length < 3) return null
const size = Number(parts[parts.length - 2])
const file = parts[parts.length - 1]
if (!Number.isFinite(size) || file.endsWith('\\')) return null
return { cls: parts[0], size, file }
}
function busy() { return state.phase === 'checking' || state.phase === 'copying' }
// robocopy error line: "2026/11/10 11:17:10 FEHLER 2 (0x00000002) Verzeichnis wird kopiert D:\x\y\" -> path
const ERR_RE = /\b(?:FEHLER|ERROR)\s+\d+\s+\(0x[0-9A-Fa-f]+\).*?\s((?:[A-Za-z]:\\|\\\\).*)$/
// which project folder a source or target path belongs to (null = none / outside)
function projectOfPath(p, source, target, scopeFolder) {
if (scopeFolder) return scopeFolder
const l = p.toLowerCase()
for (const base of [source, target]) {
const b = base.toLowerCase().replace(/\\$/, '') + '\\'
if (l.startsWith(b)) return p.slice(b.length).split('\\')[0] || null
}
return null
}
// projects with errors in a finished robocopy log (for older records without a "failed" list)
function failedFromLog(log, source, target) {
try {
const out = new Set()
for (const line of fs.readFileSync(log, 'utf16le').split(/\r?\n/)) {
const m = line.match(ERR_RE)
const p = m && projectOfPath(m[1].trim(), source, target, null)
if (p) out.add(p)
}
return [...out]
} catch { return null }
}
// scope: null = all shown projects folders, or { root, folder } of one project.
// autoCopy: continue with the copy right away (nothing is deleted, so no question needed).
// targetId: which backup target (default: the first one).
2026-11-12 14:03:53 +01:00
// opts.roots: other projects folders than the shown ones (automatic backup: all of them);
// opts.auto: started by the schedule (lib/scheduler.js), shown as such in the UI.
function check(scope = null, autoCopy = false, targetId = null, opts = {}) {
2026-11-12 09:32:23 +01:00
if (busy()) return false
const cfg = config(targetId)
2026-11-12 14:03:53 +01:00
const items = itemsFor(cfg.t, scope, opts.roots?.length ? opts.roots : roots)
2026-11-12 09:32:23 +01:00
job = { scope, items }
2026-11-12 14:03:53 +01:00
Object.assign(state, { phase: 'checking', target: cfg.t.id, scope: scope ? keyOf(scope.root, scope.folder) : null, autoCopy, auto: !!opts.auto, error: null, check: null, progress: null })
2026-11-12 09:32:23 +01:00
run(async () => {
const share = path.dirname(cfg.t.path)
if (!fs.existsSync(cfg.t.path) && !fs.existsSync(share)) throw new Error(`Backup-Ziel „${cfg.t.name}“ nicht erreichbar: ${cfg.t.path} – Laufwerk/NAS angeschlossen und eingeschaltet?`)
const newF = { n: 0, b: 0 }, changed = { n: 0, b: 0 }, extra = { n: 0, b: 0 }
const perProject = new Map()
for (const it of items) {
if (!fs.existsSync(it.source)) throw new Error(`Projektordner fehlt: ${it.source}`)
fs.mkdirSync(it.target, { recursive: true })
const checkLog = path.join(logDir, `pruefung-${stamp()}-${cfg.t.id}${slug(scope?.folder ?? (items.length > 1 ? path.basename(it.root) : ''))}.log`)
const src = it.source
const rc = await robocopy([src, it.target, ...baseArgs(cfg, it.xd), '/L', '/X', '/NJH', '/NJS', '/NDL', '/NP', '/FP', '/BYTES'], checkLog, (line) => {
2026-11-12 09:32:23 +01:00
const p = parseLine(line)
if (!p) return
if (p.cls.includes('EXTRA')) { extra.n++; extra.b += p.size; return }
if (!p.file.toLowerCase().startsWith(src.toLowerCase())) return
const bucket = /^(Neue Datei|New File)$/i.test(p.cls) ? newF : changed
bucket.n++; bucket.b += p.size
// group by project (all) or by top-level folder inside the project (one project)
const rel = p.file.slice(src.length).replace(/^\\/, '')
const key = scope
? (rel.includes('\\') ? rel.split('\\')[0] : '(Projektordner)')
: rel.includes('\\') ? keyOf(it.root, rel.split('\\')[0]) : rel
const e = perProject.get(key) ?? { name: key, files: 0, bytes: 0 }
e.files++; e.bytes += p.size
perProject.set(key, e)
})
if (state.phase === 'cancelled') return
if (rc >= 8) throw new Error(`Prüfung fehlgeschlagen (robocopy ${rc})`)
}
state.check = {
at: new Date().toISOString(), scope: state.scope,
source: items.map((i) => i.source).join(' + '), target: items.map((i) => i.target).join(' + '),
files: newF.n + changed.n, bytes: newF.b + changed.b,
newFiles: newF.n, newBytes: newF.b, changedFiles: changed.n, changedBytes: changed.b,
extraFiles: extra.n, extraBytes: extra.b,
projects: [...perProject.values()].sort((a, b) => b.bytes - a.bytes),
}
state.phase = 'ready'
if (autoCopy) {
if (state.check.files) startCopy()
else { for (const it of items) record(cfg.t, it.root, scope?.folder, 0, 0, 0, null); state.phase = 'done' } // already complete
}
})
return true
}
function copy() {
if (busy() || state.phase !== 'ready' || !state.check || !job) return false
startCopy()
return true
}
function startCopy() {
const cfg = config(state.target)
const c = state.check
const { scope, items } = job
Object.assign(state, { phase: 'copying', error: null, progress: { files: 0, filesTotal: c.files, bytes: 0, bytesTotal: c.bytes, current: '' } })
run(async () => {
const problems = []
for (const it of items) {
const log = path.join(logDir, `backup-${stamp()}-${cfg.t.id}${slug(scope?.folder ?? (items.length > 1 ? path.basename(it.root) : ''))}.log`)
const failed = new Set() // project folders with copy errors
const before = { files: state.progress.files, bytes: state.progress.bytes }
const rc = await robocopy([it.source, it.target, ...baseArgs(cfg, it.xd), '/MT:16', '/NJH', '/NDL', '/NP', '/FP', '/BYTES'], log, (line) => {
2026-11-12 09:32:23 +01:00
const err = line.match(ERR_RE)
if (err) { const pr = projectOfPath(err[1].trim(), it.source, it.target, scope?.folder); if (pr) failed.add(pr); return }
const p = parseLine(line)
if (!p || p.cls.includes('EXTRA')) return
state.progress.files++
state.progress.bytes += p.size
state.progress.current = p.file.slice(it.source.length + 1)
})
if (state.phase === 'cancelled') return
record(cfg.t, it.root, scope?.folder, state.progress.files - before.files, state.progress.bytes - before.bytes, rc, log, [...failed])
if (rc >= 8) problems.push({ rc, log, failed: [...failed].map((f) => keyOf(it.root, f)) })
}
if (problems.length) {
const failed = problems.flatMap((p) => p.failed)
const which = failed.length ? ` Betroffen: ${failed.slice(0, 5).join(', ')}${failed.length > 5 ? ' …' : ''} – alle anderen Projekte sind gesichert.` : ''
throw new Error(`Backup unvollständig (robocopy ${problems[0].rc}).${which} Protokoll: ${problems.map((p) => p.log).join(', ')}`)
}
state.phase = 'done'
state.check = null
})
}
function record(t, root, folder, files, bytes, rc, log, failed = []) {
const d = dataFor(t, root)
const entry = { at: new Date().toISOString(), files, bytes, rc, log, ok: rc < 8 }
if (rc >= 8) entry.failed = failed
if (folder) d.lastByProject[folder] = entry
else d.last = entry
save()
}
function cancel() {
if (!busy()) return false
state.phase = 'cancelled'
try { child?.kill() } catch {}
return true
}
// When the dashboard stops (window closed), don't leave robocopy running orphaned.
process.on('exit', () => { try { child?.kill() } catch {} })
function run(fn) {
fn().catch((e) => { state.phase = 'error'; state.error = String(e.message ?? e) })
}
// Last time a project (root + folder) was backed up to a target (default: the first one):
// its own backup or the last full one of its projects folder, whichever is newer.
function lastFor(root, folder, targetId) {
const t = targetById(targetId) ?? targets()[0]
if (!t) return null
const d = dataFor(t, root)
const own = d.lastByProject[folder]
// an incomplete full backup still counts for every project that had no errors
let full = null
if (d.last?.ok) full = { at: d.last.at, ok: true, how: 'Komplett-Backup' }
else if (d.last) {
if (!Array.isArray(d.last.failed) && d.last.log) d.last.failed = failedFromLog(d.last.log, root, destOf(t, root)) ?? undefined
if (Array.isArray(d.last.failed)) {
2026-11-12 20:23:53 +01:00
// failed lists top-level folders; a project in a subfolder counts by its top folder
full = d.last.failed.includes(folder) || d.last.failed.includes(folder.split(path.sep)[0])
2026-11-12 09:32:23 +01:00
? { at: d.last.at, ok: false, how: 'Komplett-Backup – Fehler in diesem Projekt' }
: { at: d.last.at, ok: true, how: 'Komplett-Backup' }
}
}
if (own && (!full || own.at > full.at)) return { ...own, how: 'Projekt' }
return full
}
// One project on every target: [{ id, name, last }]
function lastOnAllTargets(root, folder) {
return targets().map((t) => ({ id: t.id, name: t.name, last: lastFor(root, folder, t.id) }))
}
// "Last full backup" of a target over all shown folders: the oldest of them
// (none if one folder was never backed up there), files/bytes added up.
function combinedLast(t) {
const lasts = roots.map((r) => dataFor(t, r).last)
if (!lasts.length || lasts.some((l) => !l)) return null
if (lasts.length === 1) return lasts[0]
const oldest = lasts.reduce((a, b) => (a.at < b.at ? a : b))
return {
...oldest,
files: lasts.reduce((a, l) => a + (l.files ?? 0), 0),
bytes: lasts.reduce((a, l) => a + (l.bytes ?? 0), 0),
ok: lasts.every((l) => l.ok),
}
}
function getState() {
const list = targets().map((t) => {
// per-project entries, keyed like the projects in the UI
const lastByProject = {}
for (const r of roots) for (const [folder, e] of Object.entries(dataFor(t, r).lastByProject)) lastByProject[keyOf(r, folder)] = e
return { id: t.id, name: t.name, path: roots.map((r) => destOf(t, r)).join(' + ') || t.path, short: settings.targetName(t.path), last: combinedLast(t), lastByProject }
})
if (!list.length) return { ...state, targets: [], configError: 'Kein Backup-Ziel eingerichtet – in den Einstellungen (⚙) festlegen.', notConfigured: true }
return { ...state, source: roots.join(' + '), targets: list }
}
module.exports = { init, check, copy, cancel, getState, lastFor, lastOnAllTargets, busy, limitTo }