mirror of
https://github.com/linux-odyssey/linux-odyssey.git
synced 2026-11-05 19:20:12 +08:00
wip: migrate backend to new game package
This commit is contained in:
1 parent
1d843f7355
commit
1616f62755
94 files changed
+263
-3055
No files matched your search
@@ -1,11 +1,12 @@
|
||||
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 CommandHandler from '../../game/commandHandler.js'
|
||||
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)
|
||||
@@ -44,18 +45,26 @@ export const newCommand = asyncHandler(async (req: Request, res: Response) => {
|
||||
return
|
||||
}
|
||||
|
||||
const commandHandler = new CommandHandler(session, quest, c, params)
|
||||
const response = await commandHandler.run()
|
||||
if (response) {
|
||||
c.stage = response.stage
|
||||
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', response)
|
||||
pushToSession(session.id, 'response', gameSession.getResponses())
|
||||
pushToSession(session.id, 'task', gameSession.getTasks())
|
||||
}
|
||||
|
||||
res.status(200).end()
|
||||
await session.save()
|
||||
})
|
||||
@@ -22,7 +22,7 @@ function sessionSummary(session: ISession) {
|
||||
function sessionDetail(session: ISession) {
|
||||
return {
|
||||
...sessionSummary(session),
|
||||
stages: session.stages,
|
||||
stages: session.events,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { execFile } from 'child_process'
|
||||
|
||||
import { buildFileCheckCmd } from '@linux-odyssey/utils'
|
||||
import type { IFileCondition } from '@linux-odyssey/models'
|
||||
import type { IFileExistenceChecker, IFileInput } from '@linux-odyssey/game'
|
||||
|
||||
function sanitizeId(id: string) {
|
||||
return id.replace(/[^a-zA-Z0-9]/g, '')
|
||||
}
|
||||
|
||||
// eslint-disable-next-line import/prefer-default-export
|
||||
export function checkFile(id: string, file: IFileCondition) {
|
||||
return new Promise((resolve, reject) => {
|
||||
export function checkFile(id: string, file: IFileInput) {
|
||||
return new Promise<boolean>((resolve) => {
|
||||
const cmd = buildFileCheckCmd(file)
|
||||
// WARNING: This is vulnerable to command injection
|
||||
execFile(
|
||||
@@ -18,12 +18,15 @@ export function checkFile(id: string, file: IFileCondition) {
|
||||
{ timeout: 1000 },
|
||||
(error) => {
|
||||
const exists = !error
|
||||
if (exists === file.exists) {
|
||||
resolve(true)
|
||||
} else {
|
||||
reject(new Error('File check failed'))
|
||||
}
|
||||
resolve(exists)
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export class CLIFileExistenceChecker implements IFileExistenceChecker {
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
async exists(file: IFileInput) {
|
||||
return checkFile(file.path, file)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,7 @@
|
||||
import minimist from 'minimist'
|
||||
import { HydratedDocument } from 'mongoose'
|
||||
import { FileGraph } from '@linux-odyssey/file-graph'
|
||||
import {
|
||||
Condition,
|
||||
FileCondition,
|
||||
Quest,
|
||||
Stage,
|
||||
Exception,
|
||||
} from '@linux-odyssey/constants'
|
||||
import { ICondition, Quest, Stage, IException } from '@linux-odyssey/game'
|
||||
import { ICommand, ISession } from '@linux-odyssey/models'
|
||||
import { pushToSession } from '../api/socket.js'
|
||||
import SessionHandler, { ExecuteResult } from './sessionHandler.js'
|
||||
|
||||
@@ -16,6 +16,19 @@ class QuestValidationError extends Error {
|
||||
this.questId = questId
|
||||
this.error = error
|
||||
}
|
||||
|
||||
toString() {
|
||||
if (this.error?.issues) {
|
||||
const issues = this.error.issues
|
||||
.map((issue: any) => {
|
||||
const fieldPath = issue.path.join('.')
|
||||
return `- ${fieldPath}: ${issue.message}`
|
||||
})
|
||||
.join('\n')
|
||||
return `Error in quest "${this.questId}":\n${issues}`
|
||||
}
|
||||
return `Error in quest "${this.questId}": ${this.message}`
|
||||
}
|
||||
}
|
||||
|
||||
class QuestManager {
|
||||
@@ -49,9 +62,18 @@ class QuestManager {
|
||||
}
|
||||
|
||||
private async loadGlobalExceptions() {
|
||||
const exceptionsPath = path.join(this.questDirectory, 'exceptions.yml')
|
||||
const body = await fs.readFile(exceptionsPath, 'utf-8')
|
||||
return globalExceptionSchema.array().parse(yaml.parse(body))
|
||||
try {
|
||||
const exceptionsPath = path.join(this.questDirectory, 'exceptions.yml')
|
||||
const body = await fs.readFile(exceptionsPath, 'utf-8')
|
||||
return globalExceptionSchema.array().parse(yaml.parse(body))
|
||||
} catch (error) {
|
||||
logger.error('Error loading global exceptions', { error })
|
||||
throw new QuestValidationError(
|
||||
'Failed to load global exceptions',
|
||||
'global',
|
||||
error
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async loadAndUpdateQuests() {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { HydratedDocument, Types } from 'mongoose'
|
||||
import { Session, Quest, UserProfile } from '@linux-odyssey/models'
|
||||
import { Session, UserProfile } from '@linux-odyssey/models'
|
||||
import type { ISession, IUser } from '@linux-odyssey/models'
|
||||
import { createContainer, deleteContainer } from '../containers/docker.js'
|
||||
import SessionHandler from '../game/sessionHandler.js'
|
||||
import logger from '../utils/logger.js'
|
||||
import { questManager } from './quest.js'
|
||||
|
||||
async function deactivateSessions(userId: Types.ObjectId, quest: string) {
|
||||
const sessions = await Session.find({
|
||||
@@ -31,13 +31,13 @@ export async function createNewSession(
|
||||
user: HydratedDocument<IUser>,
|
||||
questId: string
|
||||
): Promise<ISession> {
|
||||
const quest = await Quest.findById(questId)
|
||||
const quest = await questManager.get(questId)
|
||||
if (!quest) {
|
||||
throw new Error(`Quest ${questId} not found`)
|
||||
}
|
||||
|
||||
// deactivate all active sessions
|
||||
deactivateSessions(user._id, quest._id).catch((err) => {
|
||||
deactivateSessions(user._id, quest.id).catch((err) => {
|
||||
logger.error(err)
|
||||
})
|
||||
|
||||
@@ -53,31 +53,24 @@ export async function createNewSession(
|
||||
containerId: container.id,
|
||||
})
|
||||
|
||||
const sessionHandler = new SessionHandler(newSession, quest)
|
||||
|
||||
sessionHandler.addNewTasks()
|
||||
|
||||
const session = sessionHandler.getSession()
|
||||
await session.save()
|
||||
|
||||
const userProfile = await UserProfile.findOne({ user: user._id })
|
||||
if (!userProfile) {
|
||||
throw new Error(`UserProfile ${user._id} not found`)
|
||||
}
|
||||
|
||||
const progress = userProfile.progress.get(quest._id)
|
||||
const progress = userProfile.progress.get(quest.id)
|
||||
if (!progress) {
|
||||
userProfile.progress.set(quest._id, {
|
||||
quest: quest._id,
|
||||
sessions: [session._id],
|
||||
userProfile.progress.set(quest.id, {
|
||||
quest: quest.id,
|
||||
sessions: [newSession._id],
|
||||
startedAt: new Date(),
|
||||
completed: false,
|
||||
})
|
||||
} else {
|
||||
progress.sessions.push(session._id)
|
||||
progress.sessions.push(newSession._id)
|
||||
}
|
||||
await userProfile.save()
|
||||
return session
|
||||
return newSession
|
||||
}
|
||||
|
||||
export async function finishSession(
|
||||
@@ -110,7 +103,7 @@ export async function isQuestUnlocked(
|
||||
if (!userProfile) {
|
||||
throw new Error(`UserProfile ${user.id} not found`)
|
||||
}
|
||||
const quest = await Quest.findById(questId)
|
||||
const quest = await questManager.get(questId)
|
||||
if (!quest) {
|
||||
throw new Error(`Quest ${questId} not found`)
|
||||
}
|
||||
|
||||
@@ -1,30 +1,27 @@
|
||||
import { TRPCError } from '@trpc/server'
|
||||
import { QuestDetailResponse } from '@linux-odyssey/constants'
|
||||
import { z } from 'zod'
|
||||
import { router, publicProcedure } from '../trpc.js'
|
||||
import { questManager } from '../models/quest.js'
|
||||
|
||||
export const questRouter = router({
|
||||
getQuests: publicProcedure.query(async () => {
|
||||
const quests = await questManager.getAll()
|
||||
const quests = questManager.getAll()
|
||||
return quests.map(({ title, id, requirements }) => ({
|
||||
id,
|
||||
title,
|
||||
requirements,
|
||||
}))
|
||||
}),
|
||||
getQuestDetail: publicProcedure
|
||||
.input(z.string())
|
||||
.query(async (opts): Promise<QuestDetailResponse> => {
|
||||
const questId = opts.input
|
||||
const quest = await questManager.get(questId)
|
||||
if (!quest) {
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Quest not found.',
|
||||
})
|
||||
}
|
||||
const { id, title, instruction, requirements } = quest
|
||||
return { id, title, instruction, requirements }
|
||||
}),
|
||||
getQuestDetail: publicProcedure.input(z.string()).query(async (opts) => {
|
||||
const questId = opts.input
|
||||
const quest = questManager.get(questId)
|
||||
if (!quest) {
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Quest not found.',
|
||||
})
|
||||
}
|
||||
const { id, title, instruction, requirements } = quest
|
||||
return { id, title, instruction, requirements }
|
||||
}),
|
||||
})
|
||||
@@ -34,7 +34,7 @@ export const sessionRouter = router({
|
||||
status: session.status,
|
||||
createdAt: session.createdAt,
|
||||
lastActivityAt: session.lastActivityAt,
|
||||
stages: session.stages,
|
||||
stages: session.events,
|
||||
}
|
||||
}
|
||||
throw new TRPCError({
|
||||
|
||||
Reference in new issue
Block a user