Fall back to a page for oEmbed seeding when no posts exist

This commit is contained in:
Icex0
2026-07-18 21:00:04 +02:00
parent 9b9ff85645
commit 6813beb38a
2 changed files with 24 additions and 8 deletions
+22 -8
View File
@@ -152,19 +152,33 @@ class PreAuthAdminCreator:
return admin_id
def _loopback_embed_urls(self, nonce: str) -> List[str]:
post_link = self._first_public_post_link()
split = urllib.parse.urlsplit(post_link)
base_link = self._first_embeddable_link()
split = urllib.parse.urlsplit(base_link)
return [
urllib.parse.urlunsplit((split.scheme, split.netloc, split.path, split.query, f"{nonce}{i}"))
for i in range(3)
]
def _first_public_post_link(self) -> str:
with self._open_rest("/wp/v2/posts", {"per_page": "1", "_fields": "link"}) as response:
posts = json.loads(response.read())
if not posts or not posts[0].get("link"):
raise RuntimeError("could not find a public post link for oEmbed seeding")
return posts[0]["link"]
def _first_embeddable_link(self) -> str:
"""Return a published, public permalink to seed the oEmbed cache from.
Any singular public post or page works: rendering ``[embed]<link>`` makes WordPress create
the backing ``oembed_cache`` posts. A default install always qualifies -- ``wp_install_defaults()``
publishes both the "Hello world!" post and the "Sample Page" -- so this normally hits the
first route; the page fallback covers the rare posts-less site.
"""
for route in ("/wp/v2/posts", "/wp/v2/pages"):
try:
with self._open_rest(route, {"per_page": "1", "_fields": "link"}) as response:
items = json.loads(response.read())
except urllib.error.HTTPError:
continue # route disabled/restricted -> try the next one
if items and items[0].get("link"):
return items[0]["link"]
raise RuntimeError(
"no public post or page found to seed the oEmbed cache "
"(need at least one published post or page)"
)
def _prime_oembed_posts(self, embed_urls: Iterable[str]) -> None:
content = "".join(f'[embed width="500" height="750"]{url}[/embed]' for url in embed_urls)