@@ -0,0 +1,83 @@
|
||||
import { apiDelete, apiGet, apiPost, compactApiParams } from "@/services/api/request";
|
||||
import type { Prompt, PromptListResponse } from "@/services/api/prompts";
|
||||
|
||||
export type AdminPromptCategory = {
|
||||
category: string;
|
||||
name: string;
|
||||
description: string;
|
||||
file: string;
|
||||
githubUrl: string;
|
||||
remote: boolean;
|
||||
};
|
||||
|
||||
export async function fetchAdminPromptCategories(token: string) {
|
||||
return apiGet<AdminPromptCategory[]>("/api/admin/prompt-categories", undefined, token);
|
||||
}
|
||||
|
||||
export async function syncAdminPromptCategory(token: string, category: string) {
|
||||
return apiPost<AdminPromptCategory[]>("/api/admin/prompt-categories/sync", { category }, token);
|
||||
}
|
||||
|
||||
export type AdminPromptQuery = {
|
||||
keyword?: string;
|
||||
category?: string;
|
||||
tag?: string[];
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
};
|
||||
|
||||
export type AdminAsset = {
|
||||
id: string;
|
||||
title: string;
|
||||
type: "text" | "image" | "video";
|
||||
coverUrl: string;
|
||||
tags: string[];
|
||||
category: string;
|
||||
description: string;
|
||||
content: string;
|
||||
url: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type AdminAssetListResponse = {
|
||||
items: AdminAsset[];
|
||||
tags: string[];
|
||||
total: number;
|
||||
};
|
||||
|
||||
export async function fetchAdminPrompts(token: string, query: AdminPromptQuery = {}) {
|
||||
return apiGet<PromptListResponse>("/api/admin/prompts", compactApiParams(query), token);
|
||||
}
|
||||
|
||||
export async function saveAdminPrompt(token: string, prompt: Partial<Prompt>) {
|
||||
return apiPost<Prompt>("/api/admin/prompts", prompt, token);
|
||||
}
|
||||
|
||||
export async function deleteAdminPrompt(token: string, id: string) {
|
||||
return apiDelete<boolean>(`/api/admin/prompts/${encodeURIComponent(id)}`, token);
|
||||
}
|
||||
|
||||
export type AdminAssetQuery = {
|
||||
keyword?: string;
|
||||
type?: string;
|
||||
tag?: string[];
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
};
|
||||
|
||||
export async function fetchAdminAssets(token: string, query: AdminAssetQuery = {}) {
|
||||
return apiGet<AdminAssetListResponse>(
|
||||
"/api/admin/assets",
|
||||
compactApiParams(query),
|
||||
token,
|
||||
);
|
||||
}
|
||||
|
||||
export async function saveAdminAsset(token: string, asset: Partial<AdminAsset>) {
|
||||
return apiPost<AdminAsset>("/api/admin/assets", asset, token);
|
||||
}
|
||||
|
||||
export async function deleteAdminAsset(token: string, id: string) {
|
||||
return apiDelete<boolean>(`/api/admin/assets/${encodeURIComponent(id)}`, token);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { apiGet, compactApiParams } from "@/services/api/request";
|
||||
|
||||
export type AssetLibraryItem = {
|
||||
id: string;
|
||||
title: string;
|
||||
type: "text" | "image" | "video";
|
||||
coverUrl: string;
|
||||
tags: string[];
|
||||
category: string;
|
||||
description: string;
|
||||
content: string;
|
||||
url: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type AssetLibraryResponse = {
|
||||
items: AssetLibraryItem[];
|
||||
tags: string[];
|
||||
total: number;
|
||||
};
|
||||
|
||||
export type AssetLibraryQuery = {
|
||||
keyword?: string;
|
||||
type?: string;
|
||||
tag?: string[];
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
};
|
||||
|
||||
export async function fetchAssetLibrary(query: AssetLibraryQuery = {}) {
|
||||
return apiGet<AssetLibraryResponse>("/api/assets", compactApiParams(query));
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { apiGet, apiPost } from "@/services/api/request";
|
||||
|
||||
export const AUTH_TOKEN_KEY = "infinite-canvas-auth-token-v1";
|
||||
|
||||
export type UserRole = "guest" | "user" | "admin";
|
||||
|
||||
export type AuthUser = {
|
||||
id: string;
|
||||
username: string;
|
||||
role: UserRole;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type AuthSession = {
|
||||
token: string;
|
||||
user: AuthUser;
|
||||
};
|
||||
|
||||
export type AuthPayload = {
|
||||
username: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export async function login(payload: AuthPayload) {
|
||||
return apiPost<AuthSession>("/api/admin/login", payload);
|
||||
}
|
||||
|
||||
export async function register(payload: AuthPayload) {
|
||||
return apiPost<AuthSession>("/api/auth/register", payload);
|
||||
}
|
||||
|
||||
export async function fetchCurrentUser(token?: string) {
|
||||
return apiGet<AuthUser>("/api/auth/me", undefined, token);
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import axios from "axios";
|
||||
|
||||
import { buildApiUrl, type AiConfig } from "@/lib/ai-config";
|
||||
import { createId } from "@/lib/id";
|
||||
import { dataUrlToFile } from "@/lib/image-utils";
|
||||
import { imageToDataUrl } from "@/services/image-storage";
|
||||
import type { ReferenceImage } from "@/types/image";
|
||||
|
||||
export type ChatCompletionMessage = {
|
||||
role: "user" | "assistant";
|
||||
content: string | Array<{ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } }>;
|
||||
};
|
||||
|
||||
type ImageApiResponse = {
|
||||
data?: Array<Record<string, unknown>>;
|
||||
error?: { message?: string };
|
||||
};
|
||||
|
||||
function resolveImageDataUrl(item: Record<string, unknown>) {
|
||||
if (typeof item.b64_json === "string" && item.b64_json) {
|
||||
return `data:image/png;base64,${item.b64_json}`;
|
||||
}
|
||||
if (typeof item.url === "string" && item.url) {
|
||||
return item.url;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseImagePayload(payload: ImageApiResponse) {
|
||||
const images =
|
||||
payload.data
|
||||
?.map(resolveImageDataUrl)
|
||||
.filter((value): value is string => Boolean(value))
|
||||
.map((dataUrl) => ({ id: createId(), dataUrl })) || [];
|
||||
|
||||
if (images.length === 0) {
|
||||
throw new Error("接口没有返回图片");
|
||||
}
|
||||
|
||||
return images;
|
||||
}
|
||||
|
||||
function readAxiosError(error: unknown, fallback: string) {
|
||||
if (axios.isAxiosError<{ error?: { message?: string } }>(error)) {
|
||||
return error.response?.data?.error?.message || (error.response?.status ? `${fallback}:${error.response.status}` : fallback);
|
||||
}
|
||||
return error instanceof Error ? error.message : fallback;
|
||||
}
|
||||
|
||||
function parseStreamChunk(chunk: string, onDelta: (value: string) => void) {
|
||||
let deltaText = "";
|
||||
for (const eventBlock of chunk.split("\n\n")) {
|
||||
const data = eventBlock.split("\n").find((line) => line.startsWith("data: "))?.slice(6);
|
||||
if (!data || data === "[DONE]") continue;
|
||||
const delta = (JSON.parse(data) as { choices?: Array<{ delta?: { content?: string } }> }).choices?.[0]?.delta?.content || "";
|
||||
deltaText += delta;
|
||||
}
|
||||
if (deltaText) onDelta(deltaText);
|
||||
}
|
||||
|
||||
export async function requestGeneration(config: AiConfig, prompt: string) {
|
||||
const n = Math.max(1, Math.min(15, Math.floor(Math.abs(Number(config.count)) || 1)));
|
||||
try {
|
||||
const response = await axios.post<ImageApiResponse>(
|
||||
buildApiUrl(config.baseUrl, "/images/generations"),
|
||||
{
|
||||
model: config.model,
|
||||
prompt,
|
||||
n,
|
||||
quality: config.quality || undefined,
|
||||
size: config.size || undefined,
|
||||
response_format: "b64_json",
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
return parseImagePayload(response.data);
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "请求失败"));
|
||||
}
|
||||
}
|
||||
|
||||
export async function requestEdit(config: AiConfig, prompt: string, references: ReferenceImage[]) {
|
||||
const n = Math.max(1, Math.min(15, Math.floor(Math.abs(Number(config.count)) || 1)));
|
||||
const formData = new FormData();
|
||||
formData.set("model", config.model);
|
||||
formData.set("prompt", prompt);
|
||||
formData.set("n", String(n));
|
||||
formData.set("response_format", "b64_json");
|
||||
if (config.quality) {
|
||||
formData.set("quality", config.quality);
|
||||
}
|
||||
if (config.size) {
|
||||
formData.set("size", config.size);
|
||||
}
|
||||
const files = await Promise.all(references.map(async (image) => dataUrlToFile({ ...image, dataUrl: await imageToDataUrl(image) })));
|
||||
files.forEach((file) => formData.append("image", file));
|
||||
|
||||
try {
|
||||
const response = await axios.post<ImageApiResponse>(buildApiUrl(config.baseUrl, "/images/edits"), formData, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
},
|
||||
});
|
||||
return parseImagePayload(response.data);
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "请求失败"));
|
||||
}
|
||||
}
|
||||
|
||||
export async function requestImageQuestion(config: AiConfig, messages: ChatCompletionMessage[], onDelta: (text: string) => void) {
|
||||
let buffer = "";
|
||||
let answer = "";
|
||||
let processedLength = 0;
|
||||
|
||||
try {
|
||||
await axios.post(
|
||||
buildApiUrl(config.baseUrl, "/chat/completions"),
|
||||
{
|
||||
model: config.model,
|
||||
messages,
|
||||
stream: true,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
responseType: "text",
|
||||
onDownloadProgress: (event) => {
|
||||
const responseText = String(event.event?.target?.responseText || "");
|
||||
const nextText = responseText.slice(processedLength);
|
||||
processedLength = responseText.length;
|
||||
buffer += nextText;
|
||||
const chunks = buffer.split("\n\n");
|
||||
buffer = chunks.pop() || "";
|
||||
for (const chunk of chunks) {
|
||||
parseStreamChunk(chunk, (delta) => {
|
||||
answer += delta;
|
||||
onDelta(answer);
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
if (buffer) {
|
||||
parseStreamChunk(buffer, (delta) => {
|
||||
answer += delta;
|
||||
onDelta(answer);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "请求失败"));
|
||||
}
|
||||
return answer || "没有返回内容";
|
||||
}
|
||||
|
||||
export async function fetchImageModels(config: AiConfig) {
|
||||
try {
|
||||
const response = await axios.get<{ data?: Array<{ id?: string }>; error?: { message?: string } }>(buildApiUrl(config.baseUrl, "/models"), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
},
|
||||
});
|
||||
return (response.data.data || [])
|
||||
.map((model) => model.id)
|
||||
.filter((id): id is string => Boolean(id))
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "读取模型失败"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { apiGet, compactApiParams } from "@/services/api/request";
|
||||
|
||||
export type Prompt = {
|
||||
id: string;
|
||||
title: string;
|
||||
coverUrl: string;
|
||||
prompt: string;
|
||||
tags: string[];
|
||||
category: string;
|
||||
githubUrl: string;
|
||||
preview: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export const ALL_PROMPTS_OPTION = "全部";
|
||||
|
||||
export type PromptListResponse = {
|
||||
items: Prompt[];
|
||||
tags: string[];
|
||||
categories: string[];
|
||||
total: number;
|
||||
};
|
||||
|
||||
export async function fetchPrompts({ keyword = "", tag = [], category = ALL_PROMPTS_OPTION, page, pageSize }: { keyword?: string; tag?: string[]; category?: string; page?: number; pageSize?: number } = {}) {
|
||||
return apiGet<PromptListResponse>("/api/prompts", compactApiParams({
|
||||
...(keyword ? { keyword } : {}),
|
||||
...(tag.length ? { tag } : {}),
|
||||
...(category !== ALL_PROMPTS_OPTION ? { category } : {}),
|
||||
...(page ? { page } : {}),
|
||||
...(pageSize ? { pageSize } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
export function formatPromptDate(value: string) {
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? "" : new Intl.DateTimeFormat("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" }).format(date);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import axios from "axios";
|
||||
|
||||
export type ApiParams = Record<string, string | string[] | number | number[] | undefined>;
|
||||
|
||||
type ApiResponse<T> = {
|
||||
code: number;
|
||||
data: T;
|
||||
msg: string;
|
||||
};
|
||||
|
||||
export function compactApiParams(params: ApiParams) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(params).filter(([, value]) => value !== "" && value !== undefined && (!Array.isArray(value) || value.length > 0)),
|
||||
) as ApiParams;
|
||||
}
|
||||
|
||||
export function serializeApiParams(params?: ApiParams) {
|
||||
const queryParams = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(params || {})) {
|
||||
if (value === undefined) continue;
|
||||
if (Array.isArray(value)) value.forEach((item) => queryParams.append(key, String(item)));
|
||||
else queryParams.set(key, String(value));
|
||||
}
|
||||
return queryParams;
|
||||
}
|
||||
|
||||
export async function apiGet<T>(url: string, params?: ApiParams, token?: string) {
|
||||
return apiRequest<T>({
|
||||
url,
|
||||
method: "GET",
|
||||
params: params || undefined,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
export async function apiPost<T>(url: string, body?: unknown, token?: string) {
|
||||
return apiRequest<T>({
|
||||
url,
|
||||
method: "POST",
|
||||
data: body ?? {},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function apiDelete<T>(url: string, token?: string) {
|
||||
return apiRequest<T>({
|
||||
url,
|
||||
method: "DELETE",
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
async function apiRequest<T>(config: { url: string; method: "GET" | "POST" | "DELETE"; params?: ApiParams; data?: unknown; headers?: Record<string, string> }) {
|
||||
let response;
|
||||
try {
|
||||
response = await axios.request<ApiResponse<T>>({
|
||||
url: config.url,
|
||||
method: config.method,
|
||||
params: config.params,
|
||||
paramsSerializer: { serialize: (params) => serializeApiParams(params as ApiParams).toString() },
|
||||
data: config.data,
|
||||
headers: config.headers,
|
||||
validateStatus: () => true,
|
||||
});
|
||||
} catch {
|
||||
throw new Error("接口连接失败,请确认后端服务已启动");
|
||||
}
|
||||
|
||||
const result = response.data;
|
||||
if (!result || typeof result !== "object") {
|
||||
throw new Error(response.status === 404 ? "接口不存在,请确认后端服务已启动" : "接口返回异常,请稍后重试");
|
||||
}
|
||||
|
||||
const payload = result as ApiResponse<T>;
|
||||
if (response.status < 200 || response.status >= 300 || payload.code !== 0) {
|
||||
throw new Error(payload.msg || "请求失败");
|
||||
}
|
||||
|
||||
return payload.data;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import localforage from "localforage";
|
||||
|
||||
import { createId } from "@/lib/id";
|
||||
import { readImageMeta } from "@/lib/image-utils";
|
||||
|
||||
export type UploadedImage = {
|
||||
url: string;
|
||||
storageKey: string;
|
||||
width: number;
|
||||
height: number;
|
||||
bytes: number;
|
||||
mimeType: string;
|
||||
};
|
||||
|
||||
const store = localforage.createInstance({ name: "infinite-canvas", storeName: "image_files" });
|
||||
const objectUrls = new Map<string, string>();
|
||||
|
||||
export async function uploadImage(input: string | Blob): Promise<UploadedImage> {
|
||||
const blob = typeof input === "string" ? await (await fetch(input)).blob() : input;
|
||||
const storageKey = `image:${createId()}`;
|
||||
await store.setItem(storageKey, blob);
|
||||
const url = URL.createObjectURL(blob);
|
||||
objectUrls.set(storageKey, url);
|
||||
const meta = await readImageMeta(url);
|
||||
return { url, storageKey, width: meta.width, height: meta.height, bytes: blob.size, mimeType: blob.type || meta.mimeType };
|
||||
}
|
||||
|
||||
export async function resolveImageUrl(storageKey?: string, fallback = "") {
|
||||
if (!storageKey) return fallback;
|
||||
const cached = objectUrls.get(storageKey);
|
||||
if (cached) return cached;
|
||||
const blob = await store.getItem<Blob>(storageKey);
|
||||
if (!blob) return fallback;
|
||||
const url = URL.createObjectURL(blob);
|
||||
objectUrls.set(storageKey, url);
|
||||
return url;
|
||||
}
|
||||
|
||||
export async function imageToDataUrl(image: { url?: string; dataUrl?: string; storageKey?: string }) {
|
||||
const url = image.dataUrl || await resolveImageUrl(image.storageKey, image.url || "");
|
||||
if (!url || url.startsWith("data:")) return url;
|
||||
return blobToDataUrl(await (await fetch(url)).blob());
|
||||
}
|
||||
|
||||
export async function deleteStoredImages(keys: Iterable<string>) {
|
||||
await Promise.all(Array.from(new Set(keys)).map(async (key) => {
|
||||
const url = objectUrls.get(key);
|
||||
if (url) URL.revokeObjectURL(url);
|
||||
objectUrls.delete(key);
|
||||
await store.removeItem(key);
|
||||
}));
|
||||
}
|
||||
|
||||
export async function cleanupUnusedImages(usedData: unknown) {
|
||||
const usedKeys = collectImageStorageKeys(usedData);
|
||||
const unused: string[] = [];
|
||||
await store.iterate((_value, key) => {
|
||||
if (!usedKeys.has(key)) unused.push(key);
|
||||
});
|
||||
await deleteStoredImages(unused);
|
||||
}
|
||||
|
||||
export function collectImageStorageKeys(value: unknown, keys = new Set<string>()) {
|
||||
if (!value || typeof value !== "object") return keys;
|
||||
if ("storageKey" in value && typeof value.storageKey === "string" && value.storageKey.startsWith("image:")) keys.add(value.storageKey);
|
||||
Object.values(value).forEach((item) => Array.isArray(item) ? item.forEach((child) => collectImageStorageKeys(child, keys)) : collectImageStorageKeys(item, keys));
|
||||
return keys;
|
||||
}
|
||||
|
||||
function blobToDataUrl(blob: Blob) {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result || ""));
|
||||
reader.onerror = () => reject(new Error("读取图片失败"));
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user