Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
18 changes: 18 additions & 0 deletions substack/mdrender.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("//")
Expand All @@ -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.
Expand All @@ -284,6 +301,7 @@ def _captioned_image(img: SyntaxTreeNode, api) -> Dict:
alt=alt,
href=getattr(img, "_link_href", None),
caption=caption,
**details,
)


Expand Down
12 changes: 8 additions & 4 deletions substack/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] = [
{
Expand All @@ -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,
Expand Down
43 changes: 43 additions & 0 deletions tests/substack/test_local_markdown_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading