Compare commits

..
2 Commits
Author SHA1 Message Date
Honey 534b5a35fc Aufgearbeitet 2026-02-08 19:53:46 +01:00
Honey 497faa72db hinzugefügt: Grund für Tausch + Discord benachrichtigung + PWA 2026-02-08 19:52:32 +01:00
10 changed files with 408 additions and 84 deletions

No files matched your search

+17 -2
View File
@@ -1,7 +1,22 @@
FROM node:20-alpine FROM node:20-alpine
WORKDIR /app WORKDIR /app
# Copy package files
COPY package*.json ./ COPY package*.json ./
RUN npm install
# Install dependencies
RUN npm install --production
# Copy all application files
COPY . . COPY . .
# Expose port
EXPOSE 3000 EXPOSE 3000
CMD ["npm", "start"]
# Set environment variables
ENV NODE_ENV=production
ENV PORT=3000
# Start the server
CMD ["node", "server.js"]
+11 -2
View File
@@ -1,11 +1,20 @@
{ {
"name": "whopays", "name": "whopays",
"version": "1.0.0", "version": "1.0.0",
"description": "Who pays app with PWA support",
"main": "server.js",
"type": "module", "type": "module",
"scripts": { "scripts": {
"start": "node server.js" "start": "node server.js",
"dev": "node server.js"
}, },
"keywords": [
"pwa",
"whopays"
],
"author": "",
"license": "ISC",
"dependencies": { "dependencies": {
"express": "^4.19.2" "express": "^4.18.2"
} }
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

+89 -12
View File
@@ -2,17 +2,43 @@
<html lang="de"> <html lang="de">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<link rel="manifest" href="manifest.json" />
<!-- PWA Meta Tags -->
<link rel="manifest" href="/manifest.json" />
<meta name="theme-color" content="#ec4899" /> <meta name="theme-color" content="#ec4899" />
<meta name="mobile-web-app-capable" content="yes" />
<!-- iOS Specific -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="WhoPays" />
<link rel="apple-touch-icon" href="/img/icon-192.png" />
<!-- Android Specific -->
<meta name="mobile-web-app-capable" content="yes" />
<title>Wer zahlt?</title> <title>Wer zahlt?</title>
<script src="https://cdn.tailwindcss.com"></script> <script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="style.css" /> <link rel="stylesheet" href="style.css" />
</head> </head>
<body <body
class="flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-yellow-50 to-pink-50 text-gray-800" class="flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-yellow-50 to-pink-50 text-gray-800 p-4"
> >
<div class="text-center space-y-8"> <!-- Install Banner (shows on compatible devices) -->
<div id="installBanner" class="hidden fixed top-0 left-0 right-0 bg-pink-500 text-white p-3 shadow-lg z-50">
<div class="max-w-md mx-auto flex items-center justify-between">
<span class="text-sm">📱 App installieren für bessere Erfahrung!</span>
<div class="space-x-2">
<button id="installBtn" class="bg-white text-pink-500 px-3 py-1 rounded-lg text-sm font-medium">
Installieren
</button>
<button id="dismissBtn" class="text-white text-sm">✕</button>
</div>
</div>
</div>
<div class="text-center space-y-8 w-full max-w-md mt-16">
<h1 class="text-4xl font-extrabold drop-shadow-sm tracking-tight"> <h1 class="text-4xl font-extrabold drop-shadow-sm tracking-tight">
Who pays? Who pays?
</h1> </h1>
@@ -35,21 +61,72 @@
</div> </div>
</div> </div>
<button <!-- Reason Input Section -->
id="toggleButton" <div class="space-y-3">
class="bg-green-500 hover:bg-green-600 text-white text-xl px-6 py-3 rounded-2xl shadow-md transition-all transform hover:scale-105 active:scale-95" <input
> id="reasonInput"
Switch 🔁 type="text"
</button> placeholder="Grund (optional) ..."
maxlength="100"
class="w-full px-4 py-3 rounded-xl border-2 border-gray-200 focus:border-pink-400 focus:outline-none text-center transition-all"
/>
<button
id="toggleButton"
class="w-full bg-green-500 hover:bg-green-600 text-white text-xl px-6 py-3 rounded-2xl shadow-md transition-all transform hover:scale-105 active:scale-95"
>
Switch 🔁
</button>
</div>
<!-- Last Reason Display -->
<div id="lastReasonBox" class="hidden bg-white/60 backdrop-blur-sm rounded-xl p-4 shadow-sm">
<p class="text-sm text-gray-600 mb-1">Letzter Grund:</p>
<p id="lastReasonText" class="text-lg font-medium text-gray-800"></p>
</div>
</div> </div>
<script src="script.js"></script> <script src="script.js"></script>
<script> <script>
// Service Worker Registration
if ("serviceWorker" in navigator) { if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service-worker.js") navigator.serviceWorker.register("/service-worker.js")
.then(() => console.log("Service Worker registriert")) .then(reg => console.log("✅ Service Worker registriert", reg.scope))
.catch(err => console.error("SW Fehler:", err)); .catch(err => console.error("❌ SW Fehler:", err));
} }
// PWA Install Prompt
let deferredPrompt;
const installBanner = document.getElementById("installBanner");
const installBtn = document.getElementById("installBtn");
const dismissBtn = document.getElementById("dismissBtn");
window.addEventListener("beforeinstallprompt", (e) => {
console.log("✅ PWA installierbar!");
e.preventDefault();
deferredPrompt = e;
installBanner.classList.remove("hidden");
});
installBtn.addEventListener("click", async () => {
if (!deferredPrompt) return;
deferredPrompt.prompt();
const { outcome } = await deferredPrompt.userChoice;
console.log(`PWA install: ${outcome}`);
deferredPrompt = null;
installBanner.classList.add("hidden");
});
dismissBtn.addEventListener("click", () => {
installBanner.classList.add("hidden");
});
window.addEventListener("appinstalled", () => {
console.log("✅ PWA erfolgreich installiert!");
deferredPrompt = null;
});
</script> </script>
</body> </body>
+28 -8
View File
@@ -1,20 +1,40 @@
{ {
"name": "WhoPays", "name": "Wer zahlt? - Who Pays",
"short_name": "WhoPays", "short_name": "WhoPays",
"description": "Entscheide spielerisch, wer zahlt",
"start_url": "/", "start_url": "/",
"scope": "/",
"display": "standalone", "display": "standalone",
"background_color": "#ffffff", "background_color": "#fef3c7",
"theme_color": "#2c3e50", "theme_color": "#ec4899",
"orientation": "portrait-primary",
"categories": ["utilities", "lifestyle"],
"icons": [ "icons": [
{ {
"src": "/icons/icon-192.png", "src": "/img/icon-192.png",
"sizes": "192x192", "sizes": "192x192",
"type": "image/png" "type": "image/png",
"purpose": "any"
}, },
{ {
"src": "/icons/icon-512.png", "src": "/img/icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/img/icon-512.png",
"sizes": "512x512", "sizes": "512x512",
"type": "image/png" "type": "image/png",
"purpose": "any"
},
{
"src": "/img/icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
} }
] ],
"screenshots": [],
"prefer_related_applications": false
} }
+35 -1
View File
@@ -1,11 +1,20 @@
const img = document.getElementById("personImg"); const img = document.getElementById("personImg");
const nameEl = document.getElementById("personName"); const nameEl = document.getElementById("personName");
const button = document.getElementById("toggleButton"); const button = document.getElementById("toggleButton");
const reasonInput = document.getElementById("reasonInput");
const lastReasonBox = document.getElementById("lastReasonBox");
const lastReasonText = document.getElementById("lastReasonText");
async function loadStatus() { async function loadStatus() {
const res = await fetch("/status"); const res = await fetch("/status");
const data = await res.json(); const data = await res.json();
showStatus(data.current, false); showStatus(data.current, false);
// Show last reason if available
if (data.lastReason) {
lastReasonText.textContent = data.lastReason;
lastReasonBox.classList.remove("hidden");
}
} }
function showStatus(person, animate = true) { function showStatus(person, animate = true) {
@@ -40,9 +49,34 @@ function showStatus(person, animate = true) {
button.addEventListener("click", async () => { button.addEventListener("click", async () => {
const res = await fetch("/toggle", { method: "POST" }); const reason = reasonInput.value.trim();
const res = await fetch("/toggle", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ reason: reason || undefined })
});
const data = await res.json(); const data = await res.json();
showStatus(data.current); showStatus(data.current);
// Update last reason display
if (reason) {
lastReasonText.textContent = reason;
lastReasonBox.classList.remove("hidden");
}
// Clear input
reasonInput.value = "";
});
// Allow Enter key to trigger switch
reasonInput.addEventListener("keypress", (e) => {
if (e.key === "Enter") {
button.click();
}
}); });
loadStatus(); loadStatus();
+104 -13
View File
@@ -1,23 +1,114 @@
const CACHE_NAME = "whopays-cache-v1"; const CACHE_NAME = "whopays-v2";
const URLS_TO_CACHE = [ const urlsToCache = [
"/", "/",
"/index.html", "/index.html",
"/style.css", "/style.css",
"/script.js" "/script.js",
"/manifest.json"
]; ];
self.addEventListener("install", event => { console.log("🔧 Service Worker: Loading...");
// Install event
self.addEventListener("install", (event) => {
console.log("⚙️ Service Worker: Installing...");
event.waitUntil( event.waitUntil(
caches.open(CACHE_NAME).then(cache => { caches.open(CACHE_NAME)
return cache.addAll(URLS_TO_CACHE); .then((cache) => {
console.log("✅ Service Worker: Cache opened");
// Try to cache files, but don't fail if some are missing
return Promise.allSettled(
urlsToCache.map(url =>
cache.add(url).catch(err => {
console.warn(`⚠️ Failed to cache: ${url}`, err);
return null;
})
)
);
})
.then(() => {
console.log("✅ Service Worker: Installed");
})
.catch(err => {
console.error("❌ Service Worker: Install failed", err);
})
);
self.skipWaiting();
});
// Activate event
self.addEventListener("activate", (event) => {
console.log("🔄 Service Worker: Activating...");
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME) {
console.log(`🗑️ Service Worker: Deleting old cache: ${cacheName}`);
return caches.delete(cacheName);
}
})
);
}).then(() => {
console.log("✅ Service Worker: Activated");
}) })
); );
self.clients.claim();
});
// Fetch event
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
// Network first for API calls
if (url.pathname.startsWith("/status") || url.pathname.startsWith("/toggle")) {
event.respondWith(
fetch(event.request)
.catch(() => {
console.warn("⚠️ API offline, returning error");
return new Response(
JSON.stringify({ error: "Offline" }),
{
headers: { "Content-Type": "application/json" },
status: 503
}
);
})
);
return;
}
// Cache first for static assets
event.respondWith(
caches.match(event.request)
.then((response) => {
if (response) {
return response;
}
return fetch(event.request).then((fetchResponse) => {
// Only cache successful responses
if (!fetchResponse || fetchResponse.status !== 200 || fetchResponse.type !== 'basic') {
return fetchResponse;
}
const responseToCache = fetchResponse.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, responseToCache);
});
return fetchResponse;
});
})
.catch((err) => {
console.warn("⚠️ Fetch failed:", err);
// Fallback for navigation requests
if (event.request.mode === 'navigate') {
return caches.match('/index.html');
}
return new Response('Offline', { status: 503 });
})
);
}); });
self.addEventListener("fetch", event => { console.log("✅ Service Worker: Script loaded");
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});
+123 -45
View File
@@ -7,8 +7,33 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
const app = express(); const app = express();
// Trust proxy - CRITICAL for reverse proxy setup
app.set('trust proxy', true);
app.use(express.json()); 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"); const stateFile = path.join(__dirname, "state.json");
@@ -18,25 +43,18 @@ const stateFile = path.join(__dirname, "state.json");
const CONFIG = { const CONFIG = {
A: { A: {
name: "Marc", name: "Marc",
color: 0x2ecc71, // grün color: 0x2ecc71,
icon: "a.png" icon: "a.png"
}, },
B: { B: {
name: "Laila", name: "Laila",
color: 0xe74c3c, // rot color: 0xe74c3c,
icon: "b.png" 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 const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL || "https://discord.com/api/webhooks/1450872860607381515/zRbiXOykKPUfLJ_H87wD2OxQJPLdro6yQzU2T48Pg4fxSNaXEqBFgxdHGTiIDmmKGHIF";
|| "http://localhost:3000";
// 🔔 Discord Webhook URL
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL
|| "https://discord.com/api/webhooks/1450872860607381515/zRbiXOykKPUfLJ_H87wD2OxQJPLdro6yQzU2T48Pg4fxSNaXEqBFgxdHGTiIDmmKGHIF";
// -------------------- // --------------------
// State Handling // State Handling
@@ -45,7 +63,7 @@ function getState() {
if (!fs.existsSync(stateFile)) { if (!fs.existsSync(stateFile)) {
fs.writeFileSync( fs.writeFileSync(
stateFile, stateFile,
JSON.stringify({ current: "A" }, null, 2) JSON.stringify({ current: "A", lastReason: null }, null, 2)
); );
} }
return JSON.parse(fs.readFileSync(stateFile, "utf-8")); return JSON.parse(fs.readFileSync(stateFile, "utf-8"));
@@ -58,12 +76,33 @@ function setState(newState) {
// -------------------- // --------------------
// Discord Webhook // Discord Webhook
// -------------------- // --------------------
async function sendDiscordEmbed(previousKey, currentKey) { async function sendDiscordEmbed(previousKey, currentKey, reason) {
const previous = CONFIG[previousKey]; const previous = CONFIG[previousKey];
const current = CONFIG[currentKey]; const current = CONFIG[currentKey];
if (!DISCORD_WEBHOOK_URL) return; if (!DISCORD_WEBHOOK_URL) return;
const fields = [
{
name: "Von",
value: previous.name,
inline: true
},
{
name: "Zu",
value: current.name,
inline: true
}
];
if (reason) {
fields.push({
name: "📝 Grund",
value: reason,
inline: false
});
}
const embed = { const embed = {
title: "💸 Zahl-Wechsel", title: "💸 Zahl-Wechsel",
description: `**${current.name}** ist jetzt dran zu zahlen`, description: `**${current.name}** ist jetzt dran zu zahlen`,
@@ -71,18 +110,7 @@ async function sendDiscordEmbed(previousKey, currentKey) {
thumbnail: { thumbnail: {
url: `${PUBLIC_BASE_URL}/img/${current.icon}` url: `${PUBLIC_BASE_URL}/img/${current.icon}`
}, },
fields: [ fields: fields,
{
name: "Von",
value: previous.name,
inline: true
},
{
name: "Zu",
value: current.name,
inline: true
}
],
footer: { footer: {
text: new Date().toLocaleString("de-DE") text: new Date().toLocaleString("de-DE")
} }
@@ -92,54 +120,104 @@ async function sendDiscordEmbed(previousKey, currentKey) {
await fetch(DISCORD_WEBHOOK_URL, { await fetch(DISCORD_WEBHOOK_URL, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({ embeds: [embed] })
embeds: [embed]
})
}); });
console.log("✅ Discord Benachrichtigung gesendet");
} catch (err) { } catch (err) {
console.error("Discord Webhook Fehler:", err.message); console.error("❌ Discord Webhook Fehler:", err.message);
} }
} }
// -------------------- // --------------------
// Routes // API Routes
// -------------------- // --------------------
// GET: aktueller Zustand
app.get("/status", (req, res) => { app.get("/status", (req, res) => {
res.json(getState()); res.json(getState());
}); });
// POST: wechseln
app.post("/toggle", async (req, res) => { app.post("/toggle", async (req, res) => {
const state = getState(); const state = getState();
const previousKey = state.current; const previousKey = state.current;
const reason = req.body?.reason;
state.current = state.current === "A" ? "B" : "A"; state.current = state.current === "A" ? "B" : "A";
state.lastReason = reason || null;
setState(state); setState(state);
console.log( const logMessage = reason
`Zahl-Wechsel: ${CONFIG[previousKey].name} → ${CONFIG[state.current].name}` ? `Zahl-Wechsel: ${CONFIG[previousKey].name} → ${CONFIG[state.current].name} (Grund: ${reason})`
); : `Zahl-Wechsel: ${CONFIG[previousKey].name} → ${CONFIG[state.current].name}`;
await sendDiscordEmbed(previousKey, state.current); console.log(logMessage);
await sendDiscordEmbed(previousKey, state.current, reason);
res.json({ res.json({
current: state.current, current: state.current,
name: CONFIG[state.current].name name: CONFIG[state.current].name,
lastReason: state.lastReason
}); });
}); });
// Fallback app.get("/health", (req, res) => {
app.get(/.*/, (req, res) => { res.json({ status: "ok" });
res.sendFile(path.join(__dirname, "public/index.html")); });
// --------------------
// 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 // Start
// -------------------- // --------------------
const PORT = process.env.PORT || 3000; const PORT = process.env.PORT || 3000;
app.listen(PORT, () => app.listen(PORT, "0.0.0.0", () => {
console.log(`WhoPays läuft auf http://localhost:${PORT}`) 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`);
});
+1 -1
View File
@@ -1,3 +1,3 @@
{ {
"current": "A" "current": "B"
} }