// User settings: which folder holds the projects and where backups go. // Stored in \settings.json. DATA is DASHBOARD_DATA (set by the portable // exe: %LOCALAPPDATA%\ProjectDashboard\data) or, when run from source, the // app's own .cache folder. // // Michi's setup (app inside \_Tools\ProjectDashboard) needs no // settings file: the projects folder is two levels up and the backup settings // come from \_Tools\Backup\backup-config.json, which is also kept in // sync on save because backup-projekte.bat reads it. const fs = require('fs') const path = require('path') const APP_DIR = path.join(__dirname, '..') const DATA_DIR = process.env.DASHBOARD_DATA ? path.resolve(process.env.DASHBOARD_DATA) : path.join(APP_DIR, '.cache', process.env.DASHBOARD_ROOT ? 'test' : '') // test instances never touch real data const FILE = path.join(DATA_DIR, 'settings.json') // ".bin": build output (e.g. tests\.bin) – WD MyCloud shares hide folders with that name, so it can't be backed up there anyway const DEFAULT_EXCLUDE_DIRS = ['node_modules', '__pycache__', '.gradle', '.venv', 'venv', '.venv-tts', '.bin'] const DEFAULT_EXCLUDE_FILES = ['Thumbs.db', 'desktop.ini', '~$*'] // \_Tools\ProjectDashboard → X function devRoot() { const parent = path.dirname(APP_DIR) return path.basename(parent).toLowerCase() === '_tools' ? path.dirname(parent) : '' } const legacyBackupFile = (root) => (root ? path.join(root, '_Tools', 'Backup', 'backup-config.json') : '') function readJson(file) { // strip a BOM (PowerShell's "Out-File -Encoding utf8" writes one) try { return JSON.parse(fs.readFileSync(file, 'utf-8').replace(/^/, '')) } catch { return null } } // short display name: "MYCLOUD-NESYFV" for \\MYCLOUD-NESYFV\..., "E: Backup" for E:\Backup function targetName(t) { const unc = t.match(/^\\\\([^\\]+)/) if (unc) return unc[1] const drive = t.match(/^([A-Za-z]:)/) return drive ? `${drive[1]} ${path.basename(t)}`.trim() : path.basename(t) } const newId = () => Math.random().toString(36).slice(2, 10) // one path (older settings / backup-config.json) -> target list const targetsFrom = (p) => (p ? [{ id: 'main', name: targetName(p), path: p }] : []) // Projects folders ("roots"): several can be registered, one is active at a time. // Display name: folder name, "D:" for a drive root. const rootName = (p) => path.basename(p) || p.replace(/[\\/]+$/, '') const rootsFrom = (p) => (p ? [{ id: 'main', name: rootName(p), path: p }] : []) const MAX_ROOTS = 30 const samePath = (a, b) => path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() const inside = (child, parent) => path.resolve(child).toLowerCase().startsWith(path.resolve(parent).toLowerCase().replace(/[\\/]+$/, '') + path.sep) function defaults() { const root = process.env.DASHBOARD_ROOT ? path.resolve(process.env.DASHBOARD_ROOT) : devRoot() const legacy = readJson(legacyBackupFile(root)) return { roots: rootsFrom(root), projectsRoot: root, // public itch.io profile ("veröffentlicht" on the cards); Michi's setup knows his itchProfile: devRoot() && !process.env.DASHBOARD_ROOT ? 'https://sn09.itch.io' : '', backup: { // several targets possible (NAS, USB disk, ...); each has its own backup state targets: Array.isArray(legacy?.targets) ? legacy.targets : targetsFrom(legacy?.target ?? ''), excludeDirs: legacy?.excludeDirs ?? DEFAULT_EXCLUDE_DIRS, excludeFiles: legacy?.excludeFiles ?? DEFAULT_EXCLUDE_FILES, // "Backup fällig": changed since the last backup and that is older than this remindDays: 7, auto: { ...AUTO_DEFAULT }, }, } } // Automatic backup (lib/scheduler.js): interval off | start | hourly | daily | weekly, // time "HH:MM" (daily/weekly), weekday 0=So … 6=Sa (weekly), target 'all' or a target id. const AUTO_DEFAULT = { interval: 'off', time: '20:00', weekday: 5, target: 'all' } function cleanAuto(a, old) { const o = { ...AUTO_DEFAULT, ...(old ?? {}) } if (!a || typeof a !== 'object') return o if (['off', 'start', 'hourly', 'daily', 'weekly'].includes(a.interval)) o.interval = a.interval if (typeof a.time === 'string' && /^([01]\d|2[0-3]):[0-5]\d$/.test(a.time)) o.time = a.time if (Number.isInteger(+a.weekday) && +a.weekday >= 0 && +a.weekday <= 6) o.weekday = +a.weekday if (typeof a.target === 'string' && a.target) o.target = a.target return o } let current = null // Optional features, switched in Einstellungen → Allgemein. itch.io: without a stored // choice it is on when an itch.io profile is set (older settings), else off. function featuresFrom(f, itchProfile) { return { itch: typeof f?.itch === 'boolean' ? f.itch : !!(itchProfile ?? '').trim() } } const itchOn = (s = get()) => !!s.features?.itch // projects in subfolders: { nested: chosen relative paths, nestedIgnored: seen, not chosen } function nestedOf(r) { const list = (v) => (Array.isArray(v) ? [...new Set(v.filter((x) => typeof x === 'string' && x && !x.split(/[\\/]/).includes('..')))].slice(0, 200) : []) return { nested: list(r?.nested), nestedIgnored: list(r?.nestedIgnored) } } // Stores the scanner's choice for one projects folder (paths already checked by lib/nested.js). function setNested(rootId, chosen, ignored) { const s = get() const roots = s.roots.map((r) => (r.id === rootId ? { ...r, ...nestedOf({ nested: chosen, nestedIgnored: ignored }) } : r)) current = { ...s, roots } persist(current) return current } function load() { const d = defaults() const saved = process.env.DASHBOARD_ROOT && !process.env.DASHBOARD_DATA ? null : readJson(FILE) const backup = { ...d.backup, ...(saved?.backup ?? {}) } if (!Array.isArray(saved?.backup?.targets) && typeof saved?.backup?.target === 'string') backup.targets = targetsFrom(saved.backup.target) delete backup.target backup.auto = cleanAuto(saved?.backup?.auto) // older settings had one "projectsRoot" let roots = Array.isArray(saved?.roots) ? saved.roots.filter((r) => r && typeof r.path === 'string' && r.path).map((r) => ({ id: String(r.id || newId()), name: String(r.name || rootName(r.path)), path: r.path, ...nestedOf(r) })) : typeof saved?.projectsRoot === 'string' ? rootsFrom(saved.projectsRoot) : d.roots // an explicit DASHBOARD_ROOT always wins (tests) if (process.env.DASHBOARD_ROOT) { const envPath = path.resolve(process.env.DASHBOARD_ROOT) roots = [{ id: 'env', name: rootName(envPath), path: envPath, ...nestedOf(roots.find((r) => samePath(r.path, envPath))) }] } current = withActive({ roots, activeRoots: Array.isArray(saved?.activeRoots) ? saved.activeRoots : [saved?.activeRoot], noneShown: saved?.noneShown === true, itchProfile: typeof saved?.itchProfile === 'string' ? saved.itchProfile : d.itchProfile, features: featuresFrom(saved?.features, typeof saved?.itchProfile === 'string' ? saved.itchProfile : d.itchProfile), backup, }) return current } // Several folders can be shown at once: activeRoots = the selected ids (in list // order, at least one). activeRoot = the first of them, projectsRoot = its path. function withActive(s) { const want = new Set((s.activeRoots ?? [s.activeRoot]).filter(Boolean)) let active = s.roots.filter((r) => want.has(r.id)) // noneShown: deliberately no folder shown (empty dashboard); else at least the first if (s.noneShown) active = [] else if (!active.length && s.roots[0]) active = [s.roots[0]] const { activeRoot: _, ...rest } = s return { ...rest, activeRoots: active.map((r) => r.id), activeRoot: active[0]?.id ?? '', projectsRoot: active[0]?.path ?? '' } } // the selected folders [{ id, name, path }] function activeRootList(s = get()) { return s.roots.filter((r) => s.activeRoots.includes(r.id)) } // What is written to settings.json (activeRoot/projectsRoot are derived, not stored). function persist(next) { const { projectsRoot, activeRoot, ...stored } = next fs.mkdirSync(DATA_DIR, { recursive: true }) fs.writeFileSync(FILE, JSON.stringify(stored, null, 2)) } // Backups of several projects folders share the targets: the first folder goes // straight into the target (as before), the others into a subfolder - their path // below the first folder if they lie inside it, else their folder name. function backupSubdir(rootPath, s = get()) { const first = s.roots[0]?.path if (!first || !rootPath || samePath(rootPath, first)) return '' if (inside(rootPath, first)) return path.relative(path.resolve(first), path.resolve(rootPath)) return rootName(path.resolve(rootPath)).replace(/[:\\/]/g, '') || 'Projekte' } function get() { return current ?? load() } function isDir(p) { try { return fs.statSync(p).isDirectory() } catch { return false } } function configured() { const s = get() return !!s.projectsRoot && isDir(s.projectsRoot) } const cleanList = (v, fallback) => Array.isArray(v) ? [...new Set(v.map((x) => String(x).trim()).filter(Boolean))].slice(0, 50) : fallback // Validates and stores new settings. Throws with a German message on bad input. function save(input) { const s = get() // path.resolve normalises ("D:\x\" → "D:\x") but keeps drive roots intact ("E:\") const norm = (v) => (v.trim() ? path.resolve(v.trim().replace(/^"(.*)"$/, '$1')) : '') let roots = s.roots let activeRoots = Array.isArray(input.activeRoots) ? input.activeRoots.map(String) : typeof input.activeRoot === 'string' ? [input.activeRoot] : s.activeRoots let activeRoot = activeRoots[0] // only for the old single-folder form below if (Array.isArray(input.roots)) { const renamed = new Map() roots = [] for (const r of input.roots.slice(0, MAX_ROOTS)) { const p = typeof r?.path === 'string' ? norm(r.path) : '' if (!p) continue if (!isDir(p)) throw new Error(`Projektordner existiert nicht: ${p}`) if (roots.some((x) => samePath(x.path, p))) throw new Error(`Projektordner doppelt: ${p}`) const old = s.roots.find((x) => x.id === r.id) roots.push({ id: old && samePath(old.path, p) ? old.id : newId(), name: String(r.name ?? '').trim().slice(0, 40) || rootName(p), path: p, // projects in subfolders (chosen in the scanner) stay with the folder ...nestedOf(old && samePath(old.path, p) ? old : s.roots.find((x) => samePath(x.path, p))), }) // a selected folder stays selected even if its path (and so its id) changed if (r.id) renamed.set(String(r.id), roots.at(-1).id) } if (!roots.length) throw new Error('Mindestens ein Projektordner ist nötig.') activeRoots = activeRoots.map((id) => renamed.get(id)).filter(Boolean) } else if (typeof input.projectsRoot === 'string') { // old single-folder form: replaces the active folder const p = norm(input.projectsRoot) if (!p || !isDir(p)) throw new Error('Der Projektordner existiert nicht.') const i = Math.max(0, roots.findIndex((r) => r.id === activeRoot)) const existing = roots.find((r) => samePath(r.path, p)) if (existing) activeRoots = [existing.id] else { roots = roots.slice() roots[i] = { id: newId(), name: rootName(p), path: p } activeRoots = [roots[i].id] } } // "no folder shown" stays until a folder is chosen again const noneShown = !!s.noneShown && !(Array.isArray(input.activeRoots) && input.activeRoots.length) const sel = withActive({ roots, activeRoots, noneShown }) const projectsRoot = sel.projectsRoot || (noneShown ? roots[0]?.path : '') if (!projectsRoot || !isDir(projectsRoot)) throw new Error('Der Projektordner existiert nicht.') let targets = s.backup.targets if (Array.isArray(input.targets)) { targets = [] const seen = new Set() for (const t of input.targets.slice(0, 10)) { const p = typeof t?.path === 'string' ? norm(t.path) : '' if (!p) continue const a = p.toLowerCase() if (seen.has(a)) throw new Error(`Backup-Ziel doppelt: ${p}`) seen.add(a) if (fs.existsSync(p) && !isDir(p)) throw new Error(`Backup-Ziel ist eine Datei, kein Ordner: ${p}`) if (!isDir(p) && !isDir(path.dirname(p))) throw new Error(`Backup-Ziel nicht erreichbar (Laufwerk/NAS angeschlossen?): ${p}`) const old = s.backup.targets.find((x) => x.id === t.id) targets.push({ // a changed path is a new target (its backup state starts fresh) id: old && old.path.toLowerCase() === a ? old.id : newId(), name: String(t.name ?? '').trim().slice(0, 40) || targetName(p), path: p, }) } } else if (typeof input.backupTarget === 'string') { targets = targetsFrom(norm(input.backupTarget)) // old single-target form } // checked for every save, so a newly added projects folder can't hold a backup target either for (const t of targets) { const clash = roots.find((r) => samePath(t.path, r.path) || inside(t.path, r.path) || inside(r.path, t.path)) if (clash) throw new Error(`Das Backup-Ziel darf nicht in einem Projektordner liegen (und keinen enthalten): ${t.path} ↔ ${clash.path}`) } let itchProfile = s.itchProfile ?? '' if (typeof input.itchProfile === 'string') { const v = input.itchProfile.trim().replace(/\/+$/, '') // "sn09" or "sn09.itch.io" is enough itchProfile = !v ? '' : /^https?:\/\//i.test(v) ? v : `https://${v.includes('.') ? v : `${v}.itch.io`}` if (itchProfile && !/^https:\/\/[a-z0-9-]+\.itch\.io$/i.test(itchProfile)) throw new Error('itch.io-Profil: z. B. https://name.itch.io') } const next = withActive({ roots, activeRoots: sel.activeRoots, noneShown, itchProfile, features: { ...(s.features ?? featuresFrom(null, itchProfile)), ...(typeof input.features?.itch === 'boolean' ? { itch: input.features.itch } : {}) }, backup: { targets, excludeDirs: cleanList(input.excludeDirs, s.backup.excludeDirs), excludeFiles: cleanList(input.excludeFiles, s.backup.excludeFiles), remindDays: Number.isFinite(+input.remindDays) && +input.remindDays >= 1 ? Math.min(365, Math.round(+input.remindDays)) : (s.backup.remindDays ?? 7), auto: cleanAuto(input.auto, s.backup.auto), }, }) // an automatic backup to a target that was removed falls back to all targets if (next.backup.auto.target !== 'all' && !targets.some((t) => t.id === next.backup.auto.target)) next.backup.auto.target = 'all' persist(next) // keep backup-projekte.bat in sync where it exists (it backs up the first folder to the first target) const legacy = legacyBackupFile(roots[0].path) if (legacy && fs.existsSync(legacy)) { fs.writeFileSync(legacy, JSON.stringify({ source: roots[0].path, target: targets[0]?.path ?? '', targets, excludeDirs: next.backup.excludeDirs, excludeFiles: next.backup.excludeFiles }, null, 2) + '\n') } current = next return current } // Quick switch (dropdown next to the logo): which folders are shown (one id or a list). function setActive(ids) { const s = get() const list = (Array.isArray(ids) ? ids : [ids]).map(String) const sel = s.roots.filter((x) => list.includes(x.id)) // [] = show no folder at all (empty dashboard, chosen in the dropdown) if (!list.filter(Boolean).length) { current = withActive({ ...s, activeRoots: [], noneShown: true }) persist(current) return current } if (!sel.length) throw new Error('Projektordner nicht gefunden.') const gone = sel.find((r) => !isDir(r.path)) if (gone) throw new Error(`Projektordner nicht erreichbar: ${gone.path}`) current = withActive({ ...s, activeRoots: sel.map((r) => r.id), noneShown: false }) persist(current) return current } // Adds projects folders (dropdown "Ordner hinzufügen" / "Mehrere einlesen"); // folders already in the list are skipped. activate: show (only) the new ones. function addRoots(paths, activate = false) { const s = get() const fresh = (Array.isArray(paths) ? paths : []) .filter((p) => typeof p === 'string' && p.trim()) .filter((p, i, all) => !s.roots.some((r) => samePath(r.path, p)) && all.findIndex((q) => samePath(q, p)) === i) if (!fresh.length) return { settings: s, added: [] } const before = new Set(s.roots.map((r) => r.id)) const next = save({ roots: [...s.roots, ...fresh.map((p) => ({ id: '', name: '', path: p }))] }) const added = next.roots.filter((r) => !before.has(r.id)) return { settings: activate && added[0] ? setActive(added.map((r) => r.id)) : next, added } } // Direct subfolders of a folder (for "Mehrere einlesen"), with how many folders each holds. function subfolders(dir) { const p = typeof dir === 'string' && dir.trim() ? path.resolve(dir.trim().replace(/^"(.*)"$/, '$1')) : '' if (!p || !isDir(p)) throw new Error('Ordner existiert nicht.') const skip = new Set(['$recycle.bin', 'system volume information', 'recovery', 'config.msi', 'node_modules']) const list = fs.readdirSync(p, { withFileTypes: true }) .filter((e) => e.isDirectory() && !e.name.startsWith('.') && !skip.has(e.name.toLowerCase())) .map((e) => { const full = path.join(p, e.name) let count = 0 try { count = fs.readdirSync(full, { withFileTypes: true }).filter((x) => x.isDirectory() && !x.name.startsWith('.')).length } catch {} return { name: e.name, path: full, count } }) .sort((a, b) => a.name.localeCompare(b.name, 'de')) return { path: p, folders: list.slice(0, 200) } } // The persisted shape (what settings.json holds; derived fields stripped) – for "Export settings". function exportData() { const { projectsRoot, activeRoot, ...stored } = get() return stored } // Overwrites settings.json with an imported object and reloads. load() is tolerant and fills gaps. function importData(obj) { if (!obj || typeof obj !== 'object' || Array.isArray(obj)) throw new Error('Ungültige Einstellungsdatei.') fs.mkdirSync(DATA_DIR, { recursive: true }) fs.writeFileSync(FILE, JSON.stringify(obj, null, 2)) current = null return load() } // Backs up settings.json (timestamped) and removes it, so the next load starts as a new user. function reset() { let backupFile = '' try { if (fs.existsSync(FILE)) { const ts = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19) backupFile = path.join(DATA_DIR, `settings-backup-${ts}.json`) fs.copyFileSync(FILE, backupFile) fs.rmSync(FILE, { force: true }) } } catch (e) { throw new Error(`Zurücksetzen fehlgeschlagen: ${e.message ?? e}`) } current = null load() return { backupFile } } module.exports = { setNested, itchOn, get, load, save, setActive, addRoots, activeRootList, subfolders, backupSubdir, configured, targetName, DATA_DIR, APP_DIR, DEFAULT_EXCLUDE_DIRS, exportData, importData, reset }