From 40cccbfcd155a74f3655fb1cd05b07594b56d8c9 Mon Sep 17 00:00:00 2001 From: nstarikov Date: Thu, 13 Aug 2026 11:43:53 +0300 Subject: [PATCH] feat: make draft video editable and footer stable --- dzen-assistant/admin/src/App.tsx | 65 +++++++++++------- dzen-assistant/app/routes.py | 35 +++++++--- dzen-assistant/app/rss.py | 11 +++- dzen-assistant/app/worker.py | 27 ++++++-- ...-13-editorial-video-and-footer-contract.md | 42 ++++++++++++ .../tests/test_article_editor_contract.py | 66 +++++++++++++++++++ 6 files changed, 208 insertions(+), 38 deletions(-) create mode 100644 dzen-assistant/docs/superpowers/plans/2026-08-13-editorial-video-and-footer-contract.md create mode 100644 dzen-assistant/tests/test_article_editor_contract.py diff --git a/dzen-assistant/admin/src/App.tsx b/dzen-assistant/admin/src/App.tsx index 21ce701..ba6d30d 100644 --- a/dzen-assistant/admin/src/App.tsx +++ b/dzen-assistant/admin/src/App.tsx @@ -105,6 +105,7 @@ type ArticleDetail = Article & { contentHtml: string editableHtml: string videoId?: number + videoSourceUrl?: string } type VideoLog = { @@ -146,6 +147,33 @@ type ImageGenerationTuneConfig = { onRegenerate?: (block: BlockAPI) => void | Promise } +type VkVideoBlockData = { sourceUrl?: string } + +class VkVideoTool { + private data: VkVideoBlockData + + constructor({ data }: { data: VkVideoBlockData }) { + this.data = data || {} + } + + static get isReadOnlySupported() { return true } + + render() { + const element = document.createElement("section") + element.className = "editor-vk-video rounded-md border border-sky-200 bg-sky-50 p-4" + const link = document.createElement("a") + link.href = this.data.sourceUrl || "#" + link.target = "_blank" + link.rel = "noreferrer" + link.className = "flex items-center gap-2 font-medium text-sky-900 underline-offset-2 hover:underline" + link.textContent = "Видео VK — можно перемещать как обычный блок" + element.append(link) + return element + } + + save() { return this.data } +} + const ARTICLES_PAGE_SIZE = 10 const CHAPTER_SELECTION_STORAGE_PREFIX = "dzen:selected-chapters:" @@ -563,7 +591,7 @@ function stripLeadingDuplicateTitleBlock(blocks: EditorBlock[], title?: string) return text === normalizedTitle ? blocks.slice(1) : blocks } -function htmlToEditorData(html: string, title?: string): OutputData { +function htmlToEditorData(html: string, title?: string, videoSourceUrl?: string): OutputData { const parser = new DOMParser() const document = parser.parseFromString(`
${html || ""}
`, "text/html") const root = document.querySelector("main") @@ -587,6 +615,10 @@ function htmlToEditorData(html: string, title?: string): OutputData { if (!(node instanceof Element)) return const tag = node.tagName.toLowerCase() if (tag === "p") { + if (node.textContent?.trim() === "[[VK_VIDEO]]") { + blocks.push({ type: "vkVideo", data: { sourceUrl: videoSourceUrl || "" } }) + return + } pushParagraph(node) return } @@ -652,28 +684,13 @@ function editorDataToHtml(data: OutputData, title?: string): string { const caption = item.caption || title return `
${escapeHtml(caption)}
${caption}
` } + if (block.type === "vkVideo") return "

[[VK_VIDEO]]

" return `

${item.text || ""}

` }) .filter(Boolean) .join("\n") } -function appendSignatureToEditorData(data: OutputData, signatureHtml: string): OutputData { - if (!signatureHtml.trim()) return data - const signatureBlocks = htmlToEditorData(signatureHtml).blocks - if (!signatureBlocks.length || signatureBlocks.every((block) => block.type === "paragraph" && !String((block.data as Record).text || "").trim())) { - return data - } - const blocks = data.blocks || [] - const tail = blocks.slice(-signatureBlocks.length) - const sameBlock = (left: EditorBlock, right: EditorBlock) => - left.type === right.type && JSON.stringify(left.data) === JSON.stringify(right.data) - if (tail.length === signatureBlocks.length && tail.every((block, index) => sameBlock(block, signatureBlocks[index]))) { - return data - } - return { ...data, blocks: [...blocks, ...signatureBlocks] } -} - function htmlToPlainText(html: string) { const parser = new DOMParser() const document = parser.parseFromString(`
${html || ""}
`, "text/html") @@ -1521,12 +1538,11 @@ export default function App() { if (!selectedArticle || !editorHolderRef.current) return editorInstanceRef.current?.destroy() editorHolderRef.current.innerHTML = "" - const articleData = htmlToEditorData(selectedArticle.editableHtml || selectedArticle.contentHtml, selectedArticle.title) - const editorData = appendSignatureToEditorData( - articleData, - selectedArticle.status !== "published" ? appSettings.signatureHtml : "", + const editorData = htmlToEditorData( + selectedArticle.editableHtml || selectedArticle.contentHtml, + selectedArticle.title, + selectedArticle.videoSourceUrl, ) - if (editorData.blocks.length !== articleData.blocks.length) setEditorDirty(true) const editor = new EditorJS({ holder: editorHolderRef.current, data: editorData, @@ -1582,6 +1598,9 @@ export default function App() { }, }, }, + vkVideo: { + class: VkVideoTool as unknown as ToolConstructable, + }, randomFrame: { class: RandomFrameTune as unknown as ToolConstructable, config: { @@ -1656,7 +1675,7 @@ export default function App() { } editor.destroy() } - }, [selectedArticle?.id, appSettings.signatureHtml]) + }, [selectedArticle?.id, selectedArticle?.videoSourceUrl]) function findImageBlockFromElement(target: EventTarget | null) { const editor = editorInstanceRef.current diff --git a/dzen-assistant/app/routes.py b/dzen-assistant/app/routes.py index 8998256..61435f5 100644 --- a/dzen-assistant/app/routes.py +++ b/dzen-assistant/app/routes.py @@ -37,7 +37,7 @@ from app.database import SessionLocal, get_session from app.models import AppSetting, Article, Frame, ImageGenerationBatch, ImageGenerationJob, PasskeyCredential, Source, Video from app.image_generation import DEFAULT_API_URL, DEFAULT_MODEL, build_prompt, normalize_api_url from app.quality import validate_article_content -from app.rss import article_url, build_feed_xml, render_article_html +from app.rss import VIDEO_PLACEHOLDER, article_url, build_feed_xml, render_article_html, split_audience_question_html from app.worker import best_thumbnail_url, generate_article_image, parse_upload_date, process_video, scan_sources, ytdlp_base_args router = APIRouter() @@ -309,6 +309,7 @@ class ArticleHtmlSanitizer(HTMLParser): allowed_attrs = { "a": {"href", "title"}, "img": {"src", "alt"}, + "p": {"class"}, } def __init__(self) -> None: @@ -329,6 +330,10 @@ class ArticleHtmlSanitizer(HTMLParser): if value is None or name not in self.allowed_attrs.get(tag, set()): continue value = value.strip() + if name == "class": + if tag == "p" and "audience-question" in value.split(): + clean_attrs.append('class="audience-question"') + continue if name in {"href", "src"} and not re.match(r"^(https?://|/media/)", value, flags=re.I): continue clean_attrs.append(f'{name}="{escape(value, quote=True)}"') @@ -377,7 +382,10 @@ def strip_article_cover_html(html: str) -> str: def editable_article_html(article: Article) -> str: - html = "\n".join(part for part in [article.lead, article.body_html, article.cta_html] if part).strip() + body_html, audience_question_html = split_audience_question_html(article.body_html) + if article.video_id and VIDEO_PLACEHOLDER not in body_html: + body_html = "\n".join(part for part in [body_html, f"

{VIDEO_PLACEHOLDER}

"] if part) + html = "\n".join(part for part in [article.lead, body_html, audience_question_html, article.cta_html] if part).strip() html = strip_article_cover_html(html) return strip_leading_duplicate_title(html, article.title) @@ -800,6 +808,7 @@ def get_article(article_id: int, session: Session = Depends(get_session), settin "slug": article.slug, "status": article.status, "videoId": article.video_id, + "videoSourceUrl": article.video.source_url if article.video else "", "url": article_url(settings, article), "featureImageUrl": article_cover_url(session, article), "createdAt": article.created_at, @@ -924,12 +933,21 @@ def update_article(article_id: int, payload: ArticleUpdateIn, session: Session = body = strip_leading_duplicate_title(body, title) if not title: raise HTTPException(status_code=422, detail="Title is required") - configured_signature = session.scalar( - select(AppSetting.value).where(AppSetting.key == SETTING_SIGNATURE) - ) or "" - signature_html = article.cta_html or configured_signature - if signature_html.strip() and body.rstrip().endswith(signature_html.strip()): - body = body[: -len(signature_html.strip())].rstrip() + signature_html = sanitize_article_editor_html(article.cta_html) + if signature_html and signature_html in body: + body = body.replace(signature_html, "").rstrip() + else: + signature_html = "" + _, prior_question = split_audience_question_html(article.body_html) + body, updated_question = split_audience_question_html(body) + audience_question_html = updated_question or prior_question + if article.video_id: + if VIDEO_PLACEHOLDER not in body: + body = "\n".join(part for part in [body.strip(), f"

{VIDEO_PLACEHOLDER}

"] if part) + elif body.count(VIDEO_PLACEHOLDER) > 1: + before, after = body.split(VIDEO_PLACEHOLDER, 1) + body = before + VIDEO_PLACEHOLDER + after.replace(VIDEO_PLACEHOLDER, "") + body = "\n".join(part for part in [body, audience_question_html] if part) lead, body_html = split_lead_and_body(body) article.title = title article.lead = lead @@ -945,6 +963,7 @@ def update_article(article_id: int, payload: ArticleUpdateIn, session: Session = "slug": article.slug, "status": article.status, "videoId": article.video_id, + "videoSourceUrl": article.video.source_url if article.video else "", "url": article_url(settings, article), "featureImageUrl": article_cover_url(session, article), "createdAt": article.created_at, diff --git a/dzen-assistant/app/rss.py b/dzen-assistant/app/rss.py index 24f642d..fb838e0 100644 --- a/dzen-assistant/app/rss.py +++ b/dzen-assistant/app/rss.py @@ -10,6 +10,8 @@ from app.captions import strip_leading_duplicate_title from app.config import Settings from app.models import Article, Frame +VIDEO_PLACEHOLDER = "[[VK_VIDEO]]" + def rfc822(dt: datetime | None) -> str: value = dt or datetime.now(timezone.utc) @@ -73,6 +75,12 @@ def video_embed_html(article: Article, rss_safe: bool = False) -> str: """.strip() +def render_video_placeholder(article: Article, html: str, rss_safe: bool = False) -> tuple[str, bool]: + if VIDEO_PLACEHOLDER not in html: + return html, False + return html.replace(VIDEO_PLACEHOLDER, video_embed_html(article, rss_safe=rss_safe), 1), True + + def premium_cta_html() -> str: return """
@@ -176,9 +184,10 @@ def media_player_xml(article: Article) -> str: def render_article_html(article: Article, include_video_embed: bool = True, rss_safe: bool = False) -> str: body_html = strip_article_cover_html(article.body_html) body_html, audience_question_html = split_audience_question_html(body_html) + body_html, has_video_placeholder = render_video_placeholder(article, body_html, rss_safe=rss_safe) body_html = sanitize_rss_html(body_html) if rss_safe else body_html parts = [article.lead, cover_html(article, rss_safe=rss_safe), body_html] - if include_video_embed: + if include_video_embed and not has_video_placeholder: parts.append(video_embed_html(article, rss_safe=rss_safe)) if audience_question_html: parts.append(audience_question_html) diff --git a/dzen-assistant/app/worker.py b/dzen-assistant/app/worker.py index cf1c98d..89f9ba7 100644 --- a/dzen-assistant/app/worker.py +++ b/dzen-assistant/app/worker.py @@ -20,6 +20,7 @@ from app.models import AppSetting, Article, Frame, Source, Video from app.models import ImageGenerationBatch, ImageGenerationJob from app.image_generation import ImageGenerationError, PolzaClient, error_from_status, extract_result_url, save_remote_image from app.quality import validate_article_content, validate_transcript_text +from app.rss import VIDEO_PLACEHOLDER settings = get_settings() @@ -534,7 +535,10 @@ def process_video(video_id: int, selected_chapters: list[dict[str, Any]] | None chapter_count = len(selected_chapters or []) chapter_note = f" по выбранным главам: {chapter_count}" if chapter_count else "" append_progress(video_id, 75, "ИИ-редактор", f"Готовлю статьи по транскрипту{chapter_note}") - articles = build_articles(video, transcript, frames, selected_chapters) + signature_html = session.scalar( + select(AppSetting.value).where(AppSetting.key == "article_signature_html") + ) or "" + articles = build_articles(video, transcript, frames, selected_chapters, signature_html) for article in articles: session.add(article) video.status = "drafted" @@ -720,6 +724,7 @@ def build_articles( transcript_path: Path, frames: list[Frame], selected_chapters: list[dict[str, Any]] | None = None, + signature_html: str = "", ) -> list[Article]: transcript = transcript_path.read_text(encoding="utf-8", errors="ignore") validate_transcript_text(transcript) @@ -727,7 +732,7 @@ def build_articles( raise RuntimeError("LLM-редактор не настроен. Черновик из сырой транскрибации не создается.") chapters = normalize_selected_chapters(selected_chapters, video.duration_seconds) if not chapters: - articles = generate_articles_with_quality_retries(video, transcript, frames) + articles = generate_articles_with_quality_retries(video, transcript, frames, signature_html=signature_html) if not articles: raise RuntimeError("LLM-редактор не вернул пригодную статью. Черновик не создан.") return articles @@ -752,6 +757,7 @@ def build_articles( chapter_transcript, chapter_frames or frames, chapter=chapter, + signature_html=signature_html, ) if not chapter_articles: raise RuntimeError(f"LLM-редактор не вернул пригодную статью для главы «{chapter['title']}».") @@ -768,6 +774,7 @@ def generate_articles_with_quality_retries( transcript: str, frames: list[Frame], chapter: dict[str, Any] | None = None, + signature_html: str = "", ) -> list[Article]: feedback = "" for attempt in range(1, QUALITY_REWRITE_ATTEMPTS + 1): @@ -780,7 +787,10 @@ def generate_articles_with_quality_retries( ) try: payload = generate_article_payload(video, transcript, chapter=chapter, quality_feedback=feedback) - articles = articles_from_payload(video, payload, frames) + if signature_html: + articles = articles_from_payload(video, payload, frames, signature_html=signature_html) + else: + articles = articles_from_payload(video, payload, frames) except (RuntimeError, json.JSONDecodeError) as exc: message = str(exc) if isinstance(exc, json.JSONDecodeError): @@ -795,7 +805,11 @@ def generate_articles_with_quality_retries( "ИИ-редактор", f"Локальная редактура после ответа LLM: {message}", ) - articles = articles_from_payload(video, neutralize_payload_first_person(payload), frames) + normalized_payload = neutralize_payload_first_person(payload) + if signature_html: + articles = articles_from_payload(video, normalized_payload, frames, signature_html=signature_html) + else: + articles = articles_from_payload(video, normalized_payload, frames) if articles: return articles raise @@ -1132,7 +1146,7 @@ def is_json_string_boundary(value: str, index: int) -> bool: return value[next_index] in '"}]' -def articles_from_payload(video: Video, payload: dict[str, Any], frames: list[Frame]) -> list[Article]: +def articles_from_payload(video: Video, payload: dict[str, Any], frames: list[Frame], signature_html: str = "") -> list[Article]: raw_articles = payload.get("articles") if not isinstance(raw_articles, list): return [] @@ -1155,7 +1169,7 @@ def articles_from_payload(video: Video, payload: dict[str, Any], frames: list[Fr title=title, lead=lead, body_html=body_html, - cta_html="", + cta_html=signature_html.strip(), feature_image_url=video.thumbnail_url or "", status="draft", ) @@ -1233,6 +1247,7 @@ def article_body_html(item: dict[str, Any], frames: list[Frame], title: str, vid parts = [ body_html, generated_content_to_html(str(item.get("conclusion") or "")), + f"

{VIDEO_PLACEHOLDER}

", audience_question_html(item, title), ] return "\n".join(part for part in parts if part).strip() diff --git a/dzen-assistant/docs/superpowers/plans/2026-08-13-editorial-video-and-footer-contract.md b/dzen-assistant/docs/superpowers/plans/2026-08-13-editorial-video-and-footer-contract.md new file mode 100644 index 0000000..53d2696 --- /dev/null +++ b/dzen-assistant/docs/superpowers/plans/2026-08-13-editorial-video-and-footer-contract.md @@ -0,0 +1,42 @@ +# Editorial Video and Footer Contract Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Create each draft with one stored signature and a movable source-video block, while keeping the audience question and signature below the video in the editor and RSS output. + +**Architecture:** Persist a safe `[[VK_VIDEO]]` marker in article HTML instead of an iframe. The admin converts that marker to an Editor.js video block; RSS replaces it with the trusted server-generated VK embed. The worker snapshots the configured signature when it creates a draft, and the API canonicalizes the footer so saving cannot duplicate it. + +**Tech Stack:** FastAPI, SQLAlchemy, Celery, React, Editor.js, unittest. + +--- + +### Task 1: Protect the persisted article contract + +**Files:** +- Modify: `app/worker.py` +- Modify: `app/routes.py` +- Modify: `app/rss.py` +- Test: `tests/test_rss.py` + +- [ ] Create drafts with the current global signature exactly once and with a `[[VK_VIDEO]]` marker before the audience question. +- [ ] Preserve exactly one canonical signature when an article is saved; honour deliberate removal of the signature. +- [ ] Render the marker at its saved location as the trusted VK embed, and keep the audience question and signature after it. +- [ ] Cover a link-bearing signature and a moved video marker with regression tests. + +### Task 2: Expose and edit the video as an Editor.js block + +**Files:** +- Modify: `admin/src/App.tsx` + +- [ ] Include the source URL in article details. +- [ ] Convert the persisted marker to a dedicated, movable Editor.js video block and serialize it back to the marker. +- [ ] For older drafts without a marker, show one video block before the question and signature; saving upgrades them. +- [ ] Remove open-time signature insertion so the signature is never recreated from settings. + +### Task 3: Verify the workflow + +**Files:** +- Test: `tests/test_rss.py` + +- [ ] Run focused backend tests, the full backend test suite, Python compilation, and the production frontend build. +- [ ] Inspect the generated article payloads to confirm one signature, one video marker, and footer ordering. diff --git a/dzen-assistant/tests/test_article_editor_contract.py b/dzen-assistant/tests/test_article_editor_contract.py new file mode 100644 index 0000000..534f7d6 --- /dev/null +++ b/dzen-assistant/tests/test_article_editor_contract.py @@ -0,0 +1,66 @@ +import unittest + +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +from app.config import Settings +from app.database import Base +from app.models import Article, Video +from app.routes import ArticleUpdateIn, editable_article_html, update_article +from app.rss import VIDEO_PLACEHOLDER, render_article_html + + +class ArticleEditorContractTest(unittest.TestCase): + def setUp(self): + self.engine = create_engine("sqlite:///:memory:") + Base.metadata.create_all(self.engine) + + def test_saving_link_signature_keeps_exactly_one_canonical_copy(self): + with Session(self.engine) as session: + article = Article( + slug="signature", title="Подпись", lead="", body_html="

Текст.

", + cta_html='

Подписаться & читать

', + ) + session.add(article) + session.commit() + + update_article( + article.id, + ArticleUpdateIn( + title=article.title, + editableHtml=( + '

Текст.

' + '

Ваше мнение: Обсудим? Пишите своё мнение в комментариях.

' + '

Подписаться & читать

' + ), + ), + session, + Settings(public_base_url="https://example.test"), + ) + session.refresh(article) + saved = editable_article_html(article) + self.assertEqual(saved.count("Подписаться & читать"), 1) + self.assertNotIn('target="_blank"', article.cta_html) + self.assertIn('class="audience-question"', article.body_html) + + def test_video_marker_stays_at_saved_position_before_footer(self): + with Session(self.engine) as session: + video = Video(external_id="1", source_url="https://vk.com/video-1_2", title="Исходное видео") + article = Article( + video=video, slug="video", title="Видео", lead="

Лид.

", + body_html=(f"

До видео.

{VIDEO_PLACEHOLDER}

После видео.

" + '

Ваше мнение: Обсудим? Пишите своё мнение в комментариях.

'), + cta_html="

Подпись.

", + ) + session.add(article) + session.commit() + html = render_article_html(article) + + self.assertLess(html.index("До видео."), html.index("video_ext.php")) + self.assertLess(html.index("video_ext.php"), html.index("После видео.")) + self.assertLess(html.index("После видео."), html.index("Ваше мнение:")) + self.assertLess(html.index("Ваше мнение:"), html.index("Подпись.")) + + +if __name__ == "__main__": + unittest.main()