Skip to content

Commit

Permalink
bug: humanize byte size error on community image upload
Browse files Browse the repository at this point in the history
  • Loading branch information
Meowcenary committed Feb 12, 2025
1 parent db96430 commit b059dfc
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
11 changes: 9 additions & 2 deletions invenio_communities/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from flask_babel import ngettext
from invenio_i18n import gettext as _

from .utils import humanize_byte_size


class CommunityError(Exception):
"""Base exception for community errors."""
Expand Down Expand Up @@ -44,10 +46,15 @@ class LogoSizeLimitError(CommunityError):

def __init__(self, limit, file_size):
"""Initialise error."""
limit_value, limit_unit = humanize_byte_size(limit)
file_size_value, file_size_unit = humanize_byte_size(file_size)
super().__init__(
_(
"Logo size limit exceeded. Limit: {limit} bytes Given: {file_size} bytes".format(
limit=ceil(limit), file_size=ceil(file_size)
"Logo size limit exceeded. Limit: {limit_value} {limit_unit} Given: {file_size_value} {file_size_unit}".format(
limit_value=limit_value,
limit_unit=limit_unit,
file_size_value=file_size_value,
file_size_unit=file_size_unit,
)
)
)
Expand Down
13 changes: 13 additions & 0 deletions invenio_communities/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

"""Utilities."""

from decimal import ROUND_HALF_UP, Decimal

from flask import session
from flask_principal import Identity
from invenio_accounts.models import Role
Expand Down Expand Up @@ -109,3 +111,14 @@ def on_datastore_post_commit(sender, session):
users = role.users.all()
for user in users:
on_user_membership_change(Identity(user.id))


def humanize_byte_size(size):
"""Converts bytes to largest unit (e.g., KB, MB, GB)."""
BYTES_PER_UNIT = 1000
s = Decimal(size)
q = Decimal("0.00")
for unit in ["B", "KB", "MB", "GB", "TB", "PB"]:
if s < BYTES_PER_UNIT:
return s.quantize(q, rounding=ROUND_HALF_UP), unit
s /= BYTES_PER_UNIT
3 changes: 3 additions & 0 deletions tests/communities/test_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,9 @@ def test_logo_max_content_length(
data=BytesIO(logo_data),
)
assert res.status_code == 400
assert (
res.json["message"] == "Logo size limit exceeded. Limit: 1.00 MB Given: 4.00 MB"
)

# Update logo with small content
logo_data = b"logo"
Expand Down

0 comments on commit b059dfc

Please sign in to comment.