feat: 多功能更新
This commit is contained in:
@@ -2,107 +2,156 @@
|
||||
|
||||
## 目标
|
||||
|
||||
本文件用于约束 AI 在本项目内的实现方式,确保代码简洁、可维护、不过度设计。
|
||||
本文档用于约束 AI 在本项目内的实现方式,确保代码简洁、可维护、安全,并与当前业务链路保持一致。
|
||||
|
||||
## 核心原则
|
||||
|
||||
- 只做当前需要的功能,不做无意义兼容层。
|
||||
- 保持单一入口和单一职责,避免重复路径和重复逻辑。
|
||||
- 默认最小改动,优先复用已有工具函数和类型。
|
||||
- 注释和文档要清晰,特别是接口字段与错误处理语义。
|
||||
- 默认最小改动,优先复用现有工具函数、类型和目录结构。
|
||||
- 保持单一入口和单一职责,避免同一业务暴露多套路由或重复实现。
|
||||
- 前端不接触 NewAPI session、完整 API Key、Lsky token 等敏感信息。
|
||||
- 注释和日志要解释意图、边界和排查信息,不输出密码、cookie、完整 key、token、图片二进制或完整 prompt。
|
||||
- 已存在的说明性注释不要随意删除,尤其是 `server/utils/openai.ts` 里的模型调用、视觉输入、流式解析等上下文注释。
|
||||
|
||||
## API 路由规范
|
||||
|
||||
- 认证相关接口统一放在 server/api/auth。
|
||||
- 当前仅保留以下入口:
|
||||
- POST /api/auth/register
|
||||
- POST /api/auth/login
|
||||
- GET /api/auth/me
|
||||
- GET /api/auth/logout
|
||||
- GET /api/auth/ready
|
||||
- 不再创建 server/api/user 的本地别名路由。
|
||||
- 对外路径由前端统一调用 auth 前缀,不允许同一业务暴露两套路由。
|
||||
- 认证相关接口统一放在 `server/api/auth`:
|
||||
- `POST /api/auth/register`
|
||||
- `POST /api/auth/login`
|
||||
- `GET /api/auth/me`
|
||||
- `GET /api/auth/logout`
|
||||
- `GET /api/auth/ready`
|
||||
- 生图相关接口统一放在 `server/api/images`:
|
||||
- `POST /api/images/generate`
|
||||
- `GET /api/images/history`
|
||||
- `GET /api/images/history/:id`
|
||||
- `DELETE /api/images/history/:id`
|
||||
- `GET /api/images/stats`
|
||||
- 不创建 `server/api/user` 之类的本地别名路由。
|
||||
- 临时排查接口不要长期保留,例如数据库健康检查类接口排查结束后必须删除。
|
||||
|
||||
## 登录状态与环境准备规范
|
||||
## 登录与环境准备
|
||||
|
||||
- 登录成功后,后端从 NewAPI Set-Cookie 中提取 session,并写入本项目 httpOnly cookie。
|
||||
- 前端不得读取、保存或透传 NewAPI session、完整 API Key 等敏感信息。
|
||||
- 前端通过 /api/auth/me 恢复登录状态,通过 /api/auth/logout 清理登录状态。
|
||||
- /api/auth/ready 只负责检查当前账号运行环境是否就绪:存在 name 为 AIArtStudio、status 为 1、未删除的 Token 即视为就绪。
|
||||
- ready 检查不到可用 Token 时,由后端使用固定参数创建 AIArtStudio Token。
|
||||
- /api/auth/ready 不返回完整 key,也不调用完整 key 获取接口;返回文案使用“环境已准备 / 环境初始化完成”等业务表达,不向前端暴露 API Key 细节。
|
||||
- 登录成功后,后端从 NewAPI `Set-Cookie` 中提取 `session`,写入本站 httpOnly cookie,同时保存 `newapi_user_id`。
|
||||
- 前端通过 `/api/auth/me` 恢复登录状态,通过 `/api/auth/logout` 清理登录状态。
|
||||
- 登录成功后前端可调用 `/api/auth/ready`,用于确认当前 NewAPI 用户是否具备可用的 `AIArtStudio` Token。
|
||||
- `/api/auth/ready` 只检查或创建环境:
|
||||
- 只认 `name === "AIArtStudio"`、`status === 1`、未软删除的 Token。
|
||||
- 没有可用 Token 时,后端按固定参数创建。
|
||||
- 不调用完整 key 获取接口,不向前端返回 key。
|
||||
- 返回文案使用“环境已准备 / 环境初始化完成”等业务表达,不暴露 API Key 细节。
|
||||
- 完整 key 只允许在服务端真实调用模型前按需获取,相关逻辑集中在 `server/utils/newApiTokens.ts`。
|
||||
|
||||
## 上游请求规范
|
||||
## 上游与模型调用
|
||||
|
||||
- 调用上游 NewAPI 必须使用 server/utils/fetch.ts 中的统一入口。
|
||||
- 普通未登录请求使用 newApiFetch。
|
||||
- 需要读取上游响应头的请求使用 newApiFetchRaw,目前主要用于登录时提取 Set-Cookie。
|
||||
- 需要 NewAPI 登录态的请求使用 newApiAuthedFetch,由服务端从 httpOnly cookie 中读取 session 和 userId 后补齐 Cookie 与 New-Api-User。
|
||||
- 上游基地址只在 fetch.ts 的 BASE_URL 维护一次。
|
||||
- 禁止在各个 handler 内重复写 baseURL。
|
||||
- 当前策略是硬编码基地址,按项目要求保持简单直接。
|
||||
- 调用 NewAPI 用户、Token 等上游接口,使用 `server/utils/fetch.ts` 的统一入口:
|
||||
- `newApiFetch`:普通未登录请求。
|
||||
- `newApiFetchRaw`:需要读取上游响应头时使用,目前主要用于登录提取 `Set-Cookie`。
|
||||
- `newApiAuthedFetch`:需要 NewAPI 登录态时使用,由服务端从 httpOnly cookie 读取 session/userId 并补齐请求头。
|
||||
- 生图模型调用集中在 `server/utils/openai.ts`。
|
||||
- 当前生图上游使用 `POST https://api.qflink.xyz/v1/chat/completions`,参数固定为:
|
||||
- `model: "gpt-image-2"`
|
||||
- `stream: true`
|
||||
- `messages: [{ role: "user", content: prompt }]`
|
||||
- 生图通过 `askImgStream` 读取 SSE 流,累积 `choices[].delta.content`,从 Markdown 图片或普通 URL 中提取图片地址。
|
||||
- `askStream` 保留给 Responses API 的其他流式文本/多模态场景,不强行复用于 chat completions SSE。
|
||||
- 不再使用 `/v1/images/generations` 作为当前生图主链路。
|
||||
|
||||
## Token 处理规范
|
||||
## 生图、图床与历史记录
|
||||
|
||||
- NewAPI Token 相关通用逻辑放在 server/utils/newApiTokens.ts。
|
||||
- handler 不直接拼装 Token 列表、创建参数或 ready 判定逻辑。
|
||||
- Token 列表接口返回的脱敏 key 只用于后端判断,不透出给前端。
|
||||
- 完整 key 获取接口必须单独设计服务端流程,默认不要在登录或 ready 阶段调用。
|
||||
- 上游 Token 内部结构类型优先留在 server/utils 内;只有前后端共享的返回契约才放入 shared/types。
|
||||
- `POST /api/images/generate` 当前同步等待生图完成后返回,不向前端透传流式进度。
|
||||
- 生图成功后返回:
|
||||
- `imageUrl`:NewAPI 上游返回的图片 URL,前端当前优先展示。
|
||||
- `hostedImageUrl`:Lsky 图床归档后的 URL,归档失败时为 `null`。
|
||||
- `revisedPrompt`:流式 chat completions 当前没有等价字段,通常为空。
|
||||
- Lsky 归档逻辑集中在 `server/utils/lsky.ts`:
|
||||
- 配置从 `LSKY_BASE_URL`、`LSKY_TOKEN`、`LSKY_STORAGE_ID` 读取。
|
||||
- 上传时先下载上游图片,再用 `multipart/form-data` 调 Lsky `/upload`。
|
||||
- 文件名格式为 `userId_username_timestamp_recordId.ext`。
|
||||
- tags 固定包含 `AIArtStudio`、`user:{userId}`、`record:{recordId}`、`model:gpt-image-2`。
|
||||
- 图床上传失败不影响本次生图成功:接口仍返回上游 `imageUrl`,数据库记录归档失败提示。
|
||||
- 数据库不保存图片 base64;不要恢复 `image_base64` 或类似大文本存图方案。
|
||||
- 历史列表不返回大体积数据;详情可返回完整上游响应和 Lsky 上传响应。
|
||||
|
||||
## 请求体处理规范
|
||||
## 数据库与 Prisma
|
||||
|
||||
- 所有接口先校验请求体:只接受 JSON 对象或 null。
|
||||
- 对上游透传字段必须使用白名单数组过滤。
|
||||
- 仅透传类型正确且文档声明的字段,忽略多余字段。
|
||||
- 不做隐式字段转换,不做猜测性补全。
|
||||
- Prisma schema 位于 `prisma/schema.prisma`,实际数据库同步以 Prisma 为准。
|
||||
- 根目录 `create_tables.sql` 是人工可读建表参考,字段变更时必须同步更新。
|
||||
- Prisma Client 从 `~~/app/generated/prisma/client` 引入,统一由 `server/utils/prisma.ts` 创建和复用。
|
||||
- 当前使用 Prisma 7 + `@prisma/adapter-mariadb`,`DATABASE_URL` 在运行时解析为 MariaDB pool config。
|
||||
- 登录或 `/api/auth/me` 成功后会 upsert `User` 快照,主键使用 NewAPI 用户 id。
|
||||
- 生图记录写入 `ImageGeneration`:
|
||||
- 开始时写 `RUNNING`。
|
||||
- 成功时写 `SUCCEEDED`、上游 URL、图床 URL、MIME、完整上游响应、完整图床响应、耗时。
|
||||
- 失败时写 `FAILED`、错误信息、耗时。
|
||||
- 删除历史采用软删除 `deletedAt`。
|
||||
- `GenerationStats` 使用固定 id `global` 记录全局统计。
|
||||
- 统计更新失败只记录日志,不应阻断用户拿到已经生成的图片。
|
||||
- 需要变更数据库结构时,同时维护 Prisma migration 和 `create_tables.sql`。
|
||||
|
||||
## 响应与错误处理规范
|
||||
## 日志规范
|
||||
|
||||
- 统一使用 createSuccessResponse 和 createErrorResponse 返回结构。
|
||||
- 上游异常统一通过 createUpstreamErrorResponse 处理。
|
||||
- 错误处理策略:尽量保留上游状态码与原始错误数据,只补统一响应外壳。
|
||||
- 避免在每个 handler 内复制复杂的错误解析代码。
|
||||
- API handler 使用 `server/utils/logging.ts` 的 `createApiLogger` 和 `toSafeLogError`。
|
||||
- 日志必须包含足够排查信息,例如 `requestId`、阶段、`userId`、`recordId`、分页、耗时、状态。
|
||||
- 生图日志阶段建议保持清晰:
|
||||
- `read_body`
|
||||
- `read_user_id`
|
||||
- `create_running_record`
|
||||
- `get_api_key`
|
||||
- `call_image_stream_api`
|
||||
- `upload_lsky`
|
||||
- `finish_success_record`
|
||||
- 不记录密码、cookie、完整 API key、Lsky token、完整 prompt、图片二进制、base64。
|
||||
- 全局请求日志中间件只记录 method、path、status、耗时,不记录请求体和响应体。
|
||||
|
||||
## 请求、响应与错误处理
|
||||
|
||||
- 所有 JSON 接口先校验请求体:只接受 JSON 对象或 `null`,数组、字符串等无效 body 直接返回 400。
|
||||
- 对上游透传字段必须使用白名单数组过滤,只透传类型正确且文档声明的字段。
|
||||
- 统一使用 `createSuccessResponse`、`createErrorResponse` 返回结构。
|
||||
- 上游异常统一通过 `createUpstreamErrorResponse` 转换。
|
||||
- 401 或登录态失效时统一清理本地 auth cookie。
|
||||
- 不在 handler 内重复实现复杂错误解析,通用判断放到 `server/utils`。
|
||||
|
||||
## 类型规范
|
||||
|
||||
- 用户相关请求/响应类型放在 shared/types/user.ts。
|
||||
- 公共响应类型放在 shared/types/index.ts。
|
||||
- OpenAI 调用基础类型放在 shared/types/openai.ts。
|
||||
- 新增接口必须先补类型,再写 handler。
|
||||
- 每个类型字段都要有中文注释,说明字段含义与可选性。
|
||||
- 仅前端需要感知的接口契约放入 shared/types;服务端内部上游适配类型不要扩散到 shared。
|
||||
- 用户相关请求/响应类型放在 `shared/types/user.ts`。
|
||||
- 公共响应类型放在 `shared/types/index.ts`。
|
||||
- 生图、历史、统计、OpenAI 基础调用类型放在 `shared/types/openai.ts`。
|
||||
- 只有前后端共享的接口契约放入 `shared/types`;服务端内部上游适配类型留在 `server/utils` 或对应 handler 内。
|
||||
- 新增或修改接口时先更新共享类型,再更新服务端和前端调用。
|
||||
- 类型字段应有中文注释,说明含义、可选性和是否可能为空。
|
||||
|
||||
## 注释规范
|
||||
## 前端接入约定
|
||||
|
||||
- 注释用中文,描述意图与边界,不写无意义废话。
|
||||
- 关键位置必须有注释:
|
||||
- 字段白名单目的
|
||||
- 请求体校验原因
|
||||
- 上游转发意图
|
||||
- 错误处理策略
|
||||
- 用户服务在 `app/services/user_service.ts`,图片服务在 `app/services/image_service.ts`。
|
||||
- 登录成功后可以调用 `UserReady()` 准备环境;`/api/auth/me` 恢复登录状态时不自动调用 ready。
|
||||
- 当前首页生图组件为 `app/components/ImageGenerateCom.vue`,优先展示响应中的 `imageUrl`。
|
||||
- `hostedImageUrl` 作为图床归档地址返回,后续需要切换展示来源时再调整前端策略。
|
||||
|
||||
## 代码风格规范
|
||||
## 代码风格
|
||||
|
||||
- TypeScript 严格类型优先,避免 any 扩散。
|
||||
- TypeScript 严格类型优先,避免 `any` 扩散。
|
||||
- 新增通用逻辑优先抽到 `server/utils`,handler 只负责入参校验、调用和统一响应。
|
||||
- 修改优先小步快改,不重构无关代码。
|
||||
- 保持现有目录结构和命名风格。
|
||||
- 新增通用逻辑优先抽到 server/utils,避免在 handler 重复实现。
|
||||
- 注释使用中文,描述意图与边界,不写机械解释。
|
||||
- 不删除已有有价值注释;确需重写文件时,要保留或迁移原注释表达的信息。
|
||||
|
||||
## AI 执行清单
|
||||
|
||||
当 AI 新增一个 API 时,按以下顺序执行:
|
||||
当 AI 新增或调整 API 时,按以下顺序执行:
|
||||
|
||||
1. 在 shared/types 中定义请求与响应类型,并写字段注释。
|
||||
2. 在 server/api/auth 新建对应 handler。
|
||||
3. 在 handler 中完成请求体校验和白名单过滤。
|
||||
4. 按请求场景选择 newApiFetch、newApiFetchRaw 或 newApiAuthedFetch 调用上游接口。
|
||||
5. 可复用的业务逻辑优先抽到 server/utils,handler 只负责入参、调用和统一响应。
|
||||
6. 用统一响应工具返回成功与错误结果。
|
||||
7. 自检 TypeScript 报错后再结束。
|
||||
1. 先阅读现有 handler、utils、shared types、Prisma schema,确认真实实现。
|
||||
2. 更新共享类型和服务端内部类型。
|
||||
3. 在 handler 中完成请求体校验、白名单过滤、鉴权和日志。
|
||||
4. 将可复用业务逻辑抽到 `server/utils`。
|
||||
5. 涉及数据库时同步修改 Prisma schema、migration、`create_tables.sql`。
|
||||
6. 确认敏感信息不进入前端响应、日志或数据库不该保存的字段。
|
||||
7. 运行 `pnpm typecheck`;涉及 Prisma schema 时运行 `prisma generate`,必要时同步数据库。
|
||||
|
||||
## 非目标
|
||||
|
||||
- 不为未来不确定需求预建兼容路由。
|
||||
- 不引入与当前需求无关的抽象层。
|
||||
- 不在多个地方维护同一配置值。
|
||||
- 不保存生成图片 base64。
|
||||
- 不把服务端密钥、session 或 token 暴露给前端。
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import { ImageService } from "~/services";
|
||||
import { useUserStore } from "~/stores";
|
||||
|
||||
const userStore = useUserStore();
|
||||
const { isOnline } = storeToRefs(userStore);
|
||||
|
||||
const prompt = ref("");
|
||||
const imageUrl = ref("");
|
||||
@@ -47,7 +50,12 @@ const generate = async () => {
|
||||
:disabled="loading"
|
||||
/>
|
||||
|
||||
<el-button type="primary" :loading="loading" @click="generate">
|
||||
<el-button
|
||||
type="primary"
|
||||
:loading="loading"
|
||||
:disabled="!isOnline"
|
||||
@click="generate"
|
||||
>
|
||||
立即生成
|
||||
</el-button>
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from "vue";
|
||||
import type {
|
||||
ICommonResponse,
|
||||
IUserLoginData,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from "vue";
|
||||
import type {
|
||||
ICommonResponse,
|
||||
IUserRegisterData,
|
||||
|
||||
+4
-3
@@ -22,12 +22,13 @@ CREATE TABLE IF NOT EXISTS `image_generations` (
|
||||
`started_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '生图开始时间',
|
||||
`ended_at` DATETIME(3) NULL COMMENT '生图结束时间',
|
||||
`duration_ms` INT NULL COMMENT '生图耗时,单位毫秒',
|
||||
`image_url` VARCHAR(2048) NULL COMMENT '上游返回的图片 URL',
|
||||
`image_base64` LONGTEXT NULL COMMENT '服务端下载图片后保存的 base64 原文',
|
||||
`image_url` VARCHAR(2048) NULL COMMENT 'NewAPI 上游返回的图片 URL',
|
||||
`hosted_image_url` VARCHAR(2048) NULL COMMENT 'Lsky 图床归档后的图片 URL',
|
||||
`image_mime_type` VARCHAR(191) NULL COMMENT '图片 MIME 类型',
|
||||
`revised_prompt` TEXT NULL COMMENT '上游返回的修订提示词',
|
||||
`upstream_response` JSON NULL COMMENT '完整上游生图接口响应',
|
||||
`error_message` TEXT NULL COMMENT '失败原因或图片下载失败信息',
|
||||
`hosted_response` JSON NULL COMMENT '完整 Lsky 图床上传接口响应',
|
||||
`error_message` TEXT NULL COMMENT '失败原因或图床归档失败提示',
|
||||
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '创建时间',
|
||||
`updated_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) COMMENT '更新时间',
|
||||
`deleted_at` DATETIME(3) NULL COMMENT '软删除时间',
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
ALTER TABLE `image_generations`
|
||||
DROP COLUMN `image_base64`,
|
||||
ADD COLUMN `hosted_image_url` VARCHAR(2048) NULL COMMENT 'Lsky 图床归档后的图片 URL' AFTER `image_url`,
|
||||
ADD COLUMN `hosted_response` JSON NULL COMMENT '完整 Lsky 图床上传接口响应' AFTER `upstream_response`;
|
||||
@@ -44,10 +44,11 @@ model ImageGeneration {
|
||||
endedAt DateTime? @map("ended_at")
|
||||
durationMs Int? @map("duration_ms")
|
||||
imageUrl String? @map("image_url") @db.VarChar(2048)
|
||||
imageBase64 String? @map("image_base64") @db.LongText
|
||||
hostedImageUrl String? @map("hosted_image_url") @db.VarChar(2048)
|
||||
imageMimeType String? @map("image_mime_type") @db.VarChar(191)
|
||||
revisedPrompt String? @map("revised_prompt") @db.Text
|
||||
upstreamResponse Json? @map("upstream_response")
|
||||
hostedResponse Json? @map("hosted_response")
|
||||
errorMessage String? @map("error_message") @db.Text
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// server/api/auth/login.post.ts
|
||||
import { consola } from "consola";
|
||||
import type { IUserLoginData, IUserLoginRequest } from "#shared/types";
|
||||
import {
|
||||
clearNewApiAuthCookies,
|
||||
createApiLogger,
|
||||
createErrorResponse,
|
||||
createSuccessResponse,
|
||||
createUpstreamErrorResponse,
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
extractCookieValueFromSetCookie,
|
||||
newApiFetchRaw,
|
||||
setNewApiAuthCookies,
|
||||
toSafeLogError,
|
||||
upsertUserSnapshot
|
||||
} from "~~/server/utils";
|
||||
|
||||
@@ -28,6 +29,7 @@ interface INewApiLoginUserData extends IUserLoginData {
|
||||
/** NewAPI 登录结果如果返回额外字段,服务端会在返回前裁剪掉 */
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* 允许从请求体透传给上游的字段列表。
|
||||
* 只有在这里声明过的字段才会被转发,其余字段一律丢弃,防止参数污染。
|
||||
@@ -40,11 +42,24 @@ const LOGIN_FIELDS = ["username", "password"] as const satisfies ReadonlyArray<
|
||||
* POST /api/auth/login
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const logger = createApiLogger("auth.login");
|
||||
const requestBody = await readBody<Partial<IUserLoginRequest> | null>(event);
|
||||
|
||||
logger.info("开始", {
|
||||
bodyType: requestBody === null ? "null" : typeof requestBody,
|
||||
hasUsername: typeof requestBody?.username === "string",
|
||||
hasPassword: typeof requestBody?.password === "string"
|
||||
});
|
||||
|
||||
// 只接受 JSON 对象或 null,避免数组/字符串等无效 body 被透传到上游。
|
||||
if (requestBody !== null && typeof requestBody !== "object") {
|
||||
if (
|
||||
requestBody !== null &&
|
||||
(typeof requestBody !== "object" || Array.isArray(requestBody))
|
||||
) {
|
||||
clearNewApiAuthCookies(event);
|
||||
logger.warn("请求体格式错误", {
|
||||
bodyType: Array.isArray(requestBody) ? "array" : typeof requestBody
|
||||
});
|
||||
return createErrorResponse(400, "请求体必须是 JSON 对象");
|
||||
}
|
||||
|
||||
@@ -70,19 +85,28 @@ export default defineEventHandler(async (event) => {
|
||||
);
|
||||
|
||||
const normalized = normalizeLoginResponse(result._data);
|
||||
const session = extractCookieValueFromSetCookie(result.headers, "session");
|
||||
|
||||
logger.info("上游登录返回", {
|
||||
success: Boolean(normalized.user),
|
||||
hasSession: Boolean(session)
|
||||
});
|
||||
|
||||
if (!normalized.user) {
|
||||
// 上游业务失败时同步清理本地旧登录态,避免继续携带坏 cookie。
|
||||
clearNewApiAuthCookies(event);
|
||||
logger.warn("登录业务失败", {
|
||||
upstreamMessage: normalized.message
|
||||
});
|
||||
return createErrorResponse(1, normalized.message, result._data ?? null);
|
||||
}
|
||||
|
||||
const session = extractCookieValueFromSetCookie(result.headers, "session");
|
||||
if (!session) {
|
||||
// 没有 session 就不能恢复 NewAPI 登录态,必须让前端明确感知失败。
|
||||
clearNewApiAuthCookies(event);
|
||||
consola.error(
|
||||
"/api/auth/login 登录成功但未收到 NewAPI session,请稍后重试"
|
||||
);
|
||||
logger.error("登录成功但未收到 NewAPI session", {
|
||||
userId: normalized.user.id
|
||||
});
|
||||
return createErrorResponse(500, "服务器错误,请稍后重试");
|
||||
}
|
||||
|
||||
@@ -94,7 +118,16 @@ export default defineEventHandler(async (event) => {
|
||||
);
|
||||
|
||||
upsertUserSnapshot(normalized.user).catch((error) => {
|
||||
consola.error("/api/auth/login 保存用户快照失败", error);
|
||||
logger.error("保存用户快照失败", {
|
||||
userId: normalized.user?.id,
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
});
|
||||
|
||||
logger.done("成功", {
|
||||
userId: normalized.user.id,
|
||||
role: normalized.user.role,
|
||||
status: normalized.user.status
|
||||
});
|
||||
|
||||
return createSuccessResponse<IUserLoginData>(
|
||||
@@ -103,7 +136,9 @@ export default defineEventHandler(async (event) => {
|
||||
);
|
||||
} catch (error) {
|
||||
clearNewApiAuthCookies(event);
|
||||
consola.error("/api/auth/login 登录失败", error);
|
||||
logger.error("失败", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createUpstreamErrorResponse(error, "登录失败");
|
||||
}
|
||||
});
|
||||
@@ -112,7 +147,6 @@ export default defineEventHandler(async (event) => {
|
||||
const normalizeLoginResponse = (
|
||||
response: NewApiLoginResponse | undefined
|
||||
): { message: string; user: IUserLoginData | null } => {
|
||||
consola.info("user data", response);
|
||||
if (isUser(response)) {
|
||||
return {
|
||||
message: "登录成功",
|
||||
@@ -121,7 +155,6 @@ const normalizeLoginResponse = (
|
||||
}
|
||||
|
||||
if (!isRecord(response)) {
|
||||
consola.error("/api/auth/login 登录失败:响应不是对象");
|
||||
return {
|
||||
message: "登录失败",
|
||||
user: null
|
||||
@@ -129,11 +162,9 @@ const normalizeLoginResponse = (
|
||||
}
|
||||
|
||||
const wrapped = response as INewApiWrappedLoginResponse;
|
||||
const message =
|
||||
wrapped.message || (wrapped.success ? "登录成功" : "登录失败");
|
||||
const message = wrapped.message || (wrapped.success ? "登录成功" : "登录失败");
|
||||
|
||||
if (wrapped.success !== true || !isUser(wrapped.data)) {
|
||||
consola.error("/api/auth/login 登录失败:上游返回的数据格式不正确");
|
||||
return {
|
||||
message,
|
||||
user: null
|
||||
|
||||
@@ -1,21 +1,31 @@
|
||||
import type { IUserLogoutData } from "#shared/types";
|
||||
import {
|
||||
clearNewApiAuthCookies,
|
||||
createApiLogger,
|
||||
createSuccessResponse,
|
||||
newApiAuthedFetch
|
||||
newApiAuthedFetch,
|
||||
toSafeLogError
|
||||
} from "~~/server/utils";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const logger = createApiLogger("auth.logout");
|
||||
logger.info("开始");
|
||||
|
||||
try {
|
||||
// 带上本站 httpOnly cookie 中的 NewAPI 登录态,请求上游销毁 session。
|
||||
await newApiAuthedFetch<IUserLogoutData>(event, "/api/user/logout", {
|
||||
method: "GET"
|
||||
});
|
||||
} catch {
|
||||
logger.info("上游登出成功");
|
||||
} catch (error) {
|
||||
// 上游 session 可能已失效,本地仍然必须清理,避免残留坏登录态。
|
||||
logger.warn("上游登出失败,继续清理本地登录态", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
} finally {
|
||||
clearNewApiAuthCookies(event);
|
||||
}
|
||||
|
||||
logger.done("成功");
|
||||
return createSuccessResponse<IUserLogoutData>(null, "登出成功");
|
||||
});
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { IUserMeData } from "#shared/types";
|
||||
import {
|
||||
clearNewApiAuthCookies,
|
||||
createApiLogger,
|
||||
createErrorResponse,
|
||||
createSuccessResponse,
|
||||
newApiAuthedFetch,
|
||||
toSafeLogError,
|
||||
upsertUserSnapshot
|
||||
} from "~~/server/utils";
|
||||
|
||||
@@ -24,6 +26,9 @@ interface INewApiSelfUserData extends IUserMeData {
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const logger = createApiLogger("auth.me");
|
||||
logger.info("开始");
|
||||
|
||||
try {
|
||||
// 从本站 httpOnly cookie 读取登录态,并转发给 NewAPI 查询当前用户。
|
||||
const result = await newApiAuthedFetch<NewApiUserResponse>(
|
||||
@@ -38,18 +43,35 @@ export default defineEventHandler(async (event) => {
|
||||
if (!normalized.user) {
|
||||
// 上游业务失败代表当前 cookie 不再可靠,清理后返回统一 401。
|
||||
clearNewApiAuthCookies(event);
|
||||
logger.warn("登录状态无效", {
|
||||
upstreamMessage: normalized.message
|
||||
});
|
||||
return createErrorResponse(401, normalized.message);
|
||||
}
|
||||
|
||||
upsertUserSnapshot(normalized.user).catch(() => {});
|
||||
upsertUserSnapshot(normalized.user).catch((error) => {
|
||||
logger.error("保存用户快照失败", {
|
||||
userId: normalized.user?.id,
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
});
|
||||
|
||||
logger.done("成功", {
|
||||
userId: normalized.user.id,
|
||||
role: normalized.user.role,
|
||||
status: normalized.user.status
|
||||
});
|
||||
|
||||
return createSuccessResponse<IUserMeData>(
|
||||
normalized.user,
|
||||
normalized.message
|
||||
);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// cookie 缺失或上游鉴权异常时统一视为未登录。
|
||||
clearNewApiAuthCookies(event);
|
||||
logger.warn("未登录或登录态失效", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createErrorResponse(401, "未登录");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,10 +1,27 @@
|
||||
import type { IUserReadyData } from "#shared/types";
|
||||
import { isUnauthorizedError } from "~~/server/utils";
|
||||
import {
|
||||
clearNewApiAuthCookies,
|
||||
createApiLogger,
|
||||
createErrorResponse,
|
||||
createSuccessResponse,
|
||||
createUpstreamErrorResponse,
|
||||
ensureAiArtStudioToken,
|
||||
isUnauthorizedError,
|
||||
toSafeLogError
|
||||
} from "~~/server/utils";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const logger = createApiLogger("auth.ready");
|
||||
logger.info("开始");
|
||||
|
||||
try {
|
||||
const result = await ensureAiArtStudioToken(event);
|
||||
|
||||
logger.done("成功", {
|
||||
ready: result.ready,
|
||||
created: result.created
|
||||
});
|
||||
|
||||
return createSuccessResponse<IUserReadyData>(
|
||||
result,
|
||||
result.created ? "环境初始化完成" : "环境已准备"
|
||||
@@ -12,9 +29,15 @@ export default defineEventHandler(async (event) => {
|
||||
} catch (error) {
|
||||
if (isUnauthorizedError(error)) {
|
||||
clearNewApiAuthCookies(event);
|
||||
logger.warn("未登录或登录态失效", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createErrorResponse(401, "未登录");
|
||||
}
|
||||
|
||||
logger.error("失败", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createUpstreamErrorResponse(error, "环境准备失败");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
// server/api/auth/register.post.ts
|
||||
import type {
|
||||
IUserRegisterData,
|
||||
IUserRegisterRequest
|
||||
} from "#shared/types";
|
||||
import type { IUserRegisterData, IUserRegisterRequest } from "#shared/types";
|
||||
import {
|
||||
createApiLogger,
|
||||
createErrorResponse,
|
||||
createSuccessResponse,
|
||||
createUpstreamErrorResponse,
|
||||
newApiFetch
|
||||
newApiFetch,
|
||||
toSafeLogError
|
||||
} from "~~/server/utils";
|
||||
|
||||
/**
|
||||
@@ -26,11 +25,28 @@ const REGISTER_FIELDS = [
|
||||
* POST /api/auth/register
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const logger = createApiLogger("auth.register");
|
||||
const requestBody = await readBody<Partial<IUserRegisterRequest> | null>(
|
||||
event
|
||||
);
|
||||
|
||||
if (requestBody !== null && typeof requestBody !== "object") {
|
||||
logger.info("开始", {
|
||||
bodyType: requestBody === null ? "null" : typeof requestBody,
|
||||
hasUsername: typeof requestBody?.username === "string",
|
||||
hasPassword: typeof requestBody?.password === "string",
|
||||
hasEmail: typeof requestBody?.email === "string",
|
||||
hasVerificationCode: typeof requestBody?.verification_code === "string",
|
||||
hasAffCode: typeof requestBody?.aff_code === "string"
|
||||
});
|
||||
|
||||
// 只接受 JSON 对象或 null,避免数组/字符串等无效 body 被透传到上游。
|
||||
if (
|
||||
requestBody !== null &&
|
||||
(typeof requestBody !== "object" || Array.isArray(requestBody))
|
||||
) {
|
||||
logger.warn("请求体格式错误", {
|
||||
bodyType: Array.isArray(requestBody) ? "array" : typeof requestBody
|
||||
});
|
||||
return createErrorResponse(400, "请求体必须是 JSON 对象");
|
||||
}
|
||||
|
||||
@@ -51,8 +67,15 @@ export default defineEventHandler(async (event) => {
|
||||
}
|
||||
});
|
||||
|
||||
logger.done("成功", {
|
||||
hasResult: Boolean(result)
|
||||
});
|
||||
|
||||
return createSuccessResponse(result, "注册成功");
|
||||
} catch (error) {
|
||||
logger.error("失败", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createUpstreamErrorResponse(error, "注册失败");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { consola } from "consola";
|
||||
import { prisma } from "~~/server/utils";
|
||||
|
||||
export default defineEventHandler(async () => {
|
||||
const startedAt = Date.now();
|
||||
|
||||
try {
|
||||
await prisma.$queryRaw`SELECT 1`;
|
||||
|
||||
return createSuccessResponse(
|
||||
{
|
||||
ok: true,
|
||||
elapsedMs: Date.now() - startedAt
|
||||
},
|
||||
"数据库连接正常"
|
||||
);
|
||||
} catch (error) {
|
||||
consola.error("[images.db-health] 数据库连接失败", error);
|
||||
|
||||
return createUpstreamErrorResponse(error, "数据库连接失败");
|
||||
}
|
||||
});
|
||||
@@ -1,20 +1,29 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { consola } from "consola";
|
||||
import type {
|
||||
IImageGenerateData,
|
||||
IImageGenerateRequest
|
||||
} from "#shared/types/openai";
|
||||
import {
|
||||
askImgStream,
|
||||
clearNewApiAuthCookies,
|
||||
createApiLogger,
|
||||
createErrorResponse,
|
||||
createRunningImageGeneration,
|
||||
downloadImageAsBase64,
|
||||
createSuccessResponse,
|
||||
createUpstreamErrorResponse,
|
||||
finishImageGenerationFailed,
|
||||
finishImageGenerationSuccess,
|
||||
getAiArtStudioTokenKey,
|
||||
getNewApiUserIdFromCookie,
|
||||
isUnauthorizedError
|
||||
getUserArchiveIdentity,
|
||||
isUnauthorizedError,
|
||||
toSafeLogError,
|
||||
uploadImageFromUrl
|
||||
} from "~~/server/utils";
|
||||
|
||||
type ApiLogger = ReturnType<typeof createApiLogger>;
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const requestId = randomUUID();
|
||||
const logger = createApiLogger("images.generate");
|
||||
let stage = "read_body";
|
||||
const requestBody = await readBody<Partial<IImageGenerateRequest> | null>(
|
||||
event
|
||||
@@ -25,87 +34,95 @@ export default defineEventHandler(async (event) => {
|
||||
requestBody !== null &&
|
||||
(typeof requestBody !== "object" || Array.isArray(requestBody))
|
||||
) {
|
||||
logger.warn("请求体格式错误", {
|
||||
bodyType: Array.isArray(requestBody) ? "array" : typeof requestBody
|
||||
});
|
||||
return createErrorResponse(400, "请求体必须是 JSON 对象");
|
||||
}
|
||||
|
||||
const prompt = requestBody?.prompt?.trim();
|
||||
if (!prompt) {
|
||||
logger.warn("缺少提示词");
|
||||
return createErrorResponse(400, "请输入图片描述");
|
||||
}
|
||||
|
||||
logger.info("开始", {
|
||||
promptLength: prompt.length
|
||||
});
|
||||
|
||||
let record: { id: bigint; startedAt: Date } | null = null;
|
||||
|
||||
try {
|
||||
consola.info("[images.generate] 开始", {
|
||||
requestId,
|
||||
promptLength: prompt.length
|
||||
});
|
||||
|
||||
stage = "read_user_id";
|
||||
const userId = getNewApiUserIdFromCookie(event);
|
||||
consola.info("[images.generate] 读取用户成功", {
|
||||
requestId,
|
||||
logger.info("读取用户成功", {
|
||||
userId
|
||||
});
|
||||
|
||||
stage = "create_running_record";
|
||||
record = await createRunningImageGeneration(userId, prompt);
|
||||
consola.info("[images.generate] 创建生图记录成功", {
|
||||
requestId,
|
||||
logger.info("创建生图记录成功", {
|
||||
recordId: record.id.toString()
|
||||
});
|
||||
|
||||
stage = "get_api_key";
|
||||
const apiKey = await getAiArtStudioTokenKey(event);
|
||||
consola.info("[images.generate] 获取服务端 key 成功", {
|
||||
requestId,
|
||||
logger.info("获取服务端 key 成功", {
|
||||
recordId: record.id.toString()
|
||||
});
|
||||
|
||||
stage = "call_image_api";
|
||||
const result = await askImg({
|
||||
stage = "call_image_stream_api";
|
||||
const result = await askImgStream({
|
||||
apiKey,
|
||||
prompt
|
||||
});
|
||||
consola.info("[images.generate] 上游生图成功", {
|
||||
requestId,
|
||||
logger.info("上游流式生图成功", {
|
||||
recordId: record.id.toString(),
|
||||
hasImageUrl: Boolean(result.imageUrl)
|
||||
hasImageUrl: Boolean(result.imageUrl),
|
||||
contentLength: getStreamContentLength(result.upstreamResponse),
|
||||
hasUsage: hasStreamUsage(result.upstreamResponse)
|
||||
});
|
||||
|
||||
stage = "download_image_base64";
|
||||
const downloadedImage = await downloadGeneratedImage(result.imageUrl);
|
||||
consola.info("[images.generate] 图片归档下载完成", {
|
||||
requestId,
|
||||
stage = "upload_lsky";
|
||||
const archiveResult = await archiveGeneratedImage({
|
||||
imageUrl: result.imageUrl,
|
||||
userId,
|
||||
recordId: record.id,
|
||||
createdAt: record.startedAt,
|
||||
logger
|
||||
});
|
||||
logger.info("图床归档完成", {
|
||||
recordId: record.id.toString(),
|
||||
hasBase64: Boolean(downloadedImage.base64),
|
||||
mimeType: downloadedImage.mimeType
|
||||
hosted: Boolean(archiveResult.hostedImageUrl),
|
||||
mimeType: archiveResult.imageMimeType
|
||||
});
|
||||
|
||||
stage = "finish_success_record";
|
||||
await finishImageGenerationSuccess(record.id, record.startedAt, {
|
||||
imageUrl: result.imageUrl,
|
||||
imageBase64: downloadedImage.base64,
|
||||
imageMimeType: downloadedImage.mimeType,
|
||||
hostedImageUrl: archiveResult.hostedImageUrl,
|
||||
imageMimeType: archiveResult.imageMimeType,
|
||||
revisedPrompt: result.revisedPrompt,
|
||||
upstreamResponse: result.upstreamResponse,
|
||||
errorMessage: downloadedImage.errorMessage
|
||||
hostedResponse: archiveResult.hostedResponse,
|
||||
errorMessage: archiveResult.errorMessage
|
||||
});
|
||||
|
||||
consola.info("[images.generate] 完成", {
|
||||
requestId,
|
||||
recordId: record.id.toString()
|
||||
logger.done("成功", {
|
||||
recordId: record.id.toString(),
|
||||
hosted: Boolean(archiveResult.hostedImageUrl)
|
||||
});
|
||||
|
||||
return createSuccessResponse<IImageGenerateData>(
|
||||
{
|
||||
imageUrl: result.imageUrl,
|
||||
hostedImageUrl: archiveResult.hostedImageUrl,
|
||||
revisedPrompt: result.revisedPrompt
|
||||
},
|
||||
"图片生成成功"
|
||||
);
|
||||
} catch (error) {
|
||||
consola.error("[images.generate] 失败", {
|
||||
requestId,
|
||||
logger.error("失败", {
|
||||
stage,
|
||||
recordId: record?.id.toString() ?? null,
|
||||
error: toSafeLogError(error)
|
||||
@@ -114,8 +131,7 @@ export default defineEventHandler(async (event) => {
|
||||
if (record) {
|
||||
await finishImageGenerationFailed(record.id, record.startedAt, error).catch(
|
||||
(recordError) => {
|
||||
consola.error("[images.generate] 更新失败记录失败", {
|
||||
requestId,
|
||||
logger.error("更新失败记录失败", {
|
||||
recordId: record?.id.toString() ?? null,
|
||||
error: toSafeLogError(recordError)
|
||||
});
|
||||
@@ -132,52 +148,75 @@ export default defineEventHandler(async (event) => {
|
||||
}
|
||||
});
|
||||
|
||||
/** 图片 URL 仍然可用时,base64 保存失败不阻断本次生成结果 */
|
||||
const downloadGeneratedImage = async (
|
||||
imageUrl: string
|
||||
): Promise<{
|
||||
base64: string | null;
|
||||
mimeType: string | null;
|
||||
const archiveGeneratedImage = async ({
|
||||
imageUrl,
|
||||
userId,
|
||||
recordId,
|
||||
createdAt,
|
||||
logger
|
||||
}: {
|
||||
imageUrl: string;
|
||||
userId: number;
|
||||
recordId: bigint;
|
||||
createdAt: Date;
|
||||
logger: ApiLogger;
|
||||
}): Promise<{
|
||||
hostedImageUrl: string | null;
|
||||
imageMimeType: string | null;
|
||||
hostedResponse: unknown;
|
||||
errorMessage: string | null;
|
||||
}> => {
|
||||
try {
|
||||
const image = await downloadImageAsBase64(imageUrl);
|
||||
// 图床归档失败不能阻断本次生成结果,前端仍可使用上游图片 URL。
|
||||
const identity = await getUserArchiveIdentity(userId);
|
||||
const uploaded = await uploadImageFromUrl({
|
||||
imageUrl,
|
||||
userId,
|
||||
username: identity.username,
|
||||
recordId,
|
||||
createdAt
|
||||
});
|
||||
|
||||
return {
|
||||
base64: image.base64,
|
||||
mimeType: image.mimeType,
|
||||
hostedImageUrl: uploaded.publicUrl,
|
||||
imageMimeType: uploaded.mimetype,
|
||||
hostedResponse: uploaded.response,
|
||||
errorMessage: null
|
||||
};
|
||||
} catch (error) {
|
||||
consola.error("[images.generate] 保存生成图片 base64 失败", {
|
||||
logger.error("图床归档失败", {
|
||||
recordId: recordId.toString(),
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
|
||||
return {
|
||||
base64: null,
|
||||
mimeType: null,
|
||||
errorMessage: "图片生成成功,但 base64 保存失败"
|
||||
hostedImageUrl: null,
|
||||
imageMimeType: null,
|
||||
hostedResponse: null,
|
||||
errorMessage: "图片生成成功,但图床归档失败"
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const toSafeLogError = (error: unknown) => {
|
||||
const maybeError = error as {
|
||||
data?: unknown;
|
||||
message?: string;
|
||||
name?: string;
|
||||
response?: {
|
||||
_data?: unknown;
|
||||
status?: number;
|
||||
};
|
||||
stack?: string;
|
||||
status?: number;
|
||||
statusCode?: number;
|
||||
};
|
||||
// 日志只读取流式聚合结果的元信息,不记录完整提示词、key 或图片内容。
|
||||
const getStreamContentLength = (upstreamResponse: unknown) => {
|
||||
if (
|
||||
upstreamResponse &&
|
||||
typeof upstreamResponse === "object" &&
|
||||
"content" in upstreamResponse &&
|
||||
typeof upstreamResponse.content === "string"
|
||||
) {
|
||||
return upstreamResponse.content.length;
|
||||
}
|
||||
|
||||
return {
|
||||
name: maybeError.name,
|
||||
message: maybeError.message,
|
||||
status: maybeError.status ?? maybeError.statusCode ?? maybeError.response?.status,
|
||||
data: maybeError.data ?? maybeError.response?._data ?? null,
|
||||
stack: maybeError.stack
|
||||
};
|
||||
return 0;
|
||||
};
|
||||
|
||||
const hasStreamUsage = (upstreamResponse: unknown) => {
|
||||
return (
|
||||
upstreamResponse !== null &&
|
||||
typeof upstreamResponse === "object" &&
|
||||
"usage" in upstreamResponse &&
|
||||
Boolean(upstreamResponse.usage)
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import type { IImageHistoryListData } from "#shared/types/openai";
|
||||
import {
|
||||
clearNewApiAuthCookies,
|
||||
createApiLogger,
|
||||
createErrorResponse,
|
||||
createSuccessResponse,
|
||||
createUpstreamErrorResponse,
|
||||
getNewApiUserIdFromCookie,
|
||||
isUnauthorizedError,
|
||||
listImageGenerationHistory
|
||||
listImageGenerationHistory,
|
||||
toSafeLogError
|
||||
} from "~~/server/utils";
|
||||
|
||||
const DEFAULT_PAGE = 1;
|
||||
@@ -11,6 +16,9 @@ const DEFAULT_PAGE_SIZE = 10;
|
||||
const MAX_PAGE_SIZE = 50;
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const logger = createApiLogger("images.history.list");
|
||||
logger.info("开始");
|
||||
|
||||
try {
|
||||
const userId = getNewApiUserIdFromCookie(event);
|
||||
const query = getQuery(event);
|
||||
@@ -19,12 +27,27 @@ export default defineEventHandler(async (event) => {
|
||||
normalizePositiveInt(query.size, DEFAULT_PAGE_SIZE),
|
||||
MAX_PAGE_SIZE
|
||||
);
|
||||
|
||||
logger.info("查询参数", {
|
||||
userId,
|
||||
page,
|
||||
pageSize
|
||||
});
|
||||
|
||||
const result = await listImageGenerationHistory({
|
||||
userId,
|
||||
page,
|
||||
pageSize
|
||||
});
|
||||
|
||||
logger.done("成功", {
|
||||
userId,
|
||||
page,
|
||||
pageSize,
|
||||
total: result.total,
|
||||
itemCount: result.items.length
|
||||
});
|
||||
|
||||
return createSuccessResponse<IImageHistoryListData>(
|
||||
result,
|
||||
"获取生图历史成功"
|
||||
@@ -32,9 +55,15 @@ export default defineEventHandler(async (event) => {
|
||||
} catch (error) {
|
||||
if (isUnauthorizedError(error)) {
|
||||
clearNewApiAuthCookies(event);
|
||||
logger.warn("未登录或登录态失效", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createErrorResponse(401, "未登录");
|
||||
}
|
||||
|
||||
logger.error("失败", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createUpstreamErrorResponse(error, "获取生图历史失败");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,27 +1,56 @@
|
||||
import {
|
||||
clearNewApiAuthCookies,
|
||||
createApiLogger,
|
||||
createErrorResponse,
|
||||
createSuccessResponse,
|
||||
createUpstreamErrorResponse,
|
||||
getNewApiUserIdFromCookie,
|
||||
isUnauthorizedError,
|
||||
softDeleteImageGeneration
|
||||
softDeleteImageGeneration,
|
||||
toSafeLogError
|
||||
} from "~~/server/utils";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const logger = createApiLogger("images.history.delete");
|
||||
logger.info("开始");
|
||||
|
||||
try {
|
||||
const userId = getNewApiUserIdFromCookie(event);
|
||||
const recordId = parseRecordId(getRouterParam(event, "id"));
|
||||
|
||||
logger.info("删除参数", {
|
||||
userId,
|
||||
recordId: recordId.toString()
|
||||
});
|
||||
|
||||
const deleted = await softDeleteImageGeneration(userId, recordId);
|
||||
|
||||
if (!deleted) {
|
||||
logger.warn("记录不存在", {
|
||||
userId,
|
||||
recordId: recordId.toString()
|
||||
});
|
||||
return createErrorResponse(404, "生图记录不存在");
|
||||
}
|
||||
|
||||
logger.done("成功", {
|
||||
userId,
|
||||
recordId: recordId.toString()
|
||||
});
|
||||
|
||||
return createSuccessResponse(null, "删除生图记录成功");
|
||||
} catch (error) {
|
||||
if (isUnauthorizedError(error)) {
|
||||
clearNewApiAuthCookies(event);
|
||||
logger.warn("未登录或登录态失效", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createErrorResponse(401, "未登录");
|
||||
}
|
||||
|
||||
logger.error("失败", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createUpstreamErrorResponse(error, "删除生图记录失败");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,21 +1,46 @@
|
||||
import type { IImageHistoryDetail } from "#shared/types/openai";
|
||||
import {
|
||||
clearNewApiAuthCookies,
|
||||
createApiLogger,
|
||||
createErrorResponse,
|
||||
createSuccessResponse,
|
||||
createUpstreamErrorResponse,
|
||||
getImageGenerationDetail,
|
||||
getNewApiUserIdFromCookie,
|
||||
isUnauthorizedError
|
||||
isUnauthorizedError,
|
||||
toSafeLogError
|
||||
} from "~~/server/utils";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const logger = createApiLogger("images.history.detail");
|
||||
logger.info("开始");
|
||||
|
||||
try {
|
||||
const userId = getNewApiUserIdFromCookie(event);
|
||||
const recordId = parseRecordId(getRouterParam(event, "id"));
|
||||
|
||||
logger.info("查询参数", {
|
||||
userId,
|
||||
recordId: recordId.toString()
|
||||
});
|
||||
|
||||
const result = await getImageGenerationDetail(userId, recordId);
|
||||
|
||||
if (!result) {
|
||||
logger.warn("记录不存在", {
|
||||
userId,
|
||||
recordId: recordId.toString()
|
||||
});
|
||||
return createErrorResponse(404, "生图记录不存在");
|
||||
}
|
||||
|
||||
logger.done("成功", {
|
||||
userId,
|
||||
recordId: recordId.toString(),
|
||||
status: result.status,
|
||||
hasHostedImageUrl: Boolean(result.hostedImageUrl)
|
||||
});
|
||||
|
||||
return createSuccessResponse<IImageHistoryDetail>(
|
||||
result,
|
||||
"获取生图详情成功"
|
||||
@@ -23,9 +48,15 @@ export default defineEventHandler(async (event) => {
|
||||
} catch (error) {
|
||||
if (isUnauthorizedError(error)) {
|
||||
clearNewApiAuthCookies(event);
|
||||
logger.warn("未登录或登录态失效", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createErrorResponse(401, "未登录");
|
||||
}
|
||||
|
||||
logger.error("失败", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createUpstreamErrorResponse(error, "获取生图详情失败");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,15 +1,35 @@
|
||||
import type { IImageGenerationStatsData } from "#shared/types/openai";
|
||||
import { getGenerationStats } from "~~/server/utils";
|
||||
import {
|
||||
createApiLogger,
|
||||
createSuccessResponse,
|
||||
createUpstreamErrorResponse,
|
||||
getGenerationStats,
|
||||
toSafeLogError
|
||||
} from "~~/server/utils";
|
||||
|
||||
export default defineEventHandler(async () => {
|
||||
const logger = createApiLogger("images.stats");
|
||||
logger.info("开始");
|
||||
|
||||
try {
|
||||
const result = await getGenerationStats();
|
||||
|
||||
logger.done("成功", {
|
||||
totalRequests: result.totalRequests,
|
||||
successRequests: result.successRequests,
|
||||
failedRequests: result.failedRequests,
|
||||
runningRequests: result.runningRequests,
|
||||
totalImages: result.totalImages
|
||||
});
|
||||
|
||||
return createSuccessResponse<IImageGenerationStatsData>(
|
||||
result,
|
||||
"获取生图统计成功"
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error("失败", {
|
||||
error: toSafeLogError(error)
|
||||
});
|
||||
return createUpstreamErrorResponse(error, "获取生图统计失败");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
export interface IDownloadedImage {
|
||||
/** 图片 base64 原文,不包含 data URL 前缀 */
|
||||
base64: string;
|
||||
/** 图片 MIME 类型 */
|
||||
mimeType: string;
|
||||
}
|
||||
|
||||
/** 下载远程图片并转成 base64,用于生图结果归档 */
|
||||
export const downloadImageAsBase64 = async (
|
||||
imageUrl: string
|
||||
): Promise<IDownloadedImage> => {
|
||||
const response = await fetch(imageUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`图片下载失败:${response.status}`);
|
||||
}
|
||||
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
|
||||
return {
|
||||
base64: Buffer.from(arrayBuffer).toString("base64"),
|
||||
mimeType: response.headers.get("content-type") || "image/png"
|
||||
};
|
||||
};
|
||||
@@ -14,17 +14,19 @@ const DEFAULT_IMAGE_MODEL = "gpt-image-2";
|
||||
const DEFAULT_IMAGE_SIZE = "1024x1024";
|
||||
|
||||
interface IFinishImageGenerationSuccessInput {
|
||||
/** 生成图片 URL */
|
||||
/** NewAPI 上游返回的生成图片 URL */
|
||||
imageUrl: string;
|
||||
/** 生成图片 base64 原文 */
|
||||
imageBase64: string | null;
|
||||
/** 图片 MIME 类型 */
|
||||
/** Lsky 图床归档后的图片 URL,归档失败时为空 */
|
||||
hostedImageUrl: string | null;
|
||||
/** 图片 MIME 类型,优先来自图床上传结果 */
|
||||
imageMimeType: string | null;
|
||||
/** 上游返回的修订提示词 */
|
||||
/** 上游返回的修订提示词,流式生图通常为空 */
|
||||
revisedPrompt?: string | null;
|
||||
/** 完整上游响应 */
|
||||
/** 完整上游响应,当前为 chat completions 流式聚合对象 */
|
||||
upstreamResponse: unknown;
|
||||
/** 成功状态下的非阻断提示,例如 base64 保存失败 */
|
||||
/** 完整 Lsky 上传响应,归档失败时为空 */
|
||||
hostedResponse: unknown;
|
||||
/** 成功状态下的非阻断提示,例如图床归档失败 */
|
||||
errorMessage?: string | null;
|
||||
}
|
||||
|
||||
@@ -65,6 +67,23 @@ export const ensureUserRecord = (userId: number) => {
|
||||
});
|
||||
};
|
||||
|
||||
/** 读取用于 Lsky 文件命名的用户标识,缺失时由调用方使用兜底名 */
|
||||
export const getUserArchiveIdentity = async (userId: number) => {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: userId
|
||||
},
|
||||
select: {
|
||||
username: true,
|
||||
displayName: true
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
username: user?.username || user?.displayName || "user"
|
||||
};
|
||||
};
|
||||
|
||||
/** 创建进行中的生图记录,并递增全局请求与进行中统计 */
|
||||
export const createRunningImageGeneration = async (
|
||||
userId: number,
|
||||
@@ -94,56 +113,34 @@ export const createRunningImageGeneration = async (
|
||||
return record;
|
||||
};
|
||||
|
||||
/** 将生图记录标记为成功,并保存 URL、base64、完整上游响应和耗时 */
|
||||
/** 将生图记录标记为成功,并保存上游 URL、图床 URL、完整响应和耗时 */
|
||||
export const finishImageGenerationSuccess = async (
|
||||
recordId: bigint,
|
||||
startedAt: Date,
|
||||
input: IFinishImageGenerationSuccessInput
|
||||
) => {
|
||||
const endedAt = new Date();
|
||||
const successData = {
|
||||
status: ImageGenerationStatus.SUCCEEDED,
|
||||
endedAt,
|
||||
durationMs: getDurationMs(startedAt, endedAt),
|
||||
imageUrl: input.imageUrl,
|
||||
imageBase64: input.imageBase64,
|
||||
imageMimeType: input.imageMimeType,
|
||||
revisedPrompt: input.revisedPrompt || null,
|
||||
upstreamResponse: input.upstreamResponse as Prisma.InputJsonValue,
|
||||
errorMessage: input.errorMessage || null
|
||||
};
|
||||
|
||||
try {
|
||||
await prisma.imageGeneration.update({
|
||||
where: {
|
||||
id: recordId
|
||||
},
|
||||
data: successData
|
||||
});
|
||||
} catch (error) {
|
||||
if (!input.imageBase64) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
consola.error("[imageGenerationRecords] 保存带 base64 的成功记录失败,重试仅保存 URL", {
|
||||
recordId: recordId.toString(),
|
||||
message: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
|
||||
await prisma.imageGeneration.update({
|
||||
where: {
|
||||
id: recordId
|
||||
},
|
||||
data: {
|
||||
...successData,
|
||||
imageBase64: null,
|
||||
errorMessage: mergeRecordMessages(
|
||||
input.errorMessage,
|
||||
"图片生成成功,但 base64 归档保存失败"
|
||||
)
|
||||
status: ImageGenerationStatus.SUCCEEDED,
|
||||
endedAt,
|
||||
durationMs: getDurationMs(startedAt, endedAt),
|
||||
imageUrl: input.imageUrl,
|
||||
hostedImageUrl: input.hostedImageUrl,
|
||||
imageMimeType: input.imageMimeType,
|
||||
revisedPrompt: input.revisedPrompt || null,
|
||||
upstreamResponse: input.upstreamResponse as Prisma.InputJsonValue,
|
||||
hostedResponse:
|
||||
input.hostedResponse === null
|
||||
? Prisma.DbNull
|
||||
: (input.hostedResponse as Prisma.InputJsonValue),
|
||||
errorMessage: input.errorMessage || null
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
await safeUpsertGenerationStats({
|
||||
successRequests: {
|
||||
@@ -188,7 +185,7 @@ export const finishImageGenerationFailed = async (
|
||||
});
|
||||
};
|
||||
|
||||
/** 查询当前用户未删除的生图历史列表,不返回 base64 和完整上游响应 */
|
||||
/** 查询当前用户未删除的生图历史列表,不返回完整上游/图床响应 */
|
||||
export const listImageGenerationHistory = async ({
|
||||
userId,
|
||||
page,
|
||||
@@ -223,7 +220,7 @@ export const listImageGenerationHistory = async ({
|
||||
};
|
||||
};
|
||||
|
||||
/** 查询当前用户单条生图历史详情 */
|
||||
/** 查询当前用户单条生图历史详情,包含完整上游与图床响应 */
|
||||
export const getImageGenerationDetail = async (
|
||||
userId: number,
|
||||
recordId: bigint
|
||||
@@ -240,9 +237,9 @@ export const getImageGenerationDetail = async (
|
||||
|
||||
return {
|
||||
...mapImageGenerationItem(record),
|
||||
imageBase64: record.imageBase64,
|
||||
imageMimeType: record.imageMimeType,
|
||||
upstreamResponse: record.upstreamResponse
|
||||
upstreamResponse: record.upstreamResponse,
|
||||
hostedResponse: record.hostedResponse
|
||||
};
|
||||
};
|
||||
|
||||
@@ -345,6 +342,7 @@ const mapImageGenerationItem = (record: {
|
||||
endedAt: Date | null;
|
||||
durationMs: number | null;
|
||||
imageUrl: string | null;
|
||||
hostedImageUrl: string | null;
|
||||
revisedPrompt: string | null;
|
||||
errorMessage: string | null;
|
||||
createdAt: Date;
|
||||
@@ -360,6 +358,7 @@ const mapImageGenerationItem = (record: {
|
||||
endedAt: record.endedAt?.toISOString() ?? null,
|
||||
durationMs: record.durationMs,
|
||||
imageUrl: record.imageUrl,
|
||||
hostedImageUrl: record.hostedImageUrl,
|
||||
revisedPrompt: record.revisedPrompt,
|
||||
errorMessage: record.errorMessage,
|
||||
createdAt: record.createdAt.toISOString()
|
||||
@@ -370,13 +369,6 @@ const getDurationMs = (startedAt: Date, endedAt: Date) => {
|
||||
return Math.max(0, endedAt.getTime() - startedAt.getTime());
|
||||
};
|
||||
|
||||
const mergeRecordMessages = (
|
||||
currentMessage: string | null | undefined,
|
||||
nextMessage: string
|
||||
) => {
|
||||
return currentMessage ? `${currentMessage}; ${nextMessage}` : nextMessage;
|
||||
};
|
||||
|
||||
const getSafeErrorMessage = (error: unknown): string => {
|
||||
if (error instanceof Error) return error.message;
|
||||
if (typeof error === "string") return error;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
export * from "./createApiResponse";
|
||||
export * from "./fetch";
|
||||
export * from "./imageAssets";
|
||||
export * from "./imageGenerationRecords";
|
||||
export * from "./logging";
|
||||
export * from "./lsky";
|
||||
export * from "./newApiAuthCookies";
|
||||
export * from "./newApiTokens";
|
||||
export * from "./openai";
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { consola } from "consola";
|
||||
|
||||
type LogMeta = Record<string, unknown>;
|
||||
|
||||
export const createApiLogger = (scope: string) => {
|
||||
const requestId = randomUUID();
|
||||
const startedAt = Date.now();
|
||||
const prefix = `[${scope}]`;
|
||||
|
||||
const withBaseMeta = (meta?: LogMeta) => ({
|
||||
requestId,
|
||||
...(meta ?? {})
|
||||
});
|
||||
|
||||
return {
|
||||
requestId,
|
||||
info(message: string, meta?: LogMeta) {
|
||||
consola.info(`${prefix} ${message}`, withBaseMeta(meta));
|
||||
},
|
||||
warn(message: string, meta?: LogMeta) {
|
||||
consola.warn(`${prefix} ${message}`, withBaseMeta(meta));
|
||||
},
|
||||
error(message: string, meta?: LogMeta) {
|
||||
consola.error(`${prefix} ${message}`, withBaseMeta(meta));
|
||||
},
|
||||
done(message: string = "完成", meta?: LogMeta) {
|
||||
consola.info(
|
||||
`${prefix} ${message}`,
|
||||
withBaseMeta({
|
||||
...(meta ?? {}),
|
||||
elapsedMs: Date.now() - startedAt
|
||||
})
|
||||
);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export const toSafeLogError = (error: unknown) => {
|
||||
const maybeError = error as {
|
||||
message?: string;
|
||||
name?: string;
|
||||
response?: {
|
||||
status?: number;
|
||||
};
|
||||
stack?: string;
|
||||
status?: number;
|
||||
statusCode?: number;
|
||||
statusMessage?: string;
|
||||
};
|
||||
|
||||
return {
|
||||
name: maybeError.name,
|
||||
message: maybeError.message ?? maybeError.statusMessage,
|
||||
status:
|
||||
maybeError.status ?? maybeError.statusCode ?? maybeError.response?.status,
|
||||
stack: maybeError.stack
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,179 @@
|
||||
import { createError } from "h3";
|
||||
|
||||
interface ILskyUploadInput {
|
||||
imageUrl: string;
|
||||
userId: number;
|
||||
username?: string | null;
|
||||
recordId: bigint;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
interface ILskyUploadResponse {
|
||||
status?: string | boolean;
|
||||
message?: string;
|
||||
data?: {
|
||||
public_url?: string;
|
||||
filename?: string;
|
||||
mimetype?: string;
|
||||
extension?: string;
|
||||
[key: string]: unknown;
|
||||
} | null;
|
||||
time?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ILskyUploadedImage {
|
||||
publicUrl: string;
|
||||
filename: string;
|
||||
mimetype: string;
|
||||
response: ILskyUploadResponse;
|
||||
}
|
||||
|
||||
export const uploadImageFromUrl = async (
|
||||
input: ILskyUploadInput
|
||||
): Promise<ILskyUploadedImage> => {
|
||||
const config = getLskyConfig();
|
||||
const downloadedImage = await downloadImage(input.imageUrl);
|
||||
const extension = getImageExtension(downloadedImage.mimeType, input.imageUrl);
|
||||
const filename = buildArchiveFilename({
|
||||
userId: input.userId,
|
||||
username: input.username,
|
||||
recordId: input.recordId,
|
||||
createdAt: input.createdAt,
|
||||
extension
|
||||
});
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append(
|
||||
"file",
|
||||
new Blob([downloadedImage.bytes], {
|
||||
type: downloadedImage.mimeType
|
||||
}),
|
||||
filename
|
||||
);
|
||||
formData.append("storage_id", String(config.storageId));
|
||||
formData.append("is_remove_exif", "true");
|
||||
formData.append("intro", `AIArtStudio image generation ${input.recordId}`);
|
||||
|
||||
for (const tag of buildArchiveTags(input.userId, input.recordId)) {
|
||||
formData.append("tags[]", tag);
|
||||
}
|
||||
|
||||
const response = await $fetch<ILskyUploadResponse>("/upload", {
|
||||
baseURL: config.baseUrl,
|
||||
method: "POST",
|
||||
body: formData,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${config.token}`
|
||||
}
|
||||
});
|
||||
|
||||
const publicUrl = response.data?.public_url;
|
||||
if (!isSuccessStatus(response.status) || !publicUrl) {
|
||||
throw createError({
|
||||
statusCode: 502,
|
||||
statusMessage: response.message || "图床上传失败"
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
publicUrl,
|
||||
filename: response.data?.filename || filename,
|
||||
mimetype: response.data?.mimetype || downloadedImage.mimeType,
|
||||
response
|
||||
};
|
||||
};
|
||||
|
||||
const getLskyConfig = () => {
|
||||
const baseUrl = process.env.LSKY_BASE_URL?.replace(/\/+$/, "");
|
||||
const token = process.env.LSKY_TOKEN;
|
||||
const storageId = Number.parseInt(process.env.LSKY_STORAGE_ID ?? "", 10);
|
||||
|
||||
if (!baseUrl) {
|
||||
throw new Error("LSKY_BASE_URL 未配置");
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
throw new Error("LSKY_TOKEN 未配置");
|
||||
}
|
||||
|
||||
if (!Number.isInteger(storageId) || storageId <= 0) {
|
||||
throw new Error("LSKY_STORAGE_ID 未配置或不是有效数字");
|
||||
}
|
||||
|
||||
return {
|
||||
baseUrl,
|
||||
token,
|
||||
storageId
|
||||
};
|
||||
};
|
||||
|
||||
const downloadImage = async (imageUrl: string) => {
|
||||
const response = await fetch(imageUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`图片下载失败:${response.status}`);
|
||||
}
|
||||
|
||||
return {
|
||||
bytes: await response.arrayBuffer(),
|
||||
mimeType: response.headers.get("content-type") || "image/png"
|
||||
};
|
||||
};
|
||||
|
||||
const buildArchiveFilename = ({
|
||||
userId,
|
||||
username,
|
||||
recordId,
|
||||
createdAt,
|
||||
extension
|
||||
}: {
|
||||
userId: number;
|
||||
username?: string | null;
|
||||
recordId: bigint;
|
||||
createdAt: Date;
|
||||
extension: string;
|
||||
}) => {
|
||||
const safeUsername = sanitizeFilenamePart(username || "user");
|
||||
const timestamp = formatTimestamp(createdAt);
|
||||
return `${userId}_${safeUsername}_${timestamp}_${recordId.toString()}.${extension}`;
|
||||
};
|
||||
|
||||
const buildArchiveTags = (userId: number, recordId: bigint) => {
|
||||
return [
|
||||
"AIArtStudio",
|
||||
`user:${userId}`,
|
||||
`record:${recordId.toString()}`,
|
||||
"model:gpt-image-2"
|
||||
];
|
||||
};
|
||||
|
||||
const sanitizeFilenamePart = (value: string) => {
|
||||
const sanitized = value
|
||||
.trim()
|
||||
.replace(/[^\p{L}\p{N}_-]+/gu, "_")
|
||||
.replace(/_+/g, "_")
|
||||
.replace(/^_+|_+$/g, "");
|
||||
|
||||
return sanitized || "user";
|
||||
};
|
||||
|
||||
const formatTimestamp = (date: Date) => {
|
||||
return date.toISOString().replace(/\D/g, "").slice(0, 14);
|
||||
};
|
||||
|
||||
const getImageExtension = (mimeType: string, imageUrl: string) => {
|
||||
const fromMimeType = mimeType.split(";")[0]?.trim().toLowerCase();
|
||||
if (fromMimeType === "image/jpeg") return "jpg";
|
||||
if (fromMimeType === "image/png") return "png";
|
||||
if (fromMimeType === "image/webp") return "webp";
|
||||
if (fromMimeType === "image/gif") return "gif";
|
||||
|
||||
const pathname = new URL(imageUrl).pathname;
|
||||
const extension = pathname.split(".").pop()?.toLowerCase();
|
||||
return extension && /^[a-z0-9]+$/.test(extension) ? extension : "png";
|
||||
};
|
||||
|
||||
const isSuccessStatus = (status: unknown) => {
|
||||
return status === true || status === "success" || status === "ok";
|
||||
};
|
||||
+186
-26
@@ -2,27 +2,47 @@
|
||||
import OpenAI from "openai";
|
||||
import type { BaseOptions, IImageGenerateData } from "#shared/types/openai";
|
||||
|
||||
const IMAGE_GENERATION_URL = "https://api.qflink.xyz/v1/images/generations";
|
||||
/** 图像生成改走 Chat Completions 流式接口,通常能更快拿到中转平台返回的图片地址 */
|
||||
const CHAT_COMPLETIONS_URL = "https://api.qflink.xyz/v1/chat/completions";
|
||||
const IMAGE_GENERATION_MODEL = "gpt-image-2";
|
||||
const IMAGE_GENERATION_SIZE = "1024x1024";
|
||||
|
||||
interface IImageGenerationResponse {
|
||||
/** 上游创建时间 */
|
||||
/** Chat Completions SSE 每个 data chunk 的最小结构 */
|
||||
interface IChatCompletionStreamChunk {
|
||||
id?: string;
|
||||
object?: string;
|
||||
created?: number;
|
||||
/** 上游图片生成结果列表 */
|
||||
data?: Array<{
|
||||
/** 上游返回的修订提示词,可能为空 */
|
||||
revised_prompt?: string;
|
||||
/** 生成图片地址 */
|
||||
url?: string;
|
||||
model?: string;
|
||||
metadata?: unknown;
|
||||
choices?: Array<{
|
||||
delta?: {
|
||||
content?: string;
|
||||
role?: string;
|
||||
};
|
||||
finish_reason?: string | null;
|
||||
index?: number;
|
||||
}>;
|
||||
usage?: unknown;
|
||||
}
|
||||
|
||||
/** 聚合后的流式生图上游响应,供服务端入库排查使用,不包含 API Key */
|
||||
interface IImageStreamUpstreamResponse {
|
||||
content: string;
|
||||
imageUrl?: string;
|
||||
chunks: Array<{
|
||||
id?: string;
|
||||
created?: number;
|
||||
model?: string;
|
||||
content?: string;
|
||||
finishReason?: string | null;
|
||||
metadata?: unknown;
|
||||
hasUsage: boolean;
|
||||
}>;
|
||||
/** 上游 token 用量 */
|
||||
usage?: unknown;
|
||||
}
|
||||
|
||||
export interface IAskImageResult extends IImageGenerateData {
|
||||
/** 完整上游生图接口返回结果,仅服务端内部保存 */
|
||||
upstreamResponse: IImageGenerationResponse;
|
||||
upstreamResponse: unknown;
|
||||
}
|
||||
|
||||
/** 通用 AI 调用函数(支持文本 / 图文 / 多模态) */
|
||||
@@ -66,7 +86,6 @@ export const askText = async (
|
||||
* | low | 低分辨率(更快、更省成本) |
|
||||
* | high | 高分辨率(更精准) |
|
||||
* | auto | 自动选择 |
|
||||
*
|
||||
*/
|
||||
export const askVision = async (
|
||||
options: BaseOptions & {
|
||||
@@ -107,40 +126,77 @@ export const askVision = async (
|
||||
return res.output_text;
|
||||
};
|
||||
|
||||
/** 调用图片生成接口,完整 API Key 只在服务端使用 */
|
||||
export const askImg = async ({
|
||||
/** 调用流式图片生成接口,完整 API Key 只在服务端使用 */
|
||||
export const askImgStream = async ({
|
||||
apiKey,
|
||||
prompt
|
||||
}: {
|
||||
apiKey: string;
|
||||
prompt: string;
|
||||
}): Promise<IAskImageResult> => {
|
||||
const result = await $fetch<IImageGenerationResponse>(IMAGE_GENERATION_URL, {
|
||||
const response = await fetch(CHAT_COMPLETIONS_URL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: {
|
||||
body: JSON.stringify({
|
||||
model: IMAGE_GENERATION_MODEL,
|
||||
prompt,
|
||||
size: IMAGE_GENERATION_SIZE
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: prompt
|
||||
}
|
||||
]
|
||||
})
|
||||
});
|
||||
|
||||
const image = result.data?.[0];
|
||||
if (!image?.url) {
|
||||
throw new Error("图片生成失败");
|
||||
if (!response.ok) {
|
||||
const message = await response.text().catch(() => "");
|
||||
throw new Error(message || `图片生成失败:${response.status}`);
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error("图片生成失败:上游没有返回流");
|
||||
}
|
||||
|
||||
const upstreamResponse = await readChatCompletionStream(response.body);
|
||||
const imageUrl = extractImageUrlFromStreamText(upstreamResponse.content);
|
||||
|
||||
return {
|
||||
imageUrl: image.url,
|
||||
revisedPrompt: image.revised_prompt,
|
||||
upstreamResponse: result
|
||||
imageUrl,
|
||||
revisedPrompt: undefined,
|
||||
upstreamResponse: {
|
||||
...upstreamResponse,
|
||||
imageUrl
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/** 调用流式接口 */
|
||||
/** 从流式累积文本中提取图片地址,兼容 Markdown 图片、常见图片 URL 和无扩展下载链接 */
|
||||
export const extractImageUrlFromStreamText = (text: string): string => {
|
||||
const markdownImageMatch = text.match(/!\[[^\]]*]\((https?:\/\/[^)\s]+)\)/i);
|
||||
if (markdownImageMatch?.[1]) {
|
||||
return cleanupImageUrl(markdownImageMatch[1]);
|
||||
}
|
||||
|
||||
const imageUrlMatch = text.match(
|
||||
/https?:\/\/[^\s)>'"]+(?:\.(?:png|jpe?g|webp|gif)(?:\?[^\s)>'"]*)?|\/file_download\/[^\s)>'"]+)/i
|
||||
);
|
||||
if (imageUrlMatch?.[0]) {
|
||||
return cleanupImageUrl(imageUrlMatch[0]);
|
||||
}
|
||||
|
||||
const urlMatch = text.match(/https?:\/\/[^\s)>'"]+/i);
|
||||
if (urlMatch?.[0]) {
|
||||
return cleanupImageUrl(urlMatch[0]);
|
||||
}
|
||||
|
||||
throw new Error("图片生成失败:未找到图片地址");
|
||||
};
|
||||
|
||||
/** 调用 Responses API 流式接口,保留给其他文本/多模态场景复用 */
|
||||
export const askStream = async (
|
||||
options: BaseOptions & {
|
||||
input: OpenAI.Responses.ResponseCreateParams["input"];
|
||||
@@ -158,3 +214,107 @@ export const askStream = async (
|
||||
|
||||
return stream;
|
||||
};
|
||||
|
||||
/** 读取 Chat Completions SSE 流,累积 delta.content 并提取 usage/chunk 元信息 */
|
||||
const readChatCompletionStream = async (
|
||||
stream: ReadableStream<Uint8Array>
|
||||
): Promise<IImageStreamUpstreamResponse> => {
|
||||
const reader = stream.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
const chunks: IImageStreamUpstreamResponse["chunks"] = [];
|
||||
let buffer = "";
|
||||
let content = "";
|
||||
let usage: unknown;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split(/\r?\n/);
|
||||
buffer = lines.pop() ?? "";
|
||||
|
||||
for (const line of lines) {
|
||||
const chunk = parseSseDataLine(line);
|
||||
if (!chunk) continue;
|
||||
|
||||
const deltaContent = collectDeltaContent(chunk);
|
||||
if (deltaContent) {
|
||||
content += deltaContent;
|
||||
}
|
||||
|
||||
if (chunk.usage) {
|
||||
usage = chunk.usage;
|
||||
}
|
||||
|
||||
chunks.push({
|
||||
id: chunk.id,
|
||||
created: chunk.created,
|
||||
model: chunk.model,
|
||||
content: deltaContent || undefined,
|
||||
finishReason: chunk.choices?.find((choice) => choice.finish_reason)
|
||||
?.finish_reason,
|
||||
metadata: chunk.metadata,
|
||||
hasUsage: Boolean(chunk.usage)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const finalText = buffer + decoder.decode();
|
||||
for (const line of finalText.split(/\r?\n/)) {
|
||||
const chunk = parseSseDataLine(line);
|
||||
if (!chunk) continue;
|
||||
|
||||
const deltaContent = collectDeltaContent(chunk);
|
||||
if (deltaContent) {
|
||||
content += deltaContent;
|
||||
}
|
||||
|
||||
if (chunk.usage) {
|
||||
usage = chunk.usage;
|
||||
}
|
||||
|
||||
chunks.push({
|
||||
id: chunk.id,
|
||||
created: chunk.created,
|
||||
model: chunk.model,
|
||||
content: deltaContent || undefined,
|
||||
finishReason: chunk.choices?.find((choice) => choice.finish_reason)
|
||||
?.finish_reason,
|
||||
metadata: chunk.metadata,
|
||||
hasUsage: Boolean(chunk.usage)
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
content,
|
||||
chunks,
|
||||
usage
|
||||
};
|
||||
};
|
||||
|
||||
/** 解析单行 SSE data,跳过空行和 [DONE] */
|
||||
const parseSseDataLine = (line: string): IChatCompletionStreamChunk | null => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed.startsWith("data:")) return null;
|
||||
|
||||
const data = trimmed.slice("data:".length).trim();
|
||||
if (!data || data === "[DONE]") return null;
|
||||
|
||||
return JSON.parse(data) as IChatCompletionStreamChunk;
|
||||
};
|
||||
|
||||
/** 收集一个 chunk 中所有 choice 的 delta.content */
|
||||
const collectDeltaContent = (chunk: IChatCompletionStreamChunk) => {
|
||||
return (
|
||||
chunk.choices
|
||||
?.map((choice) => choice.delta?.content || "")
|
||||
.filter(Boolean)
|
||||
.join("") || ""
|
||||
);
|
||||
};
|
||||
|
||||
/** 清理模型文本里 URL 后面可能粘上的句末标点 */
|
||||
const cleanupImageUrl = (url: string) => {
|
||||
return url.replace(/[,.!?,。!?]+$/u, "");
|
||||
};
|
||||
|
||||
+9
-15
@@ -3,7 +3,6 @@ import { PrismaClient } from "~~/app/generated/prisma/client";
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma?: PrismaClient;
|
||||
prismaLogged?: boolean;
|
||||
};
|
||||
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
@@ -12,7 +11,10 @@ if (!databaseUrl) {
|
||||
throw new Error("DATABASE_URL is required to initialize PrismaClient");
|
||||
}
|
||||
|
||||
type MariaDbPoolConfig = Exclude<ConstructorParameters<typeof PrismaMariaDb>[0], string>;
|
||||
type MariaDbPoolConfig = Exclude<
|
||||
ConstructorParameters<typeof PrismaMariaDb>[0],
|
||||
string
|
||||
>;
|
||||
|
||||
function getNumberParam(url: URL, name: string, fallback: number) {
|
||||
const value = url.searchParams.get(name);
|
||||
@@ -46,29 +48,21 @@ function createMariaDbConfig(urlString: string): MariaDbPoolConfig {
|
||||
database,
|
||||
connectionLimit: getNumberParam(url, "connection_limit", 5),
|
||||
acquireTimeout: getNumberParam(url, "pool_timeout", 30) * 1000,
|
||||
connectTimeout: getNumberParam(url, "connect_timeout", 10) * 1000,
|
||||
connectTimeout: getNumberParam(url, "connect_timeout", 10) * 1000
|
||||
};
|
||||
}
|
||||
|
||||
const mariaDbConfig = createMariaDbConfig(databaseUrl);
|
||||
const adapter = new PrismaMariaDb(mariaDbConfig, { database: mariaDbConfig.database });
|
||||
|
||||
if (!globalForPrisma.prismaLogged) {
|
||||
console.info("[prisma] initializing MariaDB pool", {
|
||||
host: mariaDbConfig.host,
|
||||
port: mariaDbConfig.port,
|
||||
database: mariaDbConfig.database,
|
||||
connectionLimit: mariaDbConfig.connectionLimit,
|
||||
});
|
||||
globalForPrisma.prismaLogged = true;
|
||||
}
|
||||
const adapter = new PrismaMariaDb(mariaDbConfig, {
|
||||
database: mariaDbConfig.database
|
||||
});
|
||||
|
||||
/** Reuse PrismaClient during dev hot reloads so Nuxt does not create duplicate pools. */
|
||||
export const prisma =
|
||||
globalForPrisma.prisma ??
|
||||
new PrismaClient({
|
||||
adapter,
|
||||
log: ["warn", "error"],
|
||||
log: ["warn", "error"]
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
|
||||
@@ -19,8 +19,10 @@ export interface IImageGenerateRequest {
|
||||
* 图片生成成功后返回给前端的数据。
|
||||
*/
|
||||
export interface IImageGenerateData {
|
||||
/** 生成图片的访问地址 */
|
||||
/** NewAPI 上游返回的图片访问地址,前端当前优先展示这个地址 */
|
||||
imageUrl: string;
|
||||
/** Lsky 图床归档后的图片访问地址,归档失败时为空 */
|
||||
hostedImageUrl?: string | null;
|
||||
/** 上游返回的修订提示词,可能为空 */
|
||||
revisedPrompt?: string;
|
||||
}
|
||||
@@ -56,11 +58,13 @@ export interface IImageHistoryItem {
|
||||
endedAt: string | null;
|
||||
/** 生图耗时,单位毫秒 */
|
||||
durationMs: number | null;
|
||||
/** 生成图片的访问地址 */
|
||||
/** NewAPI 上游返回的图片访问地址 */
|
||||
imageUrl: string | null;
|
||||
/** Lsky 图床归档后的图片访问地址 */
|
||||
hostedImageUrl: string | null;
|
||||
/** 上游返回的修订提示词,可能为空 */
|
||||
revisedPrompt: string | null;
|
||||
/** 失败原因或图片保存提示 */
|
||||
/** 失败原因或图床归档提示 */
|
||||
errorMessage: string | null;
|
||||
/** 记录创建时间,ISO 字符串 */
|
||||
createdAt: string;
|
||||
@@ -70,12 +74,12 @@ export interface IImageHistoryItem {
|
||||
* 生图历史详情。
|
||||
*/
|
||||
export interface IImageHistoryDetail extends IImageHistoryItem {
|
||||
/** 服务端保存的图片 base64 原文,可能为空 */
|
||||
imageBase64: string | null;
|
||||
/** 图片 MIME 类型,可能为空 */
|
||||
imageMimeType: string | null;
|
||||
/** 完整上游生图接口返回结果 */
|
||||
upstreamResponse: unknown;
|
||||
/** 完整 Lsky 图床上传接口返回结果 */
|
||||
hostedResponse: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user