Refactor socket handling and integrate database for event management
- Removed old socket handling code and replaced it with a new implementation in `app/api/socketio/route.js`. - Added MySQL database integration for managing active sessions and queue entries. - Implemented event retrieval and ticket purchasing APIs in `app/api/events/route.js` and `app/api/purchase/route.js`. - Created database schema for events, tickets, active sessions, and orders in `database/schema.sql`. - Updated front-end to handle event data fetching and ticket purchasing with improved UI components. - Removed unused SVG files from the public directory.
This commit is contained in:
59
app/api/events/route.js
Normal file
59
app/api/events/route.js
Normal file
@@ -0,0 +1,59 @@
|
||||
import mysql from 'mysql2/promise'
|
||||
|
||||
async function getDbConnection() {
|
||||
if (!process.env.MYSQL_HOST) return null
|
||||
return await mysql.createConnection({
|
||||
host: process.env.MYSQL_HOST,
|
||||
user: process.env.MYSQL_USER,
|
||||
password: process.env.MYSQL_PASSWORD,
|
||||
database: process.env.MYSQL_DATABASE,
|
||||
})
|
||||
}
|
||||
|
||||
export async function GET(request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const eventId = searchParams.get('id')
|
||||
|
||||
const connection = await getDbConnection()
|
||||
if (!connection) {
|
||||
return Response.json({ error: 'Database not configured' }, { status: 500 })
|
||||
}
|
||||
|
||||
if (eventId) {
|
||||
// Get specific event with tickets
|
||||
const [eventRows] = await connection.execute(
|
||||
'SELECT * FROM events WHERE id = ?',
|
||||
[eventId]
|
||||
)
|
||||
|
||||
const [ticketRows] = await connection.execute(
|
||||
'SELECT * FROM tickets WHERE event_id = ? ORDER BY price ASC',
|
||||
[eventId]
|
||||
)
|
||||
|
||||
if (eventRows.length === 0) {
|
||||
return Response.json({ error: 'Event not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
await connection.end()
|
||||
|
||||
return Response.json({
|
||||
event: eventRows[0],
|
||||
tickets: ticketRows
|
||||
})
|
||||
} else {
|
||||
// Get all events
|
||||
const [eventRows] = await connection.execute(
|
||||
'SELECT e.*, COUNT(t.id) as ticket_types FROM events e LEFT JOIN tickets t ON e.id = t.event_id GROUP BY e.id ORDER BY e.created_at DESC'
|
||||
)
|
||||
|
||||
await connection.end()
|
||||
|
||||
return Response.json({ events: eventRows })
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Events API error:', error)
|
||||
return Response.json({ error: 'Internal server error' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
106
app/api/purchase/route.js
Normal file
106
app/api/purchase/route.js
Normal file
@@ -0,0 +1,106 @@
|
||||
import mysql from 'mysql2/promise'
|
||||
import jwt from 'jsonwebtoken'
|
||||
|
||||
async function getDbConnection() {
|
||||
if (!process.env.MYSQL_HOST) return null
|
||||
return await mysql.createConnection({
|
||||
host: process.env.MYSQL_HOST,
|
||||
user: process.env.MYSQL_USER,
|
||||
password: process.env.MYSQL_PASSWORD,
|
||||
database: process.env.MYSQL_DATABASE,
|
||||
})
|
||||
}
|
||||
|
||||
export async function POST(request) {
|
||||
try {
|
||||
const { eventId, ticketType, quantity, token } = await request.json()
|
||||
|
||||
if (!eventId || !ticketType || !quantity || !token) {
|
||||
return Response.json({ error: 'Missing required fields' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Verify JWT token
|
||||
let decoded
|
||||
try {
|
||||
decoded = jwt.verify(token, process.env.JWT_SECRET || 'dev-secret')
|
||||
} catch (error) {
|
||||
return Response.json({ error: 'Invalid or expired token' }, { status: 401 })
|
||||
}
|
||||
|
||||
const connection = await getDbConnection()
|
||||
if (!connection) {
|
||||
return Response.json({ error: 'Database not configured' }, { status: 500 })
|
||||
}
|
||||
|
||||
// Check if token is still active in database
|
||||
const [activeRows] = await connection.execute(
|
||||
'SELECT * FROM active_sessions WHERE event_id = ? AND socket_id = ? AND expires_at > NOW()',
|
||||
[eventId, decoded.sid]
|
||||
)
|
||||
|
||||
if (activeRows.length === 0) {
|
||||
await connection.end()
|
||||
return Response.json({ error: 'Session expired or not authorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
// Get ticket information
|
||||
const [ticketRows] = await connection.execute(
|
||||
'SELECT * FROM tickets WHERE event_id = ? AND type = ?',
|
||||
[eventId, ticketType]
|
||||
)
|
||||
|
||||
if (ticketRows.length === 0) {
|
||||
await connection.end()
|
||||
return Response.json({ error: 'Ticket type not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const ticket = ticketRows[0]
|
||||
const availableQuantity = ticket.total_quantity - ticket.sold_quantity
|
||||
|
||||
if (quantity > availableQuantity) {
|
||||
await connection.end()
|
||||
return Response.json({
|
||||
error: 'Not enough tickets available',
|
||||
available: availableQuantity
|
||||
}, { status: 400 })
|
||||
}
|
||||
|
||||
const totalPrice = ticket.price * quantity
|
||||
|
||||
// Start transaction
|
||||
await connection.beginTransaction()
|
||||
|
||||
try {
|
||||
// Create order
|
||||
const [orderResult] = await connection.execute(
|
||||
'INSERT INTO orders (event_id, socket_id, ticket_type, quantity, total_price, status) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
[eventId, decoded.sid, ticketType, quantity, totalPrice, 'completed']
|
||||
)
|
||||
|
||||
// Update sold quantity
|
||||
await connection.execute(
|
||||
'UPDATE tickets SET sold_quantity = sold_quantity + ? WHERE event_id = ? AND type = ?',
|
||||
[quantity, eventId, ticketType]
|
||||
)
|
||||
|
||||
await connection.commit()
|
||||
await connection.end()
|
||||
|
||||
return Response.json({
|
||||
success: true,
|
||||
orderId: orderResult.insertId,
|
||||
totalPrice,
|
||||
message: `Successfully purchased ${quantity} ${ticketType} ticket(s)`
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
await connection.rollback()
|
||||
await connection.end()
|
||||
throw error
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Purchase API error:', error)
|
||||
return Response.json({ error: 'Purchase failed' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
import { Server } from "socket.io";
|
||||
import jwt from "jsonwebtoken";
|
||||
import mysql from "mysql2/promise";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
// Simple in-memory structures keyed by eventId
|
||||
const events = {};
|
||||
|
||||
const QUEUE_THRESHOLD = parseInt(process.env.QUEUE_THRESHOLD || "100", 10);
|
||||
const CONCURRENT_ACTIVE = parseInt(process.env.CONCURRENT_ACTIVE || "50", 10);
|
||||
const TOKEN_TTL_SECONDS = parseInt(process.env.TOKEN_TTL_SECONDS || `${15 * 60}`, 10);
|
||||
|
||||
function ensureEvent(eventId) {
|
||||
if (!events[eventId]) {
|
||||
events[eventId] = {
|
||||
sockets: new Set(), // connected socket ids
|
||||
queue: [], // array of socket ids in order
|
||||
active: new Set(), // sockets that currently hold a token (allowed to buy)
|
||||
queueOn: false,
|
||||
};
|
||||
}
|
||||
return events[eventId];
|
||||
}
|
||||
|
||||
async function createDbPool() {
|
||||
if (!process.env.MYSQL_HOST) return null;
|
||||
return mysql.createPool({
|
||||
host: process.env.MYSQL_HOST,
|
||||
user: process.env.MYSQL_USER,
|
||||
password: process.env.MYSQL_PASSWORD,
|
||||
database: process.env.MYSQL_DATABASE,
|
||||
waitForConnections: true,
|
||||
connectionLimit: 5,
|
||||
});
|
||||
}
|
||||
|
||||
function buildUpdate(ev) {
|
||||
const positionMap = {};
|
||||
ev.queue.forEach((sid, idx) => (positionMap[sid] = idx + 1));
|
||||
return {
|
||||
activeCount: ev.sockets.size,
|
||||
queueOn: ev.queueOn,
|
||||
estimatedWait: ev.queue.length * 5, // naive: 5s per person
|
||||
positions: positionMap,
|
||||
};
|
||||
}
|
||||
|
||||
function broadcastUpdate(eventId, io) {
|
||||
const ev = events[eventId];
|
||||
if (!ev) return;
|
||||
// notify all connected sockets in room
|
||||
for (const sid of ev.sockets) {
|
||||
const pos = ev.queue.indexOf(sid);
|
||||
io.to(sid).emit("queue_update", {
|
||||
activeCount: ev.sockets.size,
|
||||
position: pos === -1 ? null : pos + 1,
|
||||
estimatedWait: pos === -1 ? null : ev.queue.length * 5,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function evaluateQueue(eventId, io) {
|
||||
const ev = events[eventId];
|
||||
if (!ev) return;
|
||||
|
||||
// ensure active set size <= CONCURRENT_ACTIVE
|
||||
while (ev.active.size < CONCURRENT_ACTIVE && ev.queue.length > 0) {
|
||||
const next = ev.queue.shift();
|
||||
if (!next) break;
|
||||
// sign token
|
||||
const token = jwt.sign({ sid: next, eventId }, process.env.JWT_SECRET || "dev-secret", {
|
||||
expiresIn: TOKEN_TTL_SECONDS,
|
||||
});
|
||||
ev.active.add(next);
|
||||
io.to(next).emit("granted", { token, expiresAt: new Date(Date.now() + TOKEN_TTL_SECONDS * 1000).toISOString() });
|
||||
}
|
||||
|
||||
// If too many active (rare), revoke oldest
|
||||
if (ev.active.size > CONCURRENT_ACTIVE) {
|
||||
const toRevoke = Array.from(ev.active).slice(CONCURRENT_ACTIVE);
|
||||
toRevoke.forEach((sid) => {
|
||||
ev.active.delete(sid);
|
||||
io.to(sid).emit("revoked");
|
||||
});
|
||||
}
|
||||
|
||||
// If queue no longer needed, clear it
|
||||
if (ev.sockets.size < QUEUE_THRESHOLD) ev.queueOn = false;
|
||||
|
||||
// broadcast
|
||||
broadcastUpdate(eventId, io);
|
||||
}
|
||||
|
||||
export async function GET(req) {
|
||||
const res = NextResponse.next();
|
||||
|
||||
if (global.io) {
|
||||
console.log("Socket is already running");
|
||||
} else {
|
||||
console.log("Socket is initializing");
|
||||
const httpServer = req.socket?.server;
|
||||
|
||||
if (httpServer) {
|
||||
const io = new Server(httpServer, {
|
||||
path: "/api/socket",
|
||||
cors: { origin: true },
|
||||
});
|
||||
|
||||
global.io = io;
|
||||
|
||||
const db = await createDbPool();
|
||||
|
||||
io.on("connection", (socket) => {
|
||||
console.log("connect", socket.id);
|
||||
|
||||
socket.on("join_event", async ({ eventId }) => {
|
||||
if (!eventId) return;
|
||||
const ev = ensureEvent(eventId);
|
||||
ev.sockets.add(socket.id);
|
||||
socket.join(eventId);
|
||||
|
||||
// compute counts
|
||||
const activeCount = ev.sockets.size;
|
||||
// turn on queue if threshold reached
|
||||
if (activeCount >= QUEUE_THRESHOLD) ev.queueOn = true;
|
||||
|
||||
// if queueOn and socket not active, add to queue
|
||||
if (ev.queueOn && !ev.active.has(socket.id)) {
|
||||
if (!ev.queue.includes(socket.id)) ev.queue.push(socket.id);
|
||||
}
|
||||
|
||||
// evaluate granting
|
||||
evaluateQueue(eventId, io);
|
||||
|
||||
// send initial update
|
||||
io.to(socket.id).emit("queue_update", buildUpdate(ev));
|
||||
});
|
||||
|
||||
socket.on("disconnect", () => {
|
||||
// remove from every event
|
||||
for (const [eventId, ev] of Object.entries(events)) {
|
||||
if (ev.sockets.has(socket.id)) ev.sockets.delete(socket.id);
|
||||
const qi = ev.queue.indexOf(socket.id);
|
||||
if (qi !== -1) ev.queue.splice(qi, 1);
|
||||
if (ev.active.has(socket.id)) ev.active.delete(socket.id);
|
||||
// re-evaluate to grant next in line
|
||||
evaluateQueue(eventId, io);
|
||||
// notify remaining sockets
|
||||
broadcastUpdate(eventId, io);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return new Response("Socket.IO server initialized", { status: 200 });
|
||||
}
|
||||
@@ -1,13 +1,29 @@
|
||||
import { Server } from 'socket.io'
|
||||
import jwt from 'jsonwebtoken'
|
||||
import mysql from 'mysql2/promise'
|
||||
|
||||
// Simple in-memory structures keyed by eventId
|
||||
// Simple in-memory structures keyed by eventId (for fast access)
|
||||
const events = {}
|
||||
|
||||
const QUEUE_THRESHOLD = parseInt(process.env.QUEUE_THRESHOLD || "100", 10)
|
||||
const CONCURRENT_ACTIVE = parseInt(process.env.CONCURRENT_ACTIVE || "50", 10)
|
||||
const TOKEN_TTL_SECONDS = parseInt(process.env.TOKEN_TTL_SECONDS || `${15 * 60}`, 10)
|
||||
|
||||
// MySQL kapcsolat
|
||||
let db = null
|
||||
|
||||
async function getDbConnection() {
|
||||
if (!db && process.env.MYSQL_HOST) {
|
||||
db = await mysql.createConnection({
|
||||
host: process.env.MYSQL_HOST,
|
||||
user: process.env.MYSQL_USER,
|
||||
password: process.env.MYSQL_PASSWORD,
|
||||
database: process.env.MYSQL_DATABASE,
|
||||
})
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
function ensureEvent(eventId) {
|
||||
if (!events[eventId]) {
|
||||
events[eventId] = {
|
||||
@@ -34,29 +50,59 @@ function broadcastUpdate(eventId, io) {
|
||||
}
|
||||
}
|
||||
|
||||
function evaluateQueue(eventId, io) {
|
||||
async function evaluateQueue(eventId, io) {
|
||||
const ev = events[eventId]
|
||||
if (!ev) return
|
||||
|
||||
const connection = await getDbConnection()
|
||||
|
||||
// ensure active set size <= CONCURRENT_ACTIVE
|
||||
while (ev.active.size < CONCURRENT_ACTIVE && ev.queue.length > 0) {
|
||||
const next = ev.queue.shift()
|
||||
if (!next) break
|
||||
|
||||
// sign token
|
||||
const expiresAt = new Date(Date.now() + TOKEN_TTL_SECONDS * 1000)
|
||||
const token = jwt.sign({ sid: next, eventId }, process.env.JWT_SECRET || "dev-secret", {
|
||||
expiresIn: TOKEN_TTL_SECONDS,
|
||||
})
|
||||
|
||||
ev.active.add(next)
|
||||
io.to(next).emit("granted", { token, expiresAt: new Date(Date.now() + TOKEN_TTL_SECONDS * 1000).toISOString() })
|
||||
|
||||
// Save to database
|
||||
if (connection) {
|
||||
try {
|
||||
await connection.execute(
|
||||
'INSERT INTO active_sessions (event_id, socket_id, jwt_token, expires_at) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE jwt_token = VALUES(jwt_token), expires_at = VALUES(expires_at)',
|
||||
[eventId, next, token, expiresAt]
|
||||
)
|
||||
} catch (error) {
|
||||
console.error('DB error saving active session:', error)
|
||||
}
|
||||
}
|
||||
|
||||
io.to(next).emit("granted", { token, expiresAt: expiresAt.toISOString() })
|
||||
}
|
||||
|
||||
// If too many active (rare), revoke oldest
|
||||
if (ev.active.size > CONCURRENT_ACTIVE) {
|
||||
const toRevoke = Array.from(ev.active).slice(CONCURRENT_ACTIVE)
|
||||
toRevoke.forEach((sid) => {
|
||||
for (const sid of toRevoke) {
|
||||
ev.active.delete(sid)
|
||||
io.to(sid).emit("revoked")
|
||||
})
|
||||
|
||||
// Remove from database
|
||||
if (connection) {
|
||||
try {
|
||||
await connection.execute(
|
||||
'DELETE FROM active_sessions WHERE event_id = ? AND socket_id = ?',
|
||||
[eventId, sid]
|
||||
)
|
||||
} catch (error) {
|
||||
console.error('DB error removing active session:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If queue no longer needed, clear it
|
||||
@@ -98,18 +144,50 @@ export async function GET(req) {
|
||||
ev.sockets.add(socket.id)
|
||||
socket.join(eventId)
|
||||
|
||||
const connection = await getDbConnection()
|
||||
|
||||
// Get event threshold from database
|
||||
let eventThreshold = QUEUE_THRESHOLD
|
||||
if (connection) {
|
||||
try {
|
||||
const [rows] = await connection.execute(
|
||||
'SELECT max_concurrent_users FROM events WHERE id = ?',
|
||||
[eventId]
|
||||
)
|
||||
if (rows.length > 0) {
|
||||
eventThreshold = rows[0].max_concurrent_users
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('DB error getting event:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// compute counts
|
||||
const activeCount = ev.sockets.size
|
||||
// turn on queue if threshold reached
|
||||
if (activeCount >= QUEUE_THRESHOLD) ev.queueOn = true
|
||||
if (activeCount >= eventThreshold) ev.queueOn = true
|
||||
|
||||
// if queueOn and socket not active, add to queue
|
||||
if (ev.queueOn && !ev.active.has(socket.id)) {
|
||||
if (!ev.queue.includes(socket.id)) ev.queue.push(socket.id)
|
||||
if (!ev.queue.includes(socket.id)) {
|
||||
ev.queue.push(socket.id)
|
||||
|
||||
// Save queue position to database
|
||||
if (connection) {
|
||||
try {
|
||||
await connection.execute(
|
||||
'INSERT INTO queue_entries (event_id, socket_id, position) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE position = VALUES(position)',
|
||||
[eventId, socket.id, ev.queue.length]
|
||||
)
|
||||
} catch (error) {
|
||||
console.error('DB error saving queue entry:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// evaluate granting
|
||||
evaluateQueue(eventId, io)
|
||||
await evaluateQueue(eventId, io)
|
||||
|
||||
// send initial update
|
||||
const pos = ev.queue.indexOf(socket.id)
|
||||
|
||||
Reference in New Issue
Block a user