diff --git a/CHANGELOG.md b/CHANGELOG.md index f9d4a60..0aa1cef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,9 @@ - Nested color and highlight spans override inherited styles of the same type without creating duplicate ProseMirror marks or changing sibling styles. Repeated style properties use the last nonempty declaration. +- Local Markdown images now carry the real width, height, byte size, and + content type that Substack reports for the upload, instead of every image + being recorded as 1456x819 whatever its real shape. ### Development diff --git a/substack/mdrender.py b/substack/mdrender.py index 355889f..61d5a5f 100644 --- a/substack/mdrender.py +++ b/substack/mdrender.py @@ -250,8 +250,24 @@ def _only_image(inline: SyntaxTreeNode) -> Optional[SyntaxTreeNode]: return None +def _uploaded_image_details(uploaded: Dict) -> Dict: + """Pick the image's real size and type out of Substack's upload response.""" + details: Dict = {} + width, height = uploaded.get("imageWidth"), uploaded.get("imageHeight") + # Only trust the dimensions as a pair: a lone or malformed value would + # distort the image, which is worse than the placeholder size. + if all(type(value) is int and value > 0 for value in (width, height)): + details["width"], details["height"] = width, height + if type(uploaded.get("bytes")) is int: + details["size_bytes"] = uploaded["bytes"] + if isinstance(uploaded.get("contentType"), str): + details["mime_type"] = uploaded["contentType"] + return details + + def _captioned_image(img: SyntaxTreeNode, api) -> Dict: src = img.attrs.get("src", "") + details: Dict = {} if api is not None and ( urlsplit(src).scheme.lower() not in ("http", "https") and not src.startswith("//") @@ -274,6 +290,7 @@ def _captioned_image(img: SyntaxTreeNode, api) -> Dict: except Exception as exc: raise ValueError(f"Failed to upload local image: {path}") from exc src = url + details = _uploaded_image_details(uploaded) # markdown-it stores the image alt text as the node's content, not in attrs. alt = img.content or img.attrs.get("alt") or None # Standard markdown image title `![alt](src "caption")` maps to Substack's caption node. @@ -284,6 +301,7 @@ def _captioned_image(img: SyntaxTreeNode, api) -> Dict: alt=alt, href=getattr(img, "_link_href", None), caption=caption, + **details, ) diff --git a/substack/nodes.py b/substack/nodes.py index ce751cf..48e5bff 100644 --- a/substack/nodes.py +++ b/substack/nodes.py @@ -121,6 +121,10 @@ def captioned_image( href: Optional[str] = None, caption: Optional[List[Dict]] = None, image_size: str = "normal", + width: int = 1456, + height: int = 819, + size_bytes: Optional[int] = None, + mime_type: Optional[str] = None, ) -> Dict: content: List[Dict] = [ { @@ -130,13 +134,13 @@ def captioned_image( "srcNoWatermark": None, "fullscreen": False, "imageSize": image_size, - "height": 819, - "width": 1456, + "height": height, + "width": width, "resizeWidth": 728 if image_size == "normal" else None, - "bytes": None, + "bytes": size_bytes, "alt": alt, "title": None, - "type": None, + "type": mime_type, "href": href, "belowTheFold": False, "topImage": False, diff --git a/tests/substack/test_local_markdown_images.py b/tests/substack/test_local_markdown_images.py index 1fb7859..68dd3ff 100644 --- a/tests/substack/test_local_markdown_images.py +++ b/tests/substack/test_local_markdown_images.py @@ -124,3 +124,46 @@ def test_remote_url_unchanged(api, src): ) def test_without_api_retains_source(src): assert render(src) == src + + +def image_attrs(src, api): + post = Post(title="Image test", subtitle="", user_id=1) + post.from_markdown(f"![alt](<{src}>)", api=api) + return post.draft_body["content"][0]["content"][0]["attrs"] + + +def test_uploaded_image_takes_size_and_type_from_upload_response(tmp_path, api): + path = tmp_path / "tall.png" + path.touch() + api.get_image.return_value = { + "url": UPLOADED, + "imageWidth": 1440, + "imageHeight": 3576, + "bytes": 418331, + "contentType": "image/png", + } + attrs = image_attrs(str(path), api) + assert (attrs["width"], attrs["height"]) == (1440, 3576) + assert attrs["bytes"] == 418331 + assert attrs["type"] == "image/png" + + +@pytest.mark.parametrize( + "size", + [ + {}, + {"imageWidth": 1440}, + {"imageWidth": None, "imageHeight": None}, + {"imageWidth": 0, "imageHeight": 0}, + {"imageWidth": "1440", "imageHeight": "3576"}, + {"imageWidth": True, "imageHeight": True}, + ], +) +def test_uploaded_image_keeps_default_size_without_usable_dimensions( + tmp_path, api, size +): + path = tmp_path / "image.png" + path.touch() + api.get_image.return_value = {"url": UPLOADED, **size} + attrs = image_attrs(str(path), api) + assert (attrs["width"], attrs["height"]) == (1456, 819)