-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
707 lines (619 loc) · 24 KB
/
server.js
File metadata and controls
707 lines (619 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
import express from "express";
import http from "http";
import { WebSocketServer } from "ws";
import bodyParser from "body-parser";
import path from "path";
import { fileURLToPath } from "url";
import cookieParser from "cookie-parser";
import { listTree } from "./lib/fileTree.js";
import { loadConfigs, saveConfig, deleteConfig, getConfigById } from "./lib/configStore.js";
import { enqueueSync, getCurrentStatus, cancelSync, resetSync, getQueue, removeFromQueue, reorderQueue, pauseSync, resumeSync } from "./lib/syncEngine.js";
import { loadPlans, addPlan, deletePlan } from "./lib/planStore.js";
import { initAuth, authenticate, verifyToken, changePassword, logout } from "./lib/auth.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server, path: "/ws" });
// Global console wrapper to include caller filename
(() => {
const original = { log: console.log, warn: console.warn, error: console.error };
function getCallerFile() {
const err = new Error();
const stack = String(err.stack || '').split('\n');
// stack[0] = Error, stack[1] = here, stack[2] = caller
for (let i = 2; i < stack.length; i++) {
const m = stack[i].match(/\((.*?):\d+:\d+\)/) || stack[i].match(/at (.*?):\d+:\d+/);
if (m && m[1]) {
const p = m[1].replace(/\\/g, '/');
return p.split('/').pop();
}
}
return 'server.js';
}
function format(prefixArgs, args) {
const ts = new Date().toISOString();
const file = getCallerFile();
return [`[${ts}] [${file}]`, ...prefixArgs, ...args];
}
console.log = (...args) => original.log.apply(console, format([], args));
console.warn = (...args) => original.warn.apply(console, format([], args));
console.error = (...args) => original.error.apply(console, format([], args));
})();
app.use(bodyParser.json());
app.use(cookieParser());
// Serve all static files without authentication
app.use(express.static(path.join(__dirname, "public"), {
index: false, // Don't serve index.html automatically
dotfiles: 'ignore'
}));
// Auth middleware for protected routes
function requireAuth(req, res, next) {
const token = req.cookies?.authToken;
if (!token || !verifyToken(token)) {
return res.redirect('/login');
}
next();
}
// Login page (no auth required)
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, "public", "login.html"));
});
// Redirect root to home if authenticated
app.get('/', (req, res) => {
const token = req.cookies?.authToken;
if (token && verifyToken(token)) {
return res.redirect('/home');
}
return res.redirect('/login');
});
// Also protect /home route
app.get('/home', requireAuth, (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
// ---- In-memory chart history (persists across browser refresh, resets on new job/reset)
const chartHistory = {
startedAt: null,
points: [], // { tSec, speedBps, processedBytes, totalBytes }
pausedAt: null,
pausedTotalMs: 0,
};
// Track last job name to enrich status for clients after refresh
let lastJobName = null;
function clearChartHistory() {
chartHistory.startedAt = null;
chartHistory.points.length = 0;
chartHistory.pausedAt = null;
chartHistory.pausedTotalMs = 0;
}
const clients = new Set();
let statusSeq = 0; // Monotonic sequence for status messages
wss.on("connection", (ws) => {
clients.add(ws);
const s = getCurrentStatus();
const sanitized = s ? { ...s } : s;
if (sanitized && Array.isArray(sanitized.skippedFiles) && sanitized.skippedFiles.length > 100) {
sanitized.skippedFiles = sanitized.skippedFiles.slice(-100);
}
// Include lastJobName so UI can reflect active job after refresh (esp. for planned jobs)
ws.send(JSON.stringify({ type: "status", data: { ...sanitized, jobName: lastJobName, seq: ++statusSeq } }));
ws.on("close", () => clients.delete(ws));
});
function broadcast(status) {
// Record chart history points when we have a startedAt timestamp
if (status && status.startedAt) {
// New run detected? Reset history so tSec starts at 0 for each job
if (!chartHistory.startedAt || chartHistory.startedAt !== status.startedAt) {
clearChartHistory();
chartHistory.startedAt = status.startedAt;
}
// Track pause windows to exclude from elapsed seconds
if (status.phase === 'paused') {
if (!chartHistory.pausedAt) chartHistory.pausedAt = Date.now();
// Don't push points while paused to keep a clean time axis
} else {
if (chartHistory.pausedAt) {
chartHistory.pausedTotalMs += Math.max(0, Date.now() - chartHistory.pausedAt);
chartHistory.pausedAt = null;
}
const effectivePausedMs = chartHistory.pausedTotalMs;
const tSec = Math.max(0, (Date.now() - chartHistory.startedAt - effectivePausedMs) / 1000);
chartHistory.points.push({
tSec,
speedBps: status.speedBps || 0,
processedBytes: status.processedBytes || 0,
totalBytes: status.totalBytes || 0
});
// Cap points for memory safety (keep ~200k)
if (chartHistory.points.length > 200000) chartHistory.points.splice(0, chartHistory.points.length - 200000);
}
}
// Enrich status with last job name for clients (used for UI after refresh)
let enriched = status ? { ...status, jobName: lastJobName, seq: ++statusSeq } : status;
// Sanitize large fields for WS to avoid OOM (keep tail only)
if (enriched && Array.isArray(enriched.skippedFiles) && enriched.skippedFiles.length > 100) {
enriched = { ...enriched, skippedFiles: enriched.skippedFiles.slice(-100) };
}
const msg = JSON.stringify({ type: "status", data: enriched });
for (const c of clients) {
if (c.readyState === 1) c.send(msg);
}
}
function broadcastLog(message, data = {}) {
const payload = { type: "log", data: { message, file: 'server.js', ...data, ts: Date.now() } };
const msg = JSON.stringify(payload);
for (const c of clients) {
if (c.readyState === 1) c.send(msg);
}
}
function logSync(message, data = {}) {
console.log(message, Object.keys(data).length ? data : '');
}
// Initialize authentication
await initAuth();
// Auth middleware for protected API routes
app.use('/api', (req, res, next) => {
// Skip auth for login and logout routes
if (req.path === '/auth/login' || req.path === '/auth/logout') {
return next();
}
// Check authentication for all other API routes
const token = req.cookies?.authToken;
if (!token || !verifyToken(token)) {
return res.status(401).json({ error: 'Authentication required' });
}
next();
});
// --- AUTH API ---
app.post("/api/auth/login", async (req, res) => {
const { password } = req.body;
if (!password) {
return res.status(400).json({ error: 'Password required' });
}
const result = await authenticate(password);
if (result.success) {
res.cookie('authToken', result.token, {
httpOnly: true,
secure: false, // Set to true in production with HTTPS
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days
});
res.json({ success: true, token: result.token });
} else {
res.status(401).json({ error: result.error });
}
});
app.post("/api/auth/logout", async (req, res) => {
const token = req.cookies?.authToken;
await logout(token);
res.clearCookie('authToken');
res.json({ success: true });
});
app.post("/api/auth/change-password", async (req, res) => {
const { currentPassword, newPassword } = req.body;
if (!currentPassword || !newPassword) {
return res.status(400).json({ error: 'Current and new password required' });
}
const result = await changePassword(currentPassword, newPassword);
if (result.success) {
// Clear all sessions after password change
res.clearCookie('authToken');
res.json({ success: true });
} else {
res.status(400).json({ error: result.error });
}
});
// --- API ---
app.get("/api/configs", async (_, res) => {
const configs = await loadConfigs();
res.json(configs);
});
app.post("/api/configs", async (req, res) => {
const cfg = req.body;
if (!cfg.name || !cfg.pathA || !cfg.pathB) return res.status(400).json({ error: "Name, pathA und pathB sind erforderlich" });
const saved = await saveConfig(cfg);
const all = await loadConfigs();
logSync("💾 Config saved", { id: saved.id, name: saved.name });
res.json(all);
});
app.delete("/api/configs/:id", async (req, res) => {
await deleteConfig(req.params.id);
const all = await loadConfigs();
logSync("🗑️ Config deleted", { id: req.params.id });
res.json(all);
});
app.get("/api/tree", async (req, res) => {
let p = req.query.path;
const rawLimit = Number(req.query.limit);
if (!p || typeof p !== 'string') {
return res.status(400).json({ error: 'Pfad erforderlich' });
}
// Pfadvalidierung abhängig vom Server-OS
const isWin = process.platform === 'win32';
if (isWin) {
// Erlaube "C:" → "C:\" Normalisierung
if (/^[A-Za-z]:$/.test(p)) p = p + '\\';
if (!/^[A-Za-z]:[\\\/]/.test(p)) {
return res.status(400).json({ error: 'Ungültiger Pfad. Erwartet absoluten Windows-Pfad wie C:\\ oder D:/.' });
}
} else {
// Auf Linux/Mac nur absolute POSIX-Pfade erlauben
if (/^[A-Za-z]:/.test(p)) {
return res.status(400).json({ error: 'Windows-Pfade werden auf diesem Server nicht unterstützt.' });
}
if (!p.startsWith('/')) {
return res.status(400).json({ error: 'Ungültiger Pfad. Erwartet absoluten Pfad beginnend mit /.' });
}
}
// sinnvolle Grenzen für sehr große Verzeichnisse
const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 100), 10000) : 2000;
const treeFull = await listTree(p);
const total = Array.isArray(treeFull) ? treeFull.length : 0;
const tree = total > limit ? treeFull.slice(0, limit) : treeFull;
const truncated = total > limit;
logSync("📂 Tree loaded", { path: p, total, served: tree.length, truncated });
res.json({ root: path.basename(p) || p, tree, total, truncated, limit });
});
app.get("/api/download", async (req, res) => {
const filePath = req.query.path;
if (!filePath) {
return res.status(400).json({ error: "Pfad erforderlich" });
}
try {
const fs = await import('fs');
const stats = await fs.promises.stat(filePath);
if (!stats.isFile()) {
return res.status(400).json({ error: "Nur Dateien können heruntergeladen werden" });
}
const fileName = path.basename(filePath);
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
res.setHeader('Content-Type', 'application/octet-stream');
const fileStream = fs.createReadStream(filePath);
fileStream.pipe(res);
logSync("⬇️ Download gestartet", { file: fileName, path: filePath });
} catch (error) {
console.error("Download error:", error);
res.status(404).json({ error: "Datei nicht gefunden" });
}
});
app.get("/api/status", (_, res) => res.json(getCurrentStatus()));
app.post("/api/sync/start", async (req, res) => {
const { configId, direction } = req.body;
console.log("SYNC START REQUEST", req.body);
const cfg = await getConfigById(configId);
if (!cfg) return res.status(404).json({ error: "Config nicht gefunden" });
logSync("▶️ Sync started", { job: cfg.name, direction });
// New job -> clear old chart history so charts show the new run from zero
clearChartHistory();
lastJobName = cfg.name;
// Set startedAt for new run immediately so early statuses have correct baseline
let lastPhase = null;
const seenSkipTs = new Set();
const seenCopyTs = new Set();
enqueueSync(cfg, direction, (status) => {
broadcast(status);
// Log nur bei Phasenwechsel
if (status.phase && status.phase !== lastPhase) {
lastPhase = status.phase;
const logMap = {
scanning: "🔍 Scanning started",
copying: "📥 Copy in progress",
deleting: "🗑️ Deleting in progress",
done: "✅ Sync completed",
cancelled: "🛑 Sync cancelled",
error: "⚠️ Error"
};
logSync(logMap[status.phase] || "Status update", { job: cfg.name, error: status.error });
}
// Client-Log: übersprungene Dateien melden
if (status.lastEvent && status.lastEvent.type === "skipped" && !seenSkipTs.has(status.lastEvent.ts)) {
seenSkipTs.add(status.lastEvent.ts);
const reasonMap = { source_missing: "Quelle fehlt", unchanged: "unverändert" };
const reason = reasonMap[status.lastEvent.reason] || status.lastEvent.reason || "unbekannt";
broadcastLog(`⏭️ Übersprungen: ${status.lastEvent.rel} (${reason})`, {
rel: status.lastEvent.rel,
abs: status.lastEvent.abs,
reason,
job: cfg.name
});
}
// Client-Log: Debug, Copy Start, Copy Done
if (status.lastEvent && status.lastEvent.type === "debug" && !seenCopyTs.has(status.lastEvent.ts)) {
seenCopyTs.add(status.lastEvent.ts);
broadcastLog(`🐞 ${status.lastEvent.message}`, { job: cfg.name });
}
if (status.lastEvent && status.lastEvent.type === "copy_start" && !seenCopyTs.has(status.lastEvent.ts)) {
seenCopyTs.add(status.lastEvent.ts);
broadcastLog(`➡️ Kopiere: ${status.lastEvent.rel}`, { rel: status.lastEvent.rel, src: status.lastEvent.absSrc, dst: status.lastEvent.absDst, job: cfg.name });
}
if (status.lastEvent && status.lastEvent.type === "copy_done" && !seenCopyTs.has(status.lastEvent.ts)) {
seenCopyTs.add(status.lastEvent.ts);
broadcastLog(`✅ Fertig: ${status.lastEvent.rel}`, { rel: status.lastEvent.rel, dst: status.lastEvent.absDst, job: cfg.name });
}
}).catch(console.error);
res.json({ ok: true });
});
app.post("/api/sync/cancel", (_, res) => {
logSync("🛑 Cancel request received");
cancelSync(status => broadcast(status));
res.json({ ok: true });
});
app.post("/api/sync/pause", (_, res) => {
const ok = pauseSync(status => broadcast(status));
if (ok) {
logSync("⏸️ Pause request received");
try { broadcastLog("⏸️ UI: Pause geklickt", { phase: getCurrentStatus().phase }); } catch {}
}
res.json({ ok });
});
app.post("/api/sync/resume", (_, res) => {
const ok = resumeSync(status => broadcast(status));
if (ok) {
logSync("▶️ Resume request received");
try { broadcastLog("▶️ UI: Fortsetzen geklickt", { phase: getCurrentStatus().phase }); } catch {}
}
res.json({ ok });
});
app.post("/api/sync/reset", (_, res) => {
resetSync();
clearChartHistory();
lastJobName = null;
broadcast(getCurrentStatus());
res.json({ ok: true });
});
// Optional: Queue-Status anzeigen
app.get("/api/sync/queue", (_, res) => {
res.json(getQueue());
});
// Queue: Eintrag löschen
app.delete("/api/sync/queue/:index", (req, res) => {
const ok = removeFromQueue(Number(req.params.index));
if (!ok) return res.status(400).json({ error: "Ungültiger Index" });
res.json(getQueue());
});
// Queue: Neu anordnen (Drag & Drop)
app.post("/api/sync/queue/reorder", (req, res) => {
const { from, to } = req.body || {};
const ok = reorderQueue(from, to);
if (!ok) return res.status(400).json({ error: "Ungültige Indizes" });
res.json(getQueue());
});
// ---- Chart history API ----
app.get('/api/history', (_, res) => {
res.json({ startedAt: chartHistory.startedAt, points: chartHistory.points });
});
app.post('/api/history/reset', (_, res) => {
clearChartHistory();
res.json({ ok: true });
});
// ---------------- Start / Enqueue ----------------
app.post("/api/sync/enqueue", async (req, res) => {
const { configId, direction } = req.body;
const cfg = await getConfigById(configId);
if (!cfg) return res.status(404).json({ error: "Config nicht gefunden" });
logSync("➕ Job enqueued", { job: cfg.name, direction });
let lastLog = {};
// Clear history for a new run so planned jobs also start from t=0
clearChartHistory();
enqueueSync(cfg, direction, (status) => {
broadcast(status);
const now = Date.now();
const logMap = {
scanning: "🔍 Scanning started",
copying: "📥 Copy in progress",
deleting: "🗑️ Deleting in progress",
done: "✅ Sync completed",
cancelled: "🛑 Sync cancelled",
error: "⚠️ Error"
};
const phase = status.phase || "update";
if (phase === "copying") {
if (!lastLog.copying || now - lastLog.copying > 2000) {
lastLog.copying = now;
logSync(logMap[phase], { job: cfg.name, error: status.error });
}
} else if (phase !== lastLog.phase) {
lastLog.phase = phase;
logSync(logMap[phase] || "Status update", { job: cfg.name, error: status.error });
}
}).catch(console.error);
lastJobName = cfg.name;
res.json({ ok: true });
});
server.listen(4000, () => {
const banner = [
"███████╗██████╗ ███████╗",
"██╔════╝██╔══██╗██╔════╝",
"█████╗ ██████╔╝███████╗",
"██╔══╝ ██╔══██╗╚════██║",
"██║ ██████╔╝███████║",
"╚═╝ ╚═════╝ ╚══════╝",
"== Filebackup Server =="
];
const width = Math.max(...banner.map(l => l.length));
const border = "#".repeat(width + 8);
console.log(border);
for (const line of banner) {
const pad = " ".repeat(width - line.length);
console.log(`# ${line}${pad} #`);
}
console.log(border);
console.log("Server running at http://localhost:4000");
});
// ---------------- Plans API & Scheduler ----------------
app.get('/api/plans', async (_, res) => {
const plans = await loadPlans();
res.json(plans);
});
app.post('/api/plans', async (req, res) => {
const { configId, direction, whenTs, recurrence } = req.body || {};
if (!configId || !direction || !Number.isFinite(whenTs)) {
return res.status(400).json({ error: 'configId, direction, whenTs erforderlich' });
}
const cfg = await getConfigById(configId);
if (!cfg) return res.status(404).json({ error: 'Config nicht gefunden' });
let normalizedRecurrence = { type: 'none' };
if (recurrence && typeof recurrence === 'object') {
if (recurrence.type === 'fixed' && Number.isFinite(recurrence.everyMs) && recurrence.everyMs > 0) {
normalizedRecurrence = { type: 'fixed', everyMs: Math.floor(recurrence.everyMs) };
}
}
const plan = await addPlan({ configId, configName: cfg.name, pathA: cfg.pathA, pathB: cfg.pathB, direction, whenTs, recurrence: normalizedRecurrence });
res.json(plan);
});
app.delete('/api/plans/:id', async (req, res) => {
const ok = await deletePlan(req.params.id);
if (!ok) return res.status(404).json({ error: 'Plan nicht gefunden' });
res.json({ ok: true });
});
// ---- System API ----
app.post('/api/system/restart', async (_req, res) => {
// Only support self-restart when running as plain `node server.js` (not under nodemon)
const isProbablyNodemon = Boolean(
process.env.NODEMON === 'true' ||
(process.env._ && /nodemon/i.test(process.env._)) ||
(process.env.npm_lifecycle_script && /nodemon/i.test(process.env.npm_lifecycle_script))
);
if (isProbablyNodemon) {
return res.status(400).json({ ok: false, error: 'Restart ist im Entwicklungsmodus (nodemon) deaktiviert.' });
}
const { spawn } = await import('child_process');
try {
logSync('🔁 Restart requested');
res.json({ ok: true, restarting: true });
} catch (e) {
console.error('Restart endpoint error while responding', e);
}
const reexec = () => {
try {
const nodeExec = process.execPath;
const scriptPath = process.argv[1];
const args = process.argv.slice(2);
let child;
if (process.platform === 'win32') {
// Start in SAME window using PowerShell without opening a new window
const psCmd = `Start-Process -NoNewWindow -WorkingDirectory '${process.cwd().replace(/'/g, "''")}' -FilePath '${nodeExec.replace(/'/g, "''")}' -ArgumentList '${[scriptPath, ...args].map(a=>String(a).replace(/'/g, "''")).join(' ')}'`;
child = spawn('powershell', ['-NoProfile', '-Command', psCmd], {
stdio: 'inherit',
env: { ...process.env },
shell: false,
detached: false
});
} else {
child = spawn(nodeExec, [scriptPath, ...args], {
stdio: 'inherit',
env: { ...process.env },
shell: false,
detached: false
});
}
child.on('error', (err) => console.error('Failed to spawn child for restart', err));
console.log('Re-executed process in same terminal:', nodeExec, scriptPath, args.join(' '));
} catch (e) {
console.error('Error spawning child for restart', e);
}
};
// Allow response flush, then gracefully close and re-exec
setTimeout(() => {
let exited = false;
const forceTimer = setTimeout(() => {
if (exited) return;
console.warn('Force restarting without full graceful close');
reexec();
process.exit(0);
}, 8000);
try {
server.close(() => {
if (exited) return;
exited = true;
clearTimeout(forceTimer);
// tiny delay to ensure port is truly free before re-exec
setTimeout(() => {
reexec();
process.exit(0);
}, 300);
});
} catch (e) {
console.error('Error during server.close()', e);
try { clearTimeout(forceTimer); } catch {}
reexec();
process.exit(0);
}
}, 200);
});
// ---- System Shutdown API ----
app.post('/api/system/shutdown', async (_req, res) => {
const isProbablyNodemon = Boolean(
process.env.NODEMON === 'true' ||
(process.env._ && /nodemon/i.test(process.env._)) ||
(process.env.npm_lifecycle_script && /nodemon/i.test(process.env.npm_lifecycle_script))
);
if (isProbablyNodemon) {
return res.status(400).json({ ok: false, error: 'Shutdown ist im Entwicklungsmodus (nodemon) deaktiviert.' });
}
try {
logSync('⏻ Shutdown requested');
res.json({ ok: true, shuttingDown: true });
} catch (e) {
console.error('Shutdown endpoint response error', e);
}
setTimeout(() => {
let forced = false;
const forceTimer = setTimeout(() => {
forced = true;
console.warn('Force exiting without full graceful close (shutdown)');
process.exit(0);
}, 5000);
try {
server.close(() => {
if (!forced) {
clearTimeout(forceTimer);
process.exit(0);
}
});
} catch (e) {
console.error('Error during server.close() on shutdown', e);
try { clearTimeout(forceTimer); } catch {}
process.exit(0);
}
}, 200);
});
// Simple scheduler with recurrence: checks every 5s and enqueues due plans.
let schedulerRunning = false;
async function schedulerTick() {
if (schedulerRunning) return; // prevent overlapping
schedulerRunning = true;
try {
const now = Date.now();
const plans = await loadPlans();
const due = plans.filter(p => p.whenTs <= now);
if (due.length) {
const toKeep = [];
for (const p of due) {
const cfg = await getConfigById(p.configId);
if (!cfg) continue;
// enqueue with planned marker so it shows the clock icon in the queue while waiting
lastJobName = cfg.name;
logSync("🕒 Scheduled job enqueued", { job: cfg.name, direction: p.direction, when: new Date(p.whenTs).toISOString() });
enqueueSync(cfg, p.direction, (status) => broadcast(status), { plannedForTs: p.whenTs });
// reschedule if recurring
const r = p.recurrence || { type: 'none' };
if (r.type === 'fixed' && Number.isFinite(r.everyMs) && r.everyMs > 0) {
// compute next whenTs strictly after now
let next = p.whenTs + r.everyMs;
while (next <= now) next += r.everyMs;
toKeep.push({ ...p, whenTs: next });
}
}
// Keep non-due plans and rescheduled recurring ones
const remaining = plans.filter(p => p.whenTs > now).concat(toKeep);
const { savePlans } = await import('./lib/planStore.js');
await savePlans(remaining);
}
} catch (e) {
console.error('Scheduler error', e);
} finally {
schedulerRunning = false;
}
}
setInterval(schedulerTick, 5000);