Add files via upload
This commit is contained in:
1 parent
1bff4c6eea
commit
c3ac407e2e
10 files changed
+697
-1
No files matched your search
@@ -1 +1,56 @@
|
|||||||
# VitaChat
|
# VitaChat API auf Vercel
|
||||||
|
|
||||||
|
Serverless-Backend (Node.js) + Neon Postgres. Ersetzt das alte PHP/SQLite-Setup.
|
||||||
|
Das Protokoll ist unverändert — der Vita-Client braucht nur eine neue URL.
|
||||||
|
|
||||||
|
## Einrichtung (~10 Minuten)
|
||||||
|
|
||||||
|
### 1. Projekt anlegen
|
||||||
|
Diesen Ordner in ein GitHub-Repo pushen, dann auf vercel.com "Add New Project"
|
||||||
|
und das Repo importieren. Framework: "Other" (wird meist automatisch erkannt).
|
||||||
|
|
||||||
|
Alternativ ohne GitHub:
|
||||||
|
npm i -g vercel
|
||||||
|
vercel # im Projektordner, folgt dem Assistenten
|
||||||
|
|
||||||
|
### 2. Datenbank verbinden
|
||||||
|
Im Vercel-Dashboard: Projekt -> Storage -> Create Database -> Neon (Postgres).
|
||||||
|
Vercel legt die Variable DATABASE_URL automatisch an. Danach EINMAL neu
|
||||||
|
deployen, damit die Variable in den Funktionen ankommt (Deployments -> Redeploy).
|
||||||
|
|
||||||
|
### 3. Tabellen anlegen
|
||||||
|
Einmal im Browser aufrufen:
|
||||||
|
https://<projekt>.vercel.app/api/setup
|
||||||
|
Erwartet: OK|Datenbank bereit
|
||||||
|
|
||||||
|
### 4. Testen
|
||||||
|
curl -d "user=test&pass=1234" https://<projekt>.vercel.app/api/register
|
||||||
|
curl -d "user=test&pass=1234" https://<projekt>.vercel.app/api/login
|
||||||
|
|
||||||
|
Web-Client: https://<projekt>.vercel.app/
|
||||||
|
|
||||||
|
### 5. Vita-Client anpassen
|
||||||
|
In client/src/net.h die Basis-URL ersetzen:
|
||||||
|
|
||||||
|
#define API_BASE "https://<projekt>.vercel.app/api"
|
||||||
|
|
||||||
|
Dann neu bauen:
|
||||||
|
cd ~/vitachat/client/build && make
|
||||||
|
|
||||||
|
## Struktur
|
||||||
|
api/setup.js Tabellen anlegen (einmalig)
|
||||||
|
api/register.js POST user, pass
|
||||||
|
api/login.js POST user, pass -> OK|<token>
|
||||||
|
api/send.js POST token, to, text -> OK|<msg_id>
|
||||||
|
api/poll.js GET token, with, since -> MSG|id|from|ts|text
|
||||||
|
api/contacts.js GET token -> USER|name|online|unread|last_ts|preview
|
||||||
|
lib/db.js DB-Verbindung, Passwort-Hashing (scrypt), Protokoll-Helfer
|
||||||
|
public/index.html Web-Client (wird unter / ausgeliefert)
|
||||||
|
|
||||||
|
## Hinweise
|
||||||
|
- Passwörter: scrypt aus Nodes crypto-Modul, keine Extra-Abhängigkeit.
|
||||||
|
- Fehler kommen als "ERR|<text>" mit HTTP 200, damit der Vita-Client die
|
||||||
|
Zeile in jedem Fall lesen kann.
|
||||||
|
- Neon-Freetier schläft nach Inaktivität ein; der erste Aufruf danach
|
||||||
|
dauert ~1 s. Durch das Polling der App bleibt sie im Betrieb wach.
|
||||||
|
- Logs bei Problemen: Vercel-Dashboard -> Projekt -> Logs.
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { sql, ok, fail, auth, clean, ONLINE_SECS, PREVIEW_LEN } from '../lib/db.js';
|
||||||
|
|
||||||
|
export default async function handler(req, res) {
|
||||||
|
try {
|
||||||
|
const me = await auth(req, res);
|
||||||
|
if (!me) return;
|
||||||
|
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
// Alles in EINER Abfrage – auf Serverless zählt jede Round-Trip-Zeit.
|
||||||
|
const rows = await sql`
|
||||||
|
SELECT u.name, u.last_seen,
|
||||||
|
COALESCE(lm.ts, 0) AS last_ts,
|
||||||
|
lm.text AS last_text,
|
||||||
|
lm.sender AS last_sender,
|
||||||
|
COALESCE(un.cnt, 0) AS unread
|
||||||
|
FROM users u
|
||||||
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT m.ts, m.text, m.sender FROM messages m
|
||||||
|
WHERE (m.sender = ${me.id} AND m.recipient = u.id)
|
||||||
|
OR (m.sender = u.id AND m.recipient = ${me.id})
|
||||||
|
ORDER BY m.id DESC LIMIT 1
|
||||||
|
) lm ON TRUE
|
||||||
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT COUNT(*) AS cnt FROM messages m
|
||||||
|
WHERE m.sender = u.id AND m.recipient = ${me.id}
|
||||||
|
AND m.id > COALESCE(
|
||||||
|
(SELECT last_id FROM reads WHERE user_id = ${me.id} AND peer_id = u.id), 0)
|
||||||
|
) un ON TRUE
|
||||||
|
WHERE u.id <> ${me.id}
|
||||||
|
ORDER BY last_ts DESC, LOWER(u.name) ASC`;
|
||||||
|
|
||||||
|
const body = rows.map(r => {
|
||||||
|
const online = (now - Number(r.last_seen) < ONLINE_SECS) ? 1 : 0;
|
||||||
|
|
||||||
|
let preview = '';
|
||||||
|
if (r.last_text) {
|
||||||
|
let txt = r.last_text.slice(0, PREVIEW_LEN);
|
||||||
|
if (r.last_text.length > PREVIEW_LEN) txt += '…';
|
||||||
|
preview = (r.last_sender === me.id ? 'Du: ' : '') + txt;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `USER|${clean(r.name)}|${online}|${r.unread}|${r.last_ts}|${clean(preview)}`;
|
||||||
|
}).join('\n');
|
||||||
|
|
||||||
|
ok(res, body ? body + '\n' : '');
|
||||||
|
} catch (e) {
|
||||||
|
fail(res, 'Serverfehler: ' + e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { sql, param, ok, fail, verifyPassword, newToken } from '../lib/db.js';
|
||||||
|
|
||||||
|
export default async function handler(req, res) {
|
||||||
|
const name = param(req, 'user');
|
||||||
|
const pass = param(req, 'pass');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const rows = await sql`
|
||||||
|
SELECT id, pass_hash FROM users WHERE LOWER(name) = LOWER(${name})`;
|
||||||
|
if (!rows.length || !verifyPassword(pass, rows[0].pass_hash))
|
||||||
|
return fail(res, 'Login fehlgeschlagen');
|
||||||
|
|
||||||
|
const token = newToken();
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
await sql`UPDATE users SET token = ${token}, last_seen = ${now} WHERE id = ${rows[0].id}`;
|
||||||
|
|
||||||
|
ok(res, `OK|${token}\n`);
|
||||||
|
} catch (e) {
|
||||||
|
fail(res, 'Serverfehler: ' + e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
import { sql, param, ok, fail, auth, clean, MAX_POLL } from '../lib/db.js';
|
||||||
|
|
||||||
|
export default async function handler(req, res) {
|
||||||
|
try {
|
||||||
|
const me = await auth(req, res);
|
||||||
|
if (!me) return;
|
||||||
|
|
||||||
|
const withName = param(req, 'with');
|
||||||
|
const since = parseInt(param(req, 'since'), 10) || 0;
|
||||||
|
|
||||||
|
const other = await sql`SELECT id FROM users WHERE LOWER(name) = LOWER(${withName})`;
|
||||||
|
if (!other.length) return fail(res, 'Nutzer unbekannt');
|
||||||
|
const peer = other[0].id;
|
||||||
|
|
||||||
|
const msgs = await sql`
|
||||||
|
SELECT m.id, u.name AS sender_name, m.ts, m.text
|
||||||
|
FROM messages m JOIN users u ON u.id = m.sender
|
||||||
|
WHERE m.id > ${since}
|
||||||
|
AND ((m.sender = ${me.id} AND m.recipient = ${peer})
|
||||||
|
OR (m.sender = ${peer} AND m.recipient = ${me.id}))
|
||||||
|
ORDER BY m.id ASC
|
||||||
|
LIMIT ${MAX_POLL}`;
|
||||||
|
|
||||||
|
const body = msgs
|
||||||
|
.map(m => `MSG|${m.id}|${clean(m.sender_name)}|${m.ts}|${clean(m.text)}`)
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
|
// Chat als gelesen markieren
|
||||||
|
const maxRow = await sql`
|
||||||
|
SELECT COALESCE(MAX(id), 0) AS max_id FROM messages
|
||||||
|
WHERE (sender = ${me.id} AND recipient = ${peer})
|
||||||
|
OR (sender = ${peer} AND recipient = ${me.id})`;
|
||||||
|
const maxId = maxRow[0].max_id;
|
||||||
|
|
||||||
|
await sql`
|
||||||
|
INSERT INTO reads (user_id, peer_id, last_id)
|
||||||
|
VALUES (${me.id}, ${peer}, ${maxId})
|
||||||
|
ON CONFLICT (user_id, peer_id)
|
||||||
|
DO UPDATE SET last_id = GREATEST(reads.last_id, ${maxId})`;
|
||||||
|
|
||||||
|
ok(res, body ? body + '\n' : '');
|
||||||
|
} catch (e) {
|
||||||
|
fail(res, 'Serverfehler: ' + e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { sql, param, ok, fail, hashPassword } from '../lib/db.js';
|
||||||
|
|
||||||
|
export default async function handler(req, res) {
|
||||||
|
const name = param(req, 'user');
|
||||||
|
const pass = param(req, 'pass');
|
||||||
|
|
||||||
|
if (!/^[A-Za-z0-9_-]{2,20}$/.test(name))
|
||||||
|
return fail(res, 'Name: 2-20 Zeichen, a-z 0-9 _ -');
|
||||||
|
if (pass.length < 4)
|
||||||
|
return fail(res, 'Passwort zu kurz (min. 4)');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const exists = await sql`SELECT id FROM users WHERE LOWER(name) = LOWER(${name})`;
|
||||||
|
if (exists.length) return fail(res, 'Name bereits vergeben');
|
||||||
|
|
||||||
|
await sql`INSERT INTO users (name, pass_hash) VALUES (${name}, ${hashPassword(pass)})`;
|
||||||
|
ok(res, 'OK|registriert\n');
|
||||||
|
} catch (e) {
|
||||||
|
fail(res, 'Serverfehler: ' + e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
import { sql, param, ok, fail, auth, MAX_TEXT_LEN } from '../lib/db.js';
|
||||||
|
|
||||||
|
export default async function handler(req, res) {
|
||||||
|
try {
|
||||||
|
const me = await auth(req, res);
|
||||||
|
if (!me) return;
|
||||||
|
|
||||||
|
const to = param(req, 'to');
|
||||||
|
const text = param(req, 'text').slice(0, MAX_TEXT_LEN);
|
||||||
|
if (!text) return fail(res, 'Leere Nachricht');
|
||||||
|
|
||||||
|
const rcpt = await sql`SELECT id FROM users WHERE LOWER(name) = LOWER(${to})`;
|
||||||
|
if (!rcpt.length) return fail(res, 'Empfaenger unbekannt');
|
||||||
|
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
const ins = await sql`
|
||||||
|
INSERT INTO messages (sender, recipient, ts, text)
|
||||||
|
VALUES (${me.id}, ${rcpt[0].id}, ${now}, ${text})
|
||||||
|
RETURNING id`;
|
||||||
|
|
||||||
|
ok(res, `OK|${ins[0].id}\n`);
|
||||||
|
} catch (e) {
|
||||||
|
fail(res, 'Serverfehler: ' + e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
// Einmalig aufrufen: https://<projekt>.vercel.app/api/setup
|
||||||
|
// Legt die Tabellen an. Mehrfaches Aufrufen ist unschädlich.
|
||||||
|
import { sql, ok, fail } from '../lib/db.js';
|
||||||
|
|
||||||
|
export default async function handler(req, res) {
|
||||||
|
try {
|
||||||
|
await sql`CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
pass_hash TEXT NOT NULL,
|
||||||
|
token TEXT,
|
||||||
|
last_seen BIGINT DEFAULT 0
|
||||||
|
)`;
|
||||||
|
// Namen ohne Rücksicht auf Groß-/Kleinschreibung eindeutig halten
|
||||||
|
await sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_users_name ON users (LOWER(name))`;
|
||||||
|
|
||||||
|
await sql`CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
sender INTEGER NOT NULL,
|
||||||
|
recipient INTEGER NOT NULL,
|
||||||
|
ts BIGINT NOT NULL,
|
||||||
|
text TEXT NOT NULL
|
||||||
|
)`;
|
||||||
|
await sql`CREATE INDEX IF NOT EXISTS idx_msg ON messages (recipient, sender, id)`;
|
||||||
|
|
||||||
|
await sql`CREATE TABLE IF NOT EXISTS reads (
|
||||||
|
user_id INTEGER NOT NULL,
|
||||||
|
peer_id INTEGER NOT NULL,
|
||||||
|
last_id INTEGER NOT NULL DEFAULT 0,
|
||||||
|
PRIMARY KEY (user_id, peer_id)
|
||||||
|
)`;
|
||||||
|
|
||||||
|
ok(res, 'OK|Datenbank bereit\n');
|
||||||
|
} catch (e) {
|
||||||
|
fail(res, 'Setup fehlgeschlagen: ' + e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
// Gemeinsame Helfer für alle vitaAPI-Endpunkte (Vercel Serverless + Neon Postgres)
|
||||||
|
import { neon } from '@neondatabase/serverless';
|
||||||
|
import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
|
||||||
|
|
||||||
|
export const sql = neon(process.env.DATABASE_URL);
|
||||||
|
|
||||||
|
export const ONLINE_SECS = 60;
|
||||||
|
export const MAX_TEXT_LEN = 500;
|
||||||
|
export const MAX_POLL = 50;
|
||||||
|
export const PREVIEW_LEN = 38;
|
||||||
|
|
||||||
|
/* ---------------- Antwort-Protokoll (zeilenbasiert, Pipe-getrennt) ---------------- */
|
||||||
|
|
||||||
|
export function textHead(res) {
|
||||||
|
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
||||||
|
res.setHeader('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ok(res, body = '') {
|
||||||
|
textHead(res);
|
||||||
|
res.status(200).send(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fail(res, msg) {
|
||||||
|
textHead(res);
|
||||||
|
res.status(200).send(`ERR|${msg}\n`); // 200, damit der Vita-Client die Zeile sicher liest
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pipes und Zeilenumbrüche aus Nutzdaten entfernen, damit das Protokoll heil bleibt. */
|
||||||
|
export function clean(s) {
|
||||||
|
return String(s).replace(/\|/g, '¦').replace(/[\r\n]+/g, ' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- Parameter (GET-Query oder POST-Formulardaten) ---------------- */
|
||||||
|
|
||||||
|
export function param(req, key) {
|
||||||
|
let v = req.query?.[key];
|
||||||
|
if (v === undefined && req.body) {
|
||||||
|
if (typeof req.body === 'string') {
|
||||||
|
// Fallback, falls Vercel den Body nicht geparst hat
|
||||||
|
v = new URLSearchParams(req.body).get(key);
|
||||||
|
} else {
|
||||||
|
v = req.body[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (v ?? '').toString().trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- Passwörter (scrypt aus Node, keine Extra-Abhängigkeit) ---------------- */
|
||||||
|
|
||||||
|
export function hashPassword(pass) {
|
||||||
|
const salt = randomBytes(16);
|
||||||
|
const hash = scryptSync(pass, salt, 64);
|
||||||
|
return `${salt.toString('hex')}:${hash.toString('hex')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verifyPassword(pass, stored) {
|
||||||
|
try {
|
||||||
|
const [saltHex, hashHex] = String(stored).split(':');
|
||||||
|
if (!saltHex || !hashHex) return false;
|
||||||
|
const expected = Buffer.from(hashHex, 'hex');
|
||||||
|
const actual = scryptSync(pass, Buffer.from(saltHex, 'hex'), expected.length);
|
||||||
|
return timingSafeEqual(expected, actual);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function newToken() {
|
||||||
|
return randomBytes(16).toString('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- Authentifizierung ---------------- */
|
||||||
|
|
||||||
|
/** Gibt den Nutzer zurück oder null (dann hat der Aufrufer bereits geantwortet). */
|
||||||
|
export async function auth(req, res) {
|
||||||
|
const token = param(req, 'token');
|
||||||
|
if (!token) { fail(res, 'Kein Token'); return null; }
|
||||||
|
|
||||||
|
const rows = await sql`SELECT id, name FROM users WHERE token = ${token}`;
|
||||||
|
if (!rows.length) { fail(res, 'Ungueltiges Token'); return null; }
|
||||||
|
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
await sql`UPDATE users SET last_seen = ${now} WHERE id = ${rows[0].id}`;
|
||||||
|
return rows[0];
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"name": "vitachat-api",
|
||||||
|
"version": "3.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"description": "Messenger-Backend fuer die PS Vita (Vercel Serverless + Neon Postgres)",
|
||||||
|
"dependencies": {
|
||||||
|
"@neondatabase/serverless": "^0.10.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,346 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="de">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>VitaChat Web</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg: #0e121a;
|
||||||
|
--header: #141a26;
|
||||||
|
--card: #1a212e;
|
||||||
|
--accent: #2d7dff;
|
||||||
|
--accent-dk: #1c54b4;
|
||||||
|
--bubble-in: #2c3442;
|
||||||
|
--text: #ebf0f8;
|
||||||
|
--subtext: #8c98aa;
|
||||||
|
--online: #3cd282;
|
||||||
|
--offline: #5a6473;
|
||||||
|
--error: #ff5f5f;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; margin: 0; }
|
||||||
|
body {
|
||||||
|
background: var(--bg); color: var(--text);
|
||||||
|
font: 15px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||||
|
height: 100vh; overflow: hidden;
|
||||||
|
}
|
||||||
|
button { font: inherit; cursor: pointer; border: 0; }
|
||||||
|
input {
|
||||||
|
font: inherit; border: 0; outline: 0;
|
||||||
|
background: var(--card); color: var(--text);
|
||||||
|
border-radius: 12px; padding: 12px 16px; width: 100%;
|
||||||
|
border-bottom: 3px solid transparent;
|
||||||
|
}
|
||||||
|
input:focus { border-bottom-color: var(--accent); }
|
||||||
|
::placeholder { color: var(--subtext); }
|
||||||
|
|
||||||
|
/* ---------- Login ---------- */
|
||||||
|
#login {
|
||||||
|
height: 100vh; display: flex; flex-direction: column;
|
||||||
|
align-items: center; justify-content: center; gap: 14px;
|
||||||
|
}
|
||||||
|
#login .box { width: 320px; display: flex; flex-direction: column; gap: 14px; }
|
||||||
|
#login h1 { font-size: 28px; }
|
||||||
|
#login h1 span { color: var(--accent); }
|
||||||
|
#login .sub { color: var(--subtext); margin-bottom: 10px; }
|
||||||
|
.btn {
|
||||||
|
background: var(--accent); color: var(--text);
|
||||||
|
border-radius: 12px; padding: 12px; font-weight: 600;
|
||||||
|
}
|
||||||
|
.btn:hover { background: var(--accent-dk); }
|
||||||
|
.link { background: none; color: var(--subtext); padding: 6px; }
|
||||||
|
.link:hover { color: var(--text); }
|
||||||
|
#login-status { min-height: 20px; font-size: 13px; }
|
||||||
|
#login-status.err { color: var(--error); }
|
||||||
|
#login-status.ok { color: var(--online); }
|
||||||
|
|
||||||
|
/* ---------- App-Layout ---------- */
|
||||||
|
#app { display: none; height: 100vh; }
|
||||||
|
#app.active { display: flex; }
|
||||||
|
|
||||||
|
#sidebar {
|
||||||
|
width: 280px; min-width: 280px; background: var(--header);
|
||||||
|
display: flex; flex-direction: column; border-right: 2px solid var(--accent);
|
||||||
|
}
|
||||||
|
#sidebar header {
|
||||||
|
padding: 16px; display: flex; justify-content: space-between; align-items: center;
|
||||||
|
}
|
||||||
|
#sidebar header .me { font-weight: 600; }
|
||||||
|
#sidebar header .me small { display: block; color: var(--subtext); font-weight: 400; }
|
||||||
|
#contacts { flex: 1; overflow-y: auto; padding: 8px; }
|
||||||
|
.contact {
|
||||||
|
display: flex; align-items: center; gap: 12px;
|
||||||
|
padding: 10px 12px; border-radius: 12px; cursor: pointer;
|
||||||
|
}
|
||||||
|
.contact:hover, .contact.active { background: var(--card); }
|
||||||
|
.avatar {
|
||||||
|
width: 40px; height: 40px; border-radius: 50%;
|
||||||
|
background: var(--bubble-in); color: var(--text);
|
||||||
|
display: flex; align-items: center; justify-content: center;
|
||||||
|
font-weight: 600; flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.contact.active .avatar { background: var(--accent); }
|
||||||
|
.contact .cmeta { flex: 1; min-width: 0; }
|
||||||
|
.contact .crow { display: flex; align-items: center; gap: 7px; }
|
||||||
|
.contact .name { font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.contact .ctime { margin-left: auto; font-size: 11px; color: var(--subtext); }
|
||||||
|
.contact .preview {
|
||||||
|
font-size: 12px; color: var(--subtext);
|
||||||
|
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||||
|
}
|
||||||
|
.badge {
|
||||||
|
background: var(--accent); color: var(--text);
|
||||||
|
font-size: 11px; font-weight: 600; min-width: 20px; height: 20px;
|
||||||
|
border-radius: 10px; display: flex; align-items: center;
|
||||||
|
justify-content: center; padding: 0 6px; flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.dot { width: 10px; height: 10px; border-radius: 50%; background: var(--offline); flex-shrink: 0; }
|
||||||
|
.dot.on { background: var(--online); }
|
||||||
|
|
||||||
|
#chat { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
||||||
|
#chat-header {
|
||||||
|
background: var(--header); border-bottom: 2px solid var(--accent);
|
||||||
|
padding: 16px 20px; display: flex; align-items: center; gap: 10px;
|
||||||
|
}
|
||||||
|
#chat-header .status { color: var(--subtext); font-size: 13px; }
|
||||||
|
|
||||||
|
#messages {
|
||||||
|
flex: 1; overflow-y: auto; padding: 20px;
|
||||||
|
display: flex; flex-direction: column; gap: 4px;
|
||||||
|
}
|
||||||
|
#messages .empty { color: var(--subtext); margin: auto; }
|
||||||
|
.msg { max-width: 60%; display: flex; flex-direction: column; margin-bottom: 10px; }
|
||||||
|
.msg .bubble {
|
||||||
|
padding: 10px 14px; border-radius: 14px;
|
||||||
|
background: var(--bubble-in); word-wrap: break-word; white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
.msg .time { font-size: 11px; color: var(--subtext); margin-top: 3px; }
|
||||||
|
.msg.mine { align-self: flex-end; align-items: flex-end; }
|
||||||
|
.msg.mine .bubble { background: var(--accent); }
|
||||||
|
|
||||||
|
#composer {
|
||||||
|
display: flex; gap: 10px; padding: 14px 20px 18px;
|
||||||
|
}
|
||||||
|
#composer input { border-radius: 14px; }
|
||||||
|
#composer button {
|
||||||
|
background: var(--accent); color: var(--text);
|
||||||
|
width: 46px; border-radius: 50%; font-size: 18px; flex-shrink: 0;
|
||||||
|
}
|
||||||
|
#composer button:hover { background: var(--accent-dk); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div id="login">
|
||||||
|
<div class="box">
|
||||||
|
<h1>Vita<span>Chat</span></h1>
|
||||||
|
<div class="sub">Web-Testclient</div>
|
||||||
|
<input id="l-user" placeholder="Benutzername" autocomplete="username">
|
||||||
|
<input id="l-pass" placeholder="Passwort" type="password" autocomplete="current-password">
|
||||||
|
<button class="btn" id="l-login">Anmelden</button>
|
||||||
|
<button class="link" id="l-register">Neu hier? Registrieren</button>
|
||||||
|
<div id="login-status"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="app">
|
||||||
|
<div id="sidebar">
|
||||||
|
<header>
|
||||||
|
<div class="me"><span id="me-name"></span><small>online</small></div>
|
||||||
|
<button class="link" id="logout">Logout</button>
|
||||||
|
</header>
|
||||||
|
<div id="contacts"></div>
|
||||||
|
</div>
|
||||||
|
<div id="chat">
|
||||||
|
<div id="chat-header">
|
||||||
|
<strong id="chat-name">Kontakt wählen</strong>
|
||||||
|
<span class="dot" id="chat-dot"></span>
|
||||||
|
<span class="status" id="chat-status"></span>
|
||||||
|
</div>
|
||||||
|
<div id="messages"><div class="empty">Wähle links einen Kontakt aus</div></div>
|
||||||
|
<div id="composer">
|
||||||
|
<input id="c-text" placeholder="Nachricht schreiben ..." disabled>
|
||||||
|
<button id="c-send" disabled>➤</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const API = '/api'; // gleiche Domain (Vercel) -> kein CORS-Thema
|
||||||
|
|
||||||
|
let token = sessionStorage.getItem('vc_token') || '';
|
||||||
|
let myName = sessionStorage.getItem('vc_name') || '';
|
||||||
|
let chatWith = '';
|
||||||
|
let sinceId = 0;
|
||||||
|
let contactTimer = null, msgTimer = null;
|
||||||
|
|
||||||
|
const $ = id => document.getElementById(id);
|
||||||
|
|
||||||
|
/* ---------- API: zeilenbasiertes Pipe-Protokoll parsen ---------- */
|
||||||
|
async function api(path, params = {}, post = false) {
|
||||||
|
const body = new URLSearchParams(params);
|
||||||
|
const res = post
|
||||||
|
? await fetch(`${API}/${path}`, { method: 'POST', body })
|
||||||
|
: await fetch(`${API}/${path}?${body}`);
|
||||||
|
const text = await res.text();
|
||||||
|
return text.trim().split('\n').filter(Boolean).map(l => l.split('|'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
const d = document.createElement('div');
|
||||||
|
d.textContent = s;
|
||||||
|
return d.innerHTML;
|
||||||
|
}
|
||||||
|
function fmtRel(ts) {
|
||||||
|
const d = new Date(ts * 1000), n = new Date();
|
||||||
|
if (d.toDateString() === n.toDateString())
|
||||||
|
return d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
|
||||||
|
return d.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' });
|
||||||
|
}
|
||||||
|
function fmtTime(ts) {
|
||||||
|
return new Date(ts * 1000).toLocaleTimeString('de-DE',
|
||||||
|
{ hour: '2-digit', minute: '2-digit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Login / Registrieren ---------- */
|
||||||
|
function setLoginStatus(msg, isErr) {
|
||||||
|
const el = $('login-status');
|
||||||
|
el.textContent = msg;
|
||||||
|
el.className = isErr ? 'err' : 'ok';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doLogin() {
|
||||||
|
const user = $('l-user').value.trim(), pass = $('l-pass').value;
|
||||||
|
if (!user || !pass) return setLoginStatus('Name und Passwort eingeben', true);
|
||||||
|
const [line] = await api('login', { user, pass }, true);
|
||||||
|
if (line?.[0] === 'OK') {
|
||||||
|
token = line[1]; myName = user;
|
||||||
|
sessionStorage.setItem('vc_token', token);
|
||||||
|
sessionStorage.setItem('vc_name', myName);
|
||||||
|
enterApp();
|
||||||
|
} else {
|
||||||
|
setLoginStatus(line?.[1] || 'Fehler', true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doRegister() {
|
||||||
|
const user = $('l-user').value.trim(), pass = $('l-pass').value;
|
||||||
|
if (!user || !pass) return setLoginStatus('Name und Passwort eingeben', true);
|
||||||
|
const [line] = await api('register', { user, pass }, true);
|
||||||
|
if (line?.[0] === 'OK') setLoginStatus('Registriert! Jetzt anmelden.', false);
|
||||||
|
else setLoginStatus(line?.[1] || 'Fehler', true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function enterApp() {
|
||||||
|
$('login').style.display = 'none';
|
||||||
|
$('app').classList.add('active');
|
||||||
|
$('me-name').textContent = myName;
|
||||||
|
loadContacts();
|
||||||
|
contactTimer = setInterval(loadContacts, 10000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function doLogout() {
|
||||||
|
sessionStorage.clear();
|
||||||
|
token = ''; chatWith = ''; sinceId = 0;
|
||||||
|
clearInterval(contactTimer); clearInterval(msgTimer);
|
||||||
|
location.reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Kontakte ---------- */
|
||||||
|
async function loadContacts() {
|
||||||
|
const lines = await api('contacts', { token });
|
||||||
|
const box = $('contacts');
|
||||||
|
box.innerHTML = '';
|
||||||
|
let currentOnline = null;
|
||||||
|
|
||||||
|
for (const l of lines) {
|
||||||
|
if (l[0] !== 'USER') continue;
|
||||||
|
const [, name, online, unread = '0', lastTs = '0', preview = ''] = l;
|
||||||
|
if (name === chatWith) currentOnline = online === '1';
|
||||||
|
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = 'contact' + (name === chatWith ? ' active' : '');
|
||||||
|
div.innerHTML = `
|
||||||
|
<div class="avatar">${esc(name[0].toUpperCase())}</div>
|
||||||
|
<div class="cmeta">
|
||||||
|
<div class="crow"><span class="name">${esc(name)}</span>
|
||||||
|
<span class="dot ${online === '1' ? 'on' : ''}"></span>
|
||||||
|
<span class="ctime">${lastTs > 0 ? fmtRel(+lastTs) : ''}</span></div>
|
||||||
|
<div class="preview">${esc(preview)}</div>
|
||||||
|
</div>
|
||||||
|
${+unread > 0 ? `<div class="badge">${+unread > 99 ? 99 : unread}</div>` : ''}`;
|
||||||
|
div.onclick = () => openChat(name);
|
||||||
|
box.appendChild(div);
|
||||||
|
}
|
||||||
|
if (!box.children.length)
|
||||||
|
box.innerHTML = '<div style="padding:16px;color:var(--subtext)">Noch keine anderen Nutzer</div>';
|
||||||
|
|
||||||
|
if (currentOnline !== null) {
|
||||||
|
$('chat-dot').className = 'dot' + (currentOnline ? ' on' : '');
|
||||||
|
$('chat-status').textContent = currentOnline ? 'online' : 'offline';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Chat ---------- */
|
||||||
|
function openChat(name) {
|
||||||
|
chatWith = name;
|
||||||
|
sinceId = 0;
|
||||||
|
$('chat-name').textContent = name;
|
||||||
|
$('messages').innerHTML = '';
|
||||||
|
$('c-text').disabled = false;
|
||||||
|
$('c-send').disabled = false;
|
||||||
|
$('c-text').focus();
|
||||||
|
loadContacts(); // Markierung + Online-Status aktualisieren
|
||||||
|
clearInterval(msgTimer);
|
||||||
|
pollMessages();
|
||||||
|
msgTimer = setInterval(pollMessages, 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pollMessages() {
|
||||||
|
if (!chatWith) return;
|
||||||
|
const lines = await api('poll', { token, with: chatWith, since: sinceId });
|
||||||
|
const box = $('messages');
|
||||||
|
let added = false;
|
||||||
|
|
||||||
|
for (const l of lines) {
|
||||||
|
if (l[0] !== 'MSG') continue;
|
||||||
|
const id = parseInt(l[1]), from = l[2], ts = parseInt(l[3]);
|
||||||
|
const text = l.slice(4).join('|'); // falls '¦'-ersetzte Pipes doch auftauchen
|
||||||
|
if (id > sinceId) sinceId = id;
|
||||||
|
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = 'msg' + (from === myName ? ' mine' : '');
|
||||||
|
div.innerHTML = `<div class="bubble">${esc(text)}</div>
|
||||||
|
<div class="time">${fmtTime(ts)}</div>`;
|
||||||
|
box.appendChild(div);
|
||||||
|
added = true;
|
||||||
|
}
|
||||||
|
if (added) box.scrollTop = box.scrollHeight;
|
||||||
|
if (!box.children.length)
|
||||||
|
box.innerHTML = '<div class="empty">Noch keine Nachrichten – schreib die erste!</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendMessage() {
|
||||||
|
const input = $('c-text');
|
||||||
|
const text = input.value.trim();
|
||||||
|
if (!text || !chatWith) return;
|
||||||
|
input.value = '';
|
||||||
|
const emptyHint = $('messages').querySelector('.empty');
|
||||||
|
if (emptyHint) emptyHint.remove();
|
||||||
|
await api('send', { token, to: chatWith, text }, true);
|
||||||
|
pollMessages();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Events ---------- */
|
||||||
|
$('l-login').onclick = doLogin;
|
||||||
|
$('l-register').onclick = doRegister;
|
||||||
|
$('l-pass').addEventListener('keydown', e => e.key === 'Enter' && doLogin());
|
||||||
|
$('logout').onclick = doLogout;
|
||||||
|
$('c-send').onclick = sendMessage;
|
||||||
|
$('c-text').addEventListener('keydown', e => e.key === 'Enter' && sendMessage());
|
||||||
|
|
||||||
|
/* Session wiederherstellen */
|
||||||
|
if (token && myName) enterApp();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in new issue
Block a user