import { Session as GameSession } from '@linux-odyssey/game' import { Command, Session } from '@linux-odyssey/models' import { matchedData } from 'express-validator' import type { Request, Response } from 'express' import { pushToSession } from '../socket.js' import { finishSession } from '../../models/sessionManager.js' import { asyncHandler } from '../../middleware/error.js' import { questManager } from '../../models/quest.js' import { CLIFileExistenceChecker } from '../../containers/cli.js' export const newCommand = asyncHandler(async (req: Request, res: Response) => { const { command, pwd, output, error, params } = matchedData(req) const { sessionId } = req.user as any const session = await Session.findById(sessionId) if (!session) { res.status(404).json({ message: 'session not found' }) return } if (session.status === 'finished') { // Allow commands to be sent to finished sessions res.status(200).end() return } if (session.status !== 'active') { res.status(400).json({ message: 'session is not active' }) return } session.lastActivityAt = new Date() const c = new Command({ session, command, pwd, output, error, }) await c.save() const quest = await questManager.get(session.quest) if (!quest) { res.status(404).json({ message: 'quest not found' }) return } const gameSession = new GameSession( session, quest, new CLIFileExistenceChecker() ) const event = await gameSession.runCommand(c) if (event) { c.stage = event await c.save() session.completedEvents = gameSession.completedEvents await session.save() if ((session.status as string) === 'finished') { await finishSession(session) } pushToSession(session.id, 'response', gameSession.getResponses()) pushToSession(session.id, 'task', gameSession.getTasks()) } res.status(200).end() })