Spaces:
Running
Running
Download frontend/src/context/CloudContext.tsx from TwanAPI/UploadFile: direct link, hf CLI and curl.
- Browser
- Download file 35.1 kB
-
https://huggingface.co/spaces/TwanAPI/UploadFile/resolve/main/frontend/src/context/CloudContext.tsx
- Command line
-
hf download hf://spaces/TwanAPI/UploadFile/frontend/src/context/CloudContext.tsx
-
curl -L -o CloudContext.tsx https://huggingface.co/spaces/TwanAPI/UploadFile/resolve/main/frontend/src/context/CloudContext.tsx
35.1 kB
"use client";
import React, { createContext, useContext, useState, useEffect, useMemo } from "react";
import { useRouter } from "next/navigation";
import {
UserProfile,
FileNode,
ToastMsg,
UploadProgressItem,
AuditLogEntry,
EditingUserForm,
PermissionSet,
ShareLink,
} from "@/types/cloud";
import { apiFetch, getBackendOrigin, formatBytes, normalizeFile, buildDownloadUrl } from "@/lib/api";
interface CloudContextValue {
// Auth & System
token: string;
currentUser: UserProfile | null;
authLoading: boolean;
bucketName: string;
hfVersion: string;
healthOk: boolean;
isAdmin: boolean;
canUpload: boolean;
canDelete: boolean;
canRename: boolean;
loginWithCredentials: (username: string, password: string) => Promise<boolean>;
registerAccount: (username: string, displayName: string, password: string) => Promise<boolean>;
handleLogout: () => Promise<void>;
// Files & Explorer Filters
files: FileNode[];
loadingFiles: boolean;
currentFolder: string;
setCurrentFolder: (folder: string) => void;
categoryFilter: "all" | "video" | "image" | "archive" | "doc";
setCategoryFilter: (cat: "all" | "video" | "image" | "archive" | "doc") => void;
searchQuery: string;
setSearchQuery: (q: string) => void;
sortBy: "date_desc" | "size_desc" | "size_asc" | "name_asc";
setSortBy: (s: "date_desc" | "size_desc" | "size_asc" | "name_asc") => void;
viewMode: "grid" | "list";
setViewMode: (m: "grid" | "list") => void;
inspectedFile: FileNode | null;
setInspectedFile: (f: FileNode | null) => void;
stats: {
totalSize: number;
counts: { video: number; image: number; archive: number; doc: number };
sizes: { video: number; image: number; archive: number; doc: number };
};
// File Actions
loadFiles: (tk?: string, showToast?: boolean) => Promise<void>;
getDownloadUrl: (path: string, inline?: boolean) => string;
triggerDownload: (file: FileNode) => void;
handleDeleteFile: (file: FileNode) => Promise<void>;
handleRenameSubmit: (e: React.FormEvent) => Promise<void>;
// Modals & Upload Queue
uploadModalOpen: boolean;
setUploadModalOpen: (open: boolean) => void;
uploadTargetFolder: string;
setUploadTargetFolder: (folder: string) => void;
selectedFiles: File[];
setSelectedFiles: (files: File[]) => void;
uploadQueue: UploadProgressItem[];
startBatchUpload: () => Promise<void>;
previewFile: FileNode | null;
setPreviewFile: (f: FileNode | null) => void;
renameTarget: FileNode | null;
setRenameTarget: (f: FileNode | null) => void;
newPathInput: string;
setNewPathInput: (p: string) => void;
renaming: boolean;
// Quick Share
sharesMap: Record<string, ShareLink>;
pendingRequestsCount: number;
shareTarget: FileNode | null;
setShareTarget: (f: FileNode | null) => void;
loadShares: (tk?: string) => Promise<void>;
upsertFileShare: (
path: string,
size: number,
enabled: boolean,
requireApproval: boolean,
regenerate?: boolean
) => Promise<ShareLink | null>;
respondShareRequest: (
shareId: string,
requestId: string,
status: "approved" | "rejected"
) => Promise<ShareLink | null>;
// Admin RBAC
usersList: UserProfile[];
loadingUsers: boolean;
editingUser: EditingUserForm | null;
setEditingUser: (u: EditingUserForm | null) => void;
loadUsersList: (tk?: string) => Promise<void>;
handleSaveUser: (e: React.FormEvent) => Promise<void>;
handleQuickTogglePermission: (u: UserProfile, field: keyof PermissionSet | "role" | "active") => Promise<void>;
handleDeleteUser: (username: string) => Promise<void>;
// Logs & Notifications
auditLogs: AuditLogEntry[];
toasts: ToastMsg[];
notify: (title: string, type?: "success" | "error" | "info", detail?: string) => void;
pushLog: (action: string, target: string, status?: "success" | "warn" | "info") => void;
}
const CloudContext = createContext<CloudContextValue | null>(null);
export function CloudProvider({ children }: { children: React.ReactNode }) {
const router = useRouter();
// --- AUTH & SYSTEM STATE ---
const [token, setToken] = useState<string>("");
const [currentUser, setCurrentUser] = useState<UserProfile | null>(null);
const [authLoading, setAuthLoading] = useState<boolean>(true);
const [bucketName, setBucketName] = useState("Upload ThTuanIT");
const [hfVersion, setHfVersion] = useState("2.4.0");
const [healthOk, setHealthOk] = useState(true);
// --- FILES & EXPLORER STATE ---
const [files, setFiles] = useState<FileNode[]>([]);
const [loadingFiles, setLoadingFiles] = useState(false);
const [currentFolder, setCurrentFolder] = useState("");
const [categoryFilter, setCategoryFilter] = useState<"all" | "video" | "image" | "archive" | "doc">("all");
const [searchQuery, setSearchQuery] = useState("");
const [sortBy, setSortBy] = useState<"date_desc" | "size_desc" | "size_asc" | "name_asc">("date_desc");
const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
const [inspectedFile, setInspectedFile] = useState<FileNode | null>(null);
// --- MODALS & UPLOAD STATE ---
const [uploadModalOpen, setUploadModalOpen] = useState(false);
const [uploadTargetFolder, setUploadTargetFolder] = useState("");
const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
const [uploadQueue, setUploadQueue] = useState<UploadProgressItem[]>([]);
const [previewFile, setPreviewFile] = useState<FileNode | null>(null);
const [renameTarget, setRenameTarget] = useState<FileNode | null>(null);
const [newPathInput, setNewPathInput] = useState("");
const [renaming, setRenaming] = useState(false);
// --- QUICK SHARE STATE ---
const [sharesMap, setSharesMap] = useState<Record<string, ShareLink>>({});
const [shareTarget, setShareTarget] = useState<FileNode | null>(null);
// --- ADMIN USERS STATE ---
const [usersList, setUsersList] = useState<UserProfile[]>([]);
const [loadingUsers, setLoadingUsers] = useState(false);
const [editingUser, setEditingUser] = useState<EditingUserForm | null>(null);
// --- LOGS & TOASTS ---
const [auditLogs, setAuditLogs] = useState<AuditLogEntry[]>([
{
id: "init-1",
time: new Date().toLocaleTimeString("vi-VN"),
actor: "system",
action: "Khởi tạo kết nối Upload ThTuanIT Turbo Engine",
target: "cloud://thtuanit/storage",
status: "info",
},
]);
const [toasts, setToasts] = useState<ToastMsg[]>([]);
const pushLog = (action: string, target: string, status: "success" | "warn" | "info" = "info") => {
setAuditLogs((prev) => [
{
id: `${Date.now()}-${Math.random()}`,
time: new Date().toLocaleTimeString("vi-VN"),
actor: currentUser?.username || "system",
action,
target,
status,
},
...prev.slice(0, 49),
]);
};
const notify = (title: string, type: "success" | "error" | "info" = "info", detail?: string) => {
const id = Date.now() + Math.random();
setToasts((prev) => [...prev, { id, title, type, detail }]);
setTimeout(() => {
setToasts((prev) => prev.filter((t) => t.id !== id));
}, 4200);
};
useEffect(() => {
const savedToken = localStorage.getItem("xet_auth_token") || "";
setToken(savedToken);
checkHealth();
fetchCurrentUser(savedToken);
}, []);
async function checkHealth() {
try {
const res = await apiFetch("/health");
const data = await res.json();
setHealthOk(Boolean(data.ok));
if (data.version) setHfVersion(data.version);
} catch {
setHealthOk(false);
}
}
async function fetchCurrentUser(tk: string) {
setAuthLoading(true);
try {
const headers: Record<string, string> = {};
if (tk) headers["Authorization"] = `Bearer ${tk}`;
const res = await apiFetch("/api/auth/me", { headers });
if (res.ok) {
const data = await res.json();
setCurrentUser(data.user);
loadFiles(tk);
loadShares(tk);
if (data.user.role === "admin") {
loadUsersList(tk);
}
} else {
setCurrentUser(null);
}
} catch {
setCurrentUser(null);
} finally {
setAuthLoading(false);
}
}
async function loginWithCredentials(username: string, password: string): Promise<boolean> {
try {
const res = await apiFetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.detail || data.error || "Đăng nhập thất bại");
}
localStorage.setItem("xet_auth_token", data.token);
setToken(data.token);
setCurrentUser(data.user);
pushLog("Đăng nhập hệ thống", `@${data.user.username} (${data.user.role})`, "success");
notify(`Chào mừng ${data.user.display_name}!`, "success", `Vai trò: ${data.user.role.toUpperCase()}`);
await loadFiles(data.token);
await loadShares(data.token);
if (data.user.role === "admin") {
loadUsersList(data.token);
}
return true;
} catch (err: any) {
notify("Đăng nhập không thành công", "error", err.message);
return false;
}
}
async function registerAccount(username: string, displayName: string, password: string): Promise<boolean> {
try {
const res = await apiFetch("/api/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, display_name: displayName || username, password }),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.detail || data.error || "Đăng ký thất bại");
}
localStorage.setItem("xet_auth_token", data.token);
setToken(data.token);
setCurrentUser(data.user);
pushLog("Đăng ký tài khoản mới", `@${data.user.username}`, "success");
notify("Đăng ký tài khoản thành công!", "success", `@${data.user.username}`);
await loadFiles(data.token);
await loadShares(data.token);
return true;
} catch (err: any) {
notify("Đăng ký không thành công", "error", err.message);
return false;
}
}
async function handleLogout() {
await apiFetch("/api/auth/logout", { method: "POST" }).catch(() => {});
localStorage.removeItem("xet_auth_token");
setToken("");
setCurrentUser(null);
setFiles([]);
notify("Đã đăng xuất khỏi phiên làm việc", "info");
router.push("/login");
}
async function loadFiles(tk = token, showToast = false) {
setLoadingFiles(true);
try {
const res = await apiFetch("/api/files", {
headers: tk ? { Authorization: `Bearer ${tk}` } : {},
});
const data = await res.json();
if (!res.ok) throw new Error(data.detail || data.error || "Không thể tải danh sách tệp");
const list: FileNode[] = Array.isArray(data.items)
? data.items.map(normalizeFile)
: Array.isArray(data.entries)
? data.entries.map((p: string) => normalizeFile({ path: p, size: 0 }))
: [];
setFiles(list);
loadShares(tk);
if (showToast) {
notify("Đã đồng bộ dữ liệu Upload ThTuanIT", "success", `${list.length} tệp tin hiện có`);
pushLog("Đồng bộ danh sách tệp", `${list.length} files`, "info");
}
} catch (err: any) {
notify("Lỗi tải danh sách tệp", "error", err.message);
} finally {
setLoadingFiles(false);
}
}
function getDownloadUrl(path: string, inline = false) {
return buildDownloadUrl(path, token, inline);
}
function triggerDownload(file: FileNode) {
notify("Đang tải tệp xuống từ Upload ThTuanIT...", "info", file.path);
pushLog("Tải tệp xuống", file.path, "info");
const a = document.createElement("a");
a.href = getDownloadUrl(file.path, false);
a.download = file.name;
document.body.appendChild(a);
a.click();
a.remove();
}
async function handleDeleteFile(file: FileNode) {
if (!confirm(`Bạn có chắc chắn muốn xóa vĩnh viễn tệp "${file.path}" khỏi Upload ThTuanIT?`)) return;
try {
notify("Đang xóa tệp khỏi kho lưu trữ Upload ThTuanIT...", "info", file.path);
const res = await apiFetch(`/api/files?path=${encodeURIComponent(file.path)}`, {
method: "DELETE",
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
const data = await res.json();
if (!res.ok) throw new Error(data.detail || data.error || "Xóa thất bại");
notify("Đã xóa tệp thành công", "success", file.path);
pushLog("Xóa tệp khỏi Bucket", file.path, "warn");
if (previewFile?.path === file.path) setPreviewFile(null);
if (inspectedFile?.path === file.path) setInspectedFile(null);
loadFiles(token, false);
} catch (err: any) {
notify("Không thể xóa tệp", "error", err.message);
}
}
async function handleRenameSubmit(e: React.FormEvent) {
e.preventDefault();
if (!renameTarget || !newPathInput.trim()) return;
setRenaming(true);
try {
const res = await apiFetch("/api/files", {
method: "PUT",
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
body: JSON.stringify({
old_path: renameTarget.path,
new_path: newPathInput.trim(),
}),
});
const data = await res.json();
if (!res.ok) throw new Error(data.detail || data.error || "Đổi tên tệp thất bại");
notify("Đã đổi tên / di chuyển tệp thành công!", "success", `${renameTarget.path} → ${newPathInput.trim()}`);
pushLog("Đổi tên / Di chuyển tệp", `${renameTarget.path} → ${newPathInput.trim()}`, "success");
setRenameTarget(null);
setInspectedFile(null);
loadFiles(token, false);
} catch (err: any) {
notify("Lỗi khi đổi tên tệp", "error", err.message);
} finally {
setRenaming(false);
}
}
// --- TURBO UPLOAD ENGINE ---
async function startBatchUpload() {
if (selectedFiles.length === 0) {
notify("Vui lòng chọn ít nhất 1 tệp tin", "error");
return;
}
const cleanFolder = uploadTargetFolder.trim().replace(/^\/+|\/+$/g, "");
const batch = [...selectedFiles];
setUploadModalOpen(false);
setSelectedFiles([]);
const initialQueue: UploadProgressItem[] = batch.map((f, idx) => ({
id: `${Date.now()}-${idx}`,
path: cleanFolder ? `${cleanFolder}/${f.name}` : f.name,
progress: 0,
speedMBps: "0.0 MB/s",
etaSec: 0,
status: "uploading",
}));
setUploadQueue(initialQueue);
const totalBatchBytes = batch.reduce((acc, f) => acc + f.size, 0);
if (batch.length > 1 && totalBatchBytes <= 16 * 1024 * 1024) {
try {
await uploadBatchSingleCommitXHR(batch, cleanFolder, (pct, speedStr, eta) => {
setUploadQueue((prev) =>
prev.map((q) => ({
...q,
progress: pct,
speedMBps: speedStr,
etaSec: eta,
status: pct >= 100 ? "syncing" : "uploading",
}))
);
});
setUploadQueue((prev) => prev.map((q) => ({ ...q, progress: 100, status: "done" })));
pushLog("Turbo Batch Upload", `${batch.length} files (${formatBytes(totalBatchBytes)})`, "success");
notify(`Turbo Batch: Đã tải lên ${batch.length} tệp trong 1 lần commit!`, "success");
await loadFiles(token, false);
setTimeout(() => setUploadQueue([]), 4000);
return;
} catch (err) {
console.warn("Batch commit fallback:", err);
}
}
const CONCURRENCY = 4;
let cursor = 0;
let okCount = 0;
async function worker() {
while (cursor < batch.length) {
const i = cursor++;
const file = batch[i];
const item = initialQueue[i];
try {
await uploadSingleXHR(file, item.path, (pct, speedStr, eta) => {
setUploadQueue((prev) =>
prev.map((q) =>
q.id === item.id
? {
...q,
progress: pct,
speedMBps: speedStr,
etaSec: eta,
status: pct >= 100 ? "syncing" : "uploading",
}
: q
)
);
});
okCount++;
pushLog("Tải tệp lên Bucket", `${item.path} (${formatBytes(file.size)})`, "success");
setUploadQueue((prev) =>
prev.map((q) => (q.id === item.id ? { ...q, progress: 100, status: "done" } : q))
);
} catch (err: any) {
setUploadQueue((prev) => prev.map((q) => (q.id === item.id ? { ...q, status: "error" } : q)));
notify(`Lỗi tải lên ${file.name}`, "error", err.message);
}
}
}
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, batch.length) }, () => worker()));
if (okCount > 0) {
notify(`Turbo Upload hoàn tất ${okCount}/${batch.length} tệp!`, "success");
await loadFiles(token, false);
}
setTimeout(() => setUploadQueue([]), 4500);
}
function uploadBatchSingleCommitXHR(
batchFiles: File[],
folder: string,
onProgress: (pct: number, speedMBps: string, etaSec: number) => void
) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const form = new FormData();
if (folder) form.append("folder", folder);
batchFiles.forEach((f) => form.append("files", f));
const startedAt = performance.now();
xhr.upload.onprogress = (ev) => {
if (ev.lengthComputable) {
const pct = Math.round((ev.loaded / ev.total) * 100);
const elapsedSec = Math.max((performance.now() - startedAt) / 1000, 0.1);
const bps = ev.loaded / elapsedSec;
const speedMBps = (bps / (1024 * 1024)).toFixed(1) + " MB/s";
const etaSec = bps > 0 ? Math.ceil((ev.total - ev.loaded) / bps) : 0;
onProgress(pct, speedMBps, etaSec);
}
};
xhr.onload = () => {
try {
const data = JSON.parse(xhr.responseText || "{}");
if (xhr.status >= 200 && xhr.status < 300) resolve(data);
else reject(new Error(data.detail || data.error || `HTTP ${xhr.status}`));
} catch {
reject(new Error(`HTTP ${xhr.status}`));
}
};
xhr.onerror = () => reject(new Error("Lỗi kết nối mạng"));
xhr.open("POST", `${getBackendOrigin()}/api/upload/batch`);
if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);
xhr.send(form);
});
}
async function uploadParallelChunked(
file: File,
remotePath: string,
onProgress: (pct: number, speedMBps: string, etaSec: number) => void
) {
const authHeaders: Record<string, string> = { "Content-Type": "application/json" };
if (token) authHeaders["Authorization"] = `Bearer ${token}`;
const initRes = await apiFetch("/api/upload/init", {
method: "POST",
headers: authHeaders,
body: JSON.stringify({ path: remotePath, size: file.size }),
});
const initData = await initRes.json().catch(() => ({}));
if (!initRes.ok || !initData.upload_id) {
throw new Error(initData.detail || initData.error || `Init HTTP ${initRes.status}`);
}
const uploadId: string = initData.upload_id;
const chunkSize = 4 * 1024 * 1024; // 4 MiB per chunk
const totalChunks = Math.max(1, Math.ceil(file.size / chunkSize));
const chunkLoaded = new Float64Array(totalChunks);
const startedAt = performance.now();
const reportProgress = () => {
let loaded = 0;
for (let i = 0; i < totalChunks; i++) loaded += chunkLoaded[i];
const pct = file.size > 0 ? Math.min(99, Math.round((loaded / file.size) * 100)) : 99;
const elapsedSec = Math.max((performance.now() - startedAt) / 1000, 0.1);
const bps = loaded / elapsedSec;
const speedMBps = (bps / (1024 * 1024)).toFixed(1) + " MB/s";
const etaSec = bps > 0 ? Math.ceil(Math.max(0, file.size - loaded) / bps) : 0;
onProgress(pct, speedMBps, etaSec);
};
const sendChunkOnce = (chunkIndex: number, offset: number, blob: Blob): Promise<void> =>
new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (ev) => {
if (ev.lengthComputable) {
chunkLoaded[chunkIndex] = ev.loaded;
reportProgress();
}
};
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
chunkLoaded[chunkIndex] = blob.size;
reportProgress();
resolve();
} else {
reject(new Error(`Chunk HTTP ${xhr.status}`));
}
};
xhr.onerror = () => reject(new Error("Chunk network error"));
xhr.open(
"POST",
`${getBackendOrigin()}/api/upload/chunk?id=${encodeURIComponent(uploadId)}&offset=${offset}`
);
xhr.setRequestHeader("Content-Type", "application/octet-stream");
if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);
xhr.send(blob);
});
const sendChunkWithRetry = async (chunkIndex: number) => {
const offset = chunkIndex * chunkSize;
const end = Math.min(offset + chunkSize, file.size);
const blob = file.slice(offset, end);
let lastErr: any;
for (let attempt = 0; attempt < 3; attempt++) {
try {
await sendChunkOnce(chunkIndex, offset, blob);
return;
} catch (err) {
lastErr = err;
chunkLoaded[chunkIndex] = 0;
await new Promise((r) => setTimeout(r, 400 * (attempt + 1)));
}
}
throw lastErr;
};
const STREAM_CONCURRENCY = Math.min(8, totalChunks);
let nextChunk = 0;
const workers = Array.from({ length: STREAM_CONCURRENCY }, async () => {
while (nextChunk < totalChunks) {
const idx = nextChunk++;
await sendChunkWithRetry(idx);
}
});
await Promise.all(workers);
const elapsedSec = Math.max((performance.now() - startedAt) / 1000, 0.1);
const finalBps = file.size / elapsedSec;
const finalSpeed = (finalBps / (1024 * 1024)).toFixed(1) + " MB/s";
onProgress(100, finalSpeed, 0);
const compHeaders: Record<string, string> = {};
if (token) compHeaders["Authorization"] = `Bearer ${token}`;
const compRes = await apiFetch(`/api/upload/complete?id=${encodeURIComponent(uploadId)}`, {
method: "POST",
headers: compHeaders,
});
const compData = await compRes.json().catch(() => ({}));
if (!compRes.ok) {
throw new Error(compData.detail || compData.error || `Complete HTTP ${compRes.status}`);
}
return compData;
}
function uploadSingleXHR(
file: File,
remotePath: string,
onProgress: (pct: number, speedMBps: string, etaSec: number) => void
) {
if (file.size > 4 * 1024 * 1024) {
return uploadParallelChunked(file, remotePath, onProgress);
}
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const form = new FormData();
form.append("path", remotePath);
form.append("file", file);
const startedAt = performance.now();
xhr.upload.onprogress = (ev) => {
if (ev.lengthComputable) {
const pct = Math.round((ev.loaded / ev.total) * 100);
const elapsedSec = Math.max((performance.now() - startedAt) / 1000, 0.1);
const bps = ev.loaded / elapsedSec;
const speedMBps = (bps / (1024 * 1024)).toFixed(1) + " MB/s";
const etaSec = bps > 0 ? Math.ceil((ev.total - ev.loaded) / bps) : 0;
onProgress(pct, speedMBps, etaSec);
}
};
xhr.onload = () => {
try {
const data = JSON.parse(xhr.responseText || "{}");
if (xhr.status >= 200 && xhr.status < 300) resolve(data);
else reject(new Error(data.detail || data.error || `HTTP ${xhr.status}`));
} catch {
reject(new Error(`HTTP ${xhr.status}`));
}
};
xhr.onerror = () => reject(new Error("Lỗi kết nối mạng"));
xhr.open("POST", `${getBackendOrigin()}/api/upload`);
if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`);
xhr.send(form);
});
}
// --- QUICK SHARE OPERATIONS ---
async function loadShares(tk = token) {
if (!tk) return;
try {
const res = await apiFetch("/api/shares", {
headers: { Authorization: `Bearer ${tk}` },
});
if (!res.ok) return;
const data = await res.json();
if (Array.isArray(data.shares)) {
const map: Record<string, ShareLink> = {};
data.shares.forEach((sh: ShareLink) => {
if (sh && sh.path) {
map[sh.path] = sh;
}
});
setSharesMap(map);
}
} catch {
// ignore
}
}
useEffect(() => {
if (!token || !currentUser) return;
const timer = setInterval(() => {
loadShares(token);
}, 6000);
return () => clearInterval(timer);
}, [token, currentUser]);
async function upsertFileShare(
path: string,
size: number,
enabled: boolean,
requireApproval: boolean,
regenerate = false
): Promise<ShareLink | null> {
try {
const res = await apiFetch("/api/shares", {
method: "POST",
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
body: JSON.stringify({
path,
size,
enabled,
require_approval: requireApproval,
regenerate,
}),
});
const data = await res.json();
if (!res.ok) throw new Error(data.detail || data.error || "Không thể cập nhật chia sẻ");
const sh: ShareLink = data.share;
setSharesMap((prev) => ({ ...prev, [path]: sh }));
if (regenerate) {
notify("Đã tạo lại mã liên kết chia sẻ mới!", "success", sh.id);
pushLog("Đổi mã liên kết chia sẻ", path, "info");
} else if (enabled) {
notify(
"Đã bật liên kết chia sẻ nhanh!",
"success",
requireApproval ? "Chế độ: Hỏi xin phép trước khi xem" : "Chế độ: Ai có link đều xem được"
);
pushLog("Bật chia sẻ tệp", `${path} (${sh.id})`, "success");
} else {
notify("Đã tắt liên kết chia sẻ", "info", path);
pushLog("Tắt chia sẻ tệp", path, "warn");
}
return sh;
} catch (err: any) {
notify("Lỗi cấu hình chia sẻ", "error", err.message);
return null;
}
}
async function respondShareRequest(
shareId: string,
requestId: string,
status: "approved" | "rejected"
): Promise<ShareLink | null> {
try {
const res = await apiFetch("/api/shares/approve", {
method: "POST",
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
body: JSON.stringify({
share_id: shareId,
request_id: requestId,
status,
}),
});
const data = await res.json();
if (!res.ok) throw new Error(data.detail || data.error || "Không thể xử lý yêu cầu");
const sh: ShareLink = data.share;
setSharesMap((prev) => ({ ...prev, [sh.path]: sh }));
notify(
status === "approved" ? "Đã cho phép truy cập tệp!" : "Đã từ chối / thu hồi quyền xem tệp",
status === "approved" ? "success" : "info",
sh.file_name
);
pushLog(
status === "approved" ? "Cho phép xem tệp chia sẻ" : "Từ chối xem tệp chia sẻ",
`${sh.file_name} (${requestId})`,
status === "approved" ? "success" : "warn"
);
return sh;
} catch (err: any) {
notify("Lỗi duyệt quyền truy cập", "error", err.message);
return null;
}
}
const pendingRequestsCount = useMemo(() => {
let count = 0;
Object.values(sharesMap).forEach((sh) => {
if (sh.enabled && Array.isArray(sh.requests)) {
sh.requests.forEach((r) => {
if (r.status === "pending") count++;
});
}
});
return count;
}, [sharesMap]);
// --- ADMIN RBAC ---
async function loadUsersList(tk = token) {
setLoadingUsers(true);
try {
const res = await apiFetch("/api/admin/users", {
headers: tk ? { Authorization: `Bearer ${tk}` } : {},
});
const data = await res.json();
if (res.ok && Array.isArray(data.users)) {
setUsersList(data.users);
}
} catch {
// ignore
} finally {
setLoadingUsers(false);
}
}
async function handleSaveUser(e: React.FormEvent) {
e.preventDefault();
if (!editingUser) return;
try {
const res = await apiFetch("/api/admin/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
body: JSON.stringify(editingUser),
});
const data = await res.json();
if (!res.ok) throw new Error(data.detail || data.error || "Lưu người dùng thất bại");
notify("Đã lưu cấu hình tài khoản!", "success", `@${data.user.username} (${data.user.role})`);
pushLog("Admin cập nhật tài khoản", `@${data.user.username}`, "success");
setEditingUser(null);
loadUsersList(token);
if (currentUser && data.user.username === currentUser.username) {
setCurrentUser(data.user);
}
} catch (err: any) {
notify("Không thể lưu người dùng", "error", err.message);
}
}
async function handleQuickTogglePermission(u: UserProfile, field: keyof PermissionSet | "role" | "active") {
const updated = {
username: u.username,
display_name: u.display_name,
role: u.role,
password: "",
permissions: { ...u.permissions },
active: u.active,
};
if (field === "role") {
updated.role = u.role === "admin" ? "user" : "admin";
} else if (field === "active") {
if (u.username === "admin") {
notify("Không thể khóa tài khoản Admin gốc", "error");
return;
}
updated.active = !u.active;
} else {
updated.permissions[field] = !u.permissions[field];
}
try {
const res = await apiFetch("/api/admin/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
body: JSON.stringify(updated),
});
const data = await res.json();
if (!res.ok) throw new Error(data.detail || data.error);
notify("Đã cập nhật phân quyền tức thì", "success", `@${u.username} • ${field}`);
pushLog("Thay đổi quyền RBAC", `@${u.username} (${field})`, "info");
loadUsersList(token);
} catch (err: any) {
notify("Lỗi cập nhật quyền", "error", err.message);
}
}
async function handleDeleteUser(username: string) {
if (username === "admin") {
notify("Không thể xóa tài khoản Admin gốc", "error");
return;
}
if (!confirm(`Xóa vĩnh viễn tài khoản người dùng "@${username}"?`)) return;
try {
const res = await apiFetch(`/api/admin/users?username=${encodeURIComponent(username)}`, {
method: "DELETE",
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
const data = await res.json();
if (!res.ok) throw new Error(data.detail || data.error);
notify("Đã xóa tài khoản người dùng", "success", `@${username}`);
pushLog("Xóa tài khoản người dùng", `@${username}`, "warn");
loadUsersList(token);
} catch (err: any) {
notify("Lỗi xóa tài khoản", "error", err.message);
}
}
const stats = useMemo(() => {
const totalSize = files.reduce((acc, f) => acc + (f.size || 0), 0);
const counts = { video: 0, image: 0, archive: 0, doc: 0 };
const sizes = { video: 0, image: 0, archive: 0, doc: 0 };
files.forEach((f) => {
counts[f.category]++;
sizes[f.category] += f.size || 0;
});
return { totalSize, counts, sizes };
}, [files]);
const canUpload = Boolean(currentUser && (currentUser.role === "admin" || currentUser.permissions.can_upload));
const canDelete = Boolean(currentUser && (currentUser.role === "admin" || currentUser.permissions.can_delete));
const canRename = Boolean(currentUser && (currentUser.role === "admin" || currentUser.permissions.can_rename));
const isAdmin = currentUser?.role === "admin";
return (
<CloudContext.Provider
value={{
token,
currentUser,
authLoading,
bucketName,
hfVersion,
healthOk,
isAdmin,
canUpload,
canDelete,
canRename,
loginWithCredentials,
registerAccount,
handleLogout,
files,
loadingFiles,
currentFolder,
setCurrentFolder,
categoryFilter,
setCategoryFilter,
searchQuery,
setSearchQuery,
sortBy,
setSortBy,
viewMode,
setViewMode,
inspectedFile,
setInspectedFile,
stats,
loadFiles,
getDownloadUrl,
triggerDownload,
handleDeleteFile,
handleRenameSubmit,
uploadModalOpen,
setUploadModalOpen,
uploadTargetFolder,
setUploadTargetFolder,
selectedFiles,
setSelectedFiles,
uploadQueue,
startBatchUpload,
previewFile,
setPreviewFile,
renameTarget,
setRenameTarget,
newPathInput,
setNewPathInput,
renaming,
sharesMap,
pendingRequestsCount,
shareTarget,
setShareTarget,
loadShares,
upsertFileShare,
respondShareRequest,
usersList,
loadingUsers,
editingUser,
setEditingUser,
loadUsersList,
handleSaveUser,
handleQuickTogglePermission,
handleDeleteUser,
auditLogs,
toasts,
notify,
pushLog,
}}
>
{children}
</CloudContext.Provider>
);
}
export function useCloud() {
const ctx = useContext(CloudContext);
if (!ctx) {
throw new Error("useCloud must be used inside CloudProvider");
}
return ctx;
}
"use client";
import React, { createContext, useContext, useState, useEffect, useMemo } from "react";
import { useRouter } from "next/navigation";
import {
UserProfile,
FileNode,
ToastMsg,
UploadProgressItem,
AuditLogEntry,
EditingUserForm,
PermissionSet,
ShareLink,
} from "@/types/cloud";
import { apiFetch, getBackendOrigin, formatBytes, normalizeFile, buildDownloadUrl } from "@/lib/api";
interface CloudContextValue {
// Auth & System
token: string;
currentUser: UserProfile | null;
authLoading: boolean;
bucketName: string;
hfVersion: string;
healthOk: boolean;
isAdmin: boolean;
canUpload: boolean;
canDelete: boolean;
canRename: boolean;
loginWithCredentials: (username: string, password: string) => Promise<boolean>;
registerAccount: (username: string, displayName: string, password: string) => Promise<boolean>;
handleLogout: () => Promise<void>;
// Files & Explorer Filters
files: FileNode[];
loadingFiles: boolean;
currentFolder: string;
setCurrentFolder: (folder: string) => void;
categoryFilter: "all" | "video" | "image" | "archive" | "doc";
setCategoryFilter: (cat: "all" | "video" | "image" | "archive" | "doc") => void;
searchQuery: string;
setSearchQuery: (q: string) => void;
sortBy: "date_desc" | "size_desc" | "size_asc" | "name_asc";
setSortBy: (s: "date_desc" | "size_desc" | "size_asc" | "name_asc") => void;
viewMode: "grid" | "list";
setViewMode: (m: "grid" | "list") => void;
inspectedFile: FileNode | null;
setInspectedFile: (f: FileNode | null) => void;
stats: {
totalSize: number;
counts: { video: number; image: number; archive: number; doc: number };
sizes: { video: number; image: number; archive: number; doc: number };
};
// File Actions
loadFiles: (tk?: string, showToast?: boolean) => Promise<void>;
getDownloadUrl: (path: string, inline?: boolean) => string;
triggerDownload: (file: FileNode) => void;
handleDeleteFile: (file: FileNode) => Promise<void>;
handleRenameSubmit: (e: React.FormEvent) => Promise<void>;
// Modals & Upload Queue
uploadModalOpen: boolean;
setUploadModalOpen: (open: boolean) => void;
uploadTargetFolder: string;
setUploadTargetFolder: (folder: string) => void;
selectedFiles: File[];
setSelectedFiles: (files: File[]) => void;
uploadQueue: UploadProgressItem[];
startBatchUpload: () => Promise<void>;
previewFile: FileNode | null;
setPreviewFile: (f: FileNode | null) => void;
renameTarget: FileNode | null;
setRenameTarget: (f: FileNode | null) => void;
newPathInput: string;
setNewPathInput: (p: string) => void;
renaming: boolean;
// Quick Share
sharesMap: Record<string, ShareLink>;
pendingRequestsCount: number;
shareTarget: FileNode | null;
setShareTarget: (f: FileNode | null) => void;
loadShares: (tk?: string) => Promise<void>;
upsertFileShare: (
path: string,
size: number,
enabled: boolean,
requireApproval: boolean,
regenerate?: boolean
) => Promise<ShareLink | null>;
respondShareRequest: (
shareId: string,
requestId: string,
status: "approved" | "rejected"
) => Promise<ShareLink | null>;
// Admin RBAC
usersList: UserProfile[];
loadingUsers: boolean;
editingUser: EditingUserForm | null;