diff --git a/app/game-api/package.json b/app/game-api/package.json index 07a3f9f..e4499f9 100644 --- a/app/game-api/package.json +++ b/app/game-api/package.json @@ -32,6 +32,7 @@ }, "dependencies": { "@fastify/cors": "^11.2.0", + "@fastify/static": "^9.0.0", "@sammo-ts/common": "workspace:*", "@sammo-ts/infra": "workspace:*", "@sammo-ts/logic": "workspace:*", @@ -40,6 +41,7 @@ "es-toolkit": "^1.43.0", "fastify": "^5.6.2", "redis": "^5.10.0", + "sharp": "^0.34.4", "zod": "^4.3.5" } } diff --git a/app/game-api/src/config.ts b/app/game-api/src/config.ts index 0b68bfa..8bd5722 100644 --- a/app/game-api/src/config.ts +++ b/app/game-api/src/config.ts @@ -5,6 +5,9 @@ export interface GameApiConfig { port: number; trpcPath: string; eventsPath: string; + uploadPath: string; + uploadDir: string; + uploadPublicUrl: string | null; profile: string; scenario: string; profileName: string; @@ -34,6 +37,9 @@ export const resolveGameApiConfigFromEnv = (env: NodeJS.ProcessEnv = process.env port: parseNumberWithFallback(env.GAME_API_PORT, 14000, 'GAME_API_PORT'), trpcPath: env.GAME_TRPC_PATH ?? env.TRPC_PATH ?? '/trpc', eventsPath: env.GAME_API_EVENTS_PATH ?? '/events', + uploadPath: env.GAME_UPLOAD_PATH ?? '/uploads', + uploadDir: env.GAME_UPLOAD_DIR ?? 'uploads', + uploadPublicUrl: env.GAME_UPLOAD_PUBLIC_URL ?? null, profile, scenario, profileName, diff --git a/app/game-api/src/context.ts b/app/game-api/src/context.ts index 3ba9ced..208f88c 100644 --- a/app/game-api/src/context.ts +++ b/app/game-api/src/context.ts @@ -66,6 +66,9 @@ export interface GameApiContext { turnDaemon: TurnDaemonTransport; battleSim: BattleSimTransport; profile: GameProfile; + uploadDir: string; + uploadPath: string; + uploadPublicUrl: string | null; auth: GameSessionTokenPayload | null; accessTokenStore: RedisAccessTokenStore; flushStore: FlushStore; @@ -78,6 +81,9 @@ export const createGameApiContext = (options: { turnDaemon: TurnDaemonTransport; battleSim: BattleSimTransport; profile: GameProfile; + uploadDir: string; + uploadPath: string; + uploadPublicUrl: string | null; auth: GameSessionTokenPayload | null; accessTokenStore: RedisAccessTokenStore; flushStore: FlushStore; @@ -89,6 +95,9 @@ export const createGameApiContext = (options: { turnDaemon: options.turnDaemon, battleSim: options.battleSim, profile: options.profile, + uploadDir: options.uploadDir, + uploadPath: options.uploadPath, + uploadPublicUrl: options.uploadPublicUrl, auth: options.auth, accessTokenStore: options.accessTokenStore, flushStore: options.flushStore, diff --git a/app/game-api/src/router.ts b/app/game-api/src/router.ts index 192f85e..9625926 100644 --- a/app/game-api/src/router.ts +++ b/app/game-api/src/router.ts @@ -17,6 +17,7 @@ import { turnsRouter } from './router/turns/index.js'; import { worldRouter } from './router/world/index.js'; import { auctionRouter } from './router/auction/index.js'; import { tournamentRouter } from './router/tournament/index.js'; +import { boardRouter } from './router/board/index.js'; export const appRouter = router({ health: healthRouter, @@ -36,6 +37,7 @@ export const appRouter = router({ turnDaemon: turnDaemonRouter, auction: auctionRouter, tournament: tournamentRouter, + board: boardRouter, }); export type AppRouter = typeof appRouter; diff --git a/app/game-api/src/router/board/index.ts b/app/game-api/src/router/board/index.ts new file mode 100644 index 0000000..b046748 --- /dev/null +++ b/app/game-api/src/router/board/index.ts @@ -0,0 +1,306 @@ +import { TRPCError } from '@trpc/server'; +import { z } from 'zod'; +import path from 'path'; +import { promises as fs } from 'fs'; +import { randomUUID } from 'crypto'; +import sharp, { type WebpOptions } from 'sharp'; + +import { GamePrisma } from '@sammo-ts/infra'; + +import { authedProcedure, router } from '../../trpc.js'; +import { getMyGeneral } from '../shared/general.js'; + +const MAX_UPLOAD_BYTES = 1024 * 1024; +const MAX_LONG_EDGE = 2048; +const WEBP_QUALITY = 80; +const WEBP_MIN_SAVING_RATIO = 0.97; + +const resolveSecretPermission = (officerLevel: number): number => { + if (officerLevel >= 5) return 2; + if (officerLevel > 1) return 1; + return 0; +}; + +const assertBoardAccess = (nationId: number, officerLevel: number, isSecret: boolean) => { + if (nationId <= 0 || officerLevel <= 0) { + throw new TRPCError({ code: 'FORBIDDEN', message: '국가에 소속되어있지 않습니다.' }); + } + if (isSecret && resolveSecretPermission(officerLevel) < 2) { + throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다. 수뇌부가 아닙니다.' }); + } +}; + +const normalizeUploadPath = (value: string) => { + if (!value.startsWith('/')) { + return `/${value}`; + } + return value.replace(/\/$/, ''); +}; + +const buildPublicImageUrl = (uploadPublicUrl: string | null, uploadPath: string, filename: string) => { + if (uploadPublicUrl) { + return `${uploadPublicUrl.replace(/\/$/, '')}/${filename}`; + } + const normalizedPath = normalizeUploadPath(uploadPath); + return `${normalizedPath}/${filename}`; +}; + +const parseDataUrl = (dataUrl: string): Buffer => { + const match = dataUrl.match(/^data:([^;]+);base64,(.+)$/); + if (match) { + return Buffer.from(match[2], 'base64'); + } + return Buffer.from(dataUrl, 'base64'); +}; + +type WebpOptionsWithAnimation = WebpOptions & { animated?: boolean }; + +const buildWebpBuffer = async ( + buffer: Buffer, + { animated, resize }: { animated: boolean; resize: boolean } +): Promise => { + let pipeline = sharp(buffer, { animated: true }); + if (resize) { + pipeline = pipeline.resize({ + width: MAX_LONG_EDGE, + height: MAX_LONG_EDGE, + fit: 'inside', + withoutEnlargement: true, + }); + } + const webpOptions: WebpOptionsWithAnimation = { + quality: WEBP_QUALITY, + effort: 4, + alphaQuality: WEBP_QUALITY, + loop: 0, + ...(animated ? { animated: true } : {}), + }; + + return pipeline.webp(webpOptions).toBuffer(); +}; + +const buildAvifBuffer = async (buffer: Buffer, resize: boolean): Promise => { + let pipeline = sharp(buffer, { animated: true }); + if (resize) { + pipeline = pipeline.resize({ + width: MAX_LONG_EDGE, + height: MAX_LONG_EDGE, + fit: 'inside', + withoutEnlargement: true, + }); + } + return pipeline.avif({ quality: 60, effort: 4 }).toBuffer(); +}; + +type BoardPostRow = { + id: number; + nation_id: number; + is_secret: boolean; + author_general_id: number; + author_name: string; + title: string; + content_html: string; + created_at: Date; +}; + +type BoardCommentRow = { + id: number; + post_id: number; + author_general_id: number; + author_name: string; + content_text: string; + created_at: Date; +}; + +export const boardRouter = router({ + getArticles: authedProcedure + .input(z.object({ isSecret: z.boolean() })) + .query(async ({ ctx, input }) => { + const me = await getMyGeneral(ctx); + assertBoardAccess(me.nationId, me.officerLevel, input.isSecret); + + const posts = await ctx.db.$queryRaw(GamePrisma.sql` + SELECT + id, + nation_id, + is_secret, + author_general_id, + author_name, + title, + content_html, + created_at + FROM board_post + WHERE nation_id = ${me.nationId} AND is_secret = ${input.isSecret} + ORDER BY created_at DESC + LIMIT 100 + `); + + if (posts.length === 0) { + return []; + } + + const postIds = posts.map((post) => post.id); + const comments = await ctx.db.$queryRaw(GamePrisma.sql` + SELECT + id, + post_id, + author_general_id, + author_name, + content_text, + created_at + FROM board_comment + WHERE post_id IN (${GamePrisma.join(postIds)}) + ORDER BY created_at ASC + `); + + const commentMap = new Map(); + for (const comment of comments) { + const list = commentMap.get(comment.post_id) ?? []; + list.push(comment); + commentMap.set(comment.post_id, list); + } + + return posts.map((post) => ({ + id: post.id, + title: post.title, + contentHtml: post.content_html, + authorName: post.author_name, + createdAt: post.created_at.toISOString(), + comments: (commentMap.get(post.id) ?? []).map((comment) => ({ + id: comment.id, + authorName: comment.author_name, + content: comment.content_text, + createdAt: comment.created_at.toISOString(), + })), + })); + }), + writeArticle: authedProcedure + .input( + z.object({ + isSecret: z.boolean(), + title: z.string().trim().max(250), + contentHtml: z.string().trim().max(20000), + }) + ) + .mutation(async ({ ctx, input }) => { + const me = await getMyGeneral(ctx); + assertBoardAccess(me.nationId, me.officerLevel, input.isSecret); + + if (!input.title && !input.contentHtml) { + throw new TRPCError({ code: 'BAD_REQUEST', message: '제목 혹은 내용이 필요합니다.' }); + } + + const rows = await ctx.db.$queryRaw<{ id: number }[]>(GamePrisma.sql` + INSERT INTO board_post (nation_id, is_secret, author_general_id, author_name, title, content_html) + VALUES (${me.nationId}, ${input.isSecret}, ${me.id}, ${me.name}, ${input.title}, ${input.contentHtml}) + RETURNING id + `); + + return { id: rows[0]?.id ?? null }; + }), + writeComment: authedProcedure + .input( + z.object({ + postId: z.number().int().positive(), + content: z.string().trim().max(2000), + }) + ) + .mutation(async ({ ctx, input }) => { + const me = await getMyGeneral(ctx); + if (!input.content) { + throw new TRPCError({ code: 'BAD_REQUEST', message: '내용이 필요합니다.' }); + } + + const posts = await ctx.db.$queryRaw<{ id: number; nation_id: number; is_secret: boolean }[]>( + GamePrisma.sql` + SELECT id, nation_id, is_secret + FROM board_post + WHERE id = ${input.postId} + LIMIT 1 + ` + ); + + const post = posts[0]; + if (!post) { + throw new TRPCError({ code: 'NOT_FOUND', message: '게시물을 찾을 수 없습니다.' }); + } + + assertBoardAccess(me.nationId, me.officerLevel, post.is_secret); + + if (post.nation_id !== me.nationId) { + throw new TRPCError({ code: 'FORBIDDEN', message: '권한이 부족합니다.' }); + } + + const rows = await ctx.db.$queryRaw<{ id: number }[]>(GamePrisma.sql` + INSERT INTO board_comment (post_id, nation_id, is_secret, author_general_id, author_name, content_text) + VALUES (${post.id}, ${me.nationId}, ${post.is_secret}, ${me.id}, ${me.name}, ${input.content}) + RETURNING id + `); + + return { id: rows[0]?.id ?? null }; + }), + uploadImage: authedProcedure + .input(z.object({ dataUrl: z.string().min(1) })) + .mutation(async ({ ctx, input }) => { + const me = await getMyGeneral(ctx); + if (me.nationId <= 0 || me.officerLevel <= 0) { + throw new TRPCError({ code: 'FORBIDDEN', message: '국가에 소속되어있지 않습니다.' }); + } + + const buffer = parseDataUrl(input.dataUrl); + if (buffer.length > MAX_UPLOAD_BYTES) { + throw new TRPCError({ code: 'PAYLOAD_TOO_LARGE', message: '이미지 용량 제한(1MB)을 초과했습니다.' }); + } + + const metadata = await sharp(buffer, { animated: true }).metadata(); + if (!metadata.format || !metadata.width || !metadata.height) { + throw new TRPCError({ code: 'BAD_REQUEST', message: '이미지 정보를 확인할 수 없습니다.' }); + } + + const format = metadata.format; + const isAnimated = (metadata.pages ?? 1) > 1; + const needsResize = Math.max(metadata.width, metadata.height) > MAX_LONG_EDGE; + + const allowed = new Set(['png', 'jpeg', 'jpg', 'gif', 'webp', 'avif', 'heif', 'tiff', 'bmp']); + if (!allowed.has(format)) { + throw new TRPCError({ code: 'BAD_REQUEST', message: '지원하지 않는 이미지 형식입니다.' }); + } + + let outputBuffer = buffer; + let outputFormat = format === 'avif' ? 'avif' : 'webp'; + + if (format === 'avif') { + if (needsResize) { + outputBuffer = await buildAvifBuffer(buffer, true); + } + } else { + const webpBuffer = await buildWebpBuffer(buffer, { + animated: isAnimated || format === 'gif', + resize: needsResize, + }); + if (format === 'webp' && !needsResize && webpBuffer.length >= buffer.length * WEBP_MIN_SAVING_RATIO) { + outputBuffer = buffer; + outputFormat = 'webp'; + } else { + outputBuffer = webpBuffer; + outputFormat = 'webp'; + } + } + + await fs.mkdir(ctx.uploadDir, { recursive: true }); + const filename = `${randomUUID()}.${outputFormat}`; + await fs.writeFile(path.join(ctx.uploadDir, filename), outputBuffer); + + const outputMeta = await sharp(outputBuffer, { animated: true }).metadata(); + const url = buildPublicImageUrl(ctx.uploadPublicUrl, ctx.uploadPath, filename); + + return { + url, + width: outputMeta.width ?? metadata.width, + height: outputMeta.height ?? metadata.height, + format: outputFormat, + animated: isAnimated, + size: outputBuffer.length, + }; + }), +}); \ No newline at end of file diff --git a/app/game-api/src/server.ts b/app/game-api/src/server.ts index 897266d..38e112e 100644 --- a/app/game-api/src/server.ts +++ b/app/game-api/src/server.ts @@ -1,5 +1,7 @@ import fastify, { type FastifyRequest } from 'fastify'; import cors from '@fastify/cors'; +import fastifyStatic from '@fastify/static'; +import path from 'path'; import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify'; import { buildGameEventChannel } from '@sammo-ts/common'; import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken'; @@ -96,6 +98,11 @@ export const createGameApiServer = async () => { credentials: true, }); + await app.register(fastifyStatic, { + root: path.resolve(process.cwd(), config.uploadDir), + prefix: config.uploadPath.endsWith('/') ? config.uploadPath : `${config.uploadPath}/`, + }); + await app.register(fastifyTRPCPlugin, { prefix: config.trpcPath, trpcOptions: { @@ -113,6 +120,9 @@ export const createGameApiServer = async () => { scenario: config.scenario, name: config.profileName, }, + uploadDir: path.resolve(process.cwd(), config.uploadDir), + uploadPath: config.uploadPath, + uploadPublicUrl: config.uploadPublicUrl, auth, accessTokenStore, flushStore, diff --git a/app/game-api/test/battleSimRouter.test.ts b/app/game-api/test/battleSimRouter.test.ts index d2ca826..d0d0f49 100644 --- a/app/game-api/test/battleSimRouter.test.ts +++ b/app/game-api/test/battleSimRouter.test.ts @@ -227,6 +227,9 @@ const buildContext = (options: { state: WorldStateRow; battleSim: BattleSimTrans battleSim: options.battleSim, profile, auth, + uploadDir: 'uploads', + uploadPath: '/uploads', + uploadPublicUrl: null, redis: {} as unknown as RedisConnector['client'], accessTokenStore, flushStore: new InMemoryFlushStore(), diff --git a/app/game-api/test/router.test.ts b/app/game-api/test/router.test.ts index 001a05b..3117b91 100644 --- a/app/game-api/test/router.test.ts +++ b/app/game-api/test/router.test.ts @@ -143,6 +143,9 @@ const buildContext = (options?: { battleSim, profile, auth, + uploadDir: 'uploads', + uploadPath: '/uploads', + uploadPublicUrl: null, redis: {} as unknown as RedisConnector['client'], accessTokenStore, flushStore: new InMemoryFlushStore(), diff --git a/app/game-frontend/package.json b/app/game-frontend/package.json index 90f257d..1a1496a 100644 --- a/app/game-frontend/package.json +++ b/app/game-frontend/package.json @@ -17,6 +17,12 @@ "@sammo-ts/game-api": "workspace:*", "@sammo-ts/gateway-api": "workspace:*", "@sammo-ts/logic": "workspace:*", + "@tiptap/extension-image": "^3.5.0", + "@tiptap/extension-link": "^3.5.0", + "@tiptap/extension-placeholder": "^3.5.0", + "@tiptap/extension-underline": "^3.5.0", + "@tiptap/starter-kit": "^3.5.0", + "@tiptap/vue-3": "^3.5.0", "@trpc/client": "^11.8.1", "@trpc/server": "^11.8.1", "@vueuse/core": "^14.1.0", diff --git a/app/game-frontend/src/router/index.ts b/app/game-frontend/src/router/index.ts index 394e00e..6881d67 100644 --- a/app/game-frontend/src/router/index.ts +++ b/app/game-frontend/src/router/index.ts @@ -16,6 +16,9 @@ import NotFoundView from '../views/NotFoundView.vue'; import TournamentView from '../views/TournamentView.vue'; import MyPageView from '../views/MyPageView.vue'; import MySettingsView from '../views/MySettingsView.vue'; +import BoardView from '../views/BoardView.vue'; +import NationAffairsView from '../views/NationAffairsView.vue'; +import ScoutMessageView from '../views/ScoutMessageView.vue'; import { useSessionStore } from '../stores/session'; const routes = [ @@ -60,6 +63,24 @@ const routes = [ requiresGeneral: true, }, }, + { + path: '/nation/affairs', + name: 'nation-affairs', + component: NationAffairsView, + meta: { + requiresAuth: true, + requiresGeneral: true, + }, + }, + { + path: '/nation/recruit-message', + name: 'nation-recruit-message', + component: ScoutMessageView, + meta: { + requiresAuth: true, + requiresGeneral: true, + }, + }, { path: '/nation/generals', name: 'nation-generals', @@ -114,6 +135,24 @@ const routes = [ requiresGeneral: true, }, }, + { + path: '/board', + name: 'board', + component: BoardView, + meta: { + requiresAuth: true, + requiresGeneral: true, + }, + }, + { + path: '/board/secret', + name: 'board-secret', + component: BoardView, + meta: { + requiresAuth: true, + requiresGeneral: true, + }, + }, { path: '/my-page', name: 'my-page', diff --git a/app/game-frontend/src/views/BoardView.vue b/app/game-frontend/src/views/BoardView.vue new file mode 100644 index 0000000..a78b9f6 --- /dev/null +++ b/app/game-frontend/src/views/BoardView.vue @@ -0,0 +1,473 @@ + + +