Embed local MP4 videos in RSS
All checks were successful
Deploy Dzen assistant / deploy (push) Successful in 21s
All checks were successful
Deploy Dzen assistant / deploy (push) Successful in 21s
This commit is contained in:
parent
4585f32c72
commit
f490094e08
3 changed files with 87 additions and 37 deletions
|
|
@ -34,6 +34,7 @@ app.add_middleware(AuthMiddleware)
|
|||
settings = get_settings()
|
||||
mimetypes.add_type("image/webp", ".webp")
|
||||
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")
|
||||
|
||||
admin_dist = Path("/app/admin_dist")
|
||||
|
|
|
|||
61
app/rss.py
61
app/rss.py
|
|
@ -1,7 +1,8 @@
|
|||
from datetime import datetime, timezone
|
||||
from html import escape, unescape
|
||||
from pathlib import Path
|
||||
import re
|
||||
from urllib.parse import urlencode
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from sqlalchemy import select
|
||||
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)}"
|
||||
|
||||
|
||||
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:
|
||||
return ""
|
||||
embed_url = vk_video_embed_url(article.video.source_url)
|
||||
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"""
|
||||
<h2>Смотреть видео</h2>
|
||||
{video}
|
||||
<p><a href="{escape(article.video.source_url)}">Смотреть исходное видео VK Видео</a></p>""".strip()
|
||||
if not embed_url:
|
||||
return ""
|
||||
|
|
@ -67,10 +77,19 @@ def video_embed_html(article: Article, rss_safe: bool = False) -> str:
|
|||
</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:
|
||||
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:
|
||||
|
|
@ -220,16 +239,26 @@ def media_player_xml(article: Article) -> str:
|
|||
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)
|
||||
body_html = strip_article_cover_html(article.body_html)
|
||||
body_html, audience_question_html = split_audience_question_html(body_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
|
||||
parts = [lead_html, cover_html(article, rss_safe=rss_safe), body_html]
|
||||
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:
|
||||
parts.append(audience_question_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
|
||||
|
||||
|
||||
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:
|
||||
now = datetime.now(timezone.utc)
|
||||
articles = session.scalars(
|
||||
|
|
@ -251,7 +290,11 @@ def build_feed_xml(session: Session, settings: Settings) -> str:
|
|||
items: list[str] = []
|
||||
for article in articles:
|
||||
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 = []
|
||||
if article.video_id:
|
||||
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)}" />'
|
||||
elif frames and 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(
|
||||
f"""
|
||||
<item>
|
||||
|
|
@ -278,7 +320,6 @@ def build_feed_xml(session: Session, settings: Settings) -> str:
|
|||
<category>index</category>
|
||||
<category>comment-all</category>
|
||||
<media:rating scheme="urn:simple">nonadult</media:rating>
|
||||
{media_player}
|
||||
<description><![CDATA[{article.lead or article.title}]]></description>
|
||||
<content:encoded><![CDATA[{content}]]></content:encoded>
|
||||
{enclosure}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import unittest
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from xml.etree import ElementTree
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
|
|
@ -41,13 +43,17 @@ class RssFeedTest(unittest.TestCase):
|
|||
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:")
|
||||
Base.metadata.create_all(engine)
|
||||
with TemporaryDirectory() as temp_dir:
|
||||
video_path = Path(temp_dir) / "video.mp4"
|
||||
video_path.write_bytes(b"test")
|
||||
video = Video(
|
||||
external_id="video-123",
|
||||
source_url="https://vkvideo.ru/video-1_123",
|
||||
title="Видео",
|
||||
local_video_path=str(video_path),
|
||||
)
|
||||
article = Article(
|
||||
video=video,
|
||||
|
|
@ -76,8 +82,10 @@ class RssFeedTest(unittest.TestCase):
|
|||
self.assertIsNotNone(item)
|
||||
content = item.findtext("{http://purl.org/rss/1.0/modules/content/}encoded") or ""
|
||||
self.assertNotIn("<iframe", content.lower())
|
||||
self.assertIn('<video controls preload="metadata"', content)
|
||||
self.assertIn('type="video/mp4"', content)
|
||||
self.assertIn("Смотреть исходное видео VK Видео", content)
|
||||
self.assertIn("<media:player", xml)
|
||||
self.assertNotIn("<media:player", xml)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
Loading…
Reference in a new issue