Restore VK iframe embeds in RSS
All checks were successful
Deploy Dzen assistant / deploy (push) Successful in 13s
All checks were successful
Deploy Dzen assistant / deploy (push) Successful in 13s
This commit is contained in:
parent
f490094e08
commit
5ebc63dfe9
3 changed files with 42 additions and 92 deletions
|
|
@ -34,7 +34,6 @@ 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")
|
||||||
|
|
|
||||||
72
app/rss.py
72
app/rss.py
|
|
@ -1,8 +1,7 @@
|
||||||
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 quote, urlencode
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
@ -48,22 +47,21 @@ 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, video_url: str | None = None) -> str:
|
def video_embed_html(article: Article, rss_safe: bool = False) -> 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:
|
iframe = ""
|
||||||
video = (
|
if embed_url:
|
||||||
f'<video controls preload="metadata" width="1280" height="720">'
|
iframe = (
|
||||||
f'<source src="{escape(video_url)}" type="video/mp4" />'
|
f'<p><iframe src="{escape(embed_url)}" width="1280" height="720" '
|
||||||
"</video>"
|
'allow="autoplay; encrypted-media; fullscreen; picture-in-picture; screen-wake-lock;" '
|
||||||
|
'frameborder="0" allowfullscreen></iframe></p>'
|
||||||
)
|
)
|
||||||
else:
|
|
||||||
video = ""
|
|
||||||
return f"""
|
return f"""
|
||||||
<h2>Смотреть видео</h2>
|
<h2>Смотреть видео</h2>
|
||||||
{video}
|
{iframe}
|
||||||
<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 ""
|
||||||
|
|
@ -77,19 +75,10 @@ def video_embed_html(article: Article, rss_safe: bool = False, video_url: str |
|
||||||
</section>""".strip()
|
</section>""".strip()
|
||||||
|
|
||||||
|
|
||||||
def render_video_placeholder(
|
def render_video_placeholder(article: Article, html: str, rss_safe: bool = False) -> tuple[str, bool]:
|
||||||
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(
|
return html.replace(VIDEO_PLACEHOLDER, video_embed_html(article, rss_safe=rss_safe), 1), True
|
||||||
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:
|
||||||
|
|
@ -165,11 +154,6 @@ def cover_html(article: Article, rss_safe: bool = False) -> str:
|
||||||
|
|
||||||
|
|
||||||
def sanitize_rss_html(html: str) -> str:
|
def sanitize_rss_html(html: str) -> str:
|
||||||
# Dzen converts arbitrary iframes into an internal atomic:embed marker.
|
|
||||||
# RSS already carries the same video through media:player, so omit iframe
|
|
||||||
# markup here while keeping it available on the public article page.
|
|
||||||
html = re.sub(r"<iframe\b[^>]*>.*?</iframe\s*>", "", html, flags=re.I | re.S)
|
|
||||||
html = re.sub(r"<iframe\b[^>]*/\s*>", "", html, flags=re.I | re.S)
|
|
||||||
html = re.sub(r"\s+class=\"[^\"]*\"", "", html)
|
html = re.sub(r"\s+class=\"[^\"]*\"", "", html)
|
||||||
html = re.sub(r"\s+class='[^']*'", "", html)
|
html = re.sub(r"\s+class='[^']*'", "", html)
|
||||||
html = re.sub(r"</?(?:section|div)\b[^>]*>", "", html, flags=re.I)
|
html = re.sub(r"</?(?:section|div)\b[^>]*>", "", html, flags=re.I)
|
||||||
|
|
@ -239,26 +223,16 @@ 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(
|
def render_article_html(article: Article, include_video_embed: bool = True, rss_safe: bool = False) -> str:
|
||||||
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(
|
body_html, has_video_placeholder = render_video_placeholder(article, body_html, rss_safe=rss_safe)
|
||||||
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, video_url=video_url))
|
parts.append(video_embed_html(article, rss_safe=rss_safe))
|
||||||
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:
|
||||||
|
|
@ -268,16 +242,6 @@ def render_article_html(
|
||||||
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(
|
||||||
|
|
@ -290,11 +254,7 @@ 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(
|
content = render_article_html(article, rss_safe=True)
|
||||||
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(
|
||||||
|
|
@ -309,6 +269,7 @@ 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>
|
||||||
|
|
@ -320,6 +281,7 @@ 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}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,5 @@
|
||||||
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
|
||||||
|
|
@ -43,49 +41,40 @@ 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_native_mp4_video_without_iframe_embed_markup(self):
|
def test_rss_keeps_vk_embed_markup_for_video(self):
|
||||||
engine = create_engine("sqlite:///:memory:")
|
engine = create_engine("sqlite:///:memory:")
|
||||||
Base.metadata.create_all(engine)
|
Base.metadata.create_all(engine)
|
||||||
with TemporaryDirectory() as temp_dir:
|
video = Video(
|
||||||
video_path = Path(temp_dir) / "video.mp4"
|
external_id="video-123",
|
||||||
video_path.write_bytes(b"test")
|
source_url="https://vkvideo.ru/video-1_123",
|
||||||
video = Video(
|
title="Видео",
|
||||||
external_id="video-123",
|
)
|
||||||
source_url="https://vkvideo.ru/video-1_123",
|
article = Article(
|
||||||
title="Видео",
|
video=video,
|
||||||
local_video_path=str(video_path),
|
slug="video-article",
|
||||||
)
|
title="Статья с видео",
|
||||||
article = Article(
|
lead="<p>Лид.</p>",
|
||||||
video=video,
|
body_html="<p>Текст.</p>",
|
||||||
slug="video-article",
|
cta_html="",
|
||||||
title="Статья с видео",
|
feature_image_url="",
|
||||||
lead="<p>Лид.</p>",
|
status="published",
|
||||||
body_html=(
|
rss_guid="video-guid",
|
||||||
'<figure><iframe src="https://vkvideo.ru/video_ext.php?oid=-1&id=123" '
|
published_at=datetime.now(timezone.utc) - timedelta(minutes=1),
|
||||||
'width="1280" height="720"></iframe></figure>'
|
)
|
||||||
"<p>Текст.</p>"
|
|
||||||
),
|
|
||||||
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.assertIn("<iframe", content.lower())
|
||||||
self.assertIn('<video controls preload="metadata"', content)
|
self.assertIn("video_ext.php", content)
|
||||||
self.assertIn('type="video/mp4"', content)
|
|
||||||
self.assertIn("Смотреть исходное видео VK Видео", content)
|
self.assertIn("Смотреть исходное видео VK Видео", content)
|
||||||
self.assertNotIn("<media:player", xml)
|
self.assertIn("<media:player", xml)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue