From ac0accdde61c0e272de16ca4a0fd07ad875598dd Mon Sep 17 00:00:00 2001 From: wangwuww111 <2816108629@qq.com> Date: Wed, 4 Mar 2026 18:31:48 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E5=90=8E=E7=AB=AF=E4=BB=8ENode.js?= =?UTF-8?q?=E9=87=8D=E5=86=99=E4=B8=BAPython=20FastAPI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 8 + .idea/ai_game.iml | 15 + .idea/misc.xml | 10 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + README.md | 54 +- client/project.config.json | 3 +- docs/AI创作系统设计.md | 5 +- project.config.json | 12 +- server/.env.example | 2 +- server/app.js | 35 - server/app/__init__.py | 0 .../app/__pycache__/__init__.cpython-310.pyc | Bin 0 -> 139 bytes server/app/__pycache__/config.cpython-310.pyc | Bin 0 -> 1450 bytes .../app/__pycache__/database.cpython-310.pyc | Bin 0 -> 880 bytes server/app/__pycache__/main.cpython-310.pyc | Bin 0 -> 1382 bytes server/app/config.py | 37 + server/app/database.py | 36 + server/app/main.py | 51 + server/app/models/__init__.py | 2 + .../__pycache__/__init__.cpython-310.pyc | Bin 0 -> 322 bytes .../models/__pycache__/story.cpython-310.pyc | Bin 0 -> 2579 bytes .../models/__pycache__/user.cpython-310.pyc | Bin 0 -> 2287 bytes server/app/models/story.py | 66 + server/app/models/user.py | 58 + server/app/routers/__init__.py | 1 + .../__pycache__/__init__.cpython-310.pyc | Bin 0 -> 203 bytes .../routers/__pycache__/story.cpython-310.pyc | Bin 0 -> 6196 bytes .../routers/__pycache__/user.cpython-310.pyc | Bin 0 -> 9569 bytes server/app/routers/story.py | 221 +++ server/app/routers/user.py | 421 ++++++ server/config/db.js | 14 - server/models/story.js | 157 -- server/models/user.js | 223 --- server/package-lock.json | 1269 ----------------- server/package.json | 20 - server/requirements.txt | 10 + server/routes/story.js | 110 -- server/routes/user.js | 184 --- server/sql/init_db.py | 93 ++ 40 files changed, 1096 insertions(+), 2035 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/ai_game.iml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml delete mode 100644 server/app.js create mode 100644 server/app/__init__.py create mode 100644 server/app/__pycache__/__init__.cpython-310.pyc create mode 100644 server/app/__pycache__/config.cpython-310.pyc create mode 100644 server/app/__pycache__/database.cpython-310.pyc create mode 100644 server/app/__pycache__/main.cpython-310.pyc create mode 100644 server/app/config.py create mode 100644 server/app/database.py create mode 100644 server/app/main.py create mode 100644 server/app/models/__init__.py create mode 100644 server/app/models/__pycache__/__init__.cpython-310.pyc create mode 100644 server/app/models/__pycache__/story.cpython-310.pyc create mode 100644 server/app/models/__pycache__/user.cpython-310.pyc create mode 100644 server/app/models/story.py create mode 100644 server/app/models/user.py create mode 100644 server/app/routers/__init__.py create mode 100644 server/app/routers/__pycache__/__init__.cpython-310.pyc create mode 100644 server/app/routers/__pycache__/story.cpython-310.pyc create mode 100644 server/app/routers/__pycache__/user.cpython-310.pyc create mode 100644 server/app/routers/story.py create mode 100644 server/app/routers/user.py delete mode 100644 server/config/db.js delete mode 100644 server/models/story.js delete mode 100644 server/models/user.js delete mode 100644 server/package-lock.json delete mode 100644 server/package.json create mode 100644 server/requirements.txt delete mode 100644 server/routes/story.js delete mode 100644 server/routes/user.js create mode 100644 server/sql/init_db.py diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/ai_game.iml b/.idea/ai_game.iml new file mode 100644 index 0000000..16e044c --- /dev/null +++ b/.idea/ai_game.iml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..1a8319f --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..d17840c --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index e7f17e7..cf75bc3 100644 --- a/README.md +++ b/README.md @@ -25,18 +25,23 @@ ai_game/ │ ├── game.js │ └── game.json │ -├── server/ # Node.js 后端服务 -│ ├── routes/ -│ │ ├── story.js # 故事接口 -│ │ └── user.js # 用户接口 -│ ├── models/ -│ │ ├── story.js # 故事模型 -│ │ └── user.js # 用户模型 -│ ├── config/ +├── server/ # Python 后端服务 (FastAPI) +│ ├── app/ +│ │ ├── routers/ +│ │ │ ├── story.py # 故事接口 +│ │ │ └── user.py # 用户接口 +│ │ ├── models/ +│ │ │ ├── story.py # 故事ORM模型 +│ │ │ └── user.py # 用户ORM模型 +│ │ ├── config.py # 配置管理 +│ │ ├── database.py # 数据库连接 +│ │ └── main.py # 应用入口 │ ├── sql/ │ │ ├── schema.sql # 基础表结构 -│ │ └── schema_v2.sql # 完整表结构(含AI/UGC) -│ └── app.js +│ │ ├── init_db.py # Python建库脚本 +│ │ └── seed_stories_*.sql # 种子数据 +│ ├── requirements.txt +│ └── .env │ ├── docs/ │ └── AI创作系统设计.md @@ -49,22 +54,30 @@ ai_game/ | 层级 | 技术 | |------|------| | 客户端 | 原生微信小游戏 Canvas 2D | -| 服务端 | Node.js + Express | +| 服务端 | Python + FastAPI + SQLAlchemy | | 数据库 | MySQL 8.0 | | AI服务 | OpenAI / Claude API | ## 快速开始 -### 1. 启动后端 +### 1. 初始化数据库 ```bash cd server -npm install -cp .env.example .env # 配置数据库 -npm start +pip install -r requirements.txt +# 配置 .env 文件(数据库密码等) +python sql/init_db.py ``` -### 2. 导入客户端 +### 2. 启动后端 + +```bash +cd server +python -m app.main +# 服务运行在 http://localhost:3000 +``` + +### 3. 导入客户端 1. 微信开发者工具 → 导入项目 → 选择 `client` 目录 2. 填入 AppID @@ -137,8 +150,13 @@ npm start - [x] AI创作中心UI - [x] 首页UGC布局 - [x] 个人中心创作者功能 -- [x] 后端API完善 -- [ ] AI服务对接 +- [x] 后端基础框架(Python + FastAPI) +- [x] 故事模型设计(标题、章节、选项、结局) +- [x] 故事列表/详情接口 +- [x] 用户游玩记录接口 +- [x] AI改写结局接口(模拟) +- [ ] AI服务对接(OpenAI/Claude) +- [ ] 配额系统 - [ ] 审核系统 - [ ] 支付系统 - [ ] 社交分享 diff --git a/client/project.config.json b/client/project.config.json index 8e2bf78..e0fa724 100644 --- a/client/project.config.json +++ b/client/project.config.json @@ -1,5 +1,5 @@ { - "appid": "wx772e2f0fbc498020", + "appid": "wx27be06bc3365e84b", "compileType": "game", "projectname": "stardom-story", "setting": { @@ -42,6 +42,5 @@ "ignore": [], "include": [] }, - "isGameTourist": false, "editorSetting": {} } \ No newline at end of file diff --git a/docs/AI创作系统设计.md b/docs/AI创作系统设计.md index 66ef640..c39b613 100644 --- a/docs/AI创作系统设计.md +++ b/docs/AI创作系统设计.md @@ -380,7 +380,10 @@ class AIService { ## 九、后续迭代 ### Phase 1(当前) -- [x] AI改写结局 +- [x] AI改写结局(后端接口已完成,模拟实现) +- [x] 后端基础框架(Python + FastAPI) +- [x] 故事/用户数据模型 +- [x] 游玩记录接口 - [ ] 配额系统接入 - [ ] 基础审核流程 diff --git a/project.config.json b/project.config.json index 05a71cb..1ac1fe2 100644 --- a/project.config.json +++ b/project.config.json @@ -11,7 +11,17 @@ "disablePlugins": [], "outputPath": "" }, - "useCompilerPlugins": false + "useCompilerPlugins": false, + "compileWorklet": false, + "uploadWithSourceMap": true, + "packNpmManually": false, + "minifyWXSS": true, + "minifyWXML": true, + "localPlugins": false, + "disableUseStrict": false, + "condition": false, + "swc": false, + "disableSWC": true }, "compileType": "game", "simulatorPluginLibVersion": {}, diff --git a/server/.env.example b/server/.env.example index 1892790..1fda328 100644 --- a/server/.env.example +++ b/server/.env.example @@ -1,4 +1,4 @@ -# 服务器配置 +cd "D:\idea project\ai_game\server"# 服务器配置 PORT=3000 # MySQL数据库配置 diff --git a/server/app.js b/server/app.js deleted file mode 100644 index af1ca9f..0000000 --- a/server/app.js +++ /dev/null @@ -1,35 +0,0 @@ -const express = require('express'); -const cors = require('cors'); -require('dotenv').config(); - -const storyRoutes = require('./routes/story'); -const userRoutes = require('./routes/user'); - -const app = express(); -const PORT = process.env.PORT || 3000; - -// 中间件 -app.use(cors()); -app.use(express.json()); -app.use(express.urlencoded({ extended: true })); - -// 路由 -app.use('/api/stories', storyRoutes); -app.use('/api/user', userRoutes); - -// 健康检查 -app.get('/api/health', (req, res) => { - res.json({ status: 'ok', message: '星域故事汇服务运行中' }); -}); - -// 错误处理 -app.use((err, req, res, next) => { - console.error(err.stack); - res.status(500).json({ code: 500, message: '服务器内部错误' }); -}); - -app.listen(PORT, () => { - console.log(`星域故事汇服务器运行在 http://localhost:${PORT}`); -}); - -module.exports = app; diff --git a/server/app/__init__.py b/server/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/app/__pycache__/__init__.cpython-310.pyc b/server/app/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd9ae098006ccb3b1eaeb8546a52f258de15b6be GIT binary patch literal 139 zcmd1j<>g`kg6XrCXM*U*AOaaM0yz#qT+9L_QW%06G#UL?G8BP?5yUS&7ps`el+;9p zf};Ga)Z~(w#LW2g#N5=F;?$zD)S{Tgf`XX%_{_Y_lK6PNg34PQHo5sJr8%i~AajbD IfCLKz0NcVI`v3p{ literal 0 HcmV?d00001 diff --git a/server/app/__pycache__/config.cpython-310.pyc b/server/app/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ca8b8047e73cf6edf65a093cfa9b9467ca77f0 GIT binary patch literal 1450 zcmZuxOK&4Z5bmCbJ+{ZOolV%y2Ej^*gGF%QhN1{X>`L5xS-6ZMwIA7bFgQV#R?IkHel35`Uzx2t~_J$cd`99W1e9P1RT3Ro(Sf)mV1BZ30jH!_WD* zJ|TahvHb*KoWZLff#4(|oN}+AGcWNdV!!ZbK@w2%Dd7PRpAjAkZ|NtY2$qC5L^$zy zlSj{jB~2Q<^_UFX^$r}>e)aWt*MGjee)-e&_usT%!3r5t8-J2&@mLs>ms1UPt57w| z((F=X=&}9WCiWYw3X)Jr&ifovN__4mfe1x|`=^jp(i9Qk5O5=Dx%DRCC}}&~0^CkI z4tD^@N$hYJ@J`Zou|2^3WJmPioB`k{={uiYz;}{?!+WPh?DBm__ziy75xxUOxyKKn zCU*Ux`hRRj3SEG;gjHnzzx7=rvC@N!lqm9c@6aqiO3fc$lt!*E40Cw<#{Md$)h2zCwHrG#!_tIQC0GZs-lN)+= zLyw1{YQc#L$Pm>)(L{l@g$W9@C?>xWbr;N=qemy_ITz`JO35c8Gv`2Y3iUZ(RpmUb zs`E^ilYBa=<~HW3NjJ3aL%jAt9C?fVO#?^U9{-zABz=ZqdmuIwx|vVz1F>MyyFKcm zyLSDpb=GQkB9pTxvE1HZ-TH*#<#ESrwkCC%8DOlH5BBOBjC>tO8=bED`!NoV#_9zm M23mbTINYQE0z#5rod5s; literal 0 HcmV?d00001 diff --git a/server/app/__pycache__/database.cpython-310.pyc b/server/app/__pycache__/database.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..745b1a54f0d712a7c25ff90c3eafcd4b51f0a842 GIT binary patch literal 880 zcmY*XOKTKC5bo}oot@px#tHFp6ZIhMWkv8LBEAp>$t9vVEDXKVmCeMN>9Kn@FCr-M zns^XB1Qb1pcu{YH2>y@0YC`fCe1O%PjjY{N(O*|pSM^sVTdgL+b!_Wh>N)%~`~9CvvF8PUhydsFr(?H^gpM&;7`!1pIXpHGn~5p@}jfYQhtB z;cwKU0BR6`BO0Q);Y2O)&~s8uh~No{4vE$*X-^KOFlBS+`KO(Y58Gd!?S6Z;v-!5U zhnJ+y%ygoFR}gc(QY0}H{j>lRT()Qyv`%G#PJ!M(=KMY=6ADN&u6UI$LfqpT+SCMn zsA3IOl@@({d(V=wci3idjSI=VG_6v~EG`wqCAyf#5bAUlljVFlmW!a~GP!iU?HIS0 z7Q%R#L+jXtuw14XCW|OwiBf!rl6xrD(q@Arn0t5g^Y+sh z{|Nr^b!+$I%Ne9?YMjPfGU1u2C7B!&Rv%INo~UVj<7emE`EDwJpD2}FfTZg3H16{p zx*8O6)8%E^6};k>?@qa5JWIIf9miN5pkj|g#;8wEvCeO0tD0$trXI&aCUIIWIm zl6lBiI%qnI@+0B(j)G`^vKy{z0Eja8OY^Q1~|i zy+Pl2`$MEc>+4>@dWZE4zd5GtbQu3aF2x{&i?)yYG%A;bPDlglG3L0`rEIvpU#u}Y J{qgF7^A}G?@&y0@ literal 0 HcmV?d00001 diff --git a/server/app/__pycache__/main.cpython-310.pyc b/server/app/__pycache__/main.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d66227ded17126d64ff1a38cf9a9a57159ac7f2 GIT binary patch literal 1382 zcmZWo&2Jk;6yMoTd%bp?Hf>ryq<|2}m9UGrMF@eYkT?)3%4uY2wd_pnarR3yvklD& z6cAOxv_c^95fpMF6++MxQ7;_$FZN38mMh2bA>Qn^jtM)OnfHG4_Ragf_a<#NT@Ak5 zUwy~!n40#RQszGgl$T(NKVTsm)(9ecgfN2Li1gUN22z+AnX!efQnn&HcCb^*c2tY& zxE{OMMH+RsHQb;EaY&8Si90s1N4-&#TBI>R#4A@NHOJryPFl1+S|Ba509bnrH;W9w27{StjR7i22 z_rCvex-*{K*mHjeOKq)#3g^{8$d@m_24d@#H{QJRIwK^an*pbQcmpbZL8WBLKy>uN z5;Eo23Nsg!=L_KB#9jFlfF0ibbaG?Ax_|Q1&FR6x^!m;D%a5$*x)-|_J4RtiCL@X) zgo==}OtLg7oU4=zC7=s$bxhn0qA1<;Q_cn~5qPmuLrw`zBnu+(&?2TllFZa04G1{e z@_IqWdMa*4MQ*E@%gg{9JL7bny@O2|48&HwG%T4Zt9zgAPp|)cgnA(;|M?8ieuXJK zSl(03r4wTZiqJ9F@}~ehk(7Dr_kX!{fA8bNgCDqRR*1ogsSv?{@;d0ZHQs{lcsaUo zX|>M?4OTLqj%X-L(|`Nb>0SH%jrQb zB02mY5gkrTBI;RHL>K}Z#u~PT3}h~_o^BjRGbgFq7hdJp4~I0|cm|LM7uR&YsLpG? zuVVB4{CQAMWTooE$(Q?8N+vt|D?=%>)m|@3!yp=_LauIkz^|)(tb))nu&H2dW+|72 z&1sYdq;tM-e4nJD?_(#w%EFW<*jb0BhPrb_5idW`y78>HyI>}`sw8&R9buZRvjJC$ z!wm)SG?&mm+yaEFe!#Vd?*JQMfLj3}{;@;cVo4a~g!gW4~ zm2s9x+^8z)mz)fqCo@EGEi6Lc&IfauFB_yxf9-`hC3!?&L=c|11dFNF3=hH3+sM{+ kLq}@Zf18euOpr_%_Mc1jB~&w9R5R6V&rVF_{$>92FNdF{>i_@% literal 0 HcmV?d00001 diff --git a/server/app/config.py b/server/app/config.py new file mode 100644 index 0000000..ddae645 --- /dev/null +++ b/server/app/config.py @@ -0,0 +1,37 @@ +""" +配置管理 +""" +from pydantic_settings import BaseSettings +from functools import lru_cache + + +class Settings(BaseSettings): + """应用配置""" + # 数据库配置 + db_host: str = "localhost" + db_port: int = 3306 + db_user: str = "root" + db_password: str = "" + db_name: str = "stardom_story" + + # 服务配置 + server_host: str = "0.0.0.0" + server_port: int = 3000 + debug: bool = True + + # AI服务配置(预留) + openai_api_key: str = "" + openai_base_url: str = "https://api.openai.com/v1" + + @property + def database_url(self) -> str: + return f"mysql+aiomysql://{self.db_user}:{self.db_password}@{self.db_host}:{self.db_port}/{self.db_name}" + + class Config: + env_file = ".env" + env_file_encoding = "utf-8" + + +@lru_cache() +def get_settings() -> Settings: + return Settings() diff --git a/server/app/database.py b/server/app/database.py new file mode 100644 index 0000000..c5275f1 --- /dev/null +++ b/server/app/database.py @@ -0,0 +1,36 @@ +""" +数据库连接 +""" +from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession +from sqlalchemy.orm import sessionmaker, declarative_base +from app.config import get_settings + +settings = get_settings() + +# 创建异步引擎 +engine = create_async_engine( + settings.database_url, + echo=settings.debug, + pool_pre_ping=True, + pool_size=10, + max_overflow=20 +) + +# 创建异步会话 +AsyncSessionLocal = sessionmaker( + bind=engine, + class_=AsyncSession, + expire_on_commit=False +) + +# 基类 +Base = declarative_base() + + +async def get_db(): + """获取数据库会话""" + async with AsyncSessionLocal() as session: + try: + yield session + finally: + await session.close() diff --git a/server/app/main.py b/server/app/main.py new file mode 100644 index 0000000..53e92bd --- /dev/null +++ b/server/app/main.py @@ -0,0 +1,51 @@ +""" +星域故事汇 - Python后端服务 +""" +import uvicorn +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.config import get_settings +from app.routers import story, user + +settings = get_settings() + +# 创建应用 +app = FastAPI( + title="星域故事汇", + description="互动故事小游戏后端服务", + version="1.0.0" +) + +# 跨域配置 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# 注册路由 +app.include_router(story.router, prefix="/api/stories", tags=["故事"]) +app.include_router(user.router, prefix="/api/user", tags=["用户"]) + + +@app.get("/") +async def root(): + return {"message": "星域故事汇后端服务运行中", "version": "1.0.0"} + + +@app.get("/health") +async def health_check(): + return {"status": "ok"} + + +if __name__ == "__main__": + print(f"星域故事汇服务器运行在 http://localhost:{settings.server_port}") + uvicorn.run( + "app.main:app", + host=settings.server_host, + port=settings.server_port, + reload=settings.debug + ) diff --git a/server/app/models/__init__.py b/server/app/models/__init__.py new file mode 100644 index 0000000..2925fbb --- /dev/null +++ b/server/app/models/__init__.py @@ -0,0 +1,2 @@ +from app.models.story import Story, StoryNode, StoryChoice +from app.models.user import User, UserProgress, UserEnding diff --git a/server/app/models/__pycache__/__init__.cpython-310.pyc b/server/app/models/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee9605bcc293d882af22e9329b22bd2b9bdf9d20 GIT binary patch literal 322 zcmYk0%}N6?5XY0vezeu1haP(Lx*&V=A}WGtI@u_c(?;|rIFhBdrnj!W(mnK&T@r&`jbE|Zzd zW$p@DU`?!9nf{`Jl_F;A(ZeoI4{qff6HgA|!>hL&g9GVHFc43P&){1yA;cMFPkm$i zc2!Q|c|8o3Lv0tTK3)Zw6C}3Hz(ZYh@c#Uku>i%w|-z o)otyJLfyLog{##6Ev2>X?WlD%?Be7Gi`&lJaaVhr#A0Aaz8UO$Q literal 0 HcmV?d00001 diff --git a/server/app/models/__pycache__/story.cpython-310.pyc b/server/app/models/__pycache__/story.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d921857ad8886ddbca08534a071cb4b19c506dc GIT binary patch literal 2579 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 Ug{3b75SDhz#NHa3VS8rw4>^53&Hw-a literal 0 HcmV?d00001 diff --git a/server/app/models/story.py b/server/app/models/story.py new file mode 100644 index 0000000..350e6f3 --- /dev/null +++ b/server/app/models/story.py @@ -0,0 +1,66 @@ +""" +故事相关ORM模型 +""" +from sqlalchemy import Column, Integer, String, Text, Boolean, TIMESTAMP, ForeignKey +from sqlalchemy.orm import relationship +from sqlalchemy.sql import func +from app.database import Base + + +class Story(Base): + """故事主表""" + __tablename__ = "stories" + + id = Column(Integer, primary_key=True, autoincrement=True) + title = Column(String(100), nullable=False) + cover_url = Column(String(255), default="") + description = Column(Text) + author_id = Column(Integer, default=0) + category = Column(String(50), nullable=False) + play_count = Column(Integer, default=0) + like_count = Column(Integer, default=0) + is_featured = Column(Boolean, default=False) + status = Column(Integer, default=1) + created_at = Column(TIMESTAMP, server_default=func.now()) + updated_at = Column(TIMESTAMP, server_default=func.now(), onupdate=func.now()) + + nodes = relationship("StoryNode", back_populates="story", cascade="all, delete-orphan") + + +class StoryNode(Base): + """故事节点表""" + __tablename__ = "story_nodes" + + id = Column(Integer, primary_key=True, autoincrement=True) + story_id = Column(Integer, ForeignKey("stories.id", ondelete="CASCADE"), nullable=False) + node_key = Column(String(50), nullable=False) + content = Column(Text, nullable=False) + speaker = Column(String(50), default="") + background_image = Column(String(255), default="") + character_image = Column(String(255), default="") + bgm = Column(String(255), default="") + is_ending = Column(Boolean, default=False) + ending_name = Column(String(100), default="") + ending_score = Column(Integer, default=0) + ending_type = Column(String(20), default="") + sort_order = Column(Integer, default=0) + created_at = Column(TIMESTAMP, server_default=func.now()) + + story = relationship("Story", back_populates="nodes") + choices = relationship("StoryChoice", back_populates="node", cascade="all, delete-orphan") + + +class StoryChoice(Base): + """故事选项表""" + __tablename__ = "story_choices" + + id = Column(Integer, primary_key=True, autoincrement=True) + node_id = Column(Integer, ForeignKey("story_nodes.id", ondelete="CASCADE"), nullable=False) + story_id = Column(Integer, nullable=False) + text = Column(String(200), nullable=False) + next_node_key = Column(String(50), nullable=False) + sort_order = Column(Integer, default=0) + is_locked = Column(Boolean, default=False) + created_at = Column(TIMESTAMP, server_default=func.now()) + + node = relationship("StoryNode", back_populates="choices") diff --git a/server/app/models/user.py b/server/app/models/user.py new file mode 100644 index 0000000..277650d --- /dev/null +++ b/server/app/models/user.py @@ -0,0 +1,58 @@ +""" +用户相关ORM模型 +""" +from sqlalchemy import Column, Integer, String, Boolean, TIMESTAMP, ForeignKey, UniqueConstraint +from sqlalchemy.sql import func +from app.database import Base + + +class User(Base): + """用户表""" + __tablename__ = "users" + + id = Column(Integer, primary_key=True, autoincrement=True) + openid = Column(String(100), unique=True, nullable=False) + nickname = Column(String(100), default="") + avatar_url = Column(String(255), default="") + gender = Column(Integer, default=0) + total_play_count = Column(Integer, default=0) + total_endings = Column(Integer, default=0) + created_at = Column(TIMESTAMP, server_default=func.now()) + updated_at = Column(TIMESTAMP, server_default=func.now(), onupdate=func.now()) + + +class UserProgress(Base): + """用户进度表""" + __tablename__ = "user_progress" + + id = Column(Integer, primary_key=True, autoincrement=True) + user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + story_id = Column(Integer, ForeignKey("stories.id", ondelete="CASCADE"), nullable=False) + current_node_key = Column(String(50), default="start") + is_completed = Column(Boolean, default=False) + ending_reached = Column(String(100), default="") + is_liked = Column(Boolean, default=False) + is_collected = Column(Boolean, default=False) + play_count = Column(Integer, default=1) + created_at = Column(TIMESTAMP, server_default=func.now()) + updated_at = Column(TIMESTAMP, server_default=func.now(), onupdate=func.now()) + + __table_args__ = ( + UniqueConstraint('user_id', 'story_id', name='uk_user_story'), + ) + + +class UserEnding(Base): + """用户结局收集表""" + __tablename__ = "user_endings" + + id = Column(Integer, primary_key=True, autoincrement=True) + user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + story_id = Column(Integer, ForeignKey("stories.id", ondelete="CASCADE"), nullable=False) + ending_name = Column(String(100), nullable=False) + ending_score = Column(Integer, default=0) + unlocked_at = Column(TIMESTAMP, server_default=func.now()) + + __table_args__ = ( + UniqueConstraint('user_id', 'story_id', 'ending_name', name='uk_user_ending'), + ) diff --git a/server/app/routers/__init__.py b/server/app/routers/__init__.py new file mode 100644 index 0000000..dc58234 --- /dev/null +++ b/server/app/routers/__init__.py @@ -0,0 +1 @@ +from app.routers import story, user diff --git a/server/app/routers/__pycache__/__init__.cpython-310.pyc b/server/app/routers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2802b7d974b54eaf14e9dc6fca7715fc6294737 GIT binary patch literal 203 zcmd1j<>g`kg8o^{GgX1~V-N=!FabFZKwK;WBvKes7;_kM8KW3;nWC5&8B&;n88n$+ z0%aI9nQpNbm*f{!-eM^&PA&4&WWL3nSWuu>lwVqsT2x#FGN*_cNUUTiVg<25#4j@! ztC-A`)I^1XqWrAXV+5K~3^H4U0RY7FGGYJ# literal 0 HcmV?d00001 diff --git a/server/app/routers/__pycache__/story.cpython-310.pyc b/server/app/routers/__pycache__/story.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..724bd1905673fabd86b25b46dacb5aa1cc4711e3 GIT binary patch literal 6196 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 Y7>j>rwRfmibdhS^jTG%tEql58U-&kX$p8QV literal 0 HcmV?d00001 diff --git a/server/app/routers/__pycache__/user.cpython-310.pyc b/server/app/routers/__pycache__/user.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..695bb8f69389a181fc380d7d095343110e4f6447 GIT binary patch literal 9569 zcmbta>z5qGb?^7|^vupaw0a_m6(C>$?aKItu}oGL0?Ec}jKJ6vIg`;;?`l@_SXK8( z?4D7MWQiQv@q#&k9gLjJl5=8|bBv9X0P!Py@bSNp5B(uu!fK^Y{-EH1c__botLM2Z zlM{AN->vGpRb6%KK7O}qYXbwGhM!-)@{`g(eNxl@iz?keE-I6Ff+*%5%$XG{XI1Q+t{JrD1edL{TS?}U6))#iQn^$molEn3yF5_IAUmZiLHjd0k~RH(FVrTVL6b+raOV<&Bk1xlOv}8)voL<_9(5iPSkwr2L_? zW^N1WX)%EM0M~CoJtGEDALRO0)Q7|{>cd>$hWdzDhx$6MZ}&GhZxo|Tx^Ma;XZ2}a ztoOHw4Sr(U5*x*)bM{$1H^w}h!DERn;s&vG(TKSXaNi)d`8&9WBeshhxyMcDakCif z>0yZ-;-;>?CilD9&-k}&*5dxRh@ISjCx4OpcV@LUp4F}5Hs-mNd2a9F*%tF;#U0FZ z8}r=R!?Qi+xl8O~p4)k@<2`d#Up3k*v&4kh&D>e${zMP=|7B%&i%)X@JGlR+dit;a z+NZ^5nEOuV{_IC^-y=T9+;=hey*=EP_`KL7z98;fG-FvRx&K*v&nCrQ?!Ak9f3dIk zzO$`8=T{wH`jItVuNEUK^q&a9?S7T}70M_lzgP(TuhfK3 z6=%i|^WsR>jI753d^b(>VOg7z7&-E&w!bP$)fw>Ghr*hiFVbYYf8Z>X+qe}4U(4xm z9mZoCgl`Fbk0y+q?K^&Avxd4!b%?`?(ht>UO4UdF<8?m>Bddt{Ohs-T-#b{Hu4UcG z&F8Cyil5I%UOr!`iF%pJ>3sfpy-B_BopNGauoBBDUiq#rDAwd zlQ+;CB7eO5{(BFXgkKn&leJmM>u{lzpTTDidAKk)cUbZk1czxd<8$+J1Rd!K z91u@)^--PQU0)J+fN`}XSRw`_V6sFkVWDh88cvjf$frwXza{Kmm7$XZplqVHWL{GiOf

?~ZBwo>ah5b6++zo+H6`jF0V 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 literal 0 HcmV?d00001 diff --git a/server/app/routers/story.py b/server/app/routers/story.py new file mode 100644 index 0000000..9af1056 --- /dev/null +++ b/server/app/routers/story.py @@ -0,0 +1,221 @@ +""" +故事相关API路由 +""" +import random +from fastapi import APIRouter, Depends, Query, HTTPException +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, update, func, distinct +from typing import Optional +from pydantic import BaseModel + +from app.database import get_db +from app.models.story import Story, StoryNode, StoryChoice + +router = APIRouter() + + +# ========== 请求/响应模型 ========== +class LikeRequest(BaseModel): + like: bool + + +class RewriteRequest(BaseModel): + ending_name: str + ending_content: str + prompt: str + + +# ========== API接口 ========== + +@router.get("") +async def get_stories( + category: Optional[str] = Query(None), + featured: bool = Query(False), + limit: int = Query(20, ge=1, le=100), + offset: int = Query(0, ge=0), + db: AsyncSession = Depends(get_db) +): + """获取故事列表""" + query = select(Story).where(Story.status == 1) + + if category: + query = query.where(Story.category == category) + if featured: + query = query.where(Story.is_featured == True) + + query = query.order_by(Story.is_featured.desc(), Story.play_count.desc()) + query = query.limit(limit).offset(offset) + + result = await db.execute(query) + stories = result.scalars().all() + + data = [{ + "id": s.id, + "title": s.title, + "cover_url": s.cover_url, + "description": s.description, + "category": s.category, + "play_count": s.play_count, + "like_count": s.like_count, + "is_featured": s.is_featured + } for s in stories] + + return {"code": 0, "data": data} + + +@router.get("/hot") +async def get_hot_stories( + limit: int = Query(10, ge=1, le=50), + db: AsyncSession = Depends(get_db) +): + """获取热门故事""" + query = select(Story).where(Story.status == 1).order_by(Story.play_count.desc()).limit(limit) + result = await db.execute(query) + stories = result.scalars().all() + + data = [{ + "id": s.id, + "title": s.title, + "cover_url": s.cover_url, + "description": s.description, + "category": s.category, + "play_count": s.play_count, + "like_count": s.like_count + } for s in stories] + + return {"code": 0, "data": data} + + +@router.get("/categories") +async def get_categories(db: AsyncSession = Depends(get_db)): + """获取分类列表""" + query = select(distinct(Story.category)).where(Story.status == 1) + result = await db.execute(query) + categories = [row[0] for row in result.all()] + + return {"code": 0, "data": categories} + + +@router.get("/{story_id}") +async def get_story_detail(story_id: int, db: AsyncSession = Depends(get_db)): + """获取故事详情(含节点和选项)""" + # 获取故事 + result = await db.execute(select(Story).where(Story.id == story_id, Story.status == 1)) + story = result.scalar_one_or_none() + + if not story: + raise HTTPException(status_code=404, detail="故事不存在") + + # 获取节点 + nodes_result = await db.execute( + select(StoryNode).where(StoryNode.story_id == story_id).order_by(StoryNode.sort_order) + ) + nodes = nodes_result.scalars().all() + + # 获取选项 + choices_result = await db.execute( + select(StoryChoice).where(StoryChoice.story_id == story_id).order_by(StoryChoice.sort_order) + ) + choices = choices_result.scalars().all() + + # 组装节点和选项 + nodes_map = {} + for node in nodes: + nodes_map[node.node_key] = { + "id": node.id, + "node_key": node.node_key, + "content": node.content, + "speaker": node.speaker, + "background_image": node.background_image, + "character_image": node.character_image, + "bgm": node.bgm, + "is_ending": node.is_ending, + "ending_name": node.ending_name, + "ending_score": node.ending_score, + "ending_type": node.ending_type, + "choices": [] + } + + for choice in choices: + # 找到对应的节点 + for node in nodes: + if node.id == choice.node_id and node.node_key in nodes_map: + nodes_map[node.node_key]["choices"].append({ + "text": choice.text, + "nextNodeKey": choice.next_node_key, + "isLocked": choice.is_locked + }) + break + + data = { + "id": story.id, + "title": story.title, + "cover_url": story.cover_url, + "description": story.description, + "category": story.category, + "author_id": story.author_id, + "play_count": story.play_count, + "like_count": story.like_count, + "is_featured": story.is_featured, + "nodes": nodes_map + } + + return {"code": 0, "data": data} + + +@router.post("/{story_id}/play") +async def record_play(story_id: int, db: AsyncSession = Depends(get_db)): + """记录游玩""" + await db.execute( + update(Story).where(Story.id == story_id).values(play_count=Story.play_count + 1) + ) + await db.commit() + return {"code": 0, "message": "记录成功"} + + +@router.post("/{story_id}/like") +async def toggle_like(story_id: int, request: LikeRequest, db: AsyncSession = Depends(get_db)): + """点赞/取消点赞""" + delta = 1 if request.like else -1 + await db.execute( + update(Story).where(Story.id == story_id).values(like_count=Story.like_count + delta) + ) + await db.commit() + return {"code": 0, "message": "点赞成功" if request.like else "取消点赞成功"} + + +@router.post("/{story_id}/rewrite") +async def ai_rewrite_ending(story_id: int, request: RewriteRequest, db: AsyncSession = Depends(get_db)): + """AI改写结局""" + if not request.prompt: + raise HTTPException(status_code=400, detail="请输入改写指令") + + # 获取故事信息 + result = await db.execute(select(Story).where(Story.id == story_id)) + story = result.scalar_one_or_none() + + # 模拟AI生成(后续替换为真实API调用) + templates = [ + f"根据你的愿望「{request.prompt}」,故事有了新的发展...\n\n", + f"命运的齿轮开始转动,{request.prompt}...\n\n", + f"在另一个平行世界里,{request.prompt}成为了现实...\n\n" + ] + + template = random.choice(templates) + new_content = ( + template + + "原本的结局被改写,新的故事在这里展开。\n\n" + + f"【AI改写提示】这是基于「{request.prompt}」生成的新结局。\n" + + "实际部署时,这里将由AI大模型根据上下文生成更精彩的内容。" + ) + + return { + "code": 0, + "data": { + "content": new_content, + "speaker": "旁白", + "is_ending": True, + "ending_name": f"{request.ending_name}(改写版)", + "ending_type": "rewrite" + } + } diff --git a/server/app/routers/user.py b/server/app/routers/user.py new file mode 100644 index 0000000..c7c8c62 --- /dev/null +++ b/server/app/routers/user.py @@ -0,0 +1,421 @@ +""" +用户相关API路由 +""" +from fastapi import APIRouter, Depends, Query, HTTPException +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, update, func, text +from typing import Optional +from pydantic import BaseModel + +from app.database import get_db +from app.models.user import User, UserProgress, UserEnding +from app.models.story import Story + +router = APIRouter() + + +# ========== 请求/响应模型 ========== +class LoginRequest(BaseModel): + code: str + userInfo: Optional[dict] = None + + +class ProfileRequest(BaseModel): + nickname: str + avatarUrl: str + gender: int = 0 + + +class ProgressRequest(BaseModel): + userId: int + storyId: int + currentNodeKey: str + isCompleted: bool = False + endingReached: str = "" + + +class LikeRequest(BaseModel): + userId: int + storyId: int + isLiked: bool + + +class CollectRequest(BaseModel): + userId: int + storyId: int + isCollected: bool + + +# ========== API接口 ========== + +@router.post("/login") +async def login(request: LoginRequest, db: AsyncSession = Depends(get_db)): + """微信登录""" + # 实际部署时需要调用微信API获取openid + # 这里简化处理:用code作为openid + openid = request.code + + # 查找或创建用户 + result = await db.execute(select(User).where(User.openid == openid)) + user = result.scalar_one_or_none() + + if not user: + user_info = request.userInfo or {} + user = User( + openid=openid, + nickname=user_info.get("nickname", ""), + avatar_url=user_info.get("avatarUrl", ""), + gender=user_info.get("gender", 0) + ) + db.add(user) + await db.commit() + await db.refresh(user) + + return { + "code": 0, + "data": { + "userId": user.id, + "openid": user.openid, + "nickname": user.nickname, + "avatarUrl": user.avatar_url, + "gender": user.gender, + "total_play_count": user.total_play_count, + "total_endings": user.total_endings + } + } + + +@router.post("/profile") +async def update_profile(request: ProfileRequest, user_id: int = Query(..., alias="userId"), db: AsyncSession = Depends(get_db)): + """更新用户信息""" + await db.execute( + update(User).where(User.id == user_id).values( + nickname=request.nickname, + avatar_url=request.avatarUrl, + gender=request.gender + ) + ) + await db.commit() + return {"code": 0, "message": "更新成功"} + + +@router.get("/progress") +async def get_progress( + user_id: int = Query(..., alias="userId"), + story_id: Optional[str] = Query(None, alias="storyId"), + db: AsyncSession = Depends(get_db) +): + """获取用户进度""" + # 处理 storyId 为 "null" 字符串的情况 + story_id_int = None + if story_id and story_id != "null": + try: + story_id_int = int(story_id) + except ValueError: + pass + + query = ( + select(UserProgress, Story.title.label("story_title"), Story.cover_url) + .join(Story, UserProgress.story_id == Story.id) + .where(UserProgress.user_id == user_id) + ) + + if story_id_int: + query = query.where(UserProgress.story_id == story_id_int) + + query = query.order_by(UserProgress.updated_at.desc()) + result = await db.execute(query) + rows = result.all() + + data = [{ + "id": row.UserProgress.id, + "user_id": row.UserProgress.user_id, + "story_id": row.UserProgress.story_id, + "story_title": row.story_title, + "cover_url": row.cover_url, + "current_node_key": row.UserProgress.current_node_key, + "is_completed": row.UserProgress.is_completed, + "ending_reached": row.UserProgress.ending_reached, + "is_liked": row.UserProgress.is_liked, + "is_collected": row.UserProgress.is_collected, + "play_count": row.UserProgress.play_count + } for row in rows] + + if story_id_int: + return {"code": 0, "data": data[0] if data else None} + return {"code": 0, "data": data} + + +@router.post("/progress") +async def save_progress(request: ProgressRequest, db: AsyncSession = Depends(get_db)): + """保存用户进度""" + user_id = request.userId + story_id = request.storyId + + # 查找是否存在 + result = await db.execute( + select(UserProgress).where( + UserProgress.user_id == user_id, + UserProgress.story_id == story_id + ) + ) + progress = result.scalar_one_or_none() + + if progress: + # 更新 + await db.execute( + update(UserProgress).where(UserProgress.id == progress.id).values( + current_node_key=request.currentNodeKey, + is_completed=request.isCompleted, + ending_reached=request.endingReached, + play_count=UserProgress.play_count + 1 + ) + ) + else: + # 新建 + progress = UserProgress( + user_id=user_id, + story_id=story_id, + current_node_key=request.currentNodeKey, + is_completed=request.isCompleted, + ending_reached=request.endingReached + ) + db.add(progress) + + # 如果完成,记录结局 + if request.isCompleted and request.endingReached: + # 检查是否已存在 + ending_result = await db.execute( + select(UserEnding).where( + UserEnding.user_id == user_id, + UserEnding.story_id == story_id, + UserEnding.ending_name == request.endingReached + ) + ) + if not ending_result.scalar_one_or_none(): + ending = UserEnding( + user_id=user_id, + story_id=story_id, + ending_name=request.endingReached + ) + db.add(ending) + + # 更新用户统计 + await db.execute( + update(User).where(User.id == user_id).values( + total_play_count=User.total_play_count + 1 + ) + ) + # 更新结局总数 + count_result = await db.execute( + select(func.count()).select_from(UserEnding).where(UserEnding.user_id == user_id) + ) + count = count_result.scalar() + await db.execute( + update(User).where(User.id == user_id).values(total_endings=count) + ) + + await db.commit() + return {"code": 0, "message": "保存成功"} + + +@router.post("/like") +async def toggle_like(request: LikeRequest, db: AsyncSession = Depends(get_db)): + """点赞/取消点赞""" + user_id = request.userId + story_id = request.storyId + + result = await db.execute( + select(UserProgress).where( + UserProgress.user_id == user_id, + UserProgress.story_id == story_id + ) + ) + progress = result.scalar_one_or_none() + + if progress: + await db.execute( + update(UserProgress).where(UserProgress.id == progress.id).values(is_liked=request.isLiked) + ) + else: + progress = UserProgress( + user_id=user_id, + story_id=story_id, + is_liked=request.isLiked + ) + db.add(progress) + + await db.commit() + return {"code": 0, "message": "点赞成功" if request.isLiked else "取消点赞成功"} + + +@router.post("/collect") +async def toggle_collect(request: CollectRequest, db: AsyncSession = Depends(get_db)): + """收藏/取消收藏""" + user_id = request.userId + story_id = request.storyId + + result = await db.execute( + select(UserProgress).where( + UserProgress.user_id == user_id, + UserProgress.story_id == story_id + ) + ) + progress = result.scalar_one_or_none() + + if progress: + await db.execute( + update(UserProgress).where(UserProgress.id == progress.id).values(is_collected=request.isCollected) + ) + else: + progress = UserProgress( + user_id=user_id, + story_id=story_id, + is_collected=request.isCollected + ) + db.add(progress) + + await db.commit() + return {"code": 0, "message": "收藏成功" if request.isCollected else "取消收藏成功"} + + +@router.get("/collections") +async def get_collections(user_id: int = Query(..., alias="userId"), db: AsyncSession = Depends(get_db)): + """获取收藏列表""" + result = await db.execute( + select(Story) + .join(UserProgress, Story.id == UserProgress.story_id) + .where(UserProgress.user_id == user_id, UserProgress.is_collected == True) + .order_by(UserProgress.updated_at.desc()) + ) + stories = result.scalars().all() + + data = [{ + "id": s.id, + "title": s.title, + "cover_url": s.cover_url, + "description": s.description, + "category": s.category, + "play_count": s.play_count, + "like_count": s.like_count + } for s in stories] + + return {"code": 0, "data": data} + + +@router.get("/endings") +async def get_unlocked_endings( + user_id: int = Query(..., alias="userId"), + story_id: Optional[str] = Query(None, alias="storyId"), + db: AsyncSession = Depends(get_db) +): + """获取已解锁结局""" + # 处理 storyId 为 "null" 字符串的情况 + story_id_int = None + if story_id and story_id != "null": + try: + story_id_int = int(story_id) + except ValueError: + pass + + query = select(UserEnding).where(UserEnding.user_id == user_id) + if story_id_int: + query = query.where(UserEnding.story_id == story_id_int) + + result = await db.execute(query) + endings = result.scalars().all() + + data = [{ + "id": e.id, + "story_id": e.story_id, + "ending_name": e.ending_name, + "ending_score": e.ending_score, + "unlocked_at": str(e.unlocked_at) if e.unlocked_at else None + } for e in endings] + + return {"code": 0, "data": data} + + +@router.get("/my-works") +async def get_my_works(user_id: int = Query(..., alias="userId"), db: AsyncSession = Depends(get_db)): + """获取我的作品""" + try: + result = await db.execute( + select(Story).where(Story.author_id == user_id).order_by(Story.created_at.desc()) + ) + works = result.scalars().all() + + data = [{ + "id": w.id, + "title": w.title, + "description": w.description, + "category": w.category, + "cover_url": w.cover_url, + "play_count": w.play_count, + "like_count": w.like_count, + "status": w.status, + "created_at": str(w.created_at) if w.created_at else None, + "updated_at": str(w.updated_at) if w.updated_at else None + } for w in works] + + return {"code": 0, "data": data} + except Exception: + return {"code": 0, "data": []} + + +@router.get("/drafts") +async def get_drafts(user_id: int = Query(..., alias="userId"), db: AsyncSession = Depends(get_db)): + """获取草稿箱(预留)""" + # story_drafts表可能不存在,返回空 + return {"code": 0, "data": []} + + +@router.get("/recent-played") +async def get_recent_played( + user_id: int = Query(..., alias="userId"), + limit: int = Query(10, ge=1, le=50), + db: AsyncSession = Depends(get_db) +): + """获取最近游玩""" + result = await db.execute( + select(Story, UserProgress) + .join(UserProgress, Story.id == UserProgress.story_id) + .where(UserProgress.user_id == user_id) + .order_by(UserProgress.updated_at.desc()) + .limit(limit) + ) + rows = result.all() + + data = [{ + "id": row.Story.id, + "title": row.Story.title, + "category": row.Story.category, + "description": row.Story.description, + "cover_url": row.Story.cover_url, + "current_node_key": row.UserProgress.current_node_key, + "is_completed": row.UserProgress.is_completed, + "progress": "已完成" if row.UserProgress.is_completed else "进行中" + } for row in rows] + + return {"code": 0, "data": data} + + +@router.get("/ai-history") +async def get_ai_history(user_id: int = Query(..., alias="userId"), limit: int = Query(20), db: AsyncSession = Depends(get_db)): + """获取AI创作历史(预留)""" + return {"code": 0, "data": []} + + +@router.get("/ai-quota") +async def get_ai_quota(user_id: int = Query(..., alias="userId"), db: AsyncSession = Depends(get_db)): + """获取AI配额""" + # 返回默认值 + return { + "code": 0, + "data": { + "daily": 3, + "used": 0, + "purchased": 0, + "gift": 0 + } + } diff --git a/server/config/db.js b/server/config/db.js deleted file mode 100644 index 9542f2b..0000000 --- a/server/config/db.js +++ /dev/null @@ -1,14 +0,0 @@ -const mysql = require('mysql2/promise'); - -const pool = mysql.createPool({ - host: process.env.DB_HOST || 'localhost', - port: process.env.DB_PORT || 3306, - user: process.env.DB_USER || 'root', - password: process.env.DB_PASSWORD || '', - database: process.env.DB_NAME || 'stardom_story', - waitForConnections: true, - connectionLimit: 10, - queueLimit: 0 -}); - -module.exports = pool; diff --git a/server/models/story.js b/server/models/story.js deleted file mode 100644 index 8b5732e..0000000 --- a/server/models/story.js +++ /dev/null @@ -1,157 +0,0 @@ -const pool = require('../config/db'); - -const StoryModel = { - // 获取故事列表 - async getList(options = {}) { - const { category, featured, limit = 20, offset = 0 } = options; - let sql = `SELECT id, title, cover_url, description, category, play_count, like_count, is_featured - FROM stories WHERE status = 1`; - const params = []; - - if (category) { - sql += ' AND category = ?'; - params.push(category); - } - if (featured) { - sql += ' AND is_featured = 1'; - } - - sql += ' ORDER BY is_featured DESC, play_count DESC LIMIT ? OFFSET ?'; - params.push(limit, offset); - - const [rows] = await pool.query(sql, params); - return rows; - }, - - // 获取故事详情(含节点和选项) - async getDetail(storyId) { - // 获取故事基本信息 - const [stories] = await pool.query( - 'SELECT * FROM stories WHERE id = ? AND status = 1', - [storyId] - ); - if (stories.length === 0) return null; - - const story = stories[0]; - - // 获取所有节点 - const [nodes] = await pool.query( - `SELECT id, node_key, content, speaker, background_image, character_image, bgm, - is_ending, ending_name, ending_score, ending_type - FROM story_nodes WHERE story_id = ? ORDER BY sort_order`, - [storyId] - ); - - // 获取所有选项 - const [choices] = await pool.query( - 'SELECT id, node_id, text, next_node_key, is_locked FROM story_choices WHERE story_id = ? ORDER BY sort_order', - [storyId] - ); - - // 组装节点和选项 - const nodesMap = {}; - nodes.forEach(node => { - nodesMap[node.node_key] = { - ...node, - choices: [] - }; - }); - - choices.forEach(choice => { - const node = nodes.find(n => n.id === choice.node_id); - if (node && nodesMap[node.node_key]) { - nodesMap[node.node_key].choices.push({ - text: choice.text, - nextNodeKey: choice.next_node_key, - isLocked: choice.is_locked - }); - } - }); - - story.nodes = nodesMap; - return story; - }, - - // 增加游玩次数 - async incrementPlayCount(storyId) { - await pool.query( - 'UPDATE stories SET play_count = play_count + 1 WHERE id = ?', - [storyId] - ); - }, - - // 点赞/取消点赞 - async toggleLike(storyId, increment) { - const delta = increment ? 1 : -1; - await pool.query( - 'UPDATE stories SET like_count = like_count + ? WHERE id = ?', - [delta, storyId] - ); - }, - - // 获取热门故事 - async getHotStories(limit = 10) { - const [rows] = await pool.query( - `SELECT id, title, cover_url, description, category, play_count, like_count - FROM stories WHERE status = 1 ORDER BY play_count DESC LIMIT ?`, - [limit] - ); - return rows; - }, - - // 获取分类列表 - async getCategories() { - const [rows] = await pool.query( - 'SELECT DISTINCT category FROM stories WHERE status = 1' - ); - return rows.map(r => r.category); - }, - - // AI改写结局 - async aiRewriteEnding({ storyId, endingName, endingContent, prompt }) { - // 获取故事信息用于上下文 - const [stories] = await pool.query( - 'SELECT title, category, description FROM stories WHERE id = ?', - [storyId] - ); - const story = stories[0]; - - // TODO: 接入真实AI服务(OpenAI/Claude/自建模型) - // 这里先返回模拟结果,后续替换为真实AI调用 - const aiContent = await this.callAIService({ - storyTitle: story?.title, - storyCategory: story?.category, - originalEnding: endingContent, - userPrompt: prompt - }); - - return { - content: aiContent, - speaker: '旁白', - is_ending: true, - ending_name: `${endingName}(改写版)`, - ending_type: 'rewrite' - }; - }, - - // AI服务调用(模拟/真实) - async callAIService({ storyTitle, storyCategory, originalEnding, userPrompt }) { - // 模拟AI生成内容 - // 实际部署时替换为真实API调用 - const templates = [ - `根据你的愿望「${userPrompt}」,故事有了新的发展...\n\n`, - `命运的齿轮开始转动,${userPrompt}...\n\n`, - `在另一个平行世界里,${userPrompt}成为了现实...\n\n` - ]; - - const template = templates[Math.floor(Math.random() * templates.length)]; - const newContent = template + - `原本的结局被改写,新的故事在这里展开。\n\n` + - `【AI改写提示】这是基于「${userPrompt}」生成的新结局。\n` + - `实际部署时,这里将由AI大模型根据上下文生成更精彩的内容。`; - - return newContent; - } -}; - -module.exports = StoryModel; diff --git a/server/models/user.js b/server/models/user.js deleted file mode 100644 index 5a11cf7..0000000 --- a/server/models/user.js +++ /dev/null @@ -1,223 +0,0 @@ -const pool = require('../config/db'); - -const UserModel = { - // 通过openid查找或创建用户 - async findOrCreate(openid, userInfo = {}) { - const [existing] = await pool.query( - 'SELECT * FROM users WHERE openid = ?', - [openid] - ); - - if (existing.length > 0) { - return existing[0]; - } - - // 创建新用户 - const [result] = await pool.query( - 'INSERT INTO users (openid, nickname, avatar_url, gender) VALUES (?, ?, ?, ?)', - [openid, userInfo.nickname || '', userInfo.avatarUrl || '', userInfo.gender || 0] - ); - - return { - id: result.insertId, - openid, - nickname: userInfo.nickname || '', - avatar_url: userInfo.avatarUrl || '', - gender: userInfo.gender || 0 - }; - }, - - // 更新用户信息 - async updateProfile(userId, userInfo) { - await pool.query( - 'UPDATE users SET nickname = ?, avatar_url = ?, gender = ? WHERE id = ?', - [userInfo.nickname, userInfo.avatarUrl, userInfo.gender, userId] - ); - }, - - // 获取用户进度 - async getProgress(userId, storyId = null) { - let sql = `SELECT up.*, s.title as story_title, s.cover_url - FROM user_progress up - JOIN stories s ON up.story_id = s.id - WHERE up.user_id = ?`; - const params = [userId]; - - if (storyId) { - sql += ' AND up.story_id = ?'; - params.push(storyId); - } - - sql += ' ORDER BY up.updated_at DESC'; - const [rows] = await pool.query(sql, params); - return storyId ? rows[0] : rows; - }, - - // 保存用户进度 - async saveProgress(userId, storyId, data) { - const { currentNodeKey, isCompleted, endingReached } = data; - - await pool.query( - `INSERT INTO user_progress (user_id, story_id, current_node_key, is_completed, ending_reached) - VALUES (?, ?, ?, ?, ?) - ON DUPLICATE KEY UPDATE - current_node_key = VALUES(current_node_key), - is_completed = VALUES(is_completed), - ending_reached = VALUES(ending_reached), - play_count = play_count + 1`, - [userId, storyId, currentNodeKey, isCompleted || false, endingReached || ''] - ); - - // 如果完成了,记录结局 - if (isCompleted && endingReached) { - await pool.query( - `INSERT IGNORE INTO user_endings (user_id, story_id, ending_name) VALUES (?, ?, ?)`, - [userId, storyId, endingReached] - ); - - // 更新用户统计 - await pool.query( - 'UPDATE users SET total_play_count = total_play_count + 1, total_endings = (SELECT COUNT(*) FROM user_endings WHERE user_id = ?) WHERE id = ?', - [userId, userId] - ); - } - }, - - // 点赞/取消点赞 - async toggleLike(userId, storyId, isLiked) { - await pool.query( - `INSERT INTO user_progress (user_id, story_id, is_liked) - VALUES (?, ?, ?) - ON DUPLICATE KEY UPDATE is_liked = ?`, - [userId, storyId, isLiked, isLiked] - ); - }, - - // 收藏/取消收藏 - async toggleCollect(userId, storyId, isCollected) { - await pool.query( - `INSERT INTO user_progress (user_id, story_id, is_collected) - VALUES (?, ?, ?) - ON DUPLICATE KEY UPDATE is_collected = ?`, - [userId, storyId, isCollected, isCollected] - ); - }, - - // 获取收藏列表 - async getCollections(userId) { - const [rows] = await pool.query( - `SELECT s.id, s.title, s.cover_url, s.description, s.category, s.play_count, s.like_count - FROM user_progress up - JOIN stories s ON up.story_id = s.id - WHERE up.user_id = ? AND up.is_collected = 1 - ORDER BY up.updated_at DESC`, - [userId] - ); - return rows; - }, - - // 获取用户解锁的结局 - async getUnlockedEndings(userId, storyId = null) { - let sql = 'SELECT * FROM user_endings WHERE user_id = ?'; - const params = [userId]; - - if (storyId) { - sql += ' AND story_id = ?'; - params.push(storyId); - } - - const [rows] = await pool.query(sql, params); - return rows; - }, - - // 获取我的作品 - async getMyWorks(userId) { - try { - const [rows] = await pool.query( - `SELECT id, title, description, category, cover_url, play_count, like_count, - comment_count, status, created_at, updated_at, - COALESCE(earnings, 0) as earnings - FROM stories - WHERE author_id = ? - ORDER BY created_at DESC`, - [userId] - ); - return rows; - } catch (e) { - // 表可能还没有author_id字段,返回空数组 - return []; - } - }, - - // 获取草稿箱 - async getDrafts(userId) { - try { - const [rows] = await pool.query( - `SELECT id, title, category, node_count, source, created_at, updated_at - FROM story_drafts - WHERE user_id = ? - ORDER BY updated_at DESC`, - [userId] - ); - return rows; - } catch (e) { - // 表可能不存在,返回空数组 - return []; - } - }, - - // 获取最近游玩 - async getRecentPlayed(userId, limit = 10) { - const [rows] = await pool.query( - `SELECT s.id, s.title, s.category, s.description, s.cover_url, - up.current_node_key, up.is_completed, - CASE WHEN up.is_completed THEN '已完成' ELSE '进行中' END as progress - FROM user_progress up - JOIN stories s ON up.story_id = s.id - WHERE up.user_id = ? - ORDER BY up.updated_at DESC - LIMIT ?`, - [userId, limit] - ); - return rows; - }, - - // 获取AI创作历史 - async getAIHistory(userId, limit = 20) { - try { - const [rows] = await pool.query( - `SELECT id, gen_type, input_prompt, output_content, status, created_at - FROM ai_generations - WHERE user_id = ? - ORDER BY created_at DESC - LIMIT ?`, - [userId, limit] - ); - return rows; - } catch (e) { - return []; - } - }, - - // 获取AI配额 - async getAIQuota(userId) { - try { - const [rows] = await pool.query( - `SELECT daily_free_total as daily, daily_free_used as used, - purchased_quota as purchased, gift_quota as gift - FROM user_ai_quota - WHERE user_id = ?`, - [userId] - ); - if (rows.length > 0) { - return rows[0]; - } - // 没有记录则返回默认值 - return { daily: 3, used: 0, purchased: 0, gift: 0 }; - } catch (e) { - return { daily: 3, used: 0, purchased: 0, gift: 0 }; - } - } -}; - -module.exports = UserModel; diff --git a/server/package-lock.json b/server/package-lock.json deleted file mode 100644 index f017e7c..0000000 --- a/server/package-lock.json +++ /dev/null @@ -1,1269 +0,0 @@ -{ - "name": "stardom-story-server", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "stardom-story-server", - "version": "1.0.0", - "dependencies": { - "cors": "^2.8.5", - "dotenv": "^16.3.1", - "express": "^4.18.2", - "mysql2": "^3.6.5" - }, - "devDependencies": { - "nodemon": "^3.0.2" - } - }, - "node_modules/@types/node": { - "version": "25.3.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-25.3.3.tgz", - "integrity": "sha512-DpzbrH7wIcBaJibpKo9nnSQL0MTRdnWttGyE5haGwK86xgMOkFLp7vEyfQPGLOJh5wNYiJ3V9PmUMDhV9u8kkQ==", - "peer": true, - "dependencies": { - "undici-types": "~7.18.0" - } - }, - "node_modules/accepts": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", - "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", - "dependencies": { - "mime-types": "~2.1.34", - "negotiator": "0.6.3" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" - }, - "node_modules/aws-ssl-profiles": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", - "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", - "engines": { - "node": ">= 6.0.0" - } - }, - "node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/binary-extensions": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", - "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", - "dev": true, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/body-parser": { - "version": "1.20.4", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", - "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", - "dependencies": { - "bytes": "~3.1.2", - "content-type": "~1.0.5", - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "~1.2.0", - "http-errors": "~2.0.1", - "iconv-lite": "~0.4.24", - "on-finished": "~2.4.1", - "qs": "~6.14.0", - "raw-body": "~2.5.3", - "type-is": "~1.6.18", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/brace-expansion": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.4.tgz", - "integrity": "sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==", - "dev": true, - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "dev": true, - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/call-bound": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", - "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "get-intrinsic": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/chokidar": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", - "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", - "dev": true, - "dependencies": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" - }, - "engines": { - "node": ">= 8.10.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - }, - "optionalDependencies": { - "fsevents": "~2.3.2" - } - }, - "node_modules/content-disposition": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", - "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", - "dependencies": { - "safe-buffer": "5.2.1" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", - "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-signature": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", - "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==" - }, - "node_modules/cors": { - "version": "2.8.6", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", - "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/denque": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", - "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", - "engines": { - "node": ">=0.10" - } - }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/destroy": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", - "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/dotenv": { - "version": "16.6.1", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", - "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://dotenvx.com" - } - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" - }, - "node_modules/encodeurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", - "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" - }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/express": { - "version": "4.22.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", - "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", - "dependencies": { - "accepts": "~1.3.8", - "array-flatten": "1.1.1", - "body-parser": "~1.20.3", - "content-disposition": "~0.5.4", - "content-type": "~1.0.4", - "cookie": "~0.7.1", - "cookie-signature": "~1.0.6", - "debug": "2.6.9", - "depd": "2.0.0", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "~1.3.1", - "fresh": "~0.5.2", - "http-errors": "~2.0.0", - "merge-descriptors": "1.0.3", - "methods": "~1.1.2", - "on-finished": "~2.4.1", - "parseurl": "~1.3.3", - "path-to-regexp": "~0.1.12", - "proxy-addr": "~2.0.7", - "qs": "~6.14.0", - "range-parser": "~1.2.1", - "safe-buffer": "5.2.1", - "send": "~0.19.0", - "serve-static": "~1.16.2", - "setprototypeof": "1.2.0", - "statuses": "~2.0.1", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "engines": { - "node": ">= 0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "dev": true, - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/finalhandler": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", - "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", - "dependencies": { - "debug": "2.6.9", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "on-finished": "~2.4.1", - "parseurl": "~1.3.3", - "statuses": "~2.0.2", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/generate-function": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", - "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", - "dependencies": { - "is-property": "^1.0.2" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/http-errors": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", - "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", - "dependencies": { - "depd": "~2.0.0", - "inherits": "~2.0.4", - "setprototypeof": "~1.2.0", - "statuses": "~2.0.2", - "toidentifier": "~1.0.1" - }, - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/ignore-by-default": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", - "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==", - "dev": true - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" - }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/is-binary-path": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", - "dev": true, - "dependencies": { - "binary-extensions": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-property": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", - "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==" - }, - "node_modules/long": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", - "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==" - }, - "node_modules/lru.min": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz", - "integrity": "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA==", - "engines": { - "bun": ">=1.0.0", - "deno": ">=1.30.0", - "node": ">=8.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wellwelwel" - } - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/merge-descriptors": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", - "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/minimatch": { - "version": "10.2.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz", - "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==", - "dev": true, - "dependencies": { - "brace-expansion": "^5.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" - }, - "node_modules/mysql2": { - "version": "3.18.2", - "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.18.2.tgz", - "integrity": "sha512-UfEShBFAZZEAKjySnTUuE7BgqkYT4mx+RjoJ5aqtmwSSvNcJ/QxQPXz/y3jSxNiVRedPfgccmuBtiPCSiEEytw==", - "dependencies": { - "aws-ssl-profiles": "^1.1.2", - "denque": "^2.1.0", - "generate-function": "^2.3.1", - "iconv-lite": "^0.7.2", - "long": "^5.3.2", - "lru.min": "^1.1.4", - "named-placeholders": "^1.1.6", - "sql-escaper": "^1.3.3" - }, - "engines": { - "node": ">= 8.0" - }, - "peerDependencies": { - "@types/node": ">= 8" - } - }, - "node_modules/mysql2/node_modules/iconv-lite": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", - "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/named-placeholders": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", - "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", - "dependencies": { - "lru.min": "^1.1.0" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/negotiator": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", - "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/nodemon": { - "version": "3.1.14", - "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz", - "integrity": "sha512-jakjZi93UtB3jHMWsXL68FXSAosbLfY0In5gtKq3niLSkrWznrVBzXFNOEMJUfc9+Ke7SHWoAZsiMkNP3vq6Jw==", - "dev": true, - "dependencies": { - "chokidar": "^3.5.2", - "debug": "^4", - "ignore-by-default": "^1.0.1", - "minimatch": "^10.2.1", - "pstree.remy": "^1.1.8", - "semver": "^7.5.3", - "simple-update-notifier": "^2.0.0", - "supports-color": "^5.5.0", - "touch": "^3.1.0", - "undefsafe": "^2.0.5" - }, - "bin": { - "nodemon": "bin/nodemon.js" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/nodemon" - } - }, - "node_modules/nodemon/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/nodemon/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-inspect": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", - "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/path-to-regexp": { - "version": "0.1.12", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", - "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==" - }, - "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/pstree.remy": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", - "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", - "dev": true - }, - "node_modules/qs": { - "version": "6.14.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", - "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", - "dependencies": { - "side-channel": "^1.1.0" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/raw-body": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", - "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", - "dependencies": { - "bytes": "~3.1.2", - "http-errors": "~2.0.1", - "iconv-lite": "~0.4.24", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/readdirp": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", - "dev": true, - "dependencies": { - "picomatch": "^2.2.1" - }, - "engines": { - "node": ">=8.10.0" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" - }, - "node_modules/semver": { - "version": "7.7.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", - "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/send": { - "version": "0.19.2", - "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", - "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", - "dependencies": { - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "~0.5.2", - "http-errors": "~2.0.1", - "mime": "1.6.0", - "ms": "2.1.3", - "on-finished": "~2.4.1", - "range-parser": "~1.2.1", - "statuses": "~2.0.2" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/send/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" - }, - "node_modules/serve-static": { - "version": "1.16.3", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", - "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", - "dependencies": { - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "~0.19.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" - }, - "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", - "side-channel-map": "^1.0.1", - "side-channel-weakmap": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-list": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", - "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-map": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", - "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-weakmap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", - "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3", - "side-channel-map": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/simple-update-notifier": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", - "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", - "dev": true, - "dependencies": { - "semver": "^7.5.3" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/sql-escaper": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.3.3.tgz", - "integrity": "sha512-BsTCV265VpTp8tm1wyIm1xqQCS+Q9NHx2Sr+WcnUrgLrQ6yiDIvHYJV5gHxsj1lMBy2zm5twLaZao8Jd+S8JJw==", - "engines": { - "bun": ">=1.0.0", - "deno": ">=2.0.0", - "node": ">=12.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/mysqljs/sql-escaper?sponsor=1" - } - }, - "node_modules/statuses": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", - "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "dependencies": { - "has-flag": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "engines": { - "node": ">=0.6" - } - }, - "node_modules/touch": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", - "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", - "dev": true, - "bin": { - "nodetouch": "bin/nodetouch.js" - } - }, - "node_modules/type-is": { - "version": "1.6.18", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", - "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", - "dependencies": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/undefsafe": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", - "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", - "dev": true - }, - "node_modules/undici-types": { - "version": "7.18.2", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", - "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", - "peer": true - }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "engines": { - "node": ">= 0.8" - } - } - } -} diff --git a/server/package.json b/server/package.json deleted file mode 100644 index a870f45..0000000 --- a/server/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "stardom-story-server", - "version": "1.0.0", - "description": "星域故事汇小游戏后端服务", - "main": "app.js", - "scripts": { - "start": "node app.js", - "dev": "nodemon app.js", - "init-db": "node sql/init.js" - }, - "dependencies": { - "express": "^4.18.2", - "mysql2": "^3.6.5", - "cors": "^2.8.5", - "dotenv": "^16.3.1" - }, - "devDependencies": { - "nodemon": "^3.0.2" - } -} diff --git a/server/requirements.txt b/server/requirements.txt new file mode 100644 index 0000000..b5e1ad1 --- /dev/null +++ b/server/requirements.txt @@ -0,0 +1,10 @@ +# Python后端依赖 +fastapi==0.104.1 +uvicorn[standard]==0.24.0 +sqlalchemy==2.0.23 +aiomysql==0.2.0 +pymysql==1.1.0 +pydantic==2.5.2 +pydantic-settings==2.1.0 +python-dotenv==1.0.0 +python-multipart==0.0.6 diff --git a/server/routes/story.js b/server/routes/story.js deleted file mode 100644 index d98f9fd..0000000 --- a/server/routes/story.js +++ /dev/null @@ -1,110 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const StoryModel = require('../models/story'); - -// 获取故事列表 -router.get('/', async (req, res) => { - try { - const { category, featured, limit, offset } = req.query; - const stories = await StoryModel.getList({ - category, - featured: featured === 'true', - limit: parseInt(limit) || 20, - offset: parseInt(offset) || 0 - }); - res.json({ code: 0, data: stories }); - } catch (err) { - console.error('获取故事列表失败:', err); - res.status(500).json({ code: 500, message: '获取故事列表失败' }); - } -}); - -// 获取热门故事 -router.get('/hot', async (req, res) => { - try { - const { limit } = req.query; - const stories = await StoryModel.getHotStories(parseInt(limit) || 10); - res.json({ code: 0, data: stories }); - } catch (err) { - console.error('获取热门故事失败:', err); - res.status(500).json({ code: 500, message: '获取热门故事失败' }); - } -}); - -// 获取分类列表 -router.get('/categories', async (req, res) => { - try { - const categories = await StoryModel.getCategories(); - res.json({ code: 0, data: categories }); - } catch (err) { - console.error('获取分类列表失败:', err); - res.status(500).json({ code: 500, message: '获取分类列表失败' }); - } -}); - -// 获取故事详情 -router.get('/:id', async (req, res) => { - try { - const storyId = parseInt(req.params.id); - const story = await StoryModel.getDetail(storyId); - if (!story) { - return res.status(404).json({ code: 404, message: '故事不存在' }); - } - res.json({ code: 0, data: story }); - } catch (err) { - console.error('获取故事详情失败:', err); - res.status(500).json({ code: 500, message: '获取故事详情失败' }); - } -}); - -// 记录游玩 -router.post('/:id/play', async (req, res) => { - try { - const storyId = parseInt(req.params.id); - await StoryModel.incrementPlayCount(storyId); - res.json({ code: 0, message: '记录成功' }); - } catch (err) { - console.error('记录游玩失败:', err); - res.status(500).json({ code: 500, message: '记录游玩失败' }); - } -}); - -// 点赞 -router.post('/:id/like', async (req, res) => { - try { - const storyId = parseInt(req.params.id); - const { like } = req.body; // true: 点赞, false: 取消点赞 - await StoryModel.toggleLike(storyId, like); - res.json({ code: 0, message: like ? '点赞成功' : '取消点赞成功' }); - } catch (err) { - console.error('点赞操作失败:', err); - res.status(500).json({ code: 500, message: '点赞操作失败' }); - } -}); - -// AI改写结局 -router.post('/:id/rewrite', async (req, res) => { - try { - const storyId = parseInt(req.params.id); - const { ending_name, ending_content, prompt } = req.body; - - if (!prompt) { - return res.status(400).json({ code: 400, message: '请输入改写指令' }); - } - - // 调用AI服务生成新内容 - const result = await StoryModel.aiRewriteEnding({ - storyId, - endingName: ending_name, - endingContent: ending_content, - prompt - }); - - res.json({ code: 0, data: result }); - } catch (err) { - console.error('AI改写失败:', err); - res.status(500).json({ code: 500, message: 'AI改写失败' }); - } -}); - -module.exports = router; diff --git a/server/routes/user.js b/server/routes/user.js deleted file mode 100644 index a17e8d9..0000000 --- a/server/routes/user.js +++ /dev/null @@ -1,184 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const UserModel = require('../models/user'); - -// 模拟微信登录(实际环境需要调用微信API) -router.post('/login', async (req, res) => { - try { - const { code, userInfo } = req.body; - - // 实际项目中需要用code换取openid - // 这里为了开发测试,暂时用code作为openid - const openid = code || `test_user_${Date.now()}`; - - const user = await UserModel.findOrCreate(openid, userInfo); - res.json({ - code: 0, - data: { - userId: user.id, - openid: user.openid, - nickname: user.nickname, - avatarUrl: user.avatar_url - } - }); - } catch (err) { - console.error('登录失败:', err); - res.status(500).json({ code: 500, message: '登录失败' }); - } -}); - -// 更新用户信息 -router.post('/profile', async (req, res) => { - try { - const { userId, nickname, avatarUrl, gender } = req.body; - await UserModel.updateProfile(userId, { nickname, avatarUrl, gender }); - res.json({ code: 0, message: '更新成功' }); - } catch (err) { - console.error('更新用户信息失败:', err); - res.status(500).json({ code: 500, message: '更新用户信息失败' }); - } -}); - -// 获取用户进度 -router.get('/progress', async (req, res) => { - try { - const { userId, storyId } = req.query; - const progress = await UserModel.getProgress( - parseInt(userId), - storyId ? parseInt(storyId) : null - ); - res.json({ code: 0, data: progress }); - } catch (err) { - console.error('获取进度失败:', err); - res.status(500).json({ code: 500, message: '获取进度失败' }); - } -}); - -// 保存用户进度 -router.post('/progress', async (req, res) => { - try { - const { userId, storyId, currentNodeKey, isCompleted, endingReached } = req.body; - await UserModel.saveProgress(parseInt(userId), parseInt(storyId), { - currentNodeKey, - isCompleted, - endingReached - }); - res.json({ code: 0, message: '保存成功' }); - } catch (err) { - console.error('保存进度失败:', err); - res.status(500).json({ code: 500, message: '保存进度失败' }); - } -}); - -// 点赞操作 -router.post('/like', async (req, res) => { - try { - const { userId, storyId, isLiked } = req.body; - await UserModel.toggleLike(parseInt(userId), parseInt(storyId), isLiked); - res.json({ code: 0, message: isLiked ? '点赞成功' : '取消点赞' }); - } catch (err) { - console.error('点赞操作失败:', err); - res.status(500).json({ code: 500, message: '点赞操作失败' }); - } -}); - -// 收藏操作 -router.post('/collect', async (req, res) => { - try { - const { userId, storyId, isCollected } = req.body; - await UserModel.toggleCollect(parseInt(userId), parseInt(storyId), isCollected); - res.json({ code: 0, message: isCollected ? '收藏成功' : '取消收藏' }); - } catch (err) { - console.error('收藏操作失败:', err); - res.status(500).json({ code: 500, message: '收藏操作失败' }); - } -}); - -// 获取收藏列表 -router.get('/collections', async (req, res) => { - try { - const { userId } = req.query; - const collections = await UserModel.getCollections(parseInt(userId)); - res.json({ code: 0, data: collections }); - } catch (err) { - console.error('获取收藏列表失败:', err); - res.status(500).json({ code: 500, message: '获取收藏列表失败' }); - } -}); - -// 获取已解锁结局 -router.get('/endings', async (req, res) => { - try { - const { userId, storyId } = req.query; - const endings = await UserModel.getUnlockedEndings( - parseInt(userId), - storyId ? parseInt(storyId) : null - ); - res.json({ code: 0, data: endings }); - } catch (err) { - console.error('获取结局列表失败:', err); - res.status(500).json({ code: 500, message: '获取结局列表失败' }); - } -}); - -// 获取我的作品 -router.get('/my-works', async (req, res) => { - try { - const { userId } = req.query; - const works = await UserModel.getMyWorks(parseInt(userId)); - res.json({ code: 0, data: works }); - } catch (err) { - console.error('获取作品失败:', err); - res.status(500).json({ code: 500, message: '获取作品失败' }); - } -}); - -// 获取草稿箱 -router.get('/drafts', async (req, res) => { - try { - const { userId } = req.query; - const drafts = await UserModel.getDrafts(parseInt(userId)); - res.json({ code: 0, data: drafts }); - } catch (err) { - console.error('获取草稿失败:', err); - res.status(500).json({ code: 500, message: '获取草稿失败' }); - } -}); - -// 获取最近游玩 -router.get('/recent-played', async (req, res) => { - try { - const { userId, limit } = req.query; - const recent = await UserModel.getRecentPlayed(parseInt(userId), parseInt(limit) || 10); - res.json({ code: 0, data: recent }); - } catch (err) { - console.error('获取最近游玩失败:', err); - res.status(500).json({ code: 500, message: '获取最近游玩失败' }); - } -}); - -// 获取AI创作历史 -router.get('/ai-history', async (req, res) => { - try { - const { userId, limit } = req.query; - const history = await UserModel.getAIHistory(parseInt(userId), parseInt(limit) || 20); - res.json({ code: 0, data: history }); - } catch (err) { - console.error('获取AI历史失败:', err); - res.status(500).json({ code: 500, message: '获取AI历史失败' }); - } -}); - -// 获取AI配额 -router.get('/ai-quota', async (req, res) => { - try { - const { userId } = req.query; - const quota = await UserModel.getAIQuota(parseInt(userId)); - res.json({ code: 0, data: quota }); - } catch (err) { - console.error('获取AI配额失败:', err); - res.status(500).json({ code: 500, message: '获取AI配额失败' }); - } -}); - -module.exports = router; diff --git a/server/sql/init_db.py b/server/sql/init_db.py new file mode 100644 index 0000000..47ed19d --- /dev/null +++ b/server/sql/init_db.py @@ -0,0 +1,93 @@ +""" +数据库初始化脚本 +在IDEA中直接运行此文件即可建库 +""" +import os +import pymysql +from pathlib import Path + +# 获取当前脚本所在目录 +SQL_DIR = Path(__file__).parent + +# 数据库配置(从环境变量或默认值) +DB_CONFIG = { + 'host': os.getenv('DB_HOST', 'localhost'), + 'port': int(os.getenv('DB_PORT', 3306)), + 'user': os.getenv('DB_USER', 'root'), + 'password': os.getenv('DB_PASSWORD', '123456'), + 'charset': 'utf8mb4' +} + + +def read_sql_file(filename: str) -> str: + """读取SQL文件""" + filepath = SQL_DIR / filename + with open(filepath, 'r', encoding='utf-8') as f: + return f.read() + + +def execute_sql(cursor, sql: str, description: str): + """执行SQL语句(支持多语句)""" + print(f'{description}...') + # 按分号分割SQL语句 + statements = [s.strip() for s in sql.split(';') if s.strip()] + for stmt in statements: + if stmt: + try: + cursor.execute(stmt) + except pymysql.Error as e: + # 忽略某些错误(如数据库已存在) + if e.args[0] not in [1007, 1050]: # 数据库已存在、表已存在 + print(f' 警告: {e.args[1]}') + print(f' {description}完成!') + + +def init_database(): + """初始化数据库""" + print('=' * 50) + print('星域故事汇 - 数据库初始化') + print('=' * 50) + print(f'连接信息: {DB_CONFIG["user"]}@{DB_CONFIG["host"]}:{DB_CONFIG["port"]}') + print() + + # 连接MySQL + connection = pymysql.connect(**DB_CONFIG) + cursor = connection.cursor() + + try: + # 1. 执行schema.sql(创建数据库和表) + schema_sql = read_sql_file('schema.sql') + execute_sql(cursor, schema_sql, '创建数据库表结构') + connection.commit() + + # 2. 执行种子数据第1部分 + seed1_sql = read_sql_file('seed_stories_part1.sql') + execute_sql(cursor, seed1_sql, '导入种子数据(第1部分)') + connection.commit() + + # 3. 执行种子数据第2部分 + seed2_sql = read_sql_file('seed_stories_part2.sql') + execute_sql(cursor, seed2_sql, '导入种子数据(第2部分)') + connection.commit() + + print() + print('=' * 50) + print('数据库初始化完成!') + print('共创建10个种子故事,包含66个剧情节点和多个结局分支。') + print('=' * 50) + print() + print('现在可以启动后端服务了:') + print(' cd "D:\\idea project\\ai_game\\server"') + print(' python -m app.main') + + except Exception as e: + print(f'初始化失败: {e}') + connection.rollback() + raise + finally: + cursor.close() + connection.close() + + +if __name__ == '__main__': + init_database()