feat(storage): 素材库容量 - 展示账号文件使用进度
Refs #227 Co-authored-by: MasterChiefCN <49179444+MasterChiefCN@users.noreply.github.com>
This commit is contained in:
1 parent
914717cae6
commit
91ac4bd501
7 files changed
+179
-7
No files matched your search
@@ -106,6 +106,19 @@ func RegisterUserDataRoutes(r *gin.RouterGroup, svc *service.Service) {
|
|||||||
}
|
}
|
||||||
ok(c, gin.H{"resources": resources})
|
ok(c, gin.H{"resources": resources})
|
||||||
})
|
})
|
||||||
|
r.GET("/resources/storage-usage", func(c *gin.Context) {
|
||||||
|
user, err := currentUser(c, svc)
|
||||||
|
if err != nil {
|
||||||
|
failService(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
usage, err := svc.AccountFileStorageUsage(user.ID)
|
||||||
|
if err != nil {
|
||||||
|
failService(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ok(c, gin.H{"usage": usage})
|
||||||
|
})
|
||||||
r.POST("/resources", func(c *gin.Context) {
|
r.POST("/resources", func(c *gin.Context) {
|
||||||
user, err := currentUser(c, svc)
|
user, err := currentUser(c, svc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -8,6 +8,26 @@ import (
|
|||||||
"infinite-canvas/backend/internal/repository"
|
"infinite-canvas/backend/internal/repository"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type AccountFileStorageUsage struct {
|
||||||
|
UsedBytes int64 `json:"usedBytes"`
|
||||||
|
TotalBytes int64 `json:"totalBytes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) AccountFileStorageUsage(userID string) (*AccountFileStorageUsage, error) {
|
||||||
|
policy, err := s.RuntimePolicy()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
usedBytes, err := s.repo.UserStoredFileBytes(userID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &AccountFileStorageUsage{
|
||||||
|
UsedBytes: usedBytes,
|
||||||
|
TotalBytes: gigabytes(policy.Resource.StoredFileGB),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
func structuredBytes(usage repository.UserStorageUsage) int64 {
|
func structuredBytes(usage repository.UserStorageUsage) int64 {
|
||||||
return usage.AssetBytes + usage.CanvasBytes + usage.SessionBytes
|
return usage.AssetBytes + usage.CanvasBytes + usage.SessionBytes
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,3 +67,20 @@ func TestReserveUserUploadQuotaRejectsTotalStoredFilesAtLimit(t *testing.T) {
|
|||||||
t.Fatalf("reserveUserUploadQuota() error = %v", err)
|
t.Fatalf("reserveUserUploadQuota() error = %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAccountFileStorageUsageUsesStoredFilePolicy(t *testing.T) {
|
||||||
|
svc := newResourceTestService(t)
|
||||||
|
if err := svc.repo.Create(&model.Resource{ID: "resource-1", UserID: "user-1", Status: model.ResourceStatusReady, Size: 3 << 20}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := svc.repo.Create(&model.SessionFile{ID: "session-file-1", UserID: "user-1", SessionID: "session-1", Size: 2 << 20}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
usage, err := svc.AccountFileStorageUsage("user-1")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if usage.UsedBytes != 5<<20 || usage.TotalBytes != gigabytes(defaultRuntimePolicy().Resource.StoredFileGB) {
|
||||||
|
t.Fatalf("AccountFileStorageUsage() = %#v", usage)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { HardDrive } from "lucide-react";
|
||||||
|
|
||||||
|
import { formatBytes } from "@/lib/image-utils";
|
||||||
|
import { getAccountFileStorageUsage } from "@/services/api/resources";
|
||||||
|
|
||||||
|
export const assetStorageUsageQueryKey = ["account-file-storage-usage"] as const;
|
||||||
|
|
||||||
|
export function AssetStorageUsage() {
|
||||||
|
const query = useQuery({
|
||||||
|
queryKey: assetStorageUsageQueryKey,
|
||||||
|
queryFn: getAccountFileStorageUsage,
|
||||||
|
refetchOnMount: "always",
|
||||||
|
});
|
||||||
|
const usage = query.data;
|
||||||
|
const percent = usage?.totalBytes ? Math.min(100, (usage.usedBytes / usage.totalBytes) * 100) : 0;
|
||||||
|
const percentLabel = usage?.usedBytes && percent < 0.1 ? "<0.1%" : `${Math.round(percent * 10) / 10}%`;
|
||||||
|
const full = Boolean(usage && usage.usedBytes >= usage.totalBytes);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className={`assets-storage-usage${full ? " is-full" : ""}${usage?.usedBytes ? " has-usage" : ""}`} aria-label="账号文件容量" aria-busy={query.isPending} title="包含素材文件和 Agent 会话附件">
|
||||||
|
<span className="assets-storage-usage-icon" aria-hidden="true">
|
||||||
|
<HardDrive />
|
||||||
|
</span>
|
||||||
|
<span className="assets-storage-usage-title">账号容量</span>
|
||||||
|
{usage ? (
|
||||||
|
<>
|
||||||
|
<span className="assets-storage-usage-value">
|
||||||
|
{storageBytes(usage.usedBytes)} / {storageBytes(usage.totalBytes)}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className="assets-storage-usage-track"
|
||||||
|
role="progressbar"
|
||||||
|
aria-label="账号文件容量使用进度"
|
||||||
|
aria-valuemin={0}
|
||||||
|
aria-valuemax={usage.totalBytes}
|
||||||
|
aria-valuenow={Math.min(usage.usedBytes, usage.totalBytes)}
|
||||||
|
aria-valuetext={`已使用 ${storageBytes(usage.usedBytes)},总容量 ${storageBytes(usage.totalBytes)}`}
|
||||||
|
>
|
||||||
|
<span style={{ width: `${percent}%` }} />
|
||||||
|
</span>
|
||||||
|
<span className="assets-storage-usage-percent">{percentLabel}</span>
|
||||||
|
</>
|
||||||
|
) : query.isError ? (
|
||||||
|
<span className="assets-storage-usage-status">
|
||||||
|
容量统计暂时不可用。
|
||||||
|
<button type="button" onClick={() => void query.refetch()}>
|
||||||
|
重试
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="assets-storage-usage-status">正在统计已用容量…</span>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function storageBytes(value: number) {
|
||||||
|
return formatBytes(value) || "0 B";
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { AudioLines, Box, CheckCheck, Clapperboard, Copy, Download, FileText, FileUp, Image as ImageIcon, Link2, MoreHorizontal, PencilLine, Play, Plus, Search, Trash2, Upload, type LucideIcon } from "lucide-react";
|
import { AudioLines, Box, CheckCheck, Clapperboard, Copy, Download, FileText, FileUp, Image as ImageIcon, Link2, MoreHorizontal, PencilLine, Play, Plus, Search, Trash2, Upload, type LucideIcon } from "lucide-react";
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
import { App, Button, Drawer, Dropdown, Form, Input, Modal, Select, Space, Tag, Typography } from "antd";
|
import { App, Button, Drawer, Dropdown, Form, Input, Modal, Select, Space, Tag, Typography } from "antd";
|
||||||
import type { MenuProps } from "antd";
|
import type { MenuProps } from "antd";
|
||||||
import { useNavigate } from "react-router";
|
import { useNavigate } from "react-router";
|
||||||
@@ -17,6 +18,7 @@ import { uploadImage } from "@/services/image-storage";
|
|||||||
import { uploadMediaFile } from "@/services/file-storage";
|
import { uploadMediaFile } from "@/services/file-storage";
|
||||||
import { useAssetStore, type Asset, type AssetCategory, type AssetKind, type ImageAsset } from "@/stores/use-asset-store";
|
import { useAssetStore, type Asset, type AssetCategory, type AssetKind, type ImageAsset } from "@/stores/use-asset-store";
|
||||||
import { exportAssets, readAssetPackage } from "./asset-transfer";
|
import { exportAssets, readAssetPackage } from "./asset-transfer";
|
||||||
|
import { AssetStorageUsage, assetStorageUsageQueryKey } from "./asset-storage-usage";
|
||||||
import { deleteAssetWithRemoteSync } from "@/services/user-data-sync";
|
import { deleteAssetWithRemoteSync } from "@/services/user-data-sync";
|
||||||
|
|
||||||
type LibraryAsset = Exclude<Asset, { kind: "entity" }>;
|
type LibraryAsset = Exclude<Asset, { kind: "entity" }>;
|
||||||
@@ -65,6 +67,7 @@ const assetKindIcons: Record<LibraryAsset["kind"], LucideIcon> = {
|
|||||||
export default function AssetsPage() {
|
export default function AssetsPage() {
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const copyText = useCopyText();
|
const copyText = useCopyText();
|
||||||
const [form] = Form.useForm<AssetFormValues>();
|
const [form] = Form.useForm<AssetFormValues>();
|
||||||
const coverInputRef = useRef<HTMLInputElement>(null);
|
const coverInputRef = useRef<HTMLInputElement>(null);
|
||||||
@@ -188,6 +191,7 @@ export default function AssetsPage() {
|
|||||||
const readImageFile = async (file?: File) => {
|
const readImageFile = async (file?: File) => {
|
||||||
if (!file || !file.type.startsWith("image/")) return;
|
if (!file || !file.type.startsWith("image/")) return;
|
||||||
const image = await uploadImage(file);
|
const image = await uploadImage(file);
|
||||||
|
void queryClient.invalidateQueries({ queryKey: assetStorageUsageQueryKey });
|
||||||
const draft = { dataUrl: image.url, storageKey: image.storageKey, width: image.width, height: image.height, bytes: image.bytes, mimeType: image.mimeType };
|
const draft = { dataUrl: image.url, storageKey: image.storageKey, width: image.width, height: image.height, bytes: image.bytes, mimeType: image.mimeType };
|
||||||
setImageDraft(draft);
|
setImageDraft(draft);
|
||||||
if (!form.getFieldValue("coverUrl")) form.setFieldValue("coverUrl", draft.dataUrl);
|
if (!form.getFieldValue("coverUrl")) form.setFieldValue("coverUrl", draft.dataUrl);
|
||||||
@@ -197,6 +201,7 @@ export default function AssetsPage() {
|
|||||||
const readModelFile = async (file?: File) => {
|
const readModelFile = async (file?: File) => {
|
||||||
if (!file || !/\.(glb|gltf)$/i.test(file.name)) return;
|
if (!file || !/\.(glb|gltf)$/i.test(file.name)) return;
|
||||||
const uploaded = await uploadMediaFile(file, "model");
|
const uploaded = await uploadMediaFile(file, "model");
|
||||||
|
void queryClient.invalidateQueries({ queryKey: assetStorageUsageQueryKey });
|
||||||
addAsset({ kind: "model", title: file.name.replace(/\.(glb|gltf)$/i, ""), coverUrl: "", tags: ["3D模型"], source: "手动上传", data: { url: uploaded.url, storageKey: uploaded.storageKey, bytes: uploaded.bytes, mimeType: uploaded.mimeType, fileName: file.name }, metadata: { source: "manual" } });
|
addAsset({ kind: "model", title: file.name.replace(/\.(glb|gltf)$/i, ""), coverUrl: "", tags: ["3D模型"], source: "手动上传", data: { url: uploaded.url, storageKey: uploaded.storageKey, bytes: uploaded.bytes, mimeType: uploaded.mimeType, fileName: file.name }, metadata: { source: "manual" } });
|
||||||
message.success("3D 模型已保存");
|
message.success("3D 模型已保存");
|
||||||
};
|
};
|
||||||
@@ -277,13 +282,16 @@ export default function AssetsPage() {
|
|||||||
description="管理文本、图片、视频、音频和 3D 模型素材。"
|
description="管理文本、图片、视频、音频和 3D 模型素材。"
|
||||||
meta={<span className="app-projects-header-meta assets-header-meta">{validAssets.length} 个素材</span>}
|
meta={<span className="app-projects-header-meta assets-header-meta">{validAssets.length} 个素材</span>}
|
||||||
actions={(
|
actions={(
|
||||||
<>
|
<div className="assets-header-actions">
|
||||||
<Button className="library-primary-action" type="primary" icon={<Plus className="size-3.5" />} onClick={openCreate}>新增素材</Button>
|
<div className="assets-header-action-buttons">
|
||||||
<Button title="导出全部素材" aria-label="导出全部素材" icon={<Download className="size-4" />} onClick={() => void exportAllAssets()} />
|
<Button className="library-primary-action" type="primary" icon={<Plus className="size-3.5" />} onClick={openCreate}>新增素材</Button>
|
||||||
<Dropdown trigger={["click"]} menu={{ items: [{ key: "package", icon: <FileUp className="size-4" />, label: "导入素材包", onClick: () => assetInputRef.current?.click() }, { key: "model", icon: <Upload className="size-4" />, label: "上传 3D 模型", onClick: () => modelInputRef.current?.click() }] }}>
|
<Button title="导出全部素材" aria-label="导出全部素材" icon={<Download className="size-4" />} onClick={() => void exportAllAssets()} />
|
||||||
<Button title="导入素材" aria-label="导入素材" icon={<FileUp className="size-4" />} />
|
<Dropdown trigger={["click"]} menu={{ items: [{ key: "package", icon: <FileUp className="size-4" />, label: "导入素材包", onClick: () => assetInputRef.current?.click() }, { key: "model", icon: <Upload className="size-4" />, label: "上传 3D 模型", onClick: () => modelInputRef.current?.click() }] }}>
|
||||||
</Dropdown>
|
<Button title="导入素材" aria-label="导入素材" icon={<FileUp className="size-4" />} />
|
||||||
</>
|
</Dropdown>
|
||||||
|
</div>
|
||||||
|
<AssetStorageUsage />
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<ListToolbar className="library-toolbar" active={Boolean(keyword || kindFilter !== "all" || categoryFilter !== "all")} onReset={() => { setKeyword(""); setKindFilter("all"); setCategoryFilter("all"); setPage(1); }}>
|
<ListToolbar className="library-toolbar" active={Boolean(keyword || kindFilter !== "all" || categoryFilter !== "all")} onReset={() => { setKeyword(""); setKindFilter("all"); setCategoryFilter("all"); setPage(1); }}>
|
||||||
|
|||||||
@@ -41,6 +41,11 @@ export type UserOSSSettingInput = Pick<UserOSSSetting, "enabled" | "provider" |
|
|||||||
accessKeySecret?: string;
|
accessKeySecret?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type AccountFileStorageUsage = {
|
||||||
|
usedBytes: number;
|
||||||
|
totalBytes: number;
|
||||||
|
};
|
||||||
|
|
||||||
const api = apiClient;
|
const api = apiClient;
|
||||||
const resourceCache = new Map<string, RemoteResource>();
|
const resourceCache = new Map<string, RemoteResource>();
|
||||||
const resourceRequests = new Map<string, Promise<RemoteResource>>();
|
const resourceRequests = new Map<string, Promise<RemoteResource>>();
|
||||||
@@ -58,6 +63,11 @@ export function updateUserOSSSetting(input: UserOSSSettingInput) {
|
|||||||
return request<{ setting: UserOSSSetting }>(api.patch("/settings/oss", input));
|
return request<{ setting: UserOSSSetting }>(api.patch("/settings/oss", input));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getAccountFileStorageUsage() {
|
||||||
|
const data = await request<{ usage: AccountFileStorageUsage }>(api.get("/resources/storage-usage"));
|
||||||
|
return data.usage;
|
||||||
|
}
|
||||||
|
|
||||||
export function resourceIdFromStorageKey(storageKey?: string) {
|
export function resourceIdFromStorageKey(storageKey?: string) {
|
||||||
return storageKey?.startsWith("resource:") ? storageKey.slice("resource:".length) : "";
|
return storageKey?.startsWith("resource:") ? storageKey.slice("resource:".length) : "";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9711,6 +9711,50 @@ html:not(.dark) .creation-home .storyboard-workbench-bar-action:hover { backgrou
|
|||||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--workspace-accent) 16%, transparent);
|
box-shadow: 0 0 0 3px color-mix(in srgb, var(--workspace-accent) 16%, transparent);
|
||||||
content: "";
|
content: "";
|
||||||
}
|
}
|
||||||
|
.assets-header-actions { display: flex; max-width: 100%; flex-direction: column; align-items: flex-end; gap: 8px; }
|
||||||
|
.assets-header-action-buttons { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; }
|
||||||
|
.assets-header-actions .assets-storage-usage { justify-content: flex-end; }
|
||||||
|
.assets-storage-usage {
|
||||||
|
display: flex;
|
||||||
|
width: min(100%, 380px);
|
||||||
|
min-height: 24px;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 48%, transparent);
|
||||||
|
}
|
||||||
|
.assets-storage-usage-icon {
|
||||||
|
display: inline-flex;
|
||||||
|
flex: none;
|
||||||
|
align-items: center;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 44%, transparent);
|
||||||
|
}
|
||||||
|
.assets-storage-usage-icon svg { width: 14px; height: 14px; }
|
||||||
|
.assets-storage-usage-title { flex: none; color: color-mix(in srgb, var(--foreground) 62%, transparent); font-size: var(--fs-label); font-weight: 560; }
|
||||||
|
.assets-storage-usage-value { flex: none; color: color-mix(in srgb, var(--foreground) 76%, transparent); font-size: var(--fs-label); font-variant-numeric: tabular-nums; }
|
||||||
|
.assets-storage-usage-track {
|
||||||
|
display: block;
|
||||||
|
flex: 1 1 96px;
|
||||||
|
min-width: 48px;
|
||||||
|
max-width: 120px;
|
||||||
|
height: 4px;
|
||||||
|
overflow: hidden;
|
||||||
|
border-radius: var(--progress-bar-radius);
|
||||||
|
background: color-mix(in srgb, var(--foreground) 9%, transparent);
|
||||||
|
}
|
||||||
|
.assets-storage-usage-track > span { display: block; height: 100%; border-radius: inherit; background: var(--workspace-accent); transition: width var(--motion-state) var(--motion-ease-out); }
|
||||||
|
.assets-storage-usage.has-usage .assets-storage-usage-track > span { min-width: 2px; }
|
||||||
|
.assets-storage-usage.is-full .assets-storage-usage-track > span { background: var(--progress-bar-fill-error); }
|
||||||
|
.assets-storage-usage-percent { min-width: 38px; flex: none; font-size: var(--fs-tiny); font-variant-numeric: tabular-nums; text-align: right; }
|
||||||
|
.assets-storage-usage-status { min-width: 0; font-size: var(--fs-label); }
|
||||||
|
.assets-storage-usage-status button { margin-left: 6px; color: var(--foreground); text-decoration: underline; text-underline-offset: 2px; }
|
||||||
|
.assets-storage-usage-status button:focus-visible { outline: 2px solid var(--control-focus-ring); outline-offset: 2px; }
|
||||||
|
@media (max-width: 639px) {
|
||||||
|
.assets-header-actions { width: 100%; align-items: stretch; }
|
||||||
|
.assets-header-action-buttons,
|
||||||
|
.assets-header-actions .assets-storage-usage { justify-content: flex-start; }
|
||||||
|
.assets-storage-usage { width: 100%; }
|
||||||
|
.assets-storage-usage-track { min-width: 32px; }
|
||||||
|
}
|
||||||
/* 页头主按钮:压过 light 主题下 app-page-header 按钮的白色背景覆盖。 */
|
/* 页头主按钮:压过 light 主题下 app-page-header 按钮的白色背景覆盖。 */
|
||||||
.assets-library-page.canvas-library-page .app-page-header .library-primary-action {
|
.assets-library-page.canvas-library-page .app-page-header .library-primary-action {
|
||||||
border: 0 !important;
|
border: 0 !important;
|
||||||
|
|||||||
Reference in new issue
Block a user