dzen.nstarikov.ru/dzen-assistant/admin/src/App.tsx

1209 lines
48 KiB
TypeScript
Raw Normal View History

2026-06-27 14:07:10 +03:00
import { useEffect, useMemo, useRef, useState } from "react"
import EditorJS, { type BlockAPI, type OutputData, type ToolConstructable } from "@editorjs/editorjs"
import Header from "@editorjs/header"
import ImageTool from "@editorjs/image"
import List from "@editorjs/list"
import Quote from "@editorjs/quote"
import {
AlertTriangle,
CheckCircle2,
Clock3,
ExternalLink,
FilePenLine,
FileText,
ImagePlus,
Loader2,
Radio,
RefreshCw,
Save,
Shuffle,
Sparkles,
Trash2,
X,
} from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Textarea } from "@/components/ui/textarea"
type Dashboard = {
sources: number
videos: number
newVideos: number
processingVideos: number
drafts: number
scheduled: number
published: number
}
type VideoArticle = {
id: number
title: string
status: string
}
type Video = {
id: number
title: string
sourceUrl: string
status: string
progressPercent: number
progressStage: string
durationSeconds?: number
createdAt?: string
publishedAt?: string
errorMessage?: string
articleIds: number[]
articles?: VideoArticle[]
}
type Article = {
id: number
title: string
slug: string
status: string
url: string
createdAt?: string
publishedAt?: string
}
type ArticlesPage = {
items: Article[]
total: number
limit: number
offset: number
hasMore: boolean
}
type ArticleDetail = Article & {
contentHtml: string
editableHtml: string
videoId?: number
}
type VideoLog = {
id: number
title: string
status: string
progressPercent: number
progressStage: string
progressLog: string
errorMessage?: string
}
type EditorBlock = OutputData["blocks"][number]
type RandomFrameTuneConfig = {
onReplace?: (block: BlockAPI) => void | Promise<void>
}
const ARTICLES_PAGE_SIZE = 10
class RandomFrameTune {
private readonly block: BlockAPI
private readonly config: RandomFrameTuneConfig
static get isTune() {
return true
}
constructor({ block, config }: { block: BlockAPI; config?: RandomFrameTuneConfig }) {
this.block = block
this.config = config ?? {}
}
render() {
return {
icon: '<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 3h5v5"/><path d="M4 20 21 3"/><path d="M21 16v5h-5"/><path d="m15 15 6 6"/><path d="m4 4 5 5"/></svg>',
label: "Другой кадр",
onActivate: () => {
void this.config.onReplace?.(this.block)
},
}
}
}
const editorI18n = {
messages: {
ui: {
blockTunes: {
toggler: {
"Click to tune": "Настроить блок",
"or drag to move": "или перетащите",
},
},
inlineToolbar: {
converter: {
"Convert to": "Преобразовать в",
},
},
toolbar: {
toolbox: {
Add: "Добавить",
},
},
popover: {
Filter: "Фильтр",
"Nothing found": "Ничего не найдено",
"Convert to": "Преобразовать в",
},
},
toolNames: {
Text: "Текст",
Link: "Ссылка",
Bold: "Жирный",
Italic: "Курсив",
Heading: "Заголовок",
List: "Список",
Quote: "Цитата",
Image: "Изображение",
},
tools: {
link: {
"Add a link": "Вставьте ссылку",
},
stub: {
"The block can not be displayed correctly.": "Блок не может быть отображен корректно.",
},
header: {
"Heading 2": "Заголовок 2",
"Heading 3": "Заголовок 3",
"Enter a header": "Введите заголовок",
},
list: {
Ordered: "Нумерованный",
Unordered: "Маркированный",
},
quote: {
"Enter a quote": "Введите цитату",
"Enter a caption": "Автор или пояснение",
"Align Left": "По левому краю",
"Align Center": "По центру",
},
image: {
Caption: "Подпись",
"Select an Image": "Выбрать изображение",
"With border": "С рамкой",
"Stretch image": "Растянуть изображение",
"With background": "С фоном",
"With caption": "С подписью",
"Couldn’t upload image. Please try another.": "Не удалось загрузить изображение. Попробуйте другое.",
},
},
blockTunes: {
delete: {
Delete: "Удалить",
"Click to delete": "Нажмите, чтобы удалить",
},
moveUp: {
"Move up": "Переместить вверх",
},
moveDown: {
"Move down": "Переместить вниз",
},
randomFrame: {
"Другой кадр": "Другой кадр",
},
},
},
}
async function api<T>(path: string, init?: RequestInit): Promise<T> {
const isFormData = init?.body instanceof FormData
const response = await fetch(path, {
...init,
headers: { ...(isFormData ? {} : { "content-type": "application/json" }), ...(init?.headers ?? {}) },
})
if (!response.ok) {
throw new Error(await response.text())
}
return response.json() as Promise<T>
}
function escapeHtml(value: string) {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
}
function normalizeEditorText(value: string) {
const parser = new DOMParser()
const document = parser.parseFromString(`<main>${value || ""}</main>`, "text/html")
return (document.body.textContent || "")
.replace(/^#{1,6}\s*/, "")
.replace(/\s+/g, " ")
.trim()
.toLowerCase()
.replace(/ё/g, "е")
}
function stripLeadingDuplicateTitleBlock(blocks: EditorBlock[], title?: string) {
const normalizedTitle = normalizeEditorText(title || "")
if (!normalizedTitle || blocks.length === 0) return blocks
const first = blocks[0]
if (!["paragraph", "header"].includes(first.type)) return blocks
const text = normalizeEditorText(String((first.data as Record<string, unknown>).text || ""))
return text === normalizedTitle ? blocks.slice(1) : blocks
}
function htmlToEditorData(html: string, title?: string): OutputData {
const parser = new DOMParser()
const document = parser.parseFromString(`<main>${html || ""}</main>`, "text/html")
const root = document.querySelector("main")
const blocks: EditorBlock[] = []
function pushParagraph(element: Element) {
const text = element.innerHTML.trim()
if (text) {
blocks.push({ type: "paragraph", data: { text } })
}
}
root?.childNodes.forEach((node) => {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent?.trim()
if (text) {
blocks.push({ type: "paragraph", data: { text: escapeHtml(text) } })
}
return
}
if (!(node instanceof Element)) return
const tag = node.tagName.toLowerCase()
if (tag === "p") {
pushParagraph(node)
return
}
if (tag === "h2" || tag === "h3") {
blocks.push({ type: "header", data: { text: node.innerHTML.trim(), level: tag === "h2" ? 2 : 3 } })
return
}
if (tag === "blockquote") {
blocks.push({ type: "quote", data: { text: node.innerHTML.trim(), caption: "", alignment: "left" } })
return
}
if (tag === "ul" || tag === "ol") {
const items = Array.from(node.querySelectorAll(":scope > li")).map((item) => item.innerHTML.trim()).filter(Boolean)
blocks.push({ type: "list", data: { style: tag === "ol" ? "ordered" : "unordered", items } })
return
}
if (tag === "figure") {
const image = node.querySelector("img")
if (!image) return
blocks.push({
type: "image",
data: {
file: { url: image.getAttribute("src") || "" },
caption: node.querySelector("figcaption")?.innerHTML.trim() || image.getAttribute("alt") || "",
withBorder: false,
withBackground: false,
stretched: false,
},
})
return
}
pushParagraph(node)
})
const cleanBlocks = stripLeadingDuplicateTitleBlock(blocks, title)
return {
time: Date.now(),
blocks: cleanBlocks.length ? cleanBlocks : [{ type: "paragraph", data: { text: "" } }],
version: "2.30.8",
}
}
function editorDataToHtml(data: OutputData, title?: string): string {
return stripLeadingDuplicateTitleBlock(data.blocks || [], title)
.map((block) => {
const item = block.data as Record<string, any>
if (block.type === "header") {
const level = item.level === 3 ? 3 : 2
return `<h${level}>${item.text || ""}</h${level}>`
}
if (block.type === "list") {
const tag = item.style === "ordered" ? "ol" : "ul"
const items = Array.isArray(item.items) ? item.items : []
return `<${tag}>${items.map((value) => `<li>${value}</li>`).join("")}</${tag}>`
}
if (block.type === "quote") {
return `<blockquote>${item.text || ""}</blockquote>`
}
if (block.type === "image") {
const url = item.file?.url || item.url || ""
if (!url) return ""
const caption = item.caption || ""
return `<figure><img src="${escapeHtml(url)}" alt="${escapeHtml(caption)}"><figcaption>${caption}</figcaption></figure>`
}
return `<p>${item.text || ""}</p>`
})
.filter(Boolean)
.join("\n")
}
function formatDuration(seconds?: number) {
if (!seconds) return "—"
const minutes = Math.floor(seconds / 60)
const rest = seconds % 60
return `${minutes}:${String(rest).padStart(2, "0")}`
}
function parseApiDate(value?: string) {
if (!value) return null
const normalized = /(?:z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z`
const date = new Date(normalized)
return Number.isNaN(date.getTime()) ? null : date
}
function toDateTimeLocalValue(value?: string) {
const date = parseApiDate(value)
if (!date) return ""
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
return local.toISOString().slice(0, 16)
}
function currentDateTimeLocalValue() {
const date = new Date()
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
return local.toISOString().slice(0, 16)
}
function formatDateTime(value?: string) {
const date = parseApiDate(value)
if (!date) return ""
return new Intl.DateTimeFormat("ru-RU", {
day: "2-digit",
month: "short",
hour: "2-digit",
minute: "2-digit",
}).format(date)
}
function formatVideoDate(value?: string) {
const date = parseApiDate(value)
if (!date) return "дата неизвестна"
return new Intl.DateTimeFormat("ru-RU", {
day: "2-digit",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(date)
}
function isScheduledForFuture(value?: string) {
const date = parseApiDate(value)
return Boolean(date && date.getTime() > Date.now())
}
function dateSortValue(value?: string) {
return parseApiDate(value)?.getTime() ?? 0
}
function statusVariant(status: string) {
if (status === "published" || status === "drafted") return "default"
if (status === "error") return "destructive"
if (status === "processing") return "secondary"
return "outline"
}
function StatusBadge({ status }: { status: string }) {
const normalized = status.toLowerCase()
if (normalized === "published") {
return (
<Badge className="gap-1.5 border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-50" variant="outline">
<CheckCircle2 className="size-3.5" />
Опубликовано
</Badge>
)
}
if (normalized === "drafted" || normalized === "draft") {
return (
<Badge className="gap-1.5 border-zinc-200 bg-zinc-100 text-zinc-600 hover:bg-zinc-100" variant="outline">
<FilePenLine className="size-3.5" />
Черновик
</Badge>
)
}
if (normalized === "error") {
return (
<Badge className="gap-1.5" variant="destructive">
<AlertTriangle className="size-3.5" />
Ошибка
</Badge>
)
}
if (normalized === "processing" || normalized === "queued") {
return (
<Badge className="gap-1.5 border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-50" variant="outline">
{normalized === "processing" ? <Loader2 className="size-3.5 animate-spin" /> : <Clock3 className="size-3.5" />}
{normalized === "processing" ? "В работе" : "В очереди"}
</Badge>
)
}
return <Badge variant={statusVariant(status)}>{status}</Badge>
}
function ArticlePlaceholder() {
return (
<div className="rounded-md border bg-background p-4">
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<div className="h-6 w-24 animate-pulse rounded-full bg-muted" />
<div className="h-4 flex-1 animate-pulse rounded bg-muted" />
</div>
<div className="mt-3 h-3 w-5/6 animate-pulse rounded bg-muted" />
<div className="mt-2 h-3 w-40 animate-pulse rounded bg-muted" />
</div>
<div className="flex shrink-0 gap-2">
<div className="size-9 animate-pulse rounded-md bg-muted" />
<div className="size-9 animate-pulse rounded-md bg-muted" />
<div className="size-9 animate-pulse rounded-md bg-muted" />
</div>
</div>
</div>
)
}
export default function App() {
const [dashboard, setDashboard] = useState<Dashboard | null>(null)
const [videos, setVideos] = useState<Video[]>([])
const [articles, setArticles] = useState<Article[]>([])
const [articlesHasMore, setArticlesHasMore] = useState(false)
const [articlesLoading, setArticlesLoading] = useState(false)
const [selectedLog, setSelectedLog] = useState<VideoLog | null>(null)
const [selectedArticle, setSelectedArticle] = useState<ArticleDetail | null>(null)
const [editorTitle, setEditorTitle] = useState("")
const [publishAt, setPublishAt] = useState("")
const [editorDirty, setEditorDirty] = useState(false)
const [editorBusy, setEditorBusy] = useState(false)
const [statusMessage, setStatusMessage] = useState("")
const [busy, setBusy] = useState(false)
const [videoActionId, setVideoActionId] = useState<number | null>(null)
const editorHolderRef = useRef<HTMLDivElement | null>(null)
const editorInstanceRef = useRef<EditorJS | null>(null)
const fileInputRef = useRef<HTMLInputElement | null>(null)
const logSocketRef = useRef<WebSocket | null>(null)
const selectedArticleRef = useRef<ArticleDetail | null>(null)
const editorTitleRef = useRef("")
const titleTextareaRef = useRef<HTMLTextAreaElement | null>(null)
const articlesOffsetRef = useRef(0)
const articlesLoadingRef = useRef(false)
const articlesHasMoreRef = useRef(false)
const feedUrl = useMemo(() => `${window.location.origin}/feed`, [])
const productionVideos = useMemo(
() =>
videos
.filter((video) => !video.articles?.some((article) => article.status === "published"))
.sort((a, b) => dateSortValue(b.publishedAt || b.createdAt) - dateSortValue(a.publishedAt || a.createdAt)),
[videos]
)
const activeVideos = useMemo(() => productionVideos.filter((video) => ["queued", "processing"].includes(video.status)), [productionVideos])
const publishedArticles = useMemo(
() =>
articles
.filter((article) => article.status === "published")
.sort((a, b) => dateSortValue(b.publishedAt || b.createdAt) - dateSortValue(a.publishedAt || a.createdAt)),
[articles]
)
async function loadArticlesPage(reset = false) {
if (articlesLoadingRef.current) return
const offset = reset ? 0 : articlesOffsetRef.current
articlesLoadingRef.current = true
setArticlesLoading(true)
try {
const page = await api<ArticlesPage>(`/api/articles?status=published&limit=${ARTICLES_PAGE_SIZE}&offset=${offset}`)
articlesOffsetRef.current = offset + page.items.length
articlesHasMoreRef.current = page.hasMore
setArticlesHasMore(page.hasMore)
setArticles((current) => {
if (reset) return page.items
const existingIds = new Set(current.map((article) => article.id))
return [...current, ...page.items.filter((article) => !existingIds.has(article.id))]
})
} finally {
articlesLoadingRef.current = false
setArticlesLoading(false)
}
}
async function refresh() {
const showArticlePlaceholders = articlesOffsetRef.current === 0
if (showArticlePlaceholders) {
setArticlesLoading(true)
}
try {
const [nextDashboard, nextVideos, nextArticles] = await Promise.all([
api<Dashboard>("/api/dashboard"),
api<Video[]>("/api/videos"),
api<ArticlesPage>(`/api/articles?status=published&limit=${ARTICLES_PAGE_SIZE}&offset=0`),
])
setDashboard(nextDashboard)
setVideos(nextVideos)
setArticles(nextArticles.items)
articlesOffsetRef.current = nextArticles.items.length
articlesHasMoreRef.current = nextArticles.hasMore
setArticlesHasMore(nextArticles.hasMore)
} finally {
if (showArticlePlaceholders) {
setArticlesLoading(false)
}
}
}
useEffect(() => {
refresh().catch((error) => {
setStatusMessage(`Ошибка загрузки: ${error.message}`)
})
}, [])
useEffect(() => {
if (activeVideos.length === 0) return
const timer = window.setInterval(() => {
refresh().catch((error) => {
setStatusMessage(`Ошибка обновления: ${error.message}`)
})
}, 5000)
return () => window.clearInterval(timer)
}, [activeVideos.length])
useEffect(() => () => {
logSocketRef.current?.close()
}, [])
useEffect(() => {
selectedArticleRef.current = selectedArticle
}, [selectedArticle])
useEffect(() => {
editorTitleRef.current = editorTitle
const element = titleTextareaRef.current
if (element) {
element.style.height = "auto"
element.style.height = `${element.scrollHeight}px`
}
}, [editorTitle])
async function scanSources() {
setBusy(true)
try {
const result = await api<{ taskId: string }>("/api/sources/scan", { method: "POST" })
setStatusMessage(`Проверяю VK Видео. Task: ${result.taskId}`)
await refresh()
} finally {
setBusy(false)
}
}
async function processVideo(id: number, restart = false) {
setVideoActionId(id)
try {
const result = await api<{ taskId: string }>(`/api/videos/${id}/process`, { method: "POST" })
setStatusMessage(`${restart ? "Перезапустил" : "Поставил"} ролик #${id} в обработку. Task: ${result.taskId}`)
await refresh()
} finally {
setVideoActionId(null)
}
}
async function openVideoLog(id: number) {
logSocketRef.current?.close()
const result = await api<VideoLog>(`/api/videos/${id}/logs`)
setSelectedLog(result)
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"
const socket = new WebSocket(`${protocol}//${window.location.host}/api/videos/${id}/logs/ws`)
logSocketRef.current = socket
socket.onmessage = (event) => {
try {
setSelectedLog(JSON.parse(event.data) as VideoLog)
} catch {
// Ignore malformed frames; the next server tick will replace the state.
}
}
socket.onerror = () => {
setStatusMessage("Не удалось подключиться к live-логам. Показываю последний полученный лог.")
}
socket.onclose = () => {
if (logSocketRef.current === socket) {
logSocketRef.current = null
}
}
}
function closeVideoLog() {
logSocketRef.current?.close()
logSocketRef.current = null
setSelectedLog(null)
}
async function openArticlePreview(id: number) {
const result = await api<ArticleDetail>(`/api/articles/${id}`)
setSelectedArticle(result)
setEditorTitle(result.title)
setPublishAt(toDateTimeLocalValue(result.publishedAt) || currentDateTimeLocalValue())
setEditorDirty(false)
}
async function publishArticle(id: number, scheduledAt?: string) {
const result = await api<{ url: string; publishedAt?: string }>(`/api/articles/${id}/publish`, {
method: "POST",
body: JSON.stringify({ publishedAt: scheduledAt || null }),
})
const isFuture = isScheduledForFuture(result.publishedAt)
setStatusMessage(isFuture ? `Запланировал статью на ${formatDateTime(result.publishedAt)}: ${result.url}` : `Принял статью и отправил в RSS: ${result.url}`)
await refresh()
}
async function uploadImage(file: File) {
const body = new FormData()
body.append("file", file)
const result = await api<{ url: string }>("/api/uploads/images", {
method: "POST",
body,
})
return result.url
}
useEffect(() => {
if (!selectedArticle || !editorHolderRef.current) return
editorInstanceRef.current?.destroy()
editorHolderRef.current.innerHTML = ""
const editor = new EditorJS({
holder: editorHolderRef.current,
data: htmlToEditorData(selectedArticle.editableHtml || selectedArticle.contentHtml, selectedArticle.title),
autofocus: false,
placeholder: "Начните писать...",
inlineToolbar: ["bold", "italic", "link"],
i18n: editorI18n,
tools: {
header: {
class: Header as unknown as ToolConstructable,
inlineToolbar: ["bold", "italic", "link"],
config: {
levels: [2, 3],
defaultLevel: 2,
placeholder: "Введите заголовок",
},
},
list: {
class: List as unknown as ToolConstructable,
inlineToolbar: true,
},
quote: {
class: Quote as unknown as ToolConstructable,
inlineToolbar: true,
config: {
quotePlaceholder: "Цитата",
captionPlaceholder: "",
},
},
image: {
class: ImageTool as unknown as ToolConstructable,
tunes: ["randomFrame"],
config: {
captionPlaceholder: "Подпись к изображению",
uploader: {
uploadByFile: async (file: File) => ({
success: 1,
file: { url: await uploadImage(file) },
}),
uploadByUrl: async (url: string) => ({
success: 1,
file: { url },
}),
},
},
},
randomFrame: {
class: RandomFrameTune as unknown as ToolConstructable,
config: {
onReplace: replaceWithRandomFrame,
},
},
},
onChange: () => setEditorDirty(true),
})
editorInstanceRef.current = editor
editor.isReady.catch((error) => {
setStatusMessage(`Ошибка редактора: ${error}`)
})
return () => {
if (editorInstanceRef.current === editor) {
editorInstanceRef.current = null
}
editor.destroy()
}
}, [selectedArticle?.id])
async function insertImageFile(file: File) {
if (!file.type.startsWith("image/")) return
setEditorBusy(true)
try {
const url = await uploadImage(file)
const caption = editorTitle || selectedArticle?.title || file.name
editorInstanceRef.current?.blocks.insert("image", { file: { url }, caption })
setEditorDirty(true)
} finally {
setEditorBusy(false)
}
}
async function replaceWithRandomFrame(blockToReplace?: BlockAPI) {
const article = selectedArticleRef.current
if (!article?.videoId || !editorInstanceRef.current) return
const editor = editorInstanceRef.current
const index = editor.blocks.getCurrentBlockIndex()
const block = blockToReplace ?? (index >= 0 ? editor.blocks.getBlockByIndex(index) : undefined)
setEditorBusy(true)
block?.holder.classList.add("is-random-frame-loading")
try {
const result = await api<{ url: string; timestampSeconds: number }>(`/api/articles/${article.id}/random-frame`, { method: "POST" })
const data = {
file: { url: result.url },
caption: `${editorTitleRef.current || article.title} (${formatDuration(result.timestampSeconds)})`,
withBorder: false,
withBackground: false,
stretched: false,
}
if (block?.name === "image") {
await editor.blocks.update(block.id, data)
} else {
editor.blocks.insert("image", data, undefined, index >= 0 ? index + 1 : undefined, true)
}
setEditorDirty(true)
} finally {
block?.holder.classList.remove("is-random-frame-loading")
setEditorBusy(false)
}
}
async function saveArticle(showMessage = true) {
if (!selectedArticle) return selectedArticle
setEditorBusy(true)
try {
const editorData = await editorInstanceRef.current?.save()
const result = await api<ArticleDetail>(`/api/articles/${selectedArticle.id}`, {
method: "PATCH",
body: JSON.stringify({
title: editorTitle,
editableHtml: editorDataToHtml(editorData ?? htmlToEditorData("", editorTitle), editorTitle),
}),
})
setSelectedArticle(result)
setEditorTitle(result.title)
setEditorDirty(false)
await refresh()
if (showMessage) {
setStatusMessage(`Сохранил статью: ${result.title}`)
}
return result
} finally {
setEditorBusy(false)
}
}
async function saveAndPublishArticle() {
if (!selectedArticle) return
const article = editorDirty ? await saveArticle(false) : selectedArticle
if (!article) return
const scheduledAt = publishAt ? new Date(publishAt).toISOString() : undefined
await publishArticle(article.id, scheduledAt)
setSelectedArticle(null)
}
async function deleteArticle(id: number) {
const articleTitle = selectedArticle?.id === id ? selectedArticle.title : articles.find((article) => article.id === id)?.title
if (!window.confirm(`Удалить статью${articleTitle ? ` «${articleTitle}»` : ""}? Она пропадёт из списка и RSS.`)) return
await api<{ id: number; status: string }>(`/api/articles/${id}`, { method: "DELETE" })
setStatusMessage(`Удалил статью${articleTitle ? `: ${articleTitle}` : ""}`)
if (selectedArticle?.id === id) {
setSelectedArticle(null)
}
await refresh()
}
async function deleteVideo(id: number, title?: string) {
if (!window.confirm(`Удалить ролик${title ? ` «${title}»` : ""}? Он исчезнет из списка и больше не будет импортироваться из VK.`)) return
setVideoActionId(id)
try {
await api<{ id: number; status: string }>(`/api/videos/${id}`, { method: "DELETE" })
setStatusMessage(`Удалил ролик${title ? `: ${title}` : ""}. Он исключен из повторного импорта.`)
await refresh()
} finally {
setVideoActionId(null)
}
}
return (
<main className="min-h-screen bg-muted/35">
<div className="mx-auto flex w-full max-w-[1920px] flex-col gap-6 p-6">
<header className="flex flex-col gap-4 rounded-lg border bg-background p-5 md:flex-row md:items-center md:justify-between">
<div className="flex items-center gap-3">
<div className="flex size-10 items-center justify-center rounded-md bg-primary text-primary-foreground">
<Sparkles />
</div>
<div>
<h1 className="text-2xl font-semibold tracking-normal">Дзен-ассистент</h1>
<p className="text-sm text-muted-foreground">RSS-конвейер для статей из видео Николая Старикова</p>
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button variant="outline" onClick={() => window.open(feedUrl, "_blank")}>
<ExternalLink data-icon="inline-start" />
RSS
</Button>
<Button disabled={busy} onClick={scanSources}>
<RefreshCw data-icon="inline-start" />
Проверить VK
</Button>
</div>
</header>
<section className="grid gap-4 md:grid-cols-3 lg:grid-cols-6">
{[
["Ролики", dashboard?.videos ?? 0],
["Новые", dashboard?.newVideos ?? 0],
["В работе", dashboard?.processingVideos ?? 0],
["Черновики", dashboard?.drafts ?? 0],
["Запланировано", dashboard?.scheduled ?? 0],
["В RSS", dashboard?.published ?? 0],
].map(([label, value]) => (
<Card key={label}>
<CardHeader className="p-4">
<CardDescription>{label}</CardDescription>
<CardTitle className="text-2xl">{value}</CardTitle>
</CardHeader>
</Card>
))}
</section>
{statusMessage ? <div className="rounded-md border bg-background px-4 py-3 text-sm text-muted-foreground">{statusMessage}</div> : null}
<section className="grid gap-6 xl:grid-cols-[minmax(0,1.15fr)_minmax(480px,0.85fr)]">
<Card className="min-w-0">
<CardHeader>
<div className="flex items-start justify-between gap-4">
<div>
<CardTitle>Ролики</CardTitle>
<CardDescription>Все ролики, прогресс обработки, логи и готовые черновики в одном списке.</CardDescription>
</div>
<Badge className={activeVideos.length ? "border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-50" : ""} variant="outline">{activeVideos.length} в работе</Badge>
</div>
</CardHeader>
<CardContent className="flex max-h-[72vh] flex-col gap-3 overflow-y-auto">
{productionVideos.length > 0 ? (
productionVideos.map((video) => {
const draftArticle = video.articles?.find((article) => article.status !== "published")
const publishedArticle = video.articles?.find((article) => article.status === "published")
const fallbackArticleId = video.articleIds?.[0]
const draftArticleId = draftArticle?.id ?? (publishedArticle ? undefined : fallbackArticleId)
const progress = Math.max(0, Math.min(100, video.progressPercent || 0))
const hasStarted = video.status !== "new" || progress > 0
const isActive = ["queued", "processing"].includes(video.status)
const isSubmitting = videoActionId === video.id
const hasDraftAction = Boolean(draftArticleId)
return (
<div key={video.id} className="rounded-md border bg-background p-3">
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
{!hasDraftAction && !publishedArticle ? <StatusBadge status={video.status} /> : null}
{publishedArticle ? <StatusBadge status="published" /> : null}
<h3 className="min-w-0 flex-1 truncate text-sm font-semibold">{video.title || `Ролик #${video.id}`}</h3>
</div>
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
<span>Опубликовано: {formatVideoDate(video.publishedAt)}</span>
<span>Длительность: {formatDuration(video.durationSeconds)}</span>
</div>
{hasStarted && video.progressStage ? <p className="mt-2 line-clamp-2 text-sm text-muted-foreground">{video.progressStage}</p> : null}
{video.errorMessage ? <p className="mt-2 text-sm text-destructive">{video.errorMessage}</p> : null}
</div>
<div className="flex shrink-0 flex-wrap gap-2">
{draftArticleId ? (
<Button size="sm" onClick={() => openArticlePreview(draftArticleId)}>
<FileText data-icon="inline-start" />
Черновик
</Button>
) : publishedArticle ? (
<Button size="sm" variant="outline" onClick={() => openArticlePreview(publishedArticle.id)}>
<FileText data-icon="inline-start" />
Статья
</Button>
) : isActive ? (
<Button
size="sm"
variant="outline"
disabled={isSubmitting}
className="border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-100 hover:text-amber-900"
onClick={() => processVideo(video.id, true)}
>
<RefreshCw data-icon="inline-start" className={isSubmitting ? "animate-spin" : ""} />
Перезапустить
</Button>
) : (
<Button
size="icon"
variant="outline"
disabled={isSubmitting}
title="Обработать"
aria-label="Обработать"
onClick={() => processVideo(video.id)}
>
<RefreshCw className="size-4" />
</Button>
)}
<Button size="icon" variant="outline" title="Логи" aria-label="Логи" onClick={() => openVideoLog(video.id)}>
<FileText className="size-4" />
</Button>
<Button
size="icon"
variant="outline"
disabled={isSubmitting}
title="Удалить ролик и больше не импортировать"
aria-label="Удалить ролик и больше не импортировать"
onClick={() => deleteVideo(video.id, video.title)}
>
<Trash2 className="size-4" />
</Button>
</div>
</div>
{hasStarted ? (
<div className="mt-4 flex items-center gap-3">
<div className="h-2 flex-1 overflow-hidden rounded-full bg-muted">
<div className="h-full rounded-full bg-primary transition-all" style={{ width: `${progress}%` }} />
</div>
<span className="w-12 text-right text-sm tabular-nums text-muted-foreground">{progress}%</span>
</div>
) : null}
</div>
)
})
) : (
<div className="rounded-md border border-dashed p-6 text-sm text-muted-foreground">Новых роликов и черновиков пока нет. Готовые материалы находятся в колонке «Статьи».</div>
)}
</CardContent>
</Card>
<Card className="min-w-0">
<CardHeader>
<CardTitle>Статьи</CardTitle>
<CardDescription>Принятые материалы: уже вышедшие в RSS и отложенные по времени.</CardDescription>
</CardHeader>
<CardContent
className="flex max-h-[72vh] flex-col gap-3 overflow-y-auto"
onScroll={(event) => {
const element = event.currentTarget
const distanceToBottom = element.scrollHeight - element.scrollTop - element.clientHeight
if (distanceToBottom < 180 && articlesHasMoreRef.current) {
void loadArticlesPage()
}
}}
>
{publishedArticles.length > 0 ? (
publishedArticles.map((article) => (
<div key={article.id} className="rounded-md border bg-background p-4">
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
<button className="min-w-0 flex-1 text-left" onClick={() => openArticlePreview(article.id)}>
<div className="flex flex-wrap items-center gap-2">
{isScheduledForFuture(article.publishedAt) ? (
<Badge className="gap-1.5 border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-50" variant="outline">
<Clock3 className="size-3.5" />
Отложено
</Badge>
) : (
<StatusBadge status={article.status} />
)}
<h3 className="min-w-0 flex-1 truncate text-sm font-semibold">{article.title}</h3>
</div>
<p className="mt-2 truncate text-xs text-muted-foreground">{article.url}</p>
{article.publishedAt ? (
<p className="mt-1 text-xs text-muted-foreground">
{isScheduledForFuture(article.publishedAt) ? "Выйдет в RSS" : "В RSS"}: {formatDateTime(article.publishedAt)}
</p>
) : null}
</button>
<div className="flex shrink-0 flex-wrap gap-2">
<Button size="icon" variant="outline" title="Открыть редактор" aria-label="Открыть редактор" onClick={() => openArticlePreview(article.id)}>
<FileText className="size-4" />
</Button>
<Button size="icon" variant="outline" title="Удалить" aria-label="Удалить" onClick={() => deleteArticle(article.id)}>
<Trash2 className="size-4" />
</Button>
<Button size="icon" variant="outline" title="Открыть на сайте" aria-label="Открыть на сайте" onClick={() => window.open(article.url, "_blank")}>
<ExternalLink className="size-4" />
</Button>
</div>
</div>
</div>
))
) : articlesLoading ? (
Array.from({ length: 5 }).map((_, index) => <ArticlePlaceholder key={`article-placeholder-initial-${index}`} />)
) : (
<div className="rounded-md border border-dashed p-6 text-sm text-muted-foreground">Принятых статей пока нет. Черновики открываются из роликов слева.</div>
)}
{publishedArticles.length > 0 && articlesLoading
? Array.from({ length: 3 }).map((_, index) => <ArticlePlaceholder key={`article-placeholder-more-${index}`} />)
: null}
{articlesHasMore && !articlesLoading ? (
<Button variant="outline" className="mt-1" onClick={() => loadArticlesPage()}>
<RefreshCw data-icon="inline-start" />
Загрузить еще
</Button>
) : null}
</CardContent>
</Card>
</section>
</div>
{selectedLog ? (
<div className="modal-overlay fixed inset-0 z-50 flex items-center justify-center bg-background/80 p-4 backdrop-blur-sm">
<div className="modal-panel flex max-h-[82vh] w-full max-w-3xl flex-col rounded-lg border bg-background shadow-lg">
<div className="flex items-start justify-between gap-4 border-b p-5">
<div className="min-w-0">
<h2 className="text-lg font-semibold tracking-normal">Логи обработки</h2>
<p className="mt-1 truncate text-sm text-muted-foreground">{selectedLog.title || `Ролик #${selectedLog.id}`}</p>
</div>
<Button variant="outline" size="sm" onClick={closeVideoLog}>
Закрыть
</Button>
</div>
<div className="flex flex-col gap-4 overflow-y-auto p-5">
<div className="grid gap-3 md:grid-cols-3">
<div className="rounded-md border p-3">
<p className="text-xs text-muted-foreground">Статус</p>
<Badge className="mt-2" variant={statusVariant(selectedLog.status)}>
{selectedLog.status}
</Badge>
</div>
<div className="rounded-md border p-3">
<p className="text-xs text-muted-foreground">Этап</p>
<p className="mt-2 text-sm font-medium">{selectedLog.progressStage || "—"}</p>
</div>
<div className="rounded-md border p-3">
<p className="text-xs text-muted-foreground">Прогресс</p>
<p className="mt-2 text-sm font-medium">{selectedLog.progressPercent || 0}%</p>
</div>
</div>
{selectedLog.errorMessage ? <p className="rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">{selectedLog.errorMessage}</p> : null}
<pre className="max-h-[46vh] overflow-auto rounded-md border bg-muted/40 p-4 text-xs leading-5 text-foreground">
{selectedLog.progressLog || "Лог пока пуст."}
</pre>
</div>
</div>
</div>
) : null}
{selectedArticle ? (
<div className="modal-overlay fixed inset-0 z-50 flex items-center justify-center bg-background/80 p-3 backdrop-blur-sm">
<div className="modal-panel flex max-h-[92vh] w-full max-w-[1280px] flex-col overflow-hidden rounded-lg border bg-background shadow-lg">
<div className="flex items-start justify-between gap-4 border-b p-5">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
{isScheduledForFuture(selectedArticle.publishedAt) ? (
<Badge className="gap-1.5 border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-50" variant="outline">
<Clock3 className="size-3.5" />
Отложено
</Badge>
) : (
<StatusBadge status={selectedArticle.status} />
)}
<h2 className="min-w-0 flex-1 truncate text-lg font-semibold tracking-normal">Редактирование статьи</h2>
{editorDirty ? <Badge variant="secondary">есть правки</Badge> : null}
</div>
<p className="mt-1 text-sm text-muted-foreground">Редактируйте блоки как в Medium. Для картинки выберите image-блок и нажмите кнопку случайного кадра.</p>
</div>
<div className="flex shrink-0 flex-wrap justify-end gap-2">
<input
ref={fileInputRef}
className="hidden"
type="file"
accept="image/*"
onChange={async (event) => {
const file = event.currentTarget.files?.[0]
event.currentTarget.value = ""
if (file) await insertImageFile(file)
}}
/>
<Button
size="icon"
variant="outline"
disabled={editorBusy}
title="Вставить картинку"
aria-label="Вставить картинку"
onClick={() => {
fileInputRef.current?.click()
}}
>
<ImagePlus className="size-4" />
</Button>
<Button
size="icon"
variant="outline"
disabled={editorBusy || !selectedArticle.videoId}
title="Другой случайный кадр из видео"
aria-label="Другой случайный кадр из видео"
onClick={() => replaceWithRandomFrame()}
>
<Shuffle className="size-4" />
</Button>
<Button size="icon" variant="outline" disabled={editorBusy || !editorDirty} title="Сохранить" aria-label="Сохранить" onClick={() => saveArticle()}>
<Save className="size-4" />
</Button>
{selectedArticle.status !== "published" || isScheduledForFuture(selectedArticle.publishedAt) ? (
<>
<label className="flex h-9 items-center gap-2 rounded-md border bg-background px-3 text-xs text-muted-foreground" title="Время выхода в RSS">
<Clock3 className="size-4" />
<input
type="datetime-local"
className="w-[190px] bg-transparent text-sm text-foreground outline-none"
value={publishAt}
onChange={(event) => setPublishAt(event.target.value)}
/>
</label>
<Button size="icon" disabled={editorBusy} title="Запланировать или принять в RSS" aria-label="Запланировать или принять в RSS" onClick={saveAndPublishArticle}>
<Radio className="size-4" />
</Button>
</>
) : (
<Button size="icon" variant="outline" title="Открыть на сайте" aria-label="Открыть на сайте" onClick={() => window.open(selectedArticle.url, "_blank")}>
<ExternalLink className="size-4" />
</Button>
)}
<Button size="icon" variant="outline" disabled={editorBusy} title="Удалить" aria-label="Удалить" onClick={() => deleteArticle(selectedArticle.id)}>
<Trash2 className="size-4" />
</Button>
<Button variant="outline" size="icon" title="Закрыть" aria-label="Закрыть" onClick={() => setSelectedArticle(null)}>
<X className="size-4" />
</Button>
</div>
</div>
<div className="overflow-y-auto bg-zinc-50 p-4 sm:p-6">
<article className="mx-auto w-full max-w-[1024px] rounded-lg border bg-white px-5 py-7 shadow-sm sm:px-8 lg:px-10">
<Textarea
ref={titleTextareaRef}
rows={1}
className="mx-auto h-auto min-h-0 max-w-3xl resize-none overflow-hidden border-0 bg-transparent px-0 py-0 text-3xl font-bold leading-tight tracking-normal text-zinc-950 shadow-none focus-visible:ring-0 sm:text-4xl"
value={editorTitle}
onChange={(event) => {
setEditorTitle(event.target.value)
setEditorDirty(true)
}}
/>
<div
key={selectedArticle.id}
ref={editorHolderRef}
className="article-editor article-editorjs mt-6"
/>
</article>
</div>
</div>
</div>
) : null}
</main>
)
}