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 } 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: '', 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(path: string, init?: RequestInit): Promise { 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 } function escapeHtml(value: string) { return value .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) } function normalizeEditorText(value: string) { const parser = new DOMParser() const document = parser.parseFromString(`
${value || ""}
`, "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).text || "")) return text === normalizedTitle ? blocks.slice(1) : blocks } function htmlToEditorData(html: string, title?: string): OutputData { const parser = new DOMParser() const document = parser.parseFromString(`
${html || ""}
`, "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 if (block.type === "header") { const level = item.level === 3 ? 3 : 2 return `${item.text || ""}` } if (block.type === "list") { const tag = item.style === "ordered" ? "ol" : "ul" const items = Array.isArray(item.items) ? item.items : [] return `<${tag}>${items.map((value) => `
  • ${value}
  • `).join("")}` } if (block.type === "quote") { return `
    ${item.text || ""}
    ` } if (block.type === "image") { const url = item.file?.url || item.url || "" if (!url) return "" const caption = item.caption || "" return `
    ${escapeHtml(caption)}
    ${caption}
    ` } return `

    ${item.text || ""}

    ` }) .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 ( Опубликовано ) } if (normalized === "drafted" || normalized === "draft") { return ( Черновик ) } if (normalized === "error") { return ( Ошибка ) } if (normalized === "processing" || normalized === "queued") { return ( {normalized === "processing" ? : } {normalized === "processing" ? "В работе" : "В очереди"} ) } return {status} } function ArticlePlaceholder() { return (
    ) } export default function App() { const [dashboard, setDashboard] = useState(null) const [videos, setVideos] = useState([]) const [articles, setArticles] = useState([]) const [articlesHasMore, setArticlesHasMore] = useState(false) const [articlesLoading, setArticlesLoading] = useState(false) const [selectedLog, setSelectedLog] = useState(null) const [selectedArticle, setSelectedArticle] = useState(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(null) const editorHolderRef = useRef(null) const editorInstanceRef = useRef(null) const fileInputRef = useRef(null) const logSocketRef = useRef(null) const selectedArticleRef = useRef(null) const editorTitleRef = useRef("") const titleTextareaRef = useRef(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(`/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("/api/dashboard"), api("/api/videos"), api(`/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(`/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(`/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(`/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 (

    Дзен-ассистент

    RSS-конвейер для статей из видео Николая Старикова

    {[ ["Ролики", dashboard?.videos ?? 0], ["Новые", dashboard?.newVideos ?? 0], ["В работе", dashboard?.processingVideos ?? 0], ["Черновики", dashboard?.drafts ?? 0], ["Запланировано", dashboard?.scheduled ?? 0], ["В RSS", dashboard?.published ?? 0], ].map(([label, value]) => ( {label} {value} ))}
    {statusMessage ?
    {statusMessage}
    : null}
    Ролики Все ролики, прогресс обработки, логи и готовые черновики в одном списке.
    {activeVideos.length} в работе
    {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 (
    {!hasDraftAction && !publishedArticle ? : null} {publishedArticle ? : null}

    {video.title || `Ролик #${video.id}`}

    Опубликовано: {formatVideoDate(video.publishedAt)} Длительность: {formatDuration(video.durationSeconds)}
    {hasStarted && video.progressStage ?

    {video.progressStage}

    : null} {video.errorMessage ?

    {video.errorMessage}

    : null}
    {draftArticleId ? ( ) : publishedArticle ? ( ) : isActive ? ( ) : ( )}
    {hasStarted ? (
    {progress}%
    ) : null}
    ) }) ) : (
    Новых роликов и черновиков пока нет. Готовые материалы находятся в колонке «Статьи».
    )} Статьи Принятые материалы: уже вышедшие в RSS и отложенные по времени. { 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) => (
    )) ) : articlesLoading ? ( Array.from({ length: 5 }).map((_, index) => ) ) : (
    Принятых статей пока нет. Черновики открываются из роликов слева.
    )} {publishedArticles.length > 0 && articlesLoading ? Array.from({ length: 3 }).map((_, index) => ) : null} {articlesHasMore && !articlesLoading ? ( ) : null}
    {selectedLog ? (

    Логи обработки

    {selectedLog.title || `Ролик #${selectedLog.id}`}

    Статус

    {selectedLog.status}

    Этап

    {selectedLog.progressStage || "—"}

    Прогресс

    {selectedLog.progressPercent || 0}%

    {selectedLog.errorMessage ?

    {selectedLog.errorMessage}

    : null}
                    {selectedLog.progressLog || "Лог пока пуст."}
                  
    ) : null} {selectedArticle ? (
    {isScheduledForFuture(selectedArticle.publishedAt) ? ( Отложено ) : ( )}

    Редактирование статьи

    {editorDirty ? есть правки : null}

    Редактируйте блоки как в Medium. Для картинки выберите image-блок и нажмите кнопку случайного кадра.

    { const file = event.currentTarget.files?.[0] event.currentTarget.value = "" if (file) await insertImageFile(file) }} /> {selectedArticle.status !== "published" || isScheduledForFuture(selectedArticle.publishedAt) ? ( <> ) : ( )}