embedly: iframe sizing fix

This commit is contained in:
ZhymabekRoman 2025-06-27 01:06:13 +05:00
parent 684cc53343
commit 04e5c10424
4 changed files with 131 additions and 19 deletions

File diff suppressed because one or more lines are too long

View file

@ -218,6 +218,7 @@ class MediumParser:
preview_image_id: str,
highlights: list,
tags: list,
post_data: dict,
) -> tuple[list, str, str]:
paragraphs = content["bodyModel"]["paragraphs"]
tags_list = [tag["displayTitle"] for tag in tags]
@ -604,14 +605,75 @@ class MediumParser:
)
out_paragraphs.append(embed_template_rendered)
elif paragraph["type"] == "IFRAME":
iframe_template = jinja_env.from_string(
'<div class="mt-7"><iframe class="w-full" src="{{ host_address }}/render_iframe/{{ iframe_id }}" referrerpolicy="no-referrer" allowfullscreen="" frameborder="0" scrolling="no"></iframe></div>'
)
iframe_template_rendered = iframe_template.render(
host_address=self.host_address,
iframe_id=paragraph["iframe"]["mediaResource"]["id"],
)
out_paragraphs.append(iframe_template_rendered)
logger.debug(f"Processing IFRAME paragraph")
# First check if we have direct mediaResource in the iframe
media_resource = paragraph.get("iframe", {}).get("mediaResource", {})
# If mediaResource is just a reference, look it up in post_data
media_resource_ref = paragraph.get("iframe", {}).get("mediaResource", {}).get("__ref")
if media_resource_ref and not media_resource.get("id") and not media_resource.get("iframeSrc"):
logger.debug(f"Found media resource reference: {media_resource_ref}")
data_payload = post_data.get("data", {})
if media_resource_ref in data_payload:
media_resource = data_payload[media_resource_ref]
logger.debug(f"Found media resource for ref: {media_resource_ref}")
else:
logger.warning(f"Could not find media resource for ref: {media_resource_ref}")
# Get iframe source from mediaResource
iframe_src_val = media_resource.get("iframeSrc")
iframe_id = media_resource.get("id")
# Determine the source URL for the iframe
src = iframe_src_val
if not src and iframe_id:
logger.debug(f"Using fallback iframe URL with ID: {iframe_id}")
src = f"{self.host_address}/render_iframe/{iframe_id}"
if not src:
logger.warning("No iframe source found, skipping iframe")
current_pos += 1
continue
# Get iframe dimensions
iframe_width = media_resource.get("iframeWidth")
iframe_height = media_resource.get("iframeHeight")
# If dimensions are available in paragraph.iframe directly, use those
if not iframe_width and paragraph.get("iframe", {}).get("iframeWidth"):
iframe_width = paragraph["iframe"]["iframeWidth"]
if not iframe_height and paragraph.get("iframe", {}).get("iframeHeight"):
iframe_height = paragraph["iframe"]["iframeHeight"]
logger.debug(f"Iframe dimensions: {iframe_width}x{iframe_height}")
# Render with aspect ratio if we have valid dimensions
if iframe_width and iframe_height and iframe_width > 0:
ratio = (iframe_height / iframe_width) * 100
iframe_template = jinja_env.from_string(
"""<div class="mt-7"><div>
<iframe class="w-full" src="{{ src }}" referrerpolicy="no-referrer" width="{{ iframe_width }}" height="{{ iframe_height }}" allowfullscreen="" frameborder="0" scrolling="no"></iframe>
</div></div>"""
)
iframe_template_rendered = iframe_template.render(
src=src,
ratio=f"{ratio:.4f}",
iframe_width=iframe_width or "100%",
iframe_height=iframe_height or "100%",
)
out_paragraphs.append(iframe_template_rendered)
else:
# Fallback to responsive iframe without aspect ratio
iframe_template = jinja_env.from_string(
'<div class="mt-7"><iframe class="w-full" src="{{ src }}" width="{{ iframe_width }}" height="{{ iframe_height }}" referrerpolicy="no-referrer" allowfullscreen="" frameborder="0" scrolling="no"></iframe></div>'
)
iframe_template_rendered = iframe_template.render(
src=src,
iframe_width=iframe_width or "100%",
iframe_height=iframe_height or "100%",
)
out_paragraphs.append(iframe_template_rendered)
else:
logger.error(f"Unknown {paragraph['type']}: {paragraph}")
@ -702,6 +764,7 @@ class MediumParser:
post_data["data"]["post"]["previewImage"]["id"],
post_data["data"]["post"]["highlights"],
post_data["data"]["post"]["tags"],
post_data,
)
# Await metadata

View file

@ -40,9 +40,5 @@ def patch_iframe_content(content: str) -> str:
)
soup = BeautifulSoup(content, "html.parser")
iframe_resizer_script = BeautifulSoup(
'<script src="https://cdn.jsdelivr.net/npm/@iframe-resizer/child"></script>', "html.parser"
).script
soup.head.append(iframe_resizer_script)
return soup.prettify()

View file

@ -26,11 +26,58 @@
<meta name="theme-color" content="#ffffff">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
<script src="https://cdn.jsdelivr.net/npm/@iframe-resizer/parent"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.8.4/dist/lazyload.min.js"></script> -->
<script src="https://cdn.jsdelivr.net/npm/lightense-images@1.0.17/dist/lightense.min.js"></script>
<script>iframeResize({ license: 'GPLv3' })</script>
<script>
window._resizeIframe = function (obj) {
const logMessage = `Received _resizeIframe call: iframe=${obj.iframe ? obj.iframe.id : 'unknown'}, height=${obj.height}`;
if (obj.iframe) {
obj.iframe.height = obj.height;
}
console.log(obj.iframe)
console.log(logMessage);
};
</script>
<script>
window.addEventListener('message', function (event) {
console.log('Event data:', JSON.stringify(event.data))
if (typeof event.data === 'string') {
let parsedData = JSON.parse(event.data);
console.log('Event data type:', typeof parsedData)
if (parsedData && parsedData.method === 'iframe.resize' && parsedData.context === 'iframe.resize') {
console.log('Resizing iframe - Source:', parsedData.src, 'Height:', parsedData.height, 'Method:', parsedData.method)
const iframes = document.querySelectorAll('iframe');
for (let iframe of iframes) {
if (iframe.src === parsedData.src) {
console.log('Setting iframe height to:', parsedData.height)
console.log(iframe)
iframe.height = parsedData.height;
break;
}
}
}
}
});
</script>
<style>
.responsive-object {
position: relative;
height: 0;
overflow: hidden;
margin: 10px 0;
}
.responsive-object iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<div class="fixed bottom-4 left-4 hidden" style="z-index: 999999;">
<button id="openProblemModal"
@ -69,13 +116,17 @@
Dear Freedium users,
</br>
</br>
We've updated our donation options to provide you with more ways to support our mission. Your contributions are invaluable in helping us maintain and improve Freedium, ensuring we can continue to provide unrestricted access to quality content.
We've updated our donation options to provide you with more ways to support our mission. Your contributions
are invaluable in helping us maintain and improve Freedium, ensuring we can continue to provide unrestricted
access to quality content.
</br>
</br>
We now offer multiple platforms for donations, including Patreon, Ko-fi, and Liberapay. Each option allows you to support us in the way that's most convenient for you.
We now offer multiple platforms for donations, including Patreon, Ko-fi, and Liberapay. Each option allows
you to support us in the way that's most convenient for you.
</br>
</br>
Your support, no matter the platform or amount, makes a significant difference. It allows us to cover our operational costs and invest in enhancing Freedium's features and reliability.
Your support, no matter the platform or amount, makes a significant difference. It allows us to cover our
operational costs and invest in enhancing Freedium's features and reliability.
</br>
</br>
Thank you for being a part of the Freedium community and for your continued support.
@ -417,4 +468,4 @@
</script>
</body>
</html>
</html>