Files

572 lines
18 KiB
TypeScript

import express from 'express';
import http from 'http';
import path from 'path';
import fs from 'fs';
import { WebSocketServer, WebSocket } from 'ws';
import { createServer as createViteServer } from 'vite';
import { db } from './server/db.ts';
import { verifyToastPhoto } from './server/vlm.ts';
import { saveAndSyncPhoto, getImmichAlbums, createImmichAlbum, testImmichConnection } from './server/immich.ts';
const app = express();
const PORT = 3000;
// High body limit (50mb) for uncompressed, original high-res wedding photos
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
// Static uploads folder
const UPLOADS_DIR = path.join(process.cwd(), 'data', 'uploads');
if (!fs.existsSync(UPLOADS_DIR)) {
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
}
app.use('/api/uploads', express.static(UPLOADS_DIR));
const server = http.createServer(app);
// WebSocket Server
const wss = new WebSocketServer({ server, path: '/ws' });
export function broadcast(event: string, data: any) {
const payload = JSON.stringify({ event, data, timestamp: Date.now() });
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
try {
client.send(payload);
} catch (err) {
console.warn('Failed to send WS message to client:', err);
}
}
});
}
wss.on('connection', (ws) => {
// Send current state on connection
const state = db.getAggregatedStats();
ws.send(JSON.stringify({ event: 'STATE_SYNC', data: state, timestamp: Date.now() }));
ws.on('message', (msg) => {
try {
const parsed = JSON.parse(msg.toString());
if (parsed.type === 'PING') {
ws.send(JSON.stringify({ type: 'PONG' }));
}
} catch {
// Ignore invalid frames
}
});
});
// Periodic round countdown checker
setInterval(() => {
const state = db.getState();
const now = Date.now();
// If round was active and 5.2 seconds passed, end it automatically
if (state.round_active && state.round_start_time && now - state.round_start_time > 5200) {
const { cooldown_until } = db.endKissRound();
broadcast('KISS_ROUND_END', { cooldown_until, stats: db.getAggregatedStats() });
}
// If cooldown passed, clear it and broadcast ready state
if (state.cooldown_until && now >= state.cooldown_until) {
db.updateSettings({ cooldown_until: null });
broadcast('STATE_SYNC', db.getAggregatedStats());
}
}, 500);
// ======================== API ROUTES ========================
// 1. Health
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', time: Date.now() });
});
// 2. Auth / Onboarding
app.post('/api/auth', (req, res) => {
try {
const { ticket_id, guest_name, team_id, team_name, role } = req.body;
if (!ticket_id || !guest_name) {
return res.status(400).json({ error: 'Заполните номер билета и имя' });
}
const cleanTicket = ticket_id.trim().toUpperCase();
const guest = db.registerGuest(cleanTicket, guest_name, team_id || 'team_friends', team_name, role);
const stats = db.getAggregatedStats();
broadcast('STATE_SYNC', stats);
res.json({
success: true,
guest,
stats,
});
} catch (error: any) {
res.status(500).json({ error: error.message || 'Ошибка регистрации' });
}
});
// 3. Guest profile & stats
app.get('/api/guest/:ticketId', (req, res) => {
const { ticketId } = req.params;
const guest = db.getGuest(ticketId);
if (!guest) {
return res.status(404).json({ error: 'Гость не найден' });
}
const state = db.getState();
const myKisses = state.kiss_catches.filter((k) => k.ticket_id === guest.ticket_id);
const myKissPoints = myKisses.reduce((sum, k) => sum + k.points, 0);
const myToasts = state.toasts.filter((t) => t.ticket_id === guest.ticket_id);
const myDrinkPoints = myToasts.length * 10;
res.json({
guest,
myPoints: myKissPoints + myDrinkPoints,
myKissesCount: myKisses.length,
myToastsCount: myToasts.length,
myDrinksCount: myToasts.length,
stats: db.getAggregatedStats(),
});
});
// 4. Global State
app.get('/api/state', (req, res) => {
res.json({
...db.getAggregatedStats(),
photos: db.getState().photos.slice(0, 50),
toasts: db.getState().toasts.slice(-20).reverse(),
settings: {
couples_names: db.getState().couples_names,
cake_time_target: db.getState().cake_time_target,
immich_url: db.getState().immich_url,
immich_album_id: db.getState().immich_album_id,
immich_album_name: db.getState().immich_album_name,
ollama_url: db.getState().ollama_url,
},
});
});
// 5. Catch Kiss (Paparazzi Game)
app.post('/api/kiss/catch', (req, res) => {
try {
const { ticket_id } = req.body;
if (!ticket_id) {
return res.status(400).json({ error: 'Билет не указан' });
}
const result = db.catchKiss(ticket_id);
if (result.success) {
const stats = db.getAggregatedStats();
if (result.is_golden) {
// Broadcast golden catch overlay to projector and all devices
broadcast('KISS_ROUND_START', {
round_id: result.round_id,
first_catcher: result.catcher_info,
points: 3,
stats,
});
} else {
// Additional catch inside 5s window
broadcast('KISS_CATCH', {
round_id: result.round_id,
guest: result.guest,
points: 1,
stats,
});
}
}
res.json(result);
} catch (error: any) {
res.status(500).json({ error: error.message || 'Ошибка фиксации поцелуя' });
}
});
// 6. Drink Quest Upload with Ollama / Gemini VLM Verification
app.post('/api/toast/upload', async (req, res) => {
try {
const { ticket_id, image_base64, caption, quest_id, quest_title, quest_instruction, filename, file_type, file_created_at } = req.body;
if (!ticket_id || !image_base64) {
return res.status(400).json({ error: 'Необходимо прикрепить фото' });
}
const guest = db.getGuest(ticket_id);
const teamName = guest ? guest.team_name : '🎉 Команда Друзей';
const guestName = guest ? guest.guest_name : 'Гость';
// Respond immediately so client UI is non-blocking
res.json({
success: true,
message: 'Фото получено, отправлено на нейросетевую проверку квеста...',
});
// Run async background AI verification and upload in full original quality
(async () => {
try {
const state = db.getState();
// 1. Save photo in original quality & sync to dedicated Immich album
const uploadResult = await saveAndSyncPhoto(
image_base64,
filename || `drink-quest-${Date.now()}.jpg`,
state.immich_url,
state.immich_api_key,
state.immich_album_id,
{
mimeType: file_type,
fileCreatedAt: file_created_at,
}
);
// 2. VLM / AI Quest verification
const vlmResult = await verifyToastPhoto(
image_base64,
teamName,
guestName,
{
id: quest_id || 'quest_general',
title: quest_title || 'Праздничный тост',
instruction: quest_instruction || 'Проверь наличие бокала',
},
state.ollama_url
);
// 3. Record verified drink/toast in DB
const toast = db.addToast(
ticket_id,
uploadResult.url,
vlmResult.detected_glasses,
vlmResult.confidence,
caption ? `${caption} — ${vlmResult.toast_phrase}` : vlmResult.toast_phrase,
quest_id,
quest_title,
vlmResult.quest_completed
);
const stats = db.getAggregatedStats();
// 4. Broadcast Polaroid flash alert to projector screen & guests
broadcast('TOAST_CONFIRMED', {
toast,
photo_url: uploadResult.url,
guest_name: guestName,
team_name: teamName,
ai_cheer: toast.ai_cheer,
quest_title: quest_title || 'Праздничный бокал',
quest_completed: vlmResult.quest_completed,
detected_glasses: toast.detected_glasses,
stats,
});
} catch (bgError) {
console.error('Background drink verification error:', bgError);
}
})();
} catch (error: any) {
res.status(500).json({ error: error.message || 'Ошибка обработки квеста' });
}
});
// 7. Photos Gallery
app.get('/api/photos', (req, res) => {
res.json({
photos: db.getState().photos,
total: db.getState().photos.length,
immich_url: db.getState().immich_url,
immich_album_id: db.getState().immich_album_id,
immich_album_name: db.getState().immich_album_name,
});
});
app.post('/api/photos/upload', async (req, res) => {
try {
const { ticket_id, image_base64, caption, filename, file_type, file_created_at } = req.body;
if (!image_base64) {
return res.status(400).json({ error: 'Фото не передано' });
}
const guest = ticket_id ? db.getGuest(ticket_id) : undefined;
const state = db.getState();
// Save in 100% original quality and sync to Immich album
const uploadResult = await saveAndSyncPhoto(
image_base64,
filename || `gallery-${Date.now()}.jpg`,
state.immich_url,
state.immich_api_key,
state.immich_album_id,
{
mimeType: file_type,
fileCreatedAt: file_created_at,
}
);
const newPhoto = db.addPhoto({
ticket_id: guest?.ticket_id,
guest_name: guest?.guest_name || 'Гость',
team_id: guest?.team_id || 'team_friends',
team_name: guest?.team_name || '🎉 Команда Друзей',
url: uploadResult.url,
caption: caption || 'Свадебный кадр',
is_toast: false,
});
broadcast('NEW_PHOTO', { photo: newPhoto, stats: db.getAggregatedStats() });
res.json({
success: true,
photo: newPhoto,
immichSynced: uploadResult.syncedToImmich,
albumSynced: uploadResult.albumSynced,
});
} catch (error: any) {
res.status(500).json({ error: error.message || 'Ошибка загрузки фото' });
}
});
// Immich API management endpoints for Admin
app.get('/api/admin/immich/albums', async (req, res) => {
try {
const state = db.getState();
if (!state.immich_url || !state.immich_api_key) {
return res.status(400).json({ error: 'Immich URL или API Key не настроены' });
}
const albums = await getImmichAlbums(state.immich_url, state.immich_api_key);
res.json({ success: true, albums });
} catch (error: any) {
res.status(500).json({ error: error.message || 'Не удалось получить список альбомов Immich' });
}
});
app.post('/api/admin/immich/create-album', async (req, res) => {
try {
const state = db.getState();
if (!state.immich_url || !state.immich_api_key) {
return res.status(400).json({ error: 'Immich URL или API Key не настроены' });
}
const { album_name, description } = req.body;
const resolvedName = (album_name && album_name.trim()) || `Свадьба: ${state.couples_names || 'Анна & Дмитрий'}`;
const created = await createImmichAlbum(state.immich_url, state.immich_api_key, resolvedName, description);
// Automatically set as active album in DB settings
db.updateSettings({
immich_album_id: created.id,
immich_album_name: created.albumName,
});
broadcast('STATE_SYNC', db.getAggregatedStats());
res.json({ success: true, album: created, stats: db.getAggregatedStats() });
} catch (error: any) {
res.status(500).json({ error: error.message || 'Ошибка создания альбома в Immich' });
}
});
app.post('/api/admin/immich/test', async (req, res) => {
try {
const { immich_url, immich_api_key } = req.body;
const state = db.getState();
const url = immich_url || state.immich_url;
const key = immich_api_key || state.immich_api_key;
if (!url || !key) {
return res.status(400).json({ success: false, message: 'Укажите адрес сервера Immich и API Key' });
}
const testResult = await testImmichConnection(url, key);
res.json(testResult);
} catch (error: any) {
res.status(500).json({ success: false, message: error.message });
}
});
// 8. Admin Controls
app.post('/api/admin/kiss-trigger', (req, res) => {
try {
const { round_id, start_time } = db.startKissRound();
const stats = db.getAggregatedStats();
broadcast('KISS_ROUND_START', {
round_id,
start_time,
first_catcher: { ticket_id: 'HOST', guest_name: 'Ведущий банкета', team_name: '🎤 Ведущий' },
points: 3,
stats,
});
res.json({ success: true, round_id, start_time });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/admin/settings', (req, res) => {
try {
const payload = { ...req.body };
// Support setting exact cake time by string (e.g., "22:30" or ISO or HH:MM)
if (payload.cake_time_exact_str && typeof payload.cake_time_exact_str === 'string') {
const parts = payload.cake_time_exact_str.split(':');
if (parts.length >= 2) {
const hours = parseInt(parts[0], 10);
const minutes = parseInt(parts[1], 10);
const targetDate = new Date();
targetDate.setHours(hours, minutes, 0, 0);
// If time already passed today by more than 2 hours, assume next day or keep today
if (targetDate.getTime() < Date.now() - 2 * 3600000) {
targetDate.setDate(targetDate.getDate() + 1);
}
payload.cake_time_target = targetDate.getTime();
}
delete payload.cake_time_exact_str;
}
const updated = db.updateSettings(payload);
broadcast('SETTINGS_UPDATED', db.getAggregatedStats());
res.json({ success: true, state: updated, stats: db.getAggregatedStats() });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// Delete user session / guest
app.post('/api/admin/guest-delete', (req, res) => {
try {
const { ticket_id } = req.body;
if (!ticket_id) {
return res.status(400).json({ error: 'Билет пользователя не указан' });
}
const removed = db.removeGuest(ticket_id);
if (!removed) {
return res.status(404).json({ error: 'Пользователь не найден' });
}
const stats = db.getAggregatedStats();
broadcast('STATE_SYNC', stats);
res.json({ success: true, message: 'Сессия пользователя успешно удалена', stats });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// Batch delete guests
app.post('/api/admin/guest-batch-delete', (req, res) => {
try {
const { ticket_ids } = req.body;
if (!Array.isArray(ticket_ids) || ticket_ids.length === 0) {
return res.status(400).json({ error: 'Список билетов не указан' });
}
const count = db.batchRemoveGuests(ticket_ids);
const stats = db.getAggregatedStats();
broadcast('STATE_SYNC', stats);
res.json({ success: true, count, stats });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// Pre-create / register a named guest by admin
app.post('/api/admin/guest-create', (req, res) => {
try {
const { ticket_id, guest_name, team_id, team_name, role } = req.body;
if (!ticket_id || !guest_name) {
return res.status(400).json({ error: 'Необходимо указать номер билета и имя гостя' });
}
const guest = db.registerGuest(ticket_id, guest_name, team_id || 'team_friends', team_name, role || 'guest');
const stats = db.getAggregatedStats();
broadcast('STATE_SYNC', stats);
res.json({ success: true, guest, stats });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// Update specific user role, team, or bonus points
app.post('/api/admin/user-update', (req, res) => {
try {
const { ticket_id, role, team_id, team_name, bonus_points } = req.body;
if (!ticket_id) {
return res.status(400).json({ error: 'Билет пользователя не указан' });
}
const guest = db.getGuest(ticket_id);
if (!guest) {
return res.status(404).json({ error: 'Гость не найден' });
}
if (role) guest.role = role;
if (team_id) guest.team_id = team_id;
if (team_name) guest.team_name = team_name;
if (bonus_points && typeof bonus_points === 'number' && bonus_points > 0) {
// Award manual bonus points by host/admin
db.getState().kiss_catches.push({
id: db.getState().kiss_catches.length + 1,
ticket_id: guest.ticket_id,
guest_name: guest.guest_name,
team_id: guest.team_id,
team_name: guest.team_name,
points: bonus_points,
round_id: 999, // manual host award
timestamp: Date.now(),
});
}
db.save();
const stats = db.getAggregatedStats();
broadcast('STATE_SYNC', stats);
res.json({ success: true, guest, stats });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/admin/reset', (req, res) => {
try {
db.resetAllData();
broadcast('STATE_SYNC', db.getAggregatedStats());
res.json({ success: true });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/admin/seed', (req, res) => {
try {
db.seedDemoData();
broadcast('STATE_SYNC', db.getAggregatedStats());
res.json({ success: true });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// ======================== VITE MIDDLEWARE ========================
async function start() {
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
server.listen(PORT, '0.0.0.0', () => {
console.log(`Wedding Hub Server listening on http://0.0.0.0:${PORT}`);
});
}
start();