Add VK iframe embed block to article editor
All checks were successful
Deploy Dzen assistant / deploy (push) Successful in 30s

This commit is contained in:
nstarikov 2026-09-16 12:00:26 +03:00
parent 9fadc57429
commit e877de1d54
3 changed files with 134 additions and 2 deletions

View file

@ -170,6 +170,26 @@ type ImageGenerationTuneConfig = {
type VkVideoBlockData = { sourceUrl?: string }
type VkEmbedBlockData = { embedUrl?: string; embedCode?: string; title?: string }
function extractVkEmbedUrl(value: string) {
const source = value.trim()
if (!source) return ""
try {
const document = new DOMParser().parseFromString(source, "text/html")
const iframe = document.querySelector("iframe")
if (iframe?.src) {
const url = new URL(iframe.src)
if (url.protocol === "https:" && ["vkvideo.ru", "www.vkvideo.ru", "vk.com", "www.vk.com", "m.vk.com"].includes(url.hostname) && url.pathname === "/video_ext.php") {
return url.toString()
}
}
} catch {
// The server validates the final HTML as well; an invalid draft stays empty here.
}
return ""
}
class VkVideoTool {
private data: VkVideoBlockData
@ -195,6 +215,66 @@ class VkVideoTool {
save() { return this.data }
}
class VkEmbedTool {
private data: VkEmbedBlockData
private preview: HTMLElement | null = null
constructor({ data }: { data: VkEmbedBlockData }) {
this.data = data || {}
}
static get toolbox() {
return {
title: "VK Видео",
icon: "<svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"3\" y=\"5\" width=\"18\" height=\"14\" rx=\"2\"/><path d=\"m10 9 5 3-5 3z\"/></svg>",
}
}
static get isReadOnlySupported() { return true }
render() {
const element = document.createElement("section")
element.className = "editor-vk-embed rounded-md border border-sky-200 bg-sky-50 p-4"
const label = document.createElement("p")
label.className = "mb-2 text-sm font-medium text-sky-950"
label.textContent = "Вставка VK Видео"
const input = document.createElement("textarea")
input.className = "min-h-20 w-full resize-y rounded-md border border-sky-200 bg-background p-3 text-sm outline-none focus:ring-2 focus:ring-ring"
input.placeholder = "Вставьте iframe-код VK Видео"
input.value = this.data.embedCode || this.data.embedUrl || ""
input.addEventListener("input", () => {
this.data.embedCode = input.value
this.data.embedUrl = extractVkEmbedUrl(input.value) || (input.value.startsWith("https://") ? extractVkEmbedUrl(`<iframe src=\"${input.value}\"></iframe>`) : "")
this.renderPreview()
})
this.preview = document.createElement("div")
this.preview.className = "mt-3 overflow-hidden rounded-md bg-black"
element.append(label, input, this.preview)
this.renderPreview()
return element
}
private renderPreview() {
if (!this.preview) return
this.preview.replaceChildren()
if (!this.data.embedUrl) {
this.preview.className = "mt-3 rounded-md border border-dashed border-sky-200 p-3 text-xs text-sky-800"
this.preview.textContent = "После вставки корректного iframe здесь появится предпросмотр."
return
}
this.preview.className = "mt-3 aspect-video overflow-hidden rounded-md bg-black"
const iframe = document.createElement("iframe")
iframe.src = this.data.embedUrl
iframe.title = this.data.title || "Видео VK"
iframe.allow = "autoplay; encrypted-media; fullscreen; picture-in-picture; screen-wake-lock;"
iframe.allowFullscreen = true
iframe.className = "size-full border-0"
this.preview.append(iframe)
}
save() { return this.data }
}
const ARTICLES_PAGE_SIZE = 10
const CHAPTER_SELECTION_STORAGE_PREFIX = "dzen:selected-chapters:"
const LOCAL_VIDEO_EXTENSIONS = new Set(["mp4", "webm", "mov", "mkv"])
@ -677,6 +757,12 @@ function htmlToEditorData(html: string, title?: string, videoSourceUrl?: string)
return
}
if (tag === "figure") {
const iframe = node.querySelector("iframe")
const embedUrl = iframe ? extractVkEmbedUrl(iframe.outerHTML) : ""
if (embedUrl) {
blocks.push({ type: "vkEmbed", data: { embedUrl, embedCode: iframe?.outerHTML || "", title: iframe?.getAttribute("title") || "" } })
return
}
const image = node.querySelector("img")
if (!image) return
blocks.push({
@ -691,6 +777,11 @@ function htmlToEditorData(html: string, title?: string, videoSourceUrl?: string)
})
return
}
if (tag === "iframe") {
const embedUrl = extractVkEmbedUrl(node.outerHTML)
if (embedUrl) blocks.push({ type: "vkEmbed", data: { embedUrl, embedCode: node.outerHTML, title: node.getAttribute("title") || "" } })
return
}
pushParagraph(node)
})
@ -725,6 +816,12 @@ function editorDataToHtml(data: OutputData, title?: string): string {
const caption = item.caption || title
return `<figure><img src="${escapeHtml(url)}" alt="${escapeHtml(caption)}"><figcaption>${caption}</figcaption></figure>`
}
if (block.type === "vkEmbed") {
const embedUrl = extractVkEmbedUrl(String(item.embedCode || "")) || String(item.embedUrl || "")
if (!embedUrl) return ""
const embedTitle = escapeHtml(String(item.title || title || "Видео VK"))
return `<figure class="vk-embed"><iframe src="${escapeHtml(embedUrl)}" title="${embedTitle}" width="1280" height="720" allow="autoplay; encrypted-media; fullscreen; picture-in-picture; screen-wake-lock;" frameborder="0" allowfullscreen></iframe></figure>`
}
if (block.type === "vkVideo") return "<p>[[VK_VIDEO]]</p>"
return `<p>${item.text || ""}</p>`
})
@ -1880,6 +1977,9 @@ export default function App() {
vkVideo: {
class: VkVideoTool as unknown as ToolConstructable,
},
vkEmbed: {
class: VkEmbedTool as unknown as ToolConstructable,
},
randomFrame: {
class: RandomFrameTune as unknown as ToolConstructable,
config: {

View file

@ -13,6 +13,7 @@ import subprocess
import secrets
from typing import Any
from uuid import uuid4
from urllib.parse import urlparse
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, Request, UploadFile, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, RedirectResponse, Response
@ -502,12 +503,14 @@ class ArticleHtmlSanitizer(HTMLParser):
"figcaption",
"img",
"a",
"iframe",
}
void_tags = {"br", "img"}
allowed_attrs = {
"a": {"href", "title"},
"img": {"src", "alt"},
"p": {"class"},
"iframe": {"src", "title", "width", "height", "allow", "frameborder", "allowfullscreen"},
}
def __init__(self) -> None:
@ -517,9 +520,14 @@ class ArticleHtmlSanitizer(HTMLParser):
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
tag = tag.lower()
if tag in {"script", "style", "iframe", "object", "embed"}:
if tag in {"script", "style", "object", "embed"}:
self.skip_depth += 1
return
if tag == "iframe":
src = next((value or "" for name, value in attrs if name.lower() == "src"), "").strip()
if not is_safe_vk_embed_url(src):
self.skip_depth += 1
return
if self.skip_depth or tag not in self.allowed_tags:
return
clean_attrs: list[str] = []
@ -570,6 +578,18 @@ def sanitize_article_editor_html(html: str) -> str:
return sanitized
def is_safe_vk_embed_url(value: str) -> bool:
try:
parsed = urlparse(value)
except ValueError:
return False
return (
parsed.scheme == "https"
and parsed.hostname in {"vkvideo.ru", "www.vkvideo.ru", "vk.com", "www.vk.com", "m.vk.com"}
and parsed.path == "/video_ext.php"
)
def strip_article_cover_html(html: str) -> str:
return re.sub(
r"<figure\b[^>]*class=[\"'][^\"']*\barticle-cover\b[^\"']*[\"'][^>]*>.*?</figure>",

View file

@ -9,7 +9,7 @@ from sqlalchemy.pool import StaticPool
from app.config import Settings, get_settings
from app.database import Base, get_session
from app.models import AppSetting, Article, Video
from app.routes import SETTING_DRAFT_API_KEY_HASH, draft_api_key_hash, router
from app.routes import SETTING_DRAFT_API_KEY_HASH, draft_api_key_hash, router, sanitize_article_editor_html
class DraftApiTest(unittest.TestCase):
@ -180,6 +180,18 @@ class DraftApiTest(unittest.TestCase):
self.assertEqual(detail.status_code, 200)
self.assertEqual(detail.json()["slug"], "draft-from-video")
def test_sanitizer_keeps_vk_embed_and_removes_other_iframes(self):
html = (
'<p>До видео</p>'
'<iframe src="https://vkvideo.ru/video_ext.php?oid=-1&id=2" title="VK"></iframe>'
'<iframe src="https://example.com/video.html"></iframe>'
)
sanitized = sanitize_article_editor_html(html)
self.assertIn('src="https://vkvideo.ru/video_ext.php?oid=-1&amp;id=2"', sanitized)
self.assertNotIn("example.com", sanitized)
if __name__ == "__main__":
unittest.main()