Skip to content

Commit

Permalink
Handle bad base64 images
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexMili committed Dec 22, 2024
1 parent f0d5d08 commit fadf801
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
25 changes: 13 additions & 12 deletions src/extract_favicon/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,18 +145,19 @@ def _load_base64_img(favicon: Favicon, force: bool = False) -> Favicon:
if suffix == "svg+xml":
suffix = "svg"

bytes_content = base64.b64decode(data_img[1])
img, is_valid = _open_and_verify_image(bytes_content)
width, height, img_format = _get_meta_image(img)

favicon = favicon._replace(
width=width,
height=height,
format=img_format,
valid=is_valid,
image=img,
reachable=True,
)
if len(data_img) > 1:
bytes_content = base64.b64decode(data_img[1])
img, is_valid = _open_and_verify_image(bytes_content)
width, height, img_format = _get_meta_image(img)

favicon = favicon._replace(
width=width,
height=height,
format=img_format,
valid=is_valid,
image=img,
reachable=len(data_img[1]) > 0,
)

return favicon

Expand Down
17 changes: 17 additions & 0 deletions test/test_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,23 @@ async def test_base64_async(base64_img):
assert favicons[0].height == 1


@pytest.mark.parametrize(
"url,is_valid",
[("data:image/png;base64,", False), ("data:;base64,", False), ("data:", None)],
ids=["No img data", "No format data", "Only data"],
)
def test_base64_wrong(url, is_valid):
fav = Favicon(url, format=None, width=0, height=0)
fav = extract_favicon.loader._load_base64_img(fav)
assert fav.url == fav.url
assert fav.format is None
assert fav.http is None
assert fav.valid is is_valid
assert fav.image is None
assert fav.width == 0
assert fav.height == 0


def test_svg(svg_url):
fav = Favicon(svg_url, format=None, width=0, height=0)
favicons = extract_favicon.download([fav])
Expand Down

0 comments on commit fadf801

Please sign in to comment.