Soziales Netz im Spiel: Feed, Werbung, Markt, Kalender und Gewerbe

Jeder Spieler waehlt sich ein Handle mit @, Unternehmen und Behoerden bekommen
eigene Profile, fuer die sie Mitarbeiter freigeben.

Verwaltet wird ueber dieselbe Anmeldung wie das Webhosting: wer am IC-Computer
als Anbieter angemeldet ist, richtet Unternehmensprofile ein. Damit gibt es
genau eine Stelle, an der Verwaltungsrechte haengen - ein zweites Rechtesystem
daneben waere eine zweite Stelle, an der man jemanden zu entziehen vergisst.

Bewusst getrennt: wer fuer ein Unternehmen schreiben darf, kann sich nicht
selbst zum Verwalter machen.

Behoben gegenueber dem Ausgangsstand:

  - Die Resource startete nicht. Eine harte Abhaengigkeit zeigte auf eine
    Resource, die es nicht gibt - das verhindert den Start vollstaendig.
  - Das Schema war gegenueber dem Code stehengeblieben: eine Tabelle fehlte
    ganz, sechs Spalten fehlten. Jede Registrierung eines Handles scheiterte
    deshalb mit einem SQL-Fehler. Zwei Migrationen ziehen das nach.
  - Die Identitaet kommt jetzt von ESX statt von einem Charaktersystem, das
    hier nicht laeuft. Ohne das findet das Mailsystem die Postfaecher nicht.
  - Das Fenster hatte keinen Schliessknopf, nur ESC. Im Computerfenster ist
    diese Taste aber schon vergeben.
  - Bilder laden mit referrerpolicy="no-referrer": Bilderdienste sperren
    Hotlinks anhand der Herkunft, und die eines NUI kennen sie nicht.
  - Der Schluessel fuer den Bilder-Upload steht nicht mehr im Code, sondern in
    der server.cfg (set bleeter_imgbb_key). Er gehoert nicht in ein oeffentlich
    einsehbares Repository.

Neu: Unternehmensprofile und Mitarbeiterfreigabe, ueber Netzwerkereignisse und
Konsolenbefehle. Dazu eine Oberflaeche im IC-Computer, die dieselbe Gestaltung
benutzt - die Stildatei wird dafuer mechanisch gekapselt, statt sie nachzubauen.

Enthaelt README.md mit Einrichtung, Rechten und den Fallstricken.
This commit is contained in:
Bjoern Flessing 2026-08-09 12:00:48 +00:00
commit 20076b0aee
41 changed files with 8652 additions and 0 deletions

View file

@ -0,0 +1,65 @@
const express = require('express');
const bcrypt = require('bcryptjs');
const db = require('../db');
const { sign, requireAuth } = require('../auth');
const { getAccessibleProfiles } = require('../lib/account');
const { hasLifeinvaderPermission } = require('../lib/permissions');
const router = express.Router();
function publicAccount(account) {
return {
id: account.id,
char_id: account.char_id,
mail_address: account.mail_address,
phone_number: account.phone_number,
};
}
// Login mit Handle ODER Mail + ingame gesetztem Bleeter-Passwort
router.post('/login', async (req, res) => {
try {
const login = String((req.body && req.body.login) || '').trim().toLowerCase();
const password = String((req.body && req.body.password) || '');
if (!login || !password) return res.status(400).json({ error: 'missing_credentials' });
let account = null;
if (login.includes('@')) {
account = await db.q1('SELECT * FROM bleeter_accounts WHERE mail_address = ?', [login]);
} else {
const profile = await db.q1('SELECT account_id FROM bleeter_profiles WHERE handle = ? LIMIT 1', [login]);
if (profile && profile.account_id) {
account = await db.q1('SELECT * FROM bleeter_accounts WHERE id = ?', [profile.account_id]);
}
}
if (!account || !account.web_password_hash) {
return res.status(401).json({ error: 'invalid_login' });
}
if (account.status && account.status !== 'active') {
return res.status(403).json({ error: 'account_disabled' });
}
const ok = await bcrypt.compare(password, account.web_password_hash);
if (!ok) return res.status(401).json({ error: 'invalid_login' });
const token = sign(account);
const profiles = await getAccessibleProfiles(account);
res.json({ token, account: publicAccount(account), profiles });
} catch (err) {
console.error('[bleeter] login error', err);
res.status(500).json({ error: 'server_error' });
}
});
// Aktueller Account + zugaengliche Profile + Moderationsflag
router.get('/me', requireAuth, async (req, res) => {
const profiles = await getAccessibleProfiles(req.account);
const canModerate =
(await hasLifeinvaderPermission(db, req.account.char_id, 'profile.verify')) ||
(await hasLifeinvaderPermission(db, req.account.char_id, 'profile.staff')) ||
(await hasLifeinvaderPermission(db, req.account.char_id, 'profile.lock'));
res.json({ account: publicAccount(req.account), profiles, can_moderate: canModerate });
});
module.exports = router;

View file

@ -0,0 +1,42 @@
const express = require('express');
const db = require('../db');
const { requireAuth } = require('../auth');
const { resolveActingProfile } = require('../lib/account');
const { loadBusinesses } = require('../lib/queries');
const router = express.Router();
router.use(requireAuth);
const BUSINESS_TYPES = ['small_business', 'company', 'authority'];
async function acting(req) {
const profileId = (req.body && req.body.profileId) || req.query.profileId;
return resolveActingProfile(req.account, profileId);
}
// GET /api/businesses?profileId=
router.get('/businesses', async (req, res) => {
const { profile } = await acting(req);
res.json({ businesses: await loadBusinesses(profile ? profile.id : 0) });
});
// POST /api/business/status {profileId, status: open|closed} -> eigenes Gewerbe schalten
router.post('/business/status', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
if (!BUSINESS_TYPES.includes(profile.profile_type) || !profile.can_edit_profile) {
return res.status(403).json({ error: 'not_allowed' });
}
const status = req.body.status === 'open' ? 'open' : req.body.status === 'closed' ? 'closed' : null;
if (!status) return res.status(400).json({ error: 'invalid_status' });
await db.exec(
`INSERT INTO bleeter_business_status (profile_id, status, source)
VALUES (?, ?, 'web')
ON DUPLICATE KEY UPDATE status = VALUES(status), source = VALUES(source)`,
[profile.id, status]
);
res.json({ ok: true, status });
});
module.exports = router;

View file

@ -0,0 +1,57 @@
const express = require('express');
const db = require('../db');
const { requireAuth } = require('../auth');
const { resolveActingProfile } = require('../lib/account');
const { loadCalendarDays } = require('../lib/queries');
const router = express.Router();
router.use(requireAuth);
const BUSINESS_TYPES = ['small_business', 'company', 'authority'];
async function acting(req) {
const profileId = (req.body && req.body.profileId) || req.query.profileId;
return resolveActingProfile(req.account, profileId);
}
// GET /api/calendar?profileId=
router.get('/calendar', async (req, res) => {
const { profile } = await acting(req);
res.json({ days: await loadCalendarDays(profile ? profile.id : 0) });
});
// POST /api/events {profileId, date, time, title, location}
router.post('/events', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
if (!BUSINESS_TYPES.includes(profile.profile_type)) return res.status(403).json({ error: 'not_allowed' });
const date = String(req.body.date || '').trim().slice(0, 10);
const time = String(req.body.time || '').trim().slice(0, 5);
const title = String(req.body.title || '').trim().slice(0, 50);
const location = String(req.body.location || '').trim().slice(0, 50);
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return res.status(400).json({ error: 'invalid_date' });
if (!/^\d{2}:\d{2}$/.test(time)) return res.status(400).json({ error: 'invalid_time' });
if (!title) return res.status(400).json({ error: 'title_required' });
await db.insert(
'INSERT INTO bleeter_events (author_profile_id, title, location, starts_at) VALUES (?, ?, ?, ?)',
[profile.id, title, location || null, `${date} ${time}:00`]
);
res.json({ ok: true });
});
// DELETE /api/events/:id {profileId}
router.delete('/events/:id', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
const eventId = Number(req.params.id);
const ev = await db.q1('SELECT author_profile_id FROM bleeter_events WHERE id = ? AND deleted_at IS NULL', [eventId]);
if (!ev) return res.status(404).json({ error: 'not_found' });
if (Number(ev.author_profile_id) !== Number(profile.id)) return res.status(403).json({ error: 'not_owner' });
await db.exec("UPDATE bleeter_events SET deleted_at = NOW(), status = 'deleted' WHERE id = ?", [eventId]);
res.json({ ok: true });
});
module.exports = router;

126
web-backend/routes/feed.js Normal file
View file

@ -0,0 +1,126 @@
const express = require('express');
const db = require('../db');
const { requireAuth } = require('../auth');
const { resolveActingProfile } = require('../lib/account');
const { loadPosts, loadCommentsForPost } = require('../lib/queries');
const { canPost } = require('../lib/permissions');
const { isAllowedExternalUrl } = require('../lib/media');
const router = express.Router();
router.use(requireAuth);
// Helfer: aktives Profil aufloesen (profileId aus body/query)
async function acting(req) {
const profileId = (req.body && req.body.profileId) || req.query.profileId;
return resolveActingProfile(req.account, profileId);
}
// GET /api/feed?type=home|advertising&profileId=
router.get('/feed', async (req, res) => {
const { profile } = await acting(req);
const type = req.query.type === 'advertising' ? 'advertising'
: req.query.type === 'home' ? 'home' : null;
const posts = await loadPosts(profile ? profile.id : 0, type);
res.json({ posts });
});
// POST /api/posts {profileId, feedType, body, mediaUrl}
router.post('/posts', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
const feedType = String(req.body.feedType || '').trim();
const body = String(req.body.body || '').trim().slice(0, 2000);
const mediaUrl = String(req.body.mediaUrl || '').trim().slice(0, 500);
if (!body && !mediaUrl) return res.status(400).json({ error: 'empty_post' });
if (feedType !== 'home' && feedType !== 'advertising') return res.status(400).json({ error: 'invalid_feed' });
if (!canPost(profile.profile_type, feedType)) return res.status(403).json({ error: 'not_allowed_here' });
let mediaId = null;
if (mediaUrl) {
const check = isAllowedExternalUrl(mediaUrl);
if (!check.ok) return res.status(400).json({ error: 'media_rejected', reason: check.reason });
mediaId = await db.insert(
'INSERT INTO bleeter_media (owner_profile_id, source_type, url) VALUES (?, ?, ?)',
[profile.id, 'external_url', mediaUrl]
);
}
await db.insert(
'INSERT INTO bleeter_posts (author_profile_id, feed_type, body, media_id) VALUES (?, ?, ?, ?)',
[profile.id, feedType, body, mediaId]
);
res.json({ ok: true });
});
// DELETE /api/posts/:id {profileId}
router.delete('/posts/:id', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
const postId = Number(req.params.id);
const post = await db.q1('SELECT author_profile_id FROM bleeter_posts WHERE id = ? AND deleted_at IS NULL AND self_deleted_at IS NULL', [postId]);
if (!post) return res.status(404).json({ error: 'not_found' });
if (Number(post.author_profile_id) !== Number(profile.id)) return res.status(403).json({ error: 'not_owner' });
await db.exec('UPDATE bleeter_posts SET self_deleted_at = NOW() WHERE id = ?', [postId]);
res.json({ ok: true });
});
// POST /api/posts/:id/like {profileId} -> toggle
router.post('/posts/:id/like', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
await toggleLike(profile.id, 'post', Number(req.params.id));
res.json({ ok: true });
});
// POST /api/posts/:id/comments {profileId, body}
router.post('/posts/:id/comments', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
const postId = Number(req.params.id);
const body = String(req.body.body || '').trim().slice(0, 500);
if (!body) return res.status(400).json({ error: 'empty_comment' });
const post = await db.q1('SELECT id FROM bleeter_posts WHERE id = ? AND deleted_at IS NULL AND self_deleted_at IS NULL AND hidden_at IS NULL', [postId]);
if (!post) return res.status(404).json({ error: 'not_found' });
await db.insert('INSERT INTO bleeter_comments (post_id, author_profile_id, body) VALUES (?, ?, ?)', [postId, profile.id, body]);
const comments = await loadCommentsForPost(postId, profile.id);
res.json({ ok: true, comments });
});
// DELETE /api/comments/:id {profileId}
router.delete('/comments/:id', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
const commentId = Number(req.params.id);
const c = await db.q1('SELECT author_profile_id, post_id FROM bleeter_comments WHERE id = ? AND deleted_at IS NULL AND self_deleted_at IS NULL', [commentId]);
if (!c) return res.status(404).json({ error: 'not_found' });
if (Number(c.author_profile_id) !== Number(profile.id)) return res.status(403).json({ error: 'not_owner' });
await db.exec('UPDATE bleeter_comments SET self_deleted_at = NOW() WHERE id = ?', [commentId]);
res.json({ ok: true });
});
// POST /api/comments/:id/like {profileId} -> toggle
router.post('/comments/:id/like', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
await toggleLike(profile.id, 'comment', Number(req.params.id));
res.json({ ok: true });
});
async function toggleLike(profileId, targetType, targetId) {
const existing = await db.q1(
'SELECT id FROM bleeter_likes WHERE profile_id = ? AND target_type = ? AND target_id = ?',
[profileId, targetType, targetId]
);
if (existing) {
await db.exec('DELETE FROM bleeter_likes WHERE id = ?', [existing.id]);
} else {
await db.exec(
'INSERT IGNORE INTO bleeter_likes (profile_id, target_type, target_id) VALUES (?, ?, ?)',
[profileId, targetType, targetId]
);
}
}
module.exports = router;

View file

@ -0,0 +1,41 @@
const express = require('express');
const bcrypt = require('bcryptjs');
const db = require('../db');
require('dotenv').config();
const router = express.Router();
// Nur vom FiveM-Server erreichbar (interner Key)
function requireInternal(req, res, next) {
const key = req.headers['x-internal-key'];
if (!key || key !== process.env.INTERNAL_API_KEY) {
return res.status(403).json({ error: 'forbidden' });
}
next();
}
// POST /internal/set-password {charId, password}
// Wird ingame vom Spieler ausgeloest; Passwort wird hier gehasht gespeichert.
router.post('/set-password', requireInternal, async (req, res) => {
try {
const charId = String((req.body && req.body.charId) || '').trim();
const password = String((req.body && req.body.password) || '');
if (!charId) return res.status(400).json({ error: 'missing_char' });
if (password.length < 6) return res.status(400).json({ error: 'password_too_short' });
const account = await db.q1('SELECT id FROM bleeter_accounts WHERE char_id = ?', [charId]);
if (!account) return res.status(404).json({ error: 'no_account' });
const hash = await bcrypt.hash(password, 10);
await db.exec(
'UPDATE bleeter_accounts SET web_password_hash = ?, web_password_updated_at = NOW() WHERE id = ?',
[hash, account.id]
);
res.json({ ok: true });
} catch (err) {
console.error('[bleeter] set-password error', err.message);
res.status(500).json({ error: 'server_error' });
}
});
module.exports = router;

View file

@ -0,0 +1,63 @@
const express = require('express');
const db = require('../db');
const { requireAuth } = require('../auth');
const { resolveActingProfile } = require('../lib/account');
const { loadMarketplace } = require('../lib/queries');
const { isAllowedExternalUrl } = require('../lib/media');
const router = express.Router();
router.use(requireAuth);
async function acting(req) {
const profileId = (req.body && req.body.profileId) || req.query.profileId;
return resolveActingProfile(req.account, profileId);
}
// GET /api/marketplace?profileId=
router.get('/marketplace', async (req, res) => {
const { profile } = await acting(req);
res.json({ items: await loadMarketplace(profile ? profile.id : 0) });
});
// POST /api/marketplace {profileId, title, description, priceLabel, mediaUrl}
router.post('/marketplace', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
let title = String(req.body.title || '').trim().slice(0, 120);
let description = String(req.body.description || '').trim().slice(0, 2000);
const priceLabel = String(req.body.priceLabel || '').trim().slice(0, 80);
const mediaUrl = String(req.body.mediaUrl || '').trim().slice(0, 500);
if (!title && !description) return res.status(400).json({ error: 'empty' });
if (!description) description = title;
if (!title) title = description.slice(0, 120);
let mediaId = null;
if (mediaUrl) {
const check = isAllowedExternalUrl(mediaUrl);
if (!check.ok) return res.status(400).json({ error: 'media_rejected', reason: check.reason });
mediaId = await db.insert('INSERT INTO bleeter_media (owner_profile_id, source_type, url) VALUES (?, ?, ?)', [profile.id, 'external_url', mediaUrl]);
}
await db.insert(
`INSERT INTO bleeter_marketplace (author_profile_id, category, title, description, price_label, media_id)
VALUES (?, 'general', ?, ?, ?, ?)`,
[profile.id, title, description, priceLabel, mediaId]
);
res.json({ ok: true });
});
// DELETE /api/marketplace/:id {profileId}
router.delete('/marketplace/:id', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
const entryId = Number(req.params.id);
const entry = await db.q1('SELECT author_profile_id FROM bleeter_marketplace WHERE id = ? AND deleted_at IS NULL', [entryId]);
if (!entry) return res.status(404).json({ error: 'not_found' });
if (Number(entry.author_profile_id) !== Number(profile.id)) return res.status(403).json({ error: 'not_owner' });
await db.exec("UPDATE bleeter_marketplace SET deleted_at = NOW(), status = 'deleted' WHERE id = ?", [entryId]);
res.json({ ok: true });
});
module.exports = router;

View file

@ -0,0 +1,40 @@
const express = require('express');
const multer = require('multer');
const db = require('../db');
const { requireAuth } = require('../auth');
const { resolveActingProfile } = require('../lib/account');
const { uploadToImgbb, ALLOWED_EXT } = require('../lib/media');
const router = express.Router();
router.use(requireAuth);
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 2 * 1024 * 1024 }, // 2 MB (Config.Media.maxBytes)
});
// POST /api/media/upload (multipart: image) {profileId}
router.post('/media/upload', upload.single('image'), async (req, res) => {
try {
const { profile } = await resolveActingProfile(req.account, req.body.profileId);
if (!profile) return res.status(400).json({ error: 'no_profile' });
if (!req.file) return res.status(400).json({ error: 'no_file' });
const ext = (req.file.originalname.split('.').pop() || '').toLowerCase();
const mimeOk = /^image\/(jpe?g|png)$/i.test(req.file.mimetype || '');
if (!ALLOWED_EXT.includes(ext) && !mimeOk) return res.status(400).json({ error: 'unsupported_type' });
const { url } = await uploadToImgbb(req.file.buffer, req.file.originalname);
await db.insert(
`INSERT INTO bleeter_media (owner_profile_id, source_type, url, original_name, mime_type, size_bytes)
VALUES (?, 'upload', ?, ?, ?, ?)`,
[profile.id, url, req.file.originalname, req.file.mimetype, req.file.size]
);
res.json({ ok: true, url });
} catch (err) {
console.error('[bleeter] media upload error', err.message);
res.status(500).json({ error: 'upload_failed' });
}
});
module.exports = router;

View file

@ -0,0 +1,62 @@
const express = require('express');
const db = require('../db');
const { requireAuth } = require('../auth');
const { resolveActingProfile, findTargetProfile } = require('../lib/account');
const { hasLifeinvaderPermission, decodeBool } = require('../lib/permissions');
const router = express.Router();
router.use(requireAuth);
const PERMISSION_BY_ACTION = {
verify: 'profile.verify',
staff: 'profile.staff',
lock: 'profile.lock',
};
async function writeAudit(account, actorProfile, action, targetType, targetId, reason, payload) {
await db.insert(
`INSERT INTO bleeter_audit_logs (actor_char_id, actor_profile_id, action, target_type, target_id, reason, payload)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
[account.char_id, actorProfile ? actorProfile.id : null, action, targetType, targetId, reason || null,
payload ? JSON.stringify(payload) : null]
);
}
// POST /api/moderation/profile {profileId, action: verify|staff|lock, targetId}
router.post('/moderation/profile', async (req, res) => {
const { profile } = await resolveActingProfile(req.account, req.body.profileId);
const action = String(req.body.action || '').trim();
const target = await findTargetProfile({ targetId: req.body.targetId }, true);
if (!profile || !target) return res.status(400).json({ error: 'invalid' });
const permission = PERMISSION_BY_ACTION[action];
if (!permission || !(await hasLifeinvaderPermission(db, req.account.char_id, permission))) {
return res.status(403).json({ error: 'no_lifeinvader_rights' });
}
if (action === 'lock' && Number(profile.id) === Number(target.id)) {
return res.status(400).json({ error: 'cannot_lock_self' });
}
if (action === 'verify') {
const next = !decodeBool(target.is_verified);
await db.exec('UPDATE bleeter_profiles SET is_verified = ? WHERE id = ?', [next ? 1 : 0, target.id]);
await writeAudit(req.account, profile, next ? 'profile.verify' : 'profile.unverify', 'profile', target.id, null, { handle: target.handle, is_verified: next });
return res.json({ ok: true, is_verified: next });
}
if (action === 'staff') {
const next = !decodeBool(target.is_lifeinvader_staff);
await db.exec('UPDATE bleeter_profiles SET is_lifeinvader_staff = ? WHERE id = ?', [next ? 1 : 0, target.id]);
await writeAudit(req.account, profile, next ? 'profile.staff.add' : 'profile.staff.remove', 'profile', target.id, null, { handle: target.handle, is_lifeinvader_staff: next });
return res.json({ ok: true, is_lifeinvader_staff: next });
}
if (action === 'lock') {
const next = !decodeBool(target.is_locked);
await db.exec('UPDATE bleeter_profiles SET is_locked = ?, locked_reason = ? WHERE id = ?',
[next ? 1 : 0, next ? 'Lifeinvader moderation' : null, target.id]);
await writeAudit(req.account, profile, next ? 'profile.lock' : 'profile.unlock', 'profile', target.id, null, { handle: target.handle, is_locked: next });
return res.json({ ok: true, is_locked: next });
}
res.status(400).json({ error: 'unknown_action' });
});
module.exports = router;

View file

@ -0,0 +1,174 @@
const express = require('express');
const db = require('../db');
const { requireAuth } = require('../auth');
const { resolveActingProfile, findTargetProfile, mapProfile, getAccessibleProfiles } = require('../lib/account');
const { loadProfileDirectory, loadSocial } = require('../lib/queries');
const { canProfileBeBlocked, decodeBool } = require('../lib/permissions');
const router = express.Router();
router.use(requireAuth);
const HANDLE_RE = /^[a-z0-9._-]+$/;
async function acting(req) {
const profileId = (req.body && req.body.profileId) || req.query.profileId;
return resolveActingProfile(req.account, profileId);
}
// GET /api/directory?profileId=
router.get('/directory', async (req, res) => {
const { profile } = await acting(req);
const profiles = await loadProfileDirectory(profile ? profile.id : 0, false);
res.json({ profiles });
});
// GET /api/social?profileId=
router.get('/social', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.json({ following: [], followers: [], blocked: [] });
res.json(await loadSocial(profile.id));
});
// GET /api/profiles/:handle?profileId= -> Profil + eigene Posts
router.get('/profiles/:handle', async (req, res) => {
const { profile: viewer } = await acting(req);
const viewerId = viewer ? viewer.id : 0;
const handle = String(req.params.handle || '').toLowerCase();
const row = await db.q1(
`SELECT p.*,
(SELECT COUNT(*) FROM bleeter_follows f WHERE f.followed_profile_id=p.id) AS followers_count,
(SELECT COUNT(*) FROM bleeter_follows f WHERE f.follower_profile_id=p.id) AS following_count
FROM bleeter_profiles p WHERE p.handle = ? AND p.is_active = 1`,
[handle]
);
if (!row) return res.status(404).json({ error: 'not_found' });
const target = mapProfile(row);
const isFollowing = viewerId ? !!(await db.q1(
'SELECT 1 FROM bleeter_follows WHERE follower_profile_id = ? AND followed_profile_id = ? LIMIT 1',
[viewerId, target.id]
)) : false;
const isBlocked = viewerId ? !!(await db.q1(
'SELECT 1 FROM bleeter_blocks WHERE blocker_profile_id = ? AND blocked_profile_id = ? LIMIT 1',
[viewerId, target.id]
)) : false;
const posts = await db.q(
`SELECT posts.id, posts.feed_type, posts.body, posts.created_at, media.url AS media_url,
(SELECT COUNT(*) FROM bleeter_likes l WHERE l.target_type='post' AND l.target_id=posts.id) AS likes,
(SELECT COUNT(*) FROM bleeter_comments c WHERE c.post_id=posts.id AND c.self_deleted_at IS NULL AND c.hidden_at IS NULL AND c.deleted_at IS NULL) AS comments
FROM bleeter_posts posts
LEFT JOIN bleeter_media media ON media.id = posts.media_id
WHERE posts.author_profile_id = ? AND posts.self_deleted_at IS NULL AND posts.hidden_at IS NULL AND posts.deleted_at IS NULL
ORDER BY posts.created_at DESC LIMIT 50`,
[target.id]
);
res.json({
profile: target,
is_following: isFollowing,
is_blocked: isBlocked,
posts: posts.map(p => ({
id: p.id, feed_type: p.feed_type, body: p.body || '', media_url: p.media_url,
created_at: String(p.created_at || ''), likes: Number(p.likes) || 0, comments: Number(p.comments) || 0,
})),
});
});
// POST /api/profiles/:id/follow {profileId}
router.post('/profiles/:id/follow', async (req, res) => {
const { profile } = await acting(req);
const target = await findTargetProfile({ targetId: req.params.id });
if (!profile || !target) return res.status(400).json({ error: 'invalid' });
if (Number(profile.id) === Number(target.id)) return res.status(400).json({ error: 'self_follow' });
await db.exec('INSERT IGNORE INTO bleeter_follows (follower_profile_id, followed_profile_id) VALUES (?, ?)', [profile.id, target.id]);
res.json({ ok: true });
});
// POST /api/profiles/:id/unfollow {profileId}
router.post('/profiles/:id/unfollow', async (req, res) => {
const { profile } = await acting(req);
const target = await findTargetProfile({ targetId: req.params.id });
if (!profile || !target) return res.status(400).json({ error: 'invalid' });
await db.exec('DELETE FROM bleeter_follows WHERE follower_profile_id = ? AND followed_profile_id = ?', [profile.id, target.id]);
res.json({ ok: true });
});
// POST /api/profiles/:id/block {profileId}
router.post('/profiles/:id/block', async (req, res) => {
const { profile } = await acting(req);
const target = await findTargetProfile({ targetId: req.params.id });
if (!profile || !target) return res.status(400).json({ error: 'invalid' });
if (Number(profile.id) === Number(target.id)) return res.status(400).json({ error: 'self_block' });
if (!canProfileBeBlocked(target.profile_type, target.is_lifeinvader_staff)) return res.status(403).json({ error: 'cannot_block' });
await db.exec('INSERT IGNORE INTO bleeter_blocks (blocker_profile_id, blocked_profile_id) VALUES (?, ?)', [profile.id, target.id]);
await db.exec(
`DELETE FROM bleeter_follows
WHERE (follower_profile_id=? AND followed_profile_id=?) OR (follower_profile_id=? AND followed_profile_id=?)`,
[profile.id, target.id, target.id, profile.id]
);
res.json({ ok: true });
});
// POST /api/profiles/:id/unblock {profileId}
router.post('/profiles/:id/unblock', async (req, res) => {
const { profile } = await acting(req);
const target = await findTargetProfile({ targetId: req.params.id });
if (!profile || !target) return res.status(400).json({ error: 'invalid' });
await db.exec('DELETE FROM bleeter_blocks WHERE blocker_profile_id = ? AND blocked_profile_id = ?', [profile.id, target.id]);
res.json({ ok: true });
});
// PATCH /api/profile {profileId, displayName, avatarUrl, bannerUrl, bio} -> aktives Profil bearbeiten
router.patch('/profile', async (req, res) => {
const { profile } = await acting(req);
if (!profile) return res.status(400).json({ error: 'no_profile' });
if (!profile.can_edit_profile) return res.status(403).json({ error: 'not_allowed' });
const displayName = String(req.body.displayName || '').trim().slice(0, 80);
const avatarUrl = String(req.body.avatarUrl || '').trim().slice(0, 255);
const bannerUrl = String(req.body.bannerUrl || '').trim().slice(0, 255);
const bioMax = profile.profile_type === 'private' ? 200 : 500;
const bio = String(req.body.bio || '').trim().slice(0, bioMax);
if (!displayName) return res.status(400).json({ error: 'name_required' });
await db.exec(
'UPDATE bleeter_profiles SET display_name = ?, avatar_url = ?, banner_url = ?, bio = ? WHERE id = ?',
[displayName, avatarUrl || null, bannerUrl || null, bio, profile.id]
);
res.json({ ok: true });
});
// POST /api/register {handle, displayName} -> privates Profil anlegen (falls noch keins)
router.post('/register', async (req, res) => {
const account = req.account;
let handle = String(req.body.handle || '').trim().toLowerCase();
let displayName = String(req.body.displayName || '').trim().slice(0, 80);
if (handle.length < 2 || handle.length > 32) return res.status(400).json({ error: 'invalid_handle_length' });
if (!HANDLE_RE.test(handle)) return res.status(400).json({ error: 'invalid_handle_chars' });
if (!displayName) displayName = handle;
const existingPrivate = await db.q1(
"SELECT id FROM bleeter_profiles WHERE account_id = ? AND profile_type = 'private' LIMIT 1",
[account.id]
);
if (existingPrivate) return res.status(409).json({ error: 'already_registered' });
const reserved = await db.q1('SELECT 1 FROM bleeter_reserved_handles WHERE handle = ? LIMIT 1', [handle]);
if (reserved) return res.status(409).json({ error: 'reserved' });
const taken = await db.q1('SELECT 1 FROM bleeter_profiles WHERE handle = ? LIMIT 1', [handle]);
if (taken) return res.status(409).json({ error: 'handle_taken' });
await db.insert(
`INSERT INTO bleeter_profiles (account_id, profile_type, handle, display_name, email_contact, bio)
VALUES (?, 'private', ?, ?, ?, '')`,
[account.id, handle, displayName, account.mail_address]
);
const profiles = await getAccessibleProfiles(account);
res.json({ ok: true, profiles });
});
module.exports = router;