Aufgearbeitet

This commit is contained in:
Honey committed 2026-02-08 19:53:46 +01:00
1 parent 497faa72db
commit 534b5a35fc
6 files changed
+273 -76

No files matched your search

+87 -26
View File
@@ -7,8 +7,33 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
// Trust proxy - CRITICAL for reverse proxy setup
app.set('trust proxy', true);
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
// Logging middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url} - ${req.headers['x-forwarded-proto'] || 'http'}`);
next();
});
// CRITICAL: Serve static files with proper headers
app.use(express.static(path.join(__dirname, "public"), {
setHeaders: (res, filepath) => {
if (filepath.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
}
if (filepath.endsWith('.json')) {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
}
if (filepath.endsWith('service-worker.js')) {
res.setHeader('Service-Worker-Allowed', '/');
res.setHeader('Cache-Control', 'no-cache');
}
}
}));
const stateFile = path.join(__dirname, "state.json");
@@ -18,26 +43,19 @@ const stateFile = path.join(__dirname, "state.json");
const CONFIG = {
A: {
name: "Marc",
color: 0x2ecc71, // grün
color: 0x2ecc71,
icon: "a.png"
},
B: {
name: "Laila",
color: 0xe74c3c, // rot
color: 0xe74c3c,
icon: "b.png"
}
};
// Öffentliche URL zu deinem Server (WICHTIG für Discord Icons!)
const PUBLIC_BASE_URL = process.env.PUBLIC_BASE_URL
|| "http://localhost:3000";
const PUBLIC_BASE_URL = process.env.PUBLIC_BASE_URL || "http://localhost:3000";
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL || "https://discord.com/api/webhooks/1450872860607381515/zRbiXOykKPUfLJ_H87wD2OxQJPLdro6yQzU2T48Pg4fxSNaXEqBFgxdHGTiIDmmKGHIF";
// 🔔 Discord Webhook URL
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL
|| "https://discord.com/api/webhooks/1450872860607381515/zRbiXOykKPUfLJ_H87wD2OxQJPLdro6yQzU2T48Pg4fxSNaXEqBFgxdHGTiIDmmKGHIF";
// --------------------
// State Handling
// --------------------
@@ -77,7 +95,6 @@ async function sendDiscordEmbed(previousKey, currentKey, reason) {
}
];
// Add reason field if provided
if (reason) {
fields.push({
name: "📝 Grund",
@@ -103,9 +120,7 @@ async function sendDiscordEmbed(previousKey, currentKey, reason) {
await fetch(DISCORD_WEBHOOK_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
embeds: [embed]
})
body: JSON.stringify({ embeds: [embed] })
});
console.log("✅ Discord Benachrichtigung gesendet");
} catch (err) {
@@ -113,17 +128,14 @@ async function sendDiscordEmbed(previousKey, currentKey, reason) {
}
}
// --------------------
// Routes
// API Routes
// --------------------
// GET: aktueller Zustand
app.get("/status", (req, res) => {
res.json(getState());
});
// POST: wechseln
app.post("/toggle", async (req, res) => {
const state = getState();
const previousKey = state.current;
@@ -148,15 +160,64 @@ app.post("/toggle", async (req, res) => {
});
});
// Fallback
app.get(/.*/, (req, res) => {
res.sendFile(path.join(__dirname, "public/index.html"));
app.get("/health", (req, res) => {
res.json({ status: "ok" });
});
// --------------------
// SPA Fallback - NO CRASH
// --------------------
// Only serve index.html for navigation requests, not for missing static files
app.use((req, res, next) => {
// If request already handled by static middleware, skip
if (res.headersSent) return;
// If it's an API route that wasn't matched, 404
if (req.url.startsWith('/api/')) {
return res.status(404).json({ error: 'Not found' });
}
// If Accept header indicates browser navigation (HTML), serve index.html
const acceptsHtml = req.accepts('html');
if (acceptsHtml) {
return res.sendFile(path.join(__dirname, "public/index.html"));
}
// Otherwise 404
res.status(404).send('Not found');
});
// Error handler to prevent crashes
app.use((err, req, res, next) => {
console.error('Server error:', err);
res.status(500).json({ error: 'Internal server error' });
});
// --------------------
// Start
// --------------------
const PORT = process.env.PORT || 3000;
app.listen(PORT, () =>
console.log(`WhoPays läuft auf http://localhost:${PORT}`)
);
app.listen(PORT, "0.0.0.0", () => {
console.log(`\n✅ WhoPays läuft auf http://0.0.0.0:${PORT}\n`);
console.log(`📁 Static files directory: ${path.join(__dirname, "public")}`);
console.log(`🔒 Trust proxy: enabled (for reverse proxy support)`);
// Verify critical files exist
const criticalFiles = [
'public/index.html',
'public/service-worker.js',
'public/manifest.json'
];
console.log('\n🔍 Checking critical files:');
criticalFiles.forEach(file => {
const fullPath = path.join(__dirname, file);
const exists = fs.existsSync(fullPath);
console.log(` ${exists ? '✅' : '❌'} ${file}`);
});
console.log('\n📝 Test URLs (adjust domain for your setup):');
console.log(` http://localhost:${PORT}/`);
console.log(` http://localhost:${PORT}/service-worker.js`);
console.log(` http://localhost:${PORT}/manifest.json\n`);
});