add local video upload dashboard

This commit is contained in:
nstarikov 2026-08-15 11:23:51 +03:00
parent a3be5d07a8
commit f772a6cf4e

View file

@ -22,6 +22,7 @@ import {
Save, Save,
Settings2, Settings2,
Trash2, Trash2,
Upload,
X, X,
} from "lucide-react" } from "lucide-react"
@ -137,6 +138,21 @@ type VideoChaptersResponse = {
canSplit: boolean 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 EditorBlock = OutputData["blocks"][number]
type RandomFrameTuneConfig = { type RandomFrameTuneConfig = {
@ -176,6 +192,8 @@ class VkVideoTool {
const ARTICLES_PAGE_SIZE = 10 const ARTICLES_PAGE_SIZE = 10
const CHAPTER_SELECTION_STORAGE_PREFIX = "dzen:selected-chapters:" 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) { function chapterSelectionStorageKey(videoId: number) {
return `${CHAPTER_SELECTION_STORAGE_PREFIX}${videoId}` return `${CHAPTER_SELECTION_STORAGE_PREFIX}${videoId}`
@ -1011,6 +1029,30 @@ function formatDuration(seconds?: number) {
return `${minutes}:${String(rest).padStart(2, "0")}` 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) { function parseApiDate(value?: string) {
if (!value) return null if (!value) return null
const normalized = /(?:z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z` 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 [busy, setBusy] = useState(false)
const [manualVideoUrl, setManualVideoUrl] = useState("") const [manualVideoUrl, setManualVideoUrl] = useState("")
const [manualVideoBusy, setManualVideoBusy] = useState(false) const [manualVideoBusy, setManualVideoBusy] = useState(false)
const [videoStorage, setVideoStorage] = useState<VideoStorage | null>(null)
const [localVideoUpload, setLocalVideoUpload] = useState<LocalVideoUpload | null>(null)
const [localVideoDragActive, setLocalVideoDragActive] = useState(false)
const [videoActionId, setVideoActionId] = useState<number | null>(null) const [videoActionId, setVideoActionId] = useState<number | null>(null)
const editorHolderRef = useRef<HTMLDivElement | null>(null) const editorHolderRef = useRef<HTMLDivElement | null>(null)
const editorInstanceRef = useRef<EditorJS | null>(null) const editorInstanceRef = useRef<EditorJS | null>(null)
const featureImageInputRef = useRef<HTMLInputElement | null>(null) const featureImageInputRef = useRef<HTMLInputElement | null>(null)
const localVideoInputRef = useRef<HTMLInputElement | null>(null)
const localVideoUploadRequestRef = useRef<XMLHttpRequest | null>(null)
const featureImageHoverRef = useRef(false) const featureImageHoverRef = useRef(false)
const editorImageHoverBlockRef = useRef<BlockAPI | null>(null) const editorImageHoverBlockRef = useRef<BlockAPI | null>(null)
const pasteImageTargetRef = useRef<"feature" | "editor" | null>(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)), .sort((a, b) => dateSortValue(b.publishedAt || b.createdAt) - dateSortValue(a.publishedAt || a.createdAt)),
[articles] [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) { async function loadArticlesPage(reset = false) {
if (articlesLoadingRef.current) return if (articlesLoadingRef.current) return
@ -1253,6 +1303,14 @@ export default function App() {
} }
} }
async function loadVideoStorage() {
try {
setVideoStorage(await api<VideoStorage>("/api/storage/videos"))
} catch {
setVideoStorage(null)
}
}
useEffect(() => { useEffect(() => {
api<{ authenticated: boolean; hasPasskeys: boolean }>("/api/auth/status") api<{ authenticated: boolean; hasPasskeys: boolean }>("/api/auth/status")
.then((status) => { .then((status) => {
@ -1268,6 +1326,7 @@ export default function App() {
useEffect(() => { useEffect(() => {
if (authState !== "authenticated") return if (authState !== "authenticated") return
refresh().catch((error) => setStatusMessage(`Ошибка загрузки: ${error.message}`)) refresh().catch((error) => setStatusMessage(`Ошибка загрузки: ${error.message}`))
void loadVideoStorage()
api<AppSettings>("/api/settings").then(setAppSettings).catch(() => undefined) api<AppSettings>("/api/settings").then(setAppSettings).catch(() => undefined)
}, [authState]) }, [authState])
@ -1297,6 +1356,7 @@ export default function App() {
useEffect(() => () => { useEffect(() => () => {
logSocketRef.current?.close() logSocketRef.current?.close()
localVideoUploadRequestRef.current?.abort()
clearImageCaptionNormalizationTimers() 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) { async function prepareVideoProcessing(video: Video, recreateDrafts = false) {
if ((video.durationSeconds || 0) < 20 * 60) { if ((video.durationSeconds || 0) < 20 * 60) {
await processVideo(video.id, recreateDrafts) await processVideo(video.id, recreateDrafts)
@ -1997,6 +2138,7 @@ export default function App() {
clearStoredChapterSelection(id) clearStoredChapterSelection(id)
setStatusMessage(`Удалил ролик${title ? `: ${title}` : ""}. Он исключен из повторного импорта.`) setStatusMessage(`Удалил ролик${title ? `: ${title}` : ""}. Он исключен из повторного импорта.`)
await refresh() await refresh()
await loadVideoStorage()
} finally { } finally {
setVideoActionId(null) setVideoActionId(null)
} }
@ -2078,6 +2220,114 @@ export default function App() {
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="work-list flex max-h-[72vh] flex-col gap-2 overflow-y-auto"> <CardContent className="work-list flex max-h-[72vh] flex-col gap-2 overflow-y-auto">
<div className="grid gap-2 xl:grid-cols-[minmax(0,1fr)_13rem]">
<section
className={`local-video-upload rounded-md border border-dashed p-3 transition-colors ${
localVideoDragActive ? "border-primary bg-primary/5" : "border-border bg-background"
}`}
onDragEnter={(event) => {
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])
}}
>
<input
ref={localVideoInputRef}
className="hidden"
type="file"
accept="video/mp4,video/webm,video/quicktime,video/x-matroska,.mp4,.webm,.mov,.mkv"
onChange={(event) => {
const file = event.currentTarget.files?.[0]
event.currentTarget.value = ""
selectLocalVideo(file)
}}
/>
<div className="flex flex-wrap items-center gap-3">
<span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
<Upload className="size-4" />
</span>
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold">Загрузить видео с компьютера</p>
<p className="mt-0.5 text-xs text-muted-foreground">MP4, WebM, MOV или MKV. Перетащите файл сюда или выберите его.</p>
</div>
<Button size="sm" variant="outline" disabled={localVideoUpload?.status === "uploading"} onClick={() => localVideoInputRef.current?.click()}>
<Upload data-icon="inline-start" />
Выбрать файл
</Button>
</div>
{localVideoUpload ? (
<div className="mt-3 border-t pt-3" aria-live="polite">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="truncate text-sm font-medium" title={localVideoUpload.name}>{localVideoUpload.name}</p>
<p className={`mt-0.5 text-xs ${localVideoUpload.status === "error" ? "text-destructive" : "text-muted-foreground"}`}>
{localVideoUpload.status === "uploading"
? `Загружено ${formatFileSize(localVideoUpload.loaded)} из ${formatFileSize(localVideoUpload.total)}`
: localVideoUpload.status === "complete"
? `Загружено ${formatFileSize(localVideoUpload.total)}. Файл готов к обработке.`
: localVideoUpload.status === "cancelled"
? "Загрузка отменена."
: localVideoUpload.errorMessage || "Не удалось загрузить файл."}
</p>
</div>
{localVideoUpload.status === "uploading" ? (
<Button size="icon" variant="outline" title="Отменить загрузку" aria-label="Отменить загрузку" onClick={cancelLocalVideoUpload}>
<X className="size-4" />
</Button>
) : (
<Button size="icon" variant="ghost" title="Скрыть статус" aria-label="Скрыть статус" onClick={() => setLocalVideoUpload(null)}>
<X className="size-4" />
</Button>
)}
</div>
<div className="mt-2 flex items-center gap-3">
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted">
<div
className={localVideoUpload.status === "error" ? "h-full rounded-full bg-destructive transition-all" : "h-full rounded-full bg-primary transition-all"}
style={{ width: `${localVideoUpload.status === "complete" ? 100 : localUploadPercent}%` }}
/>
</div>
<span className="w-10 text-right text-xs tabular-nums text-muted-foreground">
{localVideoUpload.status === "uploading" ? `${localUploadPercent}%` : localVideoUpload.status === "complete" ? "100%" : ""}
</span>
</div>
</div>
) : null}
</section>
<section className={`rounded-md border bg-background p-3 ${videoStorageLow ? "border-amber-300 bg-amber-50/60" : "border-border"}`} aria-live="polite">
<div className="flex items-center justify-between gap-2">
<p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Видео на диске</p>
{videoStorage ? <span className="text-xs tabular-nums text-muted-foreground">{videoStoragePercent}%</span> : null}
</div>
{videoStorage ? (
<>
<div className="mt-3 h-1.5 overflow-hidden rounded-full bg-muted">
<div className={`h-full rounded-full transition-all ${videoStorageLow ? "bg-amber-500" : "bg-primary"}`} style={{ width: `${videoStoragePercent}%` }} />
</div>
<p className={`mt-2 text-xs leading-5 ${videoStorageLow ? "text-amber-800" : "text-muted-foreground"}`}>
Свободно {formatFileSize(videoStorage.freeBytes)} из {formatFileSize(videoStorage.totalBytes)}
</p>
</>
) : (
<p className="mt-3 text-xs leading-5 text-muted-foreground">Данные о диске недоступны.</p>
)}
</section>
</div>
{productionVideos.length > 0 ? ( {productionVideos.length > 0 ? (
productionVideos.map((video) => { productionVideos.map((video) => {
const draftArticles = video.articles?.filter((article) => article.status !== "published") ?? [] const draftArticles = video.articles?.filter((article) => article.status !== "published") ?? []