diff --git a/admin/src/App.tsx b/admin/src/App.tsx
index 9137250..26ddf6b 100644
--- a/admin/src/App.tsx
+++ b/admin/src/App.tsx
@@ -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: "",
+ }
+ }
+
+ 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(``) : "")
+ 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 `
[[VK_VIDEO]]
" return `${item.text || ""}
` }) @@ -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: { diff --git a/app/routes.py b/app/routes.py index 073363f..606ac25 100644 --- a/app/routes.py +++ b/app/routes.py @@ -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"До видео
' + '' + '' + ) + + sanitized = sanitize_article_editor_html(html) + + self.assertIn('src="https://vkvideo.ru/video_ext.php?oid=-1&id=2"', sanitized) + self.assertNotIn("example.com", sanitized) + if __name__ == "__main__": unittest.main()