@@ -145,7 +145,8 @@ const runImageArchiveTask = (
|
||||
|
||||
consola.info("[imageArchiveQueue] 归档开始", {
|
||||
workerId: workerState.workerId,
|
||||
recordId: task.id.toString(),
|
||||
recordId: task.recordId.toString(),
|
||||
imageId: task.imageId.toString(),
|
||||
attempt: task.archiveAttempts
|
||||
});
|
||||
|
||||
@@ -156,12 +157,13 @@ const runImageArchiveTask = (
|
||||
imageUrl: task.imageUrl,
|
||||
userId: task.userId,
|
||||
username: identity.username,
|
||||
recordId: task.id,
|
||||
createdAt: task.startedAt
|
||||
recordId: task.recordId,
|
||||
imageId: task.imageId,
|
||||
createdAt: task.createdAt
|
||||
});
|
||||
|
||||
// 成功后补写 hosted 字段;前端仍通过历史接口读取归档结果,不暴露图床完整响应。
|
||||
await finishImageGenerationArchiveSuccess(task.id, {
|
||||
await finishImageGenerationArchiveSuccess(task.imageId, {
|
||||
hostedImageUrl: uploaded.publicUrl,
|
||||
imageMimeType: uploaded.mimetype,
|
||||
hostedResponse: uploaded.response
|
||||
@@ -169,7 +171,8 @@ const runImageArchiveTask = (
|
||||
|
||||
consola.info("[imageArchiveQueue] 归档成功", {
|
||||
workerId: workerState.workerId,
|
||||
recordId: task.id.toString(),
|
||||
recordId: task.recordId.toString(),
|
||||
imageId: task.imageId.toString(),
|
||||
mimeType: uploaded.mimetype,
|
||||
byteLength: uploaded.byteLength,
|
||||
elapsedMs: Date.now() - startedAt
|
||||
@@ -197,7 +200,8 @@ const handleImageArchiveFailure = async (
|
||||
// 归档日志只保留排查摘要,不记录 token、图片二进制、完整图床响应或完整上游响应。
|
||||
consola.error("[imageArchiveQueue] 归档失败", {
|
||||
workerId: workerState.workerId,
|
||||
recordId: task.id.toString(),
|
||||
recordId: task.recordId.toString(),
|
||||
imageId: task.imageId.toString(),
|
||||
attempt: task.archiveAttempts,
|
||||
terminal: shouldStop,
|
||||
error: safeError
|
||||
@@ -205,13 +209,13 @@ const handleImageArchiveFailure = async (
|
||||
|
||||
if (shouldStop) {
|
||||
// 最终失败只影响归档字段,生图状态保持 SUCCEEDED,前端看到的是本地化“图片归档失败”。
|
||||
await finishImageGenerationArchiveFailed(task.id, errorMessage);
|
||||
await finishImageGenerationArchiveFailed(task.imageId, errorMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
// 可重试失败会清掉本次锁并设置下一次执行时间,期间历史记录仍表现为归档中。
|
||||
await scheduleImageGenerationArchiveRetry({
|
||||
recordId: task.id,
|
||||
imageId: task.imageId,
|
||||
nextRunAt: new Date(Date.now() + getRetryDelayMs(task.archiveAttempts)),
|
||||
errorMessage
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// server/utils/imageGenerationRecords.ts - 生图相关数据库操作:用户快照、生成记录、历史查询和统计。
|
||||
// server/utils/imageGenerationRecords.ts - 生图相关数据库操作:用户快照、批次记录、图片子记录、历史查询和统计。
|
||||
import type { IUserBasicData } from "#shared/types";
|
||||
import type {
|
||||
IImageGenerationStatsData,
|
||||
IImageHistoryDetail,
|
||||
IImageHistoryImageItem,
|
||||
IImageHistoryItem,
|
||||
IImageHistoryListData
|
||||
} from "#shared/types/openai";
|
||||
@@ -18,16 +19,16 @@ import { prisma } from "~~/server/utils/prisma";
|
||||
const GLOBAL_STATS_ID = "global";
|
||||
const DEFAULT_IMAGE_MODEL = "gpt-image-2";
|
||||
|
||||
interface IFinishImageGenerationSuccessInput {
|
||||
interface IFinishImageGenerationImageSuccessInput {
|
||||
/** NewAPI 上游返回的生成图片 URL */
|
||||
imageUrl: string;
|
||||
/** 上游返回的修订提示词,流式生图通常为空 */
|
||||
revisedPrompt?: string | null;
|
||||
/** 完整上游响应,当前为 chat completions 流式聚合对象 */
|
||||
/** 完整上游响应,仅服务端内部保存 */
|
||||
upstreamResponse: unknown;
|
||||
}
|
||||
|
||||
interface IFinishImageGenerationArchiveSuccessInput {
|
||||
interface IFinishImageGenerationImageArchiveSuccessInput {
|
||||
/** Lsky 图床归档后的图片 URL */
|
||||
hostedImageUrl: string;
|
||||
/** 图片 MIME 类型,优先来自图床上传结果 */
|
||||
@@ -37,14 +38,16 @@ interface IFinishImageGenerationArchiveSuccessInput {
|
||||
}
|
||||
|
||||
export interface IImageArchiveTask {
|
||||
/** 生图记录 ID */
|
||||
id: bigint;
|
||||
/** 生图图片子记录 ID */
|
||||
imageId: bigint;
|
||||
/** 所属生图批次记录 ID */
|
||||
recordId: bigint;
|
||||
/** NewAPI 用户 ID */
|
||||
userId: number;
|
||||
/** 上游生成图片 URL */
|
||||
imageUrl: string;
|
||||
/** 记录创建时间,用于构造图床文件名 */
|
||||
startedAt: Date;
|
||||
/** 图片子记录创建时间,用于构造图床文件名 */
|
||||
createdAt: Date;
|
||||
/** 当前这次归档是第几次尝试 */
|
||||
archiveAttempts: number;
|
||||
}
|
||||
@@ -103,10 +106,11 @@ export const getUserArchiveIdentity = async (userId: number) => {
|
||||
};
|
||||
};
|
||||
|
||||
/** 创建进行中的生图记录,并递增全局请求与进行中统计 */
|
||||
/** 创建进行中的生图批次和图片子记录,并递增全局请求/进行中统计 */
|
||||
export const createRunningImageGeneration = async (
|
||||
userId: number,
|
||||
prompt: string
|
||||
prompt: string,
|
||||
batchSize: number
|
||||
) => {
|
||||
await ensureUserRecord(userId);
|
||||
|
||||
@@ -115,7 +119,26 @@ export const createRunningImageGeneration = async (
|
||||
userId,
|
||||
prompt,
|
||||
status: ImageGenerationStatus.RUNNING,
|
||||
model: DEFAULT_IMAGE_MODEL
|
||||
model: DEFAULT_IMAGE_MODEL,
|
||||
batchSize,
|
||||
images: {
|
||||
create: Array.from({ length: batchSize }, (_, index) => ({
|
||||
userId,
|
||||
index,
|
||||
status: ImageGenerationStatus.RUNNING
|
||||
}))
|
||||
}
|
||||
},
|
||||
include: {
|
||||
images: {
|
||||
orderBy: {
|
||||
index: "asc"
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
index: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -131,22 +154,17 @@ export const createRunningImageGeneration = async (
|
||||
return record;
|
||||
};
|
||||
|
||||
/** 将生图记录标记为成功,并先写入上游结果;图床字段稍后由后台归档补写 */
|
||||
export const finishImageGenerationSuccess = async (
|
||||
recordId: bigint,
|
||||
startedAt: Date,
|
||||
input: IFinishImageGenerationSuccessInput
|
||||
/** 将单张图片子记录标记为成功,并先写入上游结果;图床字段稍后由后台归档补写 */
|
||||
export const finishImageGenerationImageSuccess = async (
|
||||
imageId: bigint,
|
||||
input: IFinishImageGenerationImageSuccessInput
|
||||
) => {
|
||||
const endedAt = new Date();
|
||||
|
||||
await prisma.imageGeneration.update({
|
||||
await prisma.imageGenerationImage.update({
|
||||
where: {
|
||||
id: recordId
|
||||
id: imageId
|
||||
},
|
||||
data: {
|
||||
status: ImageGenerationStatus.SUCCEEDED,
|
||||
endedAt,
|
||||
durationMs: getDurationMs(startedAt, endedAt),
|
||||
imageUrl: input.imageUrl,
|
||||
hostedImageUrl: null,
|
||||
imageMimeType: null,
|
||||
@@ -162,48 +180,115 @@ export const finishImageGenerationSuccess = async (
|
||||
archiveLastError: null
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
await safeUpsertGenerationStats({
|
||||
successRequests: {
|
||||
increment: 1
|
||||
/** 将单张图片子记录标记为失败,只保留服务端可排查摘要 */
|
||||
export const finishImageGenerationImageFailed = async (
|
||||
imageId: bigint,
|
||||
error: unknown
|
||||
) => {
|
||||
await prisma.imageGenerationImage.update({
|
||||
where: {
|
||||
id: imageId
|
||||
},
|
||||
runningRequests: {
|
||||
decrement: 1
|
||||
},
|
||||
totalImages: {
|
||||
increment: 1
|
||||
data: {
|
||||
status: ImageGenerationStatus.FAILED,
|
||||
errorMessage: getSafeErrorMessage(error),
|
||||
archiveStatus: ImageArchiveStatus.NOT_REQUIRED
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/** 将生图记录标记为失败,并保存失败原因和耗时 */
|
||||
export const finishImageGenerationFailed = async (
|
||||
recordId: bigint,
|
||||
startedAt: Date,
|
||||
error: unknown
|
||||
) => {
|
||||
/** 批次内所有图片都结束后,汇总批次状态与全局统计 */
|
||||
export const finishImageGenerationBatch = async ({
|
||||
recordId,
|
||||
startedAt,
|
||||
successCount,
|
||||
failedCount,
|
||||
error
|
||||
}: {
|
||||
recordId: bigint;
|
||||
startedAt: Date;
|
||||
successCount: number;
|
||||
failedCount: number;
|
||||
error?: unknown;
|
||||
}) => {
|
||||
const endedAt = new Date();
|
||||
const hasSuccess = successCount > 0;
|
||||
|
||||
await prisma.imageGeneration.update({
|
||||
where: {
|
||||
id: recordId
|
||||
},
|
||||
data: {
|
||||
status: ImageGenerationStatus.FAILED,
|
||||
status: hasSuccess
|
||||
? ImageGenerationStatus.SUCCEEDED
|
||||
: ImageGenerationStatus.FAILED,
|
||||
endedAt,
|
||||
durationMs: getDurationMs(startedAt, endedAt),
|
||||
errorMessage: getSafeErrorMessage(error)
|
||||
successCount,
|
||||
failedCount,
|
||||
errorMessage: hasSuccess ? null : getSafeErrorMessage(error)
|
||||
}
|
||||
});
|
||||
|
||||
await safeUpsertGenerationStats({
|
||||
failedRequests: {
|
||||
increment: 1
|
||||
},
|
||||
successRequests: hasSuccess
|
||||
? {
|
||||
increment: 1
|
||||
}
|
||||
: undefined,
|
||||
failedRequests: hasSuccess
|
||||
? undefined
|
||||
: {
|
||||
increment: 1
|
||||
},
|
||||
runningRequests: {
|
||||
decrement: 1
|
||||
},
|
||||
totalImages:
|
||||
successCount > 0
|
||||
? {
|
||||
increment: successCount
|
||||
}
|
||||
: undefined
|
||||
});
|
||||
};
|
||||
|
||||
/** 兼容旧调用:主链路异常且尚未逐图结算时,把整个批次标记为失败 */
|
||||
export const finishImageGenerationFailed = async (
|
||||
recordId: bigint,
|
||||
startedAt: Date,
|
||||
error: unknown
|
||||
) => {
|
||||
const record = await prisma.imageGeneration.findUnique({
|
||||
where: {
|
||||
id: recordId
|
||||
},
|
||||
select: {
|
||||
batchSize: true
|
||||
}
|
||||
});
|
||||
|
||||
await prisma.imageGenerationImage.updateMany({
|
||||
where: {
|
||||
imageGenerationId: recordId,
|
||||
status: ImageGenerationStatus.RUNNING
|
||||
},
|
||||
data: {
|
||||
status: ImageGenerationStatus.FAILED,
|
||||
errorMessage: getSafeErrorMessage(error),
|
||||
archiveStatus: ImageArchiveStatus.NOT_REQUIRED
|
||||
}
|
||||
});
|
||||
|
||||
await finishImageGenerationBatch({
|
||||
recordId,
|
||||
startedAt,
|
||||
successCount: 0,
|
||||
failedCount: record?.batchSize ?? 1,
|
||||
error
|
||||
});
|
||||
};
|
||||
|
||||
/** 领取可执行的图床归档任务;通过 updateMany 条件锁避免多实例重复处理 */
|
||||
@@ -221,7 +306,7 @@ export const claimRunnableImageArchiveTasks = async ({
|
||||
const now = new Date();
|
||||
const staleBefore = new Date(now.getTime() - lockTtlMs);
|
||||
const runnableWhere = buildRunnableArchiveWhere(now, staleBefore);
|
||||
const candidates = await prisma.imageGeneration.findMany({
|
||||
const candidates = await prisma.imageGenerationImage.findMany({
|
||||
where: runnableWhere,
|
||||
select: {
|
||||
id: true
|
||||
@@ -241,7 +326,7 @@ export const claimRunnableImageArchiveTasks = async ({
|
||||
for (const candidate of candidates) {
|
||||
if (tasks.length >= limit) break;
|
||||
|
||||
const claimed = await prisma.imageGeneration.updateMany({
|
||||
const claimed = await prisma.imageGenerationImage.updateMany({
|
||||
where: {
|
||||
id: candidate.id,
|
||||
...runnableWhere
|
||||
@@ -259,25 +344,27 @@ export const claimRunnableImageArchiveTasks = async ({
|
||||
|
||||
if (claimed.count !== 1) continue;
|
||||
|
||||
const task = await prisma.imageGeneration.findUnique({
|
||||
const task = await prisma.imageGenerationImage.findUnique({
|
||||
where: {
|
||||
id: candidate.id
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
imageGenerationId: true,
|
||||
userId: true,
|
||||
imageUrl: true,
|
||||
startedAt: true,
|
||||
createdAt: true,
|
||||
archiveAttempts: true
|
||||
}
|
||||
});
|
||||
|
||||
if (task?.imageUrl) {
|
||||
tasks.push({
|
||||
id: task.id,
|
||||
imageId: task.id,
|
||||
recordId: task.imageGenerationId,
|
||||
userId: task.userId,
|
||||
imageUrl: task.imageUrl,
|
||||
startedAt: task.startedAt,
|
||||
createdAt: task.createdAt,
|
||||
archiveAttempts: task.archiveAttempts
|
||||
});
|
||||
}
|
||||
@@ -288,12 +375,12 @@ export const claimRunnableImageArchiveTasks = async ({
|
||||
|
||||
/** 后台归档成功后回写图床地址、MIME 和图床响应 */
|
||||
export const finishImageGenerationArchiveSuccess = async (
|
||||
recordId: bigint,
|
||||
input: IFinishImageGenerationArchiveSuccessInput
|
||||
imageId: bigint,
|
||||
input: IFinishImageGenerationImageArchiveSuccessInput
|
||||
) => {
|
||||
await prisma.imageGeneration.update({
|
||||
await prisma.imageGenerationImage.update({
|
||||
where: {
|
||||
id: recordId
|
||||
id: imageId
|
||||
},
|
||||
data: {
|
||||
hostedImageUrl: input.hostedImageUrl,
|
||||
@@ -311,17 +398,17 @@ export const finishImageGenerationArchiveSuccess = async (
|
||||
|
||||
/** 归档可重试失败时释放任务锁并安排下一次执行,前端仍显示归档中 */
|
||||
export const scheduleImageGenerationArchiveRetry = async ({
|
||||
recordId,
|
||||
imageId,
|
||||
nextRunAt,
|
||||
errorMessage
|
||||
}: {
|
||||
recordId: bigint;
|
||||
imageId: bigint;
|
||||
nextRunAt: Date;
|
||||
errorMessage: string;
|
||||
}) => {
|
||||
await prisma.imageGeneration.update({
|
||||
await prisma.imageGenerationImage.update({
|
||||
where: {
|
||||
id: recordId
|
||||
id: imageId
|
||||
},
|
||||
data: {
|
||||
archiveStatus: ImageArchiveStatus.PENDING,
|
||||
@@ -336,12 +423,12 @@ export const scheduleImageGenerationArchiveRetry = async ({
|
||||
|
||||
/** 后台归档最终失败时仅补写本地错误文案,不影响已成功的生图状态 */
|
||||
export const finishImageGenerationArchiveFailed = async (
|
||||
recordId: bigint,
|
||||
imageId: bigint,
|
||||
errorMessage: string = "图片归档失败"
|
||||
) => {
|
||||
await prisma.imageGeneration.update({
|
||||
await prisma.imageGenerationImage.update({
|
||||
where: {
|
||||
id: recordId
|
||||
id: imageId
|
||||
},
|
||||
data: {
|
||||
archiveStatus: ImageArchiveStatus.FAILED,
|
||||
@@ -354,7 +441,7 @@ export const finishImageGenerationArchiveFailed = async (
|
||||
});
|
||||
};
|
||||
|
||||
/** 查询当前用户未删除的生图历史列表,不返回完整上游/图床响应 */
|
||||
/** 查询当前用户未删除的生图批次历史列表,不返回完整上游/图床响应 */
|
||||
export const listImageGenerationHistory = async ({
|
||||
userId,
|
||||
page,
|
||||
@@ -373,13 +460,7 @@ export const listImageGenerationHistory = async ({
|
||||
prisma.imageGeneration.count({ where }),
|
||||
prisma.imageGeneration.findMany({
|
||||
where,
|
||||
include: {
|
||||
plazaPost: {
|
||||
select: {
|
||||
status: true
|
||||
}
|
||||
}
|
||||
},
|
||||
include: historyInclude,
|
||||
orderBy: {
|
||||
createdAt: "desc"
|
||||
},
|
||||
@@ -396,7 +477,7 @@ export const listImageGenerationHistory = async ({
|
||||
};
|
||||
};
|
||||
|
||||
/** 查询当前用户单条生图历史详情,内部响应字段固定隐藏为 null */
|
||||
/** 查询当前用户单条生图批次详情,内部响应字段固定隐藏为 null */
|
||||
export const getImageGenerationDetail = async (
|
||||
userId: number,
|
||||
recordId: bigint
|
||||
@@ -407,26 +488,15 @@ export const getImageGenerationDetail = async (
|
||||
userId,
|
||||
deletedAt: null
|
||||
},
|
||||
include: {
|
||||
plazaPost: {
|
||||
select: {
|
||||
status: true
|
||||
}
|
||||
}
|
||||
}
|
||||
include: historyInclude
|
||||
});
|
||||
|
||||
if (!record) return null;
|
||||
|
||||
return {
|
||||
...mapImageGenerationItem(record),
|
||||
imageMimeType: record.imageMimeType,
|
||||
upstreamResponse: null,
|
||||
hostedResponse: null
|
||||
};
|
||||
return mapImageGenerationItem(record);
|
||||
};
|
||||
|
||||
/** 软删除当前用户单条生图历史 */
|
||||
/** 软删除当前用户单条生图批次历史 */
|
||||
export const softDeleteImageGeneration = async (
|
||||
userId: number,
|
||||
recordId: bigint
|
||||
@@ -482,8 +552,12 @@ const upsertGenerationStats = (update: Prisma.GenerationStatsUpdateInput) => {
|
||||
const safeUpsertGenerationStats = async (
|
||||
update: Prisma.GenerationStatsUpdateInput
|
||||
) => {
|
||||
const cleanUpdate = Object.fromEntries(
|
||||
Object.entries(update).filter(([, value]) => value !== undefined)
|
||||
) as Prisma.GenerationStatsUpdateInput;
|
||||
|
||||
try {
|
||||
await upsertGenerationStats(update);
|
||||
await upsertGenerationStats(cleanUpdate);
|
||||
} catch (error) {
|
||||
consola.error("[imageGenerationRecords] 更新生图统计失败", {
|
||||
message: error instanceof Error ? error.message : String(error)
|
||||
@@ -503,14 +577,16 @@ const buildStatsCreateInput = (update: Prisma.GenerationStatsUpdateInput) => {
|
||||
};
|
||||
};
|
||||
|
||||
/** 只领取成功生成、未删除、已到执行时间或锁超时的归档任务 */
|
||||
/** 只领取成功生成、所属批次未删除、已到执行时间或锁超时的归档任务 */
|
||||
const buildRunnableArchiveWhere = (now: Date, staleBefore: Date) => {
|
||||
return {
|
||||
status: ImageGenerationStatus.SUCCEEDED,
|
||||
deletedAt: null,
|
||||
imageUrl: {
|
||||
not: null
|
||||
},
|
||||
imageGeneration: {
|
||||
deletedAt: null
|
||||
},
|
||||
OR: [
|
||||
{
|
||||
archiveStatus: ImageArchiveStatus.PENDING,
|
||||
@@ -532,7 +608,7 @@ const buildRunnableArchiveWhere = (now: Date, staleBefore: Date) => {
|
||||
}
|
||||
}
|
||||
]
|
||||
} satisfies Prisma.ImageGenerationWhereInput;
|
||||
} satisfies Prisma.ImageGenerationImageWhereInput;
|
||||
};
|
||||
|
||||
/** 从 Prisma increment 操作里取出增量;非 increment 操作在创建时按 0 处理 */
|
||||
@@ -549,43 +625,97 @@ const getIncrementValue = (value: unknown): number => {
|
||||
return 0;
|
||||
};
|
||||
|
||||
/** 将 Prisma 记录转换为前端类型,BigInt/Date 在这里统一序列化 */
|
||||
const mapImageGenerationItem = (record: {
|
||||
id: bigint;
|
||||
userId: number;
|
||||
prompt: string;
|
||||
status: ImageGenerationStatus;
|
||||
model: string;
|
||||
startedAt: Date;
|
||||
endedAt: Date | null;
|
||||
durationMs: number | null;
|
||||
imageUrl: string | null;
|
||||
hostedImageUrl: string | null;
|
||||
revisedPrompt: string | null;
|
||||
errorMessage: string | null;
|
||||
createdAt: Date;
|
||||
plazaPost?: {
|
||||
status: PlazaPostStatus;
|
||||
} | null;
|
||||
}): IImageHistoryItem => {
|
||||
const historyInclude = {
|
||||
images: {
|
||||
orderBy: {
|
||||
index: "asc" as const
|
||||
}
|
||||
},
|
||||
plazaPost: {
|
||||
select: {
|
||||
status: true,
|
||||
coverImageId: true,
|
||||
images: {
|
||||
select: {
|
||||
imageGenerationImageId: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
type ImageGenerationWithHistory = Prisma.ImageGenerationGetPayload<{
|
||||
include: typeof historyInclude;
|
||||
}>;
|
||||
|
||||
/** 将 Prisma 批次记录转换为前端类型,BigInt/Date 在这里统一序列化 */
|
||||
const mapImageGenerationItem = (
|
||||
record: ImageGenerationWithHistory
|
||||
): IImageHistoryItem => {
|
||||
const images = record.images.map((image) =>
|
||||
mapImageGenerationImageItem(image, record.plazaPost)
|
||||
);
|
||||
const publicImageIds = getPublicImageIds(record.plazaPost);
|
||||
|
||||
return {
|
||||
id: record.id.toString(),
|
||||
userId: record.userId,
|
||||
prompt: record.prompt,
|
||||
status: record.status,
|
||||
model: record.model,
|
||||
batchSize: record.batchSize,
|
||||
successCount: record.successCount,
|
||||
failedCount: record.failedCount,
|
||||
startedAt: record.startedAt.toISOString(),
|
||||
endedAt: record.endedAt?.toISOString() ?? null,
|
||||
durationMs: record.durationMs,
|
||||
imageUrl: record.imageUrl,
|
||||
hostedImageUrl: record.hostedImageUrl,
|
||||
revisedPrompt: record.revisedPrompt,
|
||||
errorMessage: getPublicRecordMessage(record.status, record.errorMessage),
|
||||
isPublic: record.plazaPost?.status === PlazaPostStatus.PUBLIC,
|
||||
errorMessage: getPublicBatchMessage(record.status, record.errorMessage),
|
||||
isPublic:
|
||||
record.plazaPost?.status === PlazaPostStatus.PUBLIC &&
|
||||
publicImageIds.size > 0,
|
||||
coverImageId: record.plazaPost?.coverImageId?.toString() ?? null,
|
||||
images,
|
||||
createdAt: record.createdAt.toISOString()
|
||||
};
|
||||
};
|
||||
|
||||
const mapImageGenerationImageItem = (
|
||||
image: ImageGenerationWithHistory["images"][number],
|
||||
plazaPost: ImageGenerationWithHistory["plazaPost"]
|
||||
): IImageHistoryImageItem => {
|
||||
const publicImageIds = getPublicImageIds(plazaPost);
|
||||
|
||||
return {
|
||||
id: image.id.toString(),
|
||||
index: image.index,
|
||||
status: image.status,
|
||||
imageUrl: image.imageUrl,
|
||||
hostedImageUrl: image.hostedImageUrl,
|
||||
imageMimeType: image.imageMimeType,
|
||||
revisedPrompt: image.revisedPrompt,
|
||||
errorMessage: getPublicImageMessage(image.status, image.errorMessage),
|
||||
isPublic:
|
||||
plazaPost?.status === PlazaPostStatus.PUBLIC && publicImageIds.has(image.id),
|
||||
isCover:
|
||||
plazaPost?.status === PlazaPostStatus.PUBLIC &&
|
||||
plazaPost.coverImageId === image.id,
|
||||
createdAt: image.createdAt.toISOString()
|
||||
};
|
||||
};
|
||||
|
||||
/** 展示图优先使用公开封面,其次使用第一张成功图,再兜底第一张子记录 */
|
||||
const getPublicImageIds = (
|
||||
plazaPost: ImageGenerationWithHistory["plazaPost"]
|
||||
): Set<bigint> => {
|
||||
if (!plazaPost || plazaPost.status !== PlazaPostStatus.PUBLIC) {
|
||||
return new Set();
|
||||
}
|
||||
|
||||
return new Set(
|
||||
plazaPost.images.map((image) => image.imageGenerationImageId)
|
||||
);
|
||||
};
|
||||
|
||||
/** 计算耗时并兜底为非负数,避免系统时间抖动导致负值 */
|
||||
const getDurationMs = (startedAt: Date, endedAt: Date) => {
|
||||
return Math.max(0, endedAt.getTime() - startedAt.getTime());
|
||||
@@ -598,8 +728,17 @@ const getSafeErrorMessage = (error: unknown): string => {
|
||||
return "图片生成失败";
|
||||
};
|
||||
|
||||
/** 返回给前端的记录错误只保留本地泛化文案,具体内部错误留在数据库和服务端日志 */
|
||||
const getPublicRecordMessage = (
|
||||
/** 批次错误返回本地泛化文案,具体内部错误留在数据库和服务端日志 */
|
||||
const getPublicBatchMessage = (
|
||||
status: ImageGenerationStatus,
|
||||
errorMessage: string | null
|
||||
): string | null => {
|
||||
if (!errorMessage) return null;
|
||||
return status === ImageGenerationStatus.FAILED ? "图片生成失败" : null;
|
||||
};
|
||||
|
||||
/** 图片错误返回本地泛化文案,归档失败和生成失败分开表达 */
|
||||
const getPublicImageMessage = (
|
||||
status: ImageGenerationStatus,
|
||||
errorMessage: string | null
|
||||
): string | null => {
|
||||
|
||||
+20
-4
@@ -6,6 +6,7 @@ interface ILskyUploadInput {
|
||||
userId: number;
|
||||
username?: string | null;
|
||||
recordId: bigint;
|
||||
imageId: bigint;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
@@ -55,6 +56,7 @@ export const uploadImageFromUrl = async (
|
||||
userId: input.userId,
|
||||
username: input.username,
|
||||
recordId: input.recordId,
|
||||
imageId: input.imageId,
|
||||
createdAt: input.createdAt,
|
||||
extension
|
||||
});
|
||||
@@ -69,9 +71,16 @@ export const uploadImageFromUrl = async (
|
||||
);
|
||||
formData.append("storage_id", String(config.storageId));
|
||||
formData.append("is_remove_exif", "true");
|
||||
formData.append("intro", `AIArtStudio image generation ${input.recordId}`);
|
||||
formData.append(
|
||||
"intro",
|
||||
`AIArtStudio image generation ${input.recordId} image ${input.imageId}`
|
||||
);
|
||||
|
||||
for (const tag of buildArchiveTags(input.userId, input.recordId)) {
|
||||
for (const tag of buildArchiveTags(
|
||||
input.userId,
|
||||
input.recordId,
|
||||
input.imageId
|
||||
)) {
|
||||
formData.append("tags[]", tag);
|
||||
}
|
||||
|
||||
@@ -231,26 +240,33 @@ const buildArchiveFilename = ({
|
||||
userId,
|
||||
username,
|
||||
recordId,
|
||||
imageId,
|
||||
createdAt,
|
||||
extension
|
||||
}: {
|
||||
userId: number;
|
||||
username?: string | null;
|
||||
recordId: bigint;
|
||||
imageId: bigint;
|
||||
createdAt: Date;
|
||||
extension: string;
|
||||
}) => {
|
||||
const safeUsername = sanitizeFilenamePart(username || "user");
|
||||
const timestamp = formatTimestamp(createdAt);
|
||||
return `${userId}_${safeUsername}_${timestamp}_${recordId.toString()}.${extension}`;
|
||||
return `${userId}_${safeUsername}_${timestamp}_${recordId.toString()}_${imageId.toString()}.${extension}`;
|
||||
};
|
||||
|
||||
/** 给图片打固定标签,便于后续在图床里按项目、用户、记录和模型筛选 */
|
||||
const buildArchiveTags = (userId: number, recordId: bigint) => {
|
||||
const buildArchiveTags = (
|
||||
userId: number,
|
||||
recordId: bigint,
|
||||
imageId: bigint
|
||||
) => {
|
||||
return [
|
||||
"AIArtStudio",
|
||||
`user:${userId}`,
|
||||
`record:${recordId.toString()}`,
|
||||
`image:${imageId.toString()}`,
|
||||
"model:gpt-image-2"
|
||||
];
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// server/utils/openai.ts - OpenAI/NewAPI 调用工具:文本、视觉、Responses 流式和 Chat Completions 流式生图。
|
||||
import OpenAI from "openai";
|
||||
import type { BaseOptions, IImageGenerateData } from "#shared/types/openai";
|
||||
import type { BaseOptions } from "#shared/types/openai";
|
||||
|
||||
/** 图像生成改走 Chat Completions 流式接口,通常能更快拿到中转平台返回的图片地址 */
|
||||
const CHAT_COMPLETIONS_URL = "https://api.qflink.xyz/v1/chat/completions";
|
||||
@@ -36,7 +36,11 @@ interface IImageStreamUpstreamResponse {
|
||||
usage?: unknown;
|
||||
}
|
||||
|
||||
export interface IAskImageResult extends IImageGenerateData {
|
||||
export interface IAskImageResult {
|
||||
/** 上游返回的生成图片访问地址 */
|
||||
imageUrl: string;
|
||||
/** 上游返回的修订提示词,可能为空 */
|
||||
revisedPrompt?: string | null;
|
||||
/** 完整上游生图接口返回结果,仅服务端内部保存 */
|
||||
upstreamResponse: unknown;
|
||||
}
|
||||
@@ -251,8 +255,8 @@ const readChatCompletionStream = async (
|
||||
}
|
||||
|
||||
finishReason =
|
||||
chunk.choices?.find((choice) => choice.finish_reason)
|
||||
?.finish_reason ?? finishReason;
|
||||
chunk.choices?.find((choice) => choice.finish_reason)?.finish_reason ??
|
||||
finishReason;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+204
-37
@@ -1,8 +1,9 @@
|
||||
// server/utils/plazaPosts.ts - 广场发布记录数据库操作:公开、取消公开、广场列表查询。
|
||||
// 广场帖子与 ImageGeneration 一对一关联,状态流转:PUBLIC → HIDDEN(用户自主) / REMOVED(管理员下架,不可恢复)。
|
||||
// server/utils/plazaPosts.ts - 广场发布记录数据库操作:公开、取消公开、广场列表和公开详情查询。
|
||||
// 广场帖子与 ImageGeneration 批次一对一关联,帖子内通过 PlazaPostImage 关联用户选择公开的图片集合。
|
||||
// 本文件不向调用方暴露上游响应、图床响应或内部错误字段。
|
||||
import type {
|
||||
IImagePublicStateData,
|
||||
IPlazaPostDetail,
|
||||
IPlazaPostItem,
|
||||
IPlazaPostListData
|
||||
} from "#shared/types/openai";
|
||||
@@ -15,28 +16,50 @@ import { prisma } from "~~/server/utils/prisma";
|
||||
/** 作者未设置昵称时的展示兜底文案 */
|
||||
const ANONYMOUS_AUTHOR_NAME = "匿名用户";
|
||||
|
||||
/** 发布操作的三种结果:成功返回公开状态、记录不存在返回 null、已被管理员下架返回 "REMOVED" */
|
||||
export type PublishPlazaPostResult = IImagePublicStateData | null | "REMOVED";
|
||||
/** 发布操作结果:成功返回公开状态,记录不存在返回 null,已下架或参数非法返回对应字面量 */
|
||||
export type PublishPlazaPostResult =
|
||||
| IImagePublicStateData
|
||||
| null
|
||||
| "REMOVED"
|
||||
| "INVALID_IMAGES";
|
||||
|
||||
/**
|
||||
* 将指定生图记录发布到广场。
|
||||
* 将指定生图批次发布到广场。
|
||||
* - 记录不存在或已软删除时返回 null。
|
||||
* - 记录已被管理员 REMOVED 时返回 "REMOVED",调用方应提示用户无法重新发布。
|
||||
* - 其余情况 upsert 为 PUBLIC,允许重复调用(幂等)。
|
||||
* - imageIds 和 coverImageId 必须由调用方显式传入,不再兼容空 body 默认公开全部。
|
||||
* - coverImageId 必须属于公开图片集合;所有公开图片必须属于该批次且生成成功。
|
||||
*/
|
||||
export const publishImageGenerationToPlaza = async (
|
||||
userId: number,
|
||||
recordId: bigint
|
||||
): Promise<PublishPlazaPostResult> => {
|
||||
export const publishImageGenerationToPlaza = async ({
|
||||
userId,
|
||||
recordId,
|
||||
imageIds,
|
||||
coverImageId
|
||||
}: {
|
||||
userId: number;
|
||||
recordId: bigint;
|
||||
imageIds: bigint[];
|
||||
coverImageId: bigint;
|
||||
}): Promise<PublishPlazaPostResult> => {
|
||||
const record = await prisma.imageGeneration.findFirst({
|
||||
where: {
|
||||
id: recordId,
|
||||
userId,
|
||||
deletedAt: null
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
include: {
|
||||
images: {
|
||||
where: {
|
||||
status: ImageGenerationStatus.SUCCEEDED
|
||||
},
|
||||
orderBy: {
|
||||
index: "asc"
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
index: true
|
||||
}
|
||||
},
|
||||
plazaPost: {
|
||||
select: {
|
||||
status: true
|
||||
@@ -48,29 +71,71 @@ export const publishImageGenerationToPlaza = async (
|
||||
if (!record) return null;
|
||||
if (record.plazaPost?.status === PlazaPostStatus.REMOVED) return "REMOVED";
|
||||
|
||||
await prisma.plazaPost.upsert({
|
||||
where: {
|
||||
imageGenerationId: record.id
|
||||
},
|
||||
create: {
|
||||
imageGenerationId: record.id,
|
||||
userId: record.userId,
|
||||
status: PlazaPostStatus.PUBLIC
|
||||
},
|
||||
update: {
|
||||
status: PlazaPostStatus.PUBLIC,
|
||||
hiddenAt: null,
|
||||
removedAt: null
|
||||
}
|
||||
const availableImageIds = new Set(record.images.map((image) => image.id));
|
||||
const selectedImageIds = Array.from(new Set(imageIds));
|
||||
|
||||
if (selectedImageIds.length === 0) return "INVALID_IMAGES";
|
||||
if (selectedImageIds.some((imageId) => !availableImageIds.has(imageId))) {
|
||||
return "INVALID_IMAGES";
|
||||
}
|
||||
|
||||
const selectedImageIdSet = new Set(selectedImageIds);
|
||||
if (!selectedImageIdSet.has(coverImageId)) {
|
||||
return "INVALID_IMAGES";
|
||||
}
|
||||
|
||||
const sortedSelectedImages = record.images.filter((image) =>
|
||||
selectedImageIdSet.has(image.id)
|
||||
);
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const post = await tx.plazaPost.upsert({
|
||||
where: {
|
||||
imageGenerationId: record.id
|
||||
},
|
||||
create: {
|
||||
imageGenerationId: record.id,
|
||||
coverImageId,
|
||||
userId: record.userId,
|
||||
status: PlazaPostStatus.PUBLIC
|
||||
},
|
||||
update: {
|
||||
coverImageId,
|
||||
status: PlazaPostStatus.PUBLIC,
|
||||
hiddenAt: null,
|
||||
removedAt: null
|
||||
}
|
||||
});
|
||||
|
||||
await tx.plazaPostImage.deleteMany({
|
||||
where: {
|
||||
plazaPostId: post.id
|
||||
}
|
||||
});
|
||||
|
||||
await tx.plazaPostImage.createMany({
|
||||
data: sortedSelectedImages.map((image, sortOrder) => ({
|
||||
plazaPostId: post.id,
|
||||
imageGenerationImageId: image.id,
|
||||
sortOrder
|
||||
}))
|
||||
});
|
||||
|
||||
return {
|
||||
post,
|
||||
imageIds: sortedSelectedImages.map((image) => image.id.toString())
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
isPublic: true
|
||||
isPublic: true,
|
||||
imageIds: result.imageIds,
|
||||
coverImageId: result.post.coverImageId.toString()
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 将指定生图记录从广场隐藏(用户主动操作)。
|
||||
* 将指定生图批次从广场隐藏(用户主动操作)。
|
||||
* - 记录不存在或已软删除时返回 null。
|
||||
* - 帖子不存在或已被 REMOVED 时 updateMany count 为 0,同样返回 null。
|
||||
* - 不允许将 REMOVED 状态改为 HIDDEN,REMOVED 由管理员操作,不在此处处理。
|
||||
@@ -116,10 +181,10 @@ export const hideImageGenerationFromPlaza = async (
|
||||
/**
|
||||
* 分页查询广场公开列表。
|
||||
* 只返回满足以下全部条件的记录:
|
||||
* - PlazaPost.status = PUBLIC
|
||||
* - 关联的 ImageGeneration.status = SUCCEEDED
|
||||
* - 关联的 ImageGeneration 未软删除
|
||||
* - 关联的 ImageGeneration.hostedImageUrl 不为 null(图床归档完成)
|
||||
* - PlazaPost.status = PUBLIC
|
||||
* - 关联的 ImageGeneration.status = SUCCEEDED
|
||||
* - 关联的 ImageGeneration 未软删除
|
||||
* - 关联的封面 ImageGenerationImage 已成功生成并完成图床归档
|
||||
*
|
||||
* count 与 findMany 并行执行以减少网络往返耗时。
|
||||
* 返回字段仅包含广场展示所需的公开信息,不含上游响应、图床响应或错误详情。
|
||||
@@ -135,7 +200,10 @@ export const listPlazaPosts = async ({
|
||||
status: PlazaPostStatus.PUBLIC,
|
||||
imageGeneration: {
|
||||
status: ImageGenerationStatus.SUCCEEDED,
|
||||
deletedAt: null,
|
||||
deletedAt: null
|
||||
},
|
||||
coverImage: {
|
||||
status: ImageGenerationStatus.SUCCEEDED,
|
||||
hostedImageUrl: {
|
||||
not: null
|
||||
}
|
||||
@@ -150,10 +218,20 @@ export const listPlazaPosts = async ({
|
||||
imageGeneration: {
|
||||
select: {
|
||||
id: true,
|
||||
prompt: true,
|
||||
prompt: true
|
||||
}
|
||||
},
|
||||
coverImage: {
|
||||
select: {
|
||||
id: true,
|
||||
hostedImageUrl: true
|
||||
}
|
||||
},
|
||||
images: {
|
||||
select: {
|
||||
imageGenerationImageId: true
|
||||
}
|
||||
},
|
||||
user: {
|
||||
select: {
|
||||
displayName: true,
|
||||
@@ -179,6 +257,87 @@ export const listPlazaPosts = async ({
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 查询广场公开详情。
|
||||
* 只返回已归档成功且属于公开集合的图片;详情接口同样不暴露上游响应、图床响应或内部错误。
|
||||
*/
|
||||
export const getPlazaPostDetail = async (
|
||||
postId: bigint
|
||||
): Promise<IPlazaPostDetail | null> => {
|
||||
const post = await prisma.plazaPost.findFirst({
|
||||
where: {
|
||||
id: postId,
|
||||
status: PlazaPostStatus.PUBLIC,
|
||||
imageGeneration: {
|
||||
status: ImageGenerationStatus.SUCCEEDED,
|
||||
deletedAt: null
|
||||
},
|
||||
coverImage: {
|
||||
status: ImageGenerationStatus.SUCCEEDED,
|
||||
hostedImageUrl: {
|
||||
not: null
|
||||
}
|
||||
}
|
||||
},
|
||||
include: {
|
||||
imageGeneration: {
|
||||
select: {
|
||||
id: true,
|
||||
prompt: true
|
||||
}
|
||||
},
|
||||
coverImage: {
|
||||
select: {
|
||||
id: true,
|
||||
hostedImageUrl: true
|
||||
}
|
||||
},
|
||||
images: {
|
||||
orderBy: {
|
||||
sortOrder: "asc"
|
||||
},
|
||||
include: {
|
||||
imageGenerationImage: {
|
||||
select: {
|
||||
id: true,
|
||||
index: true,
|
||||
hostedImageUrl: true,
|
||||
imageMimeType: true,
|
||||
status: true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
user: {
|
||||
select: {
|
||||
displayName: true,
|
||||
username: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const item = post ? mapPlazaPostItem(post) : null;
|
||||
if (!post || !item) return null;
|
||||
|
||||
return {
|
||||
...item,
|
||||
images: post.images
|
||||
.map((image) => image.imageGenerationImage)
|
||||
.filter(
|
||||
(image): image is typeof image & { hostedImageUrl: string } =>
|
||||
image.status === ImageGenerationStatus.SUCCEEDED &&
|
||||
Boolean(image.hostedImageUrl)
|
||||
)
|
||||
.map((image) => ({
|
||||
id: image.id.toString(),
|
||||
index: image.index,
|
||||
hostedImageUrl: image.hostedImageUrl,
|
||||
imageMimeType: image.imageMimeType
|
||||
}))
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 将 Prisma 查询结果映射为广场展示条目。
|
||||
* hostedImageUrl 在 where 条件中已过滤,此处二次检查是为了满足类型收窄。
|
||||
@@ -190,20 +349,28 @@ const mapPlazaPostItem = (post: {
|
||||
imageGeneration: {
|
||||
id: bigint;
|
||||
prompt: string;
|
||||
};
|
||||
coverImage: {
|
||||
id: bigint;
|
||||
hostedImageUrl: string | null;
|
||||
};
|
||||
images: Array<{
|
||||
imageGenerationImageId: bigint;
|
||||
}>;
|
||||
user: {
|
||||
displayName: string;
|
||||
username: string;
|
||||
};
|
||||
}): IPlazaPostItem | null => {
|
||||
if (!post.imageGeneration.hostedImageUrl) return null;
|
||||
if (!post.coverImage.hostedImageUrl) return null;
|
||||
|
||||
return {
|
||||
id: post.id.toString(),
|
||||
imageGenerationId: post.imageGeneration.id.toString(),
|
||||
coverImageId: post.coverImage.id.toString(),
|
||||
prompt: post.imageGeneration.prompt,
|
||||
hostedImageUrl: post.imageGeneration.hostedImageUrl,
|
||||
hostedImageUrl: post.coverImage.hostedImageUrl,
|
||||
imageCount: post.images.length,
|
||||
authorDisplayName:
|
||||
post.user.displayName || post.user.username || ANONYMOUS_AUTHOR_NAME,
|
||||
publishedAt: post.publishedAt.toISOString()
|
||||
|
||||
Reference in New Issue
Block a user