From f772a6cf4e43fa8c1e6cb6349668a4cec591f489 Mon Sep 17 00:00:00 2001 From: nstarikov Date: Sat, 15 Aug 2026 11:23:51 +0300 Subject: [PATCH] add local video upload dashboard --- dzen-assistant/admin/src/App.tsx | 250 +++++++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) diff --git a/dzen-assistant/admin/src/App.tsx b/dzen-assistant/admin/src/App.tsx index ba6d30d..8aa88a3 100644 --- a/dzen-assistant/admin/src/App.tsx +++ b/dzen-assistant/admin/src/App.tsx @@ -22,6 +22,7 @@ import { Save, Settings2, Trash2, + Upload, X, } from "lucide-react" @@ -137,6 +138,21 @@ type VideoChaptersResponse = { canSplit: boolean } +type VideoStorage = { + totalBytes: number + usedBytes: number + freeBytes: number + usedPercent: number +} + +type LocalVideoUpload = { + name: string + loaded: number + total: number + status: "uploading" | "complete" | "cancelled" | "error" + errorMessage?: string +} + type EditorBlock = OutputData["blocks"][number] type RandomFrameTuneConfig = { @@ -176,6 +192,8 @@ class VkVideoTool { const ARTICLES_PAGE_SIZE = 10 const CHAPTER_SELECTION_STORAGE_PREFIX = "dzen:selected-chapters:" +const LOCAL_VIDEO_EXTENSIONS = new Set(["mp4", "webm", "mov", "mkv"]) +const LOW_STORAGE_WARNING_BYTES = 10 * 1024 * 1024 * 1024 function chapterSelectionStorageKey(videoId: number) { return `${CHAPTER_SELECTION_STORAGE_PREFIX}${videoId}` @@ -1011,6 +1029,30 @@ function formatDuration(seconds?: number) { return `${minutes}:${String(rest).padStart(2, "0")}` } +function formatFileSize(bytes?: number) { + const value = Math.max(0, bytes || 0) + if (value >= 1024 * 1024 * 1024) { + return `${(value / (1024 * 1024 * 1024)).toLocaleString("ru-RU", { maximumFractionDigits: 1 })} ГБ` + } + if (value >= 1024 * 1024) { + return `${(value / (1024 * 1024)).toLocaleString("ru-RU", { maximumFractionDigits: 1 })} МБ` + } + return `${Math.round(value / 1024).toLocaleString("ru-RU")} КБ` +} + +function uploadErrorMessage(responseText: string) { + try { + const payload = JSON.parse(responseText) as { detail?: string } + return payload.detail || responseText + } catch { + return responseText || "Не удалось загрузить видео." + } +} + +function localVideoExtension(file: File) { + return file.name.split(".").pop()?.toLowerCase() || "" +} + function parseApiDate(value?: string) { if (!value) return null const normalized = /(?:z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z` @@ -1162,10 +1204,15 @@ export default function App() { const [busy, setBusy] = useState(false) const [manualVideoUrl, setManualVideoUrl] = useState("") const [manualVideoBusy, setManualVideoBusy] = useState(false) + const [videoStorage, setVideoStorage] = useState(null) + const [localVideoUpload, setLocalVideoUpload] = useState(null) + const [localVideoDragActive, setLocalVideoDragActive] = useState(false) const [videoActionId, setVideoActionId] = useState(null) const editorHolderRef = useRef(null) const editorInstanceRef = useRef(null) const featureImageInputRef = useRef(null) + const localVideoInputRef = useRef(null) + const localVideoUploadRequestRef = useRef(null) const featureImageHoverRef = useRef(false) const editorImageHoverBlockRef = useRef(null) const pasteImageTargetRef = useRef<"feature" | "editor" | null>(null) @@ -1209,6 +1256,9 @@ export default function App() { .sort((a, b) => dateSortValue(b.publishedAt || b.createdAt) - dateSortValue(a.publishedAt || a.createdAt)), [articles] ) + const localUploadPercent = localVideoUpload?.total ? Math.min(100, Math.round((localVideoUpload.loaded / localVideoUpload.total) * 100)) : 0 + const videoStoragePercent = Math.max(0, Math.min(100, videoStorage?.usedPercent ?? 0)) + const videoStorageLow = Boolean(videoStorage && videoStorage.freeBytes < LOW_STORAGE_WARNING_BYTES) async function loadArticlesPage(reset = false) { if (articlesLoadingRef.current) return @@ -1253,6 +1303,14 @@ export default function App() { } } + async function loadVideoStorage() { + try { + setVideoStorage(await api("/api/storage/videos")) + } catch { + setVideoStorage(null) + } + } + useEffect(() => { api<{ authenticated: boolean; hasPasskeys: boolean }>("/api/auth/status") .then((status) => { @@ -1268,6 +1326,7 @@ export default function App() { useEffect(() => { if (authState !== "authenticated") return refresh().catch((error) => setStatusMessage(`Ошибка загрузки: ${error.message}`)) + void loadVideoStorage() api("/api/settings").then(setAppSettings).catch(() => undefined) }, [authState]) @@ -1297,6 +1356,7 @@ export default function App() { useEffect(() => () => { logSocketRef.current?.close() + localVideoUploadRequestRef.current?.abort() clearImageCaptionNormalizationTimers() }, []) @@ -1354,6 +1414,87 @@ export default function App() { } } + function uploadLocalVideo(file: File) { + if (localVideoUpload?.status === "uploading") return + if (!LOCAL_VIDEO_EXTENSIONS.has(localVideoExtension(file))) { + setLocalVideoUpload({ + name: file.name, + loaded: 0, + total: file.size, + status: "error", + errorMessage: "Поддерживаются файлы MP4, WebM, MOV и MKV.", + }) + return + } + + setLocalVideoUpload({ name: file.name, loaded: 0, total: file.size, status: "uploading" }) + const request = new XMLHttpRequest() + localVideoUploadRequestRef.current = request + request.open("POST", "/api/videos/upload") + request.responseType = "text" + request.withCredentials = true + request.upload.onprogress = (event) => { + setLocalVideoUpload((current) => { + if (!current || current.status !== "uploading") return current + return { + ...current, + loaded: event.loaded, + total: event.lengthComputable ? event.total : file.size, + } + }) + } + request.onload = () => { + if (localVideoUploadRequestRef.current === request) { + localVideoUploadRequestRef.current = null + } + if (request.status < 200 || request.status >= 300) { + setLocalVideoUpload({ + name: file.name, + loaded: 0, + total: file.size, + status: "error", + errorMessage: uploadErrorMessage(request.responseText), + }) + return + } + setLocalVideoUpload({ name: file.name, loaded: file.size, total: file.size, status: "complete" }) + setStatusMessage(`Видео «${file.name}» загружено и готово к обработке.`) + void Promise.all([refresh(), loadVideoStorage()]).catch((error) => { + setStatusMessage(`Видео загружено, но список не обновился: ${error instanceof Error ? error.message : String(error)}`) + }) + } + request.onerror = () => { + if (localVideoUploadRequestRef.current === request) { + localVideoUploadRequestRef.current = null + } + setLocalVideoUpload({ + name: file.name, + loaded: 0, + total: file.size, + status: "error", + errorMessage: "Сеть прервала загрузку. Попробуйте ещё раз.", + }) + } + request.onabort = () => { + if (localVideoUploadRequestRef.current === request) { + localVideoUploadRequestRef.current = null + } + setLocalVideoUpload((current) => current ? { ...current, status: "cancelled" } : current) + } + const formData = new FormData() + formData.append("file", file) + request.send(formData) + } + + function selectLocalVideo(file?: File | null) { + if (!file) return + uploadLocalVideo(file) + } + + function cancelLocalVideoUpload() { + localVideoUploadRequestRef.current?.abort() + } + async function prepareVideoProcessing(video: Video, recreateDrafts = false) { if ((video.durationSeconds || 0) < 20 * 60) { await processVideo(video.id, recreateDrafts) @@ -1997,6 +2138,7 @@ export default function App() { clearStoredChapterSelection(id) setStatusMessage(`Удалил ролик${title ? `: ${title}` : ""}. Он исключен из повторного импорта.`) await refresh() + await loadVideoStorage() } finally { setVideoActionId(null) } @@ -2078,6 +2220,114 @@ export default function App() { +
+
{ + event.preventDefault() + if (localVideoUpload?.status !== "uploading") setLocalVideoDragActive(true) + }} + onDragOver={(event) => { + event.preventDefault() + event.dataTransfer.dropEffect = "copy" + if (localVideoUpload?.status !== "uploading") setLocalVideoDragActive(true) + }} + onDragLeave={(event) => { + if (event.currentTarget.contains(event.relatedTarget as Node)) return + setLocalVideoDragActive(false) + }} + onDrop={(event) => { + event.preventDefault() + setLocalVideoDragActive(false) + if (localVideoUpload?.status === "uploading") return + selectLocalVideo(event.dataTransfer.files?.[0]) + }} + > + { + const file = event.currentTarget.files?.[0] + event.currentTarget.value = "" + selectLocalVideo(file) + }} + /> +
+ + + +
+

Загрузить видео с компьютера

+

MP4, WebM, MOV или MKV. Перетащите файл сюда или выберите его.

+
+ +
+ {localVideoUpload ? ( +
+
+
+

{localVideoUpload.name}

+

+ {localVideoUpload.status === "uploading" + ? `Загружено ${formatFileSize(localVideoUpload.loaded)} из ${formatFileSize(localVideoUpload.total)}` + : localVideoUpload.status === "complete" + ? `Загружено ${formatFileSize(localVideoUpload.total)}. Файл готов к обработке.` + : localVideoUpload.status === "cancelled" + ? "Загрузка отменена." + : localVideoUpload.errorMessage || "Не удалось загрузить файл."} +

+
+ {localVideoUpload.status === "uploading" ? ( + + ) : ( + + )} +
+
+
+
+
+ + {localVideoUpload.status === "uploading" ? `${localUploadPercent}%` : localVideoUpload.status === "complete" ? "100%" : ""} + +
+
+ ) : null} +
+ +
+
+

Видео на диске

+ {videoStorage ? {videoStoragePercent}% : null} +
+ {videoStorage ? ( + <> +
+
+
+

+ Свободно {formatFileSize(videoStorage.freeBytes)} из {formatFileSize(videoStorage.totalBytes)} +

+ + ) : ( +

Данные о диске недоступны.

+ )} +
+
{productionVideos.length > 0 ? ( productionVideos.map((video) => { const draftArticles = video.articles?.filter((article) => article.status !== "published") ?? []