Embed local MP4 videos in RSS
All checks were successful
Deploy Dzen assistant / deploy (push) Successful in 21s

This commit is contained in:
nstarikov 2026-09-17 15:30:32 +03:00
parent 4585f32c72
commit f490094e08
3 changed files with 87 additions and 37 deletions

View file

@ -34,6 +34,7 @@ app.add_middleware(AuthMiddleware)
settings = get_settings() settings = get_settings()
mimetypes.add_type("image/webp", ".webp") mimetypes.add_type("image/webp", ".webp")
app.mount("/media", StaticFiles(directory=settings.media_path, check_dir=False), name="media") app.mount("/media", StaticFiles(directory=settings.media_path, check_dir=False), name="media")
app.mount("/videos", StaticFiles(directory=settings.videos_path, check_dir=False), name="videos")
app.mount("/posts-static", StaticFiles(directory=settings.posts_path, check_dir=False), name="posts-static") app.mount("/posts-static", StaticFiles(directory=settings.posts_path, check_dir=False), name="posts-static")
admin_dist = Path("/app/admin_dist") admin_dist = Path("/app/admin_dist")

View file

@ -1,7 +1,8 @@
from datetime import datetime, timezone from datetime import datetime, timezone
from html import escape, unescape from html import escape, unescape
from pathlib import Path
import re import re
from urllib.parse import urlencode from urllib.parse import quote, urlencode
from sqlalchemy import select from sqlalchemy import select
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@ -47,13 +48,22 @@ def vk_video_embed_url(source_url: str) -> str | None:
return f"https://vkvideo.ru/video_ext.php?{urlencode(params)}" return f"https://vkvideo.ru/video_ext.php?{urlencode(params)}"
def video_embed_html(article: Article, rss_safe: bool = False) -> str: def video_embed_html(article: Article, rss_safe: bool = False, video_url: str | None = None) -> str:
if not article.video or not article.video.source_url: if not article.video or not article.video.source_url:
return "" return ""
embed_url = vk_video_embed_url(article.video.source_url) embed_url = vk_video_embed_url(article.video.source_url)
if rss_safe: if rss_safe:
if video_url:
video = (
f'<video controls preload="metadata" width="1280" height="720">'
f'<source src="{escape(video_url)}" type="video/mp4" />'
"</video>"
)
else:
video = ""
return f""" return f"""
<h2>Смотреть видео</h2> <h2>Смотреть видео</h2>
{video}
<p><a href="{escape(article.video.source_url)}">Смотреть исходное видео VK Видео</a></p>""".strip() <p><a href="{escape(article.video.source_url)}">Смотреть исходное видео VK Видео</a></p>""".strip()
if not embed_url: if not embed_url:
return "" return ""
@ -67,10 +77,19 @@ def video_embed_html(article: Article, rss_safe: bool = False) -> str:
</section>""".strip() </section>""".strip()
def render_video_placeholder(article: Article, html: str, rss_safe: bool = False) -> tuple[str, bool]: def render_video_placeholder(
article: Article,
html: str,
rss_safe: bool = False,
video_url: str | None = None,
) -> tuple[str, bool]:
if VIDEO_PLACEHOLDER not in html: if VIDEO_PLACEHOLDER not in html:
return html, False return html, False
return html.replace(VIDEO_PLACEHOLDER, video_embed_html(article, rss_safe=rss_safe), 1), True return html.replace(
VIDEO_PLACEHOLDER,
video_embed_html(article, rss_safe=rss_safe, video_url=video_url),
1,
), True
def premium_cta_html() -> str: def premium_cta_html() -> str:
@ -220,16 +239,26 @@ def media_player_xml(article: Article) -> str:
return f'<media:player url="{escape(embed_url)}" width="1280" height="720" />' return f'<media:player url="{escape(embed_url)}" width="1280" height="720" />'
def render_article_html(article: Article, include_video_embed: bool = True, rss_safe: bool = False) -> str: def render_article_html(
article: Article,
include_video_embed: bool = True,
rss_safe: bool = False,
video_url: str | None = None,
) -> str:
lead_html, lead_question_html = split_audience_question_html(article.lead) lead_html, lead_question_html = split_audience_question_html(article.lead)
body_html = strip_article_cover_html(article.body_html) body_html = strip_article_cover_html(article.body_html)
body_html, audience_question_html = split_audience_question_html(body_html) body_html, audience_question_html = split_audience_question_html(body_html)
audience_question_html = audience_question_html or lead_question_html audience_question_html = audience_question_html or lead_question_html
body_html, has_video_placeholder = render_video_placeholder(article, body_html, rss_safe=rss_safe) body_html, has_video_placeholder = render_video_placeholder(
article,
body_html,
rss_safe=rss_safe,
video_url=video_url,
)
body_html = sanitize_rss_html(body_html) if rss_safe else body_html body_html = sanitize_rss_html(body_html) if rss_safe else body_html
parts = [lead_html, cover_html(article, rss_safe=rss_safe), body_html] parts = [lead_html, cover_html(article, rss_safe=rss_safe), body_html]
if include_video_embed and not has_video_placeholder: if include_video_embed and not has_video_placeholder:
parts.append(video_embed_html(article, rss_safe=rss_safe)) parts.append(video_embed_html(article, rss_safe=rss_safe, video_url=video_url))
if audience_question_html: if audience_question_html:
parts.append(audience_question_html) parts.append(audience_question_html)
if article.cta_html: if article.cta_html:
@ -239,6 +268,16 @@ def render_article_html(article: Article, include_video_embed: bool = True, rss_
return sanitize_rss_html(html) if rss_safe else html return sanitize_rss_html(html) if rss_safe else html
def local_video_public_url(article: Article, settings: Settings) -> str | None:
"""Return a public MP4 URL only when the downloaded source still exists."""
if not article.video or not article.video.local_video_path:
return None
path = Path(article.video.local_video_path)
if not path.is_file() or path.suffix.lower() != ".mp4":
return None
return f"{settings.public_base_url.rstrip('/')}/videos/{article.video.id}/{quote(path.name)}"
def build_feed_xml(session: Session, settings: Settings) -> str: def build_feed_xml(session: Session, settings: Settings) -> str:
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
articles = session.scalars( articles = session.scalars(
@ -251,7 +290,11 @@ def build_feed_xml(session: Session, settings: Settings) -> str:
items: list[str] = [] items: list[str] = []
for article in articles: for article in articles:
link = article_url(settings, article) link = article_url(settings, article)
content = render_article_html(article, rss_safe=True) content = render_article_html(
article,
rss_safe=True,
video_url=local_video_public_url(article, settings),
)
frames = [] frames = []
if article.video_id: if article.video_id:
frames = session.scalars( frames = session.scalars(
@ -266,7 +309,6 @@ def build_feed_xml(session: Session, settings: Settings) -> str:
enclosure = f'<enclosure url="{escape(cover_url)}" type="{image_mime_type(cover_url)}" />' enclosure = f'<enclosure url="{escape(cover_url)}" type="{image_mime_type(cover_url)}" />'
elif frames and frames[0].public_url: elif frames and frames[0].public_url:
enclosure = f'<enclosure url="{escape(frames[0].public_url)}" type="{image_mime_type(frames[0].public_url)}" />' enclosure = f'<enclosure url="{escape(frames[0].public_url)}" type="{image_mime_type(frames[0].public_url)}" />'
media_player = media_player_xml(article)
items.append( items.append(
f""" f"""
<item> <item>
@ -278,7 +320,6 @@ def build_feed_xml(session: Session, settings: Settings) -> str:
<category>index</category> <category>index</category>
<category>comment-all</category> <category>comment-all</category>
<media:rating scheme="urn:simple">nonadult</media:rating> <media:rating scheme="urn:simple">nonadult</media:rating>
{media_player}
<description><![CDATA[{article.lead or article.title}]]></description> <description><![CDATA[{article.lead or article.title}]]></description>
<content:encoded><![CDATA[{content}]]></content:encoded> <content:encoded><![CDATA[{content}]]></content:encoded>
{enclosure} {enclosure}

View file

@ -1,5 +1,7 @@
import unittest import unittest
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from pathlib import Path
from tempfile import TemporaryDirectory
from xml.etree import ElementTree from xml.etree import ElementTree
from sqlalchemy import create_engine from sqlalchemy import create_engine
@ -41,43 +43,49 @@ class RssFeedTest(unittest.TestCase):
self.assertIn("<p>Тестовый лид.</p>", content) self.assertIn("<p>Тестовый лид.</p>", content)
self.assertIn("<p>Основной текст.</p>", content) self.assertIn("<p>Основной текст.</p>", content)
def test_rss_uses_media_player_without_iframe_embed_markup(self): def test_rss_uses_native_mp4_video_without_iframe_embed_markup(self):
engine = create_engine("sqlite:///:memory:") engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine) Base.metadata.create_all(engine)
video = Video( with TemporaryDirectory() as temp_dir:
external_id="video-123", video_path = Path(temp_dir) / "video.mp4"
source_url="https://vkvideo.ru/video-1_123", video_path.write_bytes(b"test")
title="Видео", video = Video(
) external_id="video-123",
article = Article( source_url="https://vkvideo.ru/video-1_123",
video=video, title="Видео",
slug="video-article", local_video_path=str(video_path),
title="Статья с видео", )
lead="<p>Лид.</p>", article = Article(
body_html=( video=video,
'<figure><iframe src="https://vkvideo.ru/video_ext.php?oid=-1&amp;id=123" ' slug="video-article",
'width="1280" height="720"></iframe></figure>' title="Статья с видео",
"<p>Текст.</p>" lead="<p>Лид.</p>",
), body_html=(
cta_html="", '<figure><iframe src="https://vkvideo.ru/video_ext.php?oid=-1&amp;id=123" '
feature_image_url="", 'width="1280" height="720"></iframe></figure>'
status="published", "<p>Текст.</p>"
rss_guid="video-guid", ),
published_at=datetime.now(timezone.utc) - timedelta(minutes=1), cta_html="",
) feature_image_url="",
status="published",
rss_guid="video-guid",
published_at=datetime.now(timezone.utc) - timedelta(minutes=1),
)
with Session(engine) as session: with Session(engine) as session:
session.add(article) session.add(article)
session.commit() session.commit()
xml = build_feed_xml(session, Settings(public_base_url="https://example.test")) xml = build_feed_xml(session, Settings(public_base_url="https://example.test"))
root = ElementTree.fromstring(xml) root = ElementTree.fromstring(xml)
item = root.find("./channel/item") item = root.find("./channel/item")
self.assertIsNotNone(item) self.assertIsNotNone(item)
content = item.findtext("{http://purl.org/rss/1.0/modules/content/}encoded") or "" content = item.findtext("{http://purl.org/rss/1.0/modules/content/}encoded") or ""
self.assertNotIn("<iframe", content.lower()) self.assertNotIn("<iframe", content.lower())
self.assertIn('<video controls preload="metadata"', content)
self.assertIn('type="video/mp4"', content)
self.assertIn("Смотреть исходное видео VK Видео", content) self.assertIn("Смотреть исходное видео VK Видео", content)
self.assertIn("<media:player", xml) self.assertNotIn("<media:player", xml)
if __name__ == "__main__": if __name__ == "__main__":