Extend the public API: news excerpts/detail, game team logos, sponsor logo dimensions, player licenses
- news: NewsItemOut gains `excerpt` (truncated body); GET /news/{slug}/
fetches a single item. slug already auto-populates on save, but a
data migration backfills any pre-existing blank ones.
- games: home_team/away_team change from plain strings to {id, name,
logo_url} objects -- home links to the actual Team (logo from the
club's own logo, since teams have none of their own), away links
to the actual Opponent (which already had a logo field). Breaking
change for any existing consumer of the old string shape.
- sponsors: SponsorOut gains logo_width/logo_height, computed in
Sponsor.save() -- Pillow for raster, a bounded regex read of the
SVG root tag for vector logos (not a full XML parse, since that's
exposed to entity-expansion attacks on untrusted uploads). A data
migration backfills dimensions for existing sponsor logos.
- teams: PlayerOut gains `license`, sourced from ClubMembership (not
Member -- it's per-club, per-season), batched in one query.
This commit is contained in:
@@ -21,6 +21,8 @@ class SponsorOut(Schema):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
logo_url: str | None
|
||||
logo_width: int | None
|
||||
logo_height: int | None
|
||||
url: str | None
|
||||
start_date: date
|
||||
end_date: date | None
|
||||
@@ -31,6 +33,8 @@ def _to_sponsor_out(sponsor, request) -> SponsorOut:
|
||||
id=sponsor.pk,
|
||||
name=sponsor.name,
|
||||
logo_url=request.build_absolute_uri(sponsor.logo.url) if sponsor.logo else None,
|
||||
logo_width=sponsor.logo_width,
|
||||
logo_height=sponsor.logo_height,
|
||||
url=sponsor.url or None,
|
||||
start_date=sponsor.start_date,
|
||||
end_date=sponsor.end_date,
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Generated by Django 6.0.6 on 2026-08-07 14:26
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
from club.services.images import get_image_dimensions
|
||||
|
||||
|
||||
def backfill_logo_dimensions(apps, schema_editor):
|
||||
"""Existing sponsors uploaded a logo before these fields existed, so
|
||||
Sponsor.save()'s new dimension computation never ran for them."""
|
||||
Sponsor = apps.get_model("club", "Sponsor")
|
||||
for sponsor in Sponsor.objects.exclude(logo=""):
|
||||
width, height = get_image_dimensions(sponsor.logo)
|
||||
Sponsor.objects.filter(pk=sponsor.pk).update(logo_width=width, logo_height=height)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('club', '0019_sponsor'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='sponsor',
|
||||
name='logo_height',
|
||||
field=models.PositiveIntegerField(blank=True, editable=False, null=True, verbose_name='logo height'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='sponsor',
|
||||
name='logo_width',
|
||||
field=models.PositiveIntegerField(blank=True, editable=False, null=True, verbose_name='logo width'),
|
||||
),
|
||||
migrations.RunPython(backfill_logo_dimensions, migrations.RunPython.noop),
|
||||
]
|
||||
@@ -174,6 +174,12 @@ class Sponsor(ClubScopedModel):
|
||||
# Pillow validation can't read those.
|
||||
validators=[FileExtensionValidator(allowed_extensions=["png", "jpg", "jpeg", "gif", "webp", "svg"])],
|
||||
)
|
||||
# Not user-editable: recomputed from the logo file itself on every save, same reasoning
|
||||
# NewsPhoto/TeamPhoto don't need this -- FileField (not ImageField) means Django never
|
||||
# populates width/height on its own. The public API exposes these so a consumer can lay
|
||||
# out a sponsor strip without waiting on the image to load.
|
||||
logo_width = models.PositiveIntegerField(_("logo width"), null=True, blank=True, editable=False)
|
||||
logo_height = models.PositiveIntegerField(_("logo height"), null=True, blank=True, editable=False)
|
||||
url = models.URLField(_("URL"), blank=True, help_text=_("The sponsor's own website, if they have one."))
|
||||
|
||||
start_date = models.DateField(_("start date"))
|
||||
@@ -191,6 +197,14 @@ class Sponsor(ClubScopedModel):
|
||||
if self.end_date is not None and self.start_date is not None and self.end_date < self.start_date:
|
||||
raise ValidationError({"end_date": _("End date can't be before the start date.")})
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
# Deferred: club.services (via its __init__) imports back from club.models, so a
|
||||
# module-level import here would be circular.
|
||||
from club.services.images import get_image_dimensions
|
||||
|
||||
self.logo_width, self.logo_height = get_image_dimensions(self.logo) if self.logo else (None, None)
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
|
||||
class Season(ClubScopedModel):
|
||||
start_date = models.DateField(_("start date"))
|
||||
|
||||
82
club/services/images.py
Normal file
82
club/services/images.py
Normal file
@@ -0,0 +1,82 @@
|
||||
"""Dimensions for uploads that aren't Django ImageFields.
|
||||
|
||||
Logos (Club.logo, Sponsor.logo) are plain FileFields, not ImageFields --
|
||||
Pillow can't validate SVGs, and crests/sponsor logos are commonly vector
|
||||
files -- so there's no automatic width_field/height_field the way there
|
||||
would be on an ImageField. This fills that gap: Pillow for raster formats,
|
||||
a bounded regex read of the root <svg> tag for vector ones (not a full XML
|
||||
parse -- this reads untrusted uploads, and a parser is exposed to entity
|
||||
expansion attacks a plain attribute read never is).
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
_SVG_TAG_RE = re.compile(rb"<svg\b[^>]*>", re.IGNORECASE | re.DOTALL)
|
||||
_WIDTH_RE = re.compile(rb"""\bwidth\s*=\s*["']([^"']+)["']""", re.IGNORECASE)
|
||||
_HEIGHT_RE = re.compile(rb"""\bheight\s*=\s*["']([^"']+)["']""", re.IGNORECASE)
|
||||
_VIEWBOX_RE = re.compile(rb"""\bviewBox\s*=\s*["']\s*([\d.+-]+)[ ,]+([\d.+-]+)[ ,]+([\d.+-]+)[ ,]+([\d.+-]+)""", re.IGNORECASE)
|
||||
_LEADING_NUMBER_RE = re.compile(r"[\d.]+")
|
||||
|
||||
#: The root <svg> tag is always near the top of the file -- no need to read
|
||||
#: (or regex-scan) anything past a small header.
|
||||
_SVG_HEAD_BYTES = 8192
|
||||
|
||||
|
||||
def _svg_length(raw: bytes) -> int | None:
|
||||
"""Parse an SVG length attribute (``"200"``, ``"200px"``) to a rounded
|
||||
int, or None if it's relative (``"100%"``) and so not a real pixel size."""
|
||||
text = raw.decode("utf-8", errors="ignore").strip()
|
||||
if text.endswith("%"):
|
||||
return None
|
||||
match = _LEADING_NUMBER_RE.match(text)
|
||||
return round(float(match.group(0))) if match else None
|
||||
|
||||
|
||||
def _svg_dimensions(file) -> tuple[int | None, int | None]:
|
||||
try:
|
||||
file.seek(0)
|
||||
head = file.read(_SVG_HEAD_BYTES)
|
||||
except OSError:
|
||||
return None, None
|
||||
# Reset for whatever reads the file next (e.g. FileField writing it to storage).
|
||||
file.seek(0)
|
||||
|
||||
tag_match = _SVG_TAG_RE.search(head)
|
||||
svg_tag = tag_match.group(0) if tag_match else head
|
||||
|
||||
width_match, height_match = _WIDTH_RE.search(svg_tag), _HEIGHT_RE.search(svg_tag)
|
||||
if width_match and height_match:
|
||||
width, height = _svg_length(width_match.group(1)), _svg_length(height_match.group(1))
|
||||
if width and height:
|
||||
return width, height
|
||||
|
||||
viewbox_match = _VIEWBOX_RE.search(svg_tag)
|
||||
if viewbox_match:
|
||||
_, _, width, height = viewbox_match.groups()
|
||||
return round(float(width)), round(float(height))
|
||||
|
||||
return None, None
|
||||
|
||||
|
||||
def get_image_dimensions(file) -> tuple[int | None, int | None]:
|
||||
"""Best-effort (width, height) for an uploaded logo -- (None, None) if the
|
||||
file can't be read as an image (corrupt upload, unrecognised format)."""
|
||||
if not file:
|
||||
return None, None
|
||||
|
||||
name = getattr(file, "name", "") or ""
|
||||
if name.lower().endswith(".svg"):
|
||||
return _svg_dimensions(file)
|
||||
|
||||
try:
|
||||
file.seek(0)
|
||||
with Image.open(file) as image:
|
||||
size = image.size
|
||||
# Reset for whatever reads the file next (e.g. FileField writing it to storage) --
|
||||
# only on the success path, since a failed open/read leaves nothing to rewind.
|
||||
file.seek(0)
|
||||
return size
|
||||
except (OSError, UnidentifiedImageError):
|
||||
return None, None
|
||||
Reference in New Issue
Block a user