Skip to content

Commit

Permalink
move assets to media folder
Browse files Browse the repository at this point in the history
  • Loading branch information
laggron42 committed Jan 15, 2025
1 parent 3d2c5ac commit 5e44962
Show file tree
Hide file tree
Showing 15 changed files with 121 additions and 10 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pgbackups

# static
static
media

# cache
.pytest_cache
Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ repos:
- black
- --filter-files
- repo: https://github.com/RobertCraigie/pyright-python
rev: v1.1.335
rev: v1.1.390
hooks:
- id: pyright
language_version: python3.13
Expand Down
106 changes: 106 additions & 0 deletions admin_panel/bd_models/migrations/0002_move_upload_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Generated by Django 5.1.4 on 2025-01-15 13:27

from pathlib import Path
from typing import TYPE_CHECKING

from bd_models.models import Ball, Economy, Regime, Special
from django.db import migrations
from django.db.models import Case, ImageField, When
from django.db.models.expressions import F, Value
from django.db.models.functions import Concat, Replace

if TYPE_CHECKING:
from django.apps.registry import Apps
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.models import Expression

MEDIA = Path("./media")
OLD_STATIC = Path("../static/uploads")
CORE_SRC = Path("../ballsdex/core/image_generator/src")

DEFAULT_ASSETS = [
"capitalist.png",
"communist.png",
"democracy.png",
"dictatorship.png",
"shiny.png",
"union.png",
]


def _replace_text(column: str, reverse: bool = False) -> "dict[str, Expression]":
if reverse:
r = Case(
When(
**{f"{column}__in": DEFAULT_ASSETS},
then=Concat(
Value("/ballsdex/core/image_generator/src/", output_field=ImageField()),
F(column),
),
),
default=Concat(Value("/static/uploads/", output_field=ImageField()), F(column)),
)
else:
r = Replace(
Replace(F(column), Value("/ballsdex/core/image_generator/src/"), Value("")),
Value("/static/uploads/", output_field=ImageField()),
Value("", output_field=ImageField()),
)
return {column: r}


def _check_reserved_names():
for file in OLD_STATIC.glob("*"):
if file.name in DEFAULT_ASSETS:
raise ValueError(
f"The file {file.absolute()} has a reserved name and will conflict with Ballsdex "
"prodivded assets. You need to delete it or move it before proceeding. "
"Once this is done, reupload the asset via the new admin panel."
)


def move_forwards(apps: "Apps", schema_editor: "BaseDatabaseSchemaEditor"):
assert MEDIA.is_dir(follow_symlinks=False)
assert OLD_STATIC.is_dir(follow_symlinks=False)
assert CORE_SRC.is_dir(follow_symlinks=False)
_check_reserved_names()

Ball.objects.update(**_replace_text("wild_card"), **_replace_text("collection_card"))
Economy.objects.update(**_replace_text("icon"))
Regime.objects.update(**_replace_text("background"))
Special.objects.update(**_replace_text("background"))

for file in OLD_STATIC.glob("*"):
if file.name == ".gitkeep":
continue
file.rename(MEDIA / file.name)
# the files in /ballsdex/core/image_generator/src/ will be moved by git


def move_backwards(apps: "Apps", schema_editor: "BaseDatabaseSchemaEditor"):
assert MEDIA.is_dir(follow_symlinks=False)
assert OLD_STATIC.is_dir(follow_symlinks=False)

Ball.objects.update(
**_replace_text("wild_card", reverse=True),
**_replace_text("collection_card", reverse=True),
)
Economy.objects.update(**_replace_text("icon", reverse=True))
Regime.objects.update(**_replace_text("background", reverse=True))
Special.objects.update(**_replace_text("background", reverse=True))

for file in MEDIA.glob("*"):
if file.name in DEFAULT_ASSETS:
continue
if file.name == ".gitkeep":
continue
file.rename(OLD_STATIC / file.name)


class Migration(migrations.Migration):

dependencies = [
("bd_models", "0001_initial"),
]

operations = [migrations.RunPython(move_forwards, move_backwards, atomic=True)]
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
2 changes: 1 addition & 1 deletion admin_panel/preview/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async def render_image(request: HttpRequest, ball_pk: int) -> HttpResponse:

ball = await Ball.get(pk=ball_pk)
instance = BallInstance(ball=ball, count=1)
image = draw_card(instance)
image = draw_card(instance, media_path="./media/")

response = HttpResponse(content_type="image/png")
image.save(response, "PNG") # type: ignore
Expand Down
12 changes: 7 additions & 5 deletions ballsdex/core/image_generator/image_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,22 @@
credits_font = ImageFont.truetype(str(SOURCES_PATH / "arial.ttf"), 40)


def draw_card(ball_instance: "BallInstance"):
def draw_card(ball_instance: "BallInstance", media_path: str = "../admin_panel/media/"):
ball = ball_instance.countryball
ball_health = (237, 115, 101, 255)
ball_credits = ball.credits

if special_image := ball_instance.special_card:
image = Image.open("." + special_image)
image = Image.open(media_path + special_image)
if ball_instance.specialcard and ball_instance.specialcard.credits:
ball_credits += f" • {ball_instance.specialcard.credits}"
else:
image = Image.open("." + ball.cached_regime.background)
image = Image.open(media_path + ball.cached_regime.background)
image = image.convert("RGBA")
icon = (
Image.open("." + ball.cached_economy.icon).convert("RGBA") if ball.cached_economy else None
Image.open(media_path + ball.cached_economy.icon).convert("RGBA")
if ball.cached_economy
else None
)

draw = ImageDraw.Draw(image)
Expand Down Expand Up @@ -95,7 +97,7 @@ def draw_card(ball_instance: "BallInstance"):
stroke_fill=(255, 255, 255, 255),
)

artwork = Image.open("." + ball.collection_card).convert("RGBA")
artwork = Image.open(media_path + ball.collection_card).convert("RGBA")
image.paste(ImageOps.fit(artwork, artwork_size), CORNERS[0]) # type: ignore

if icon:
Expand Down
2 changes: 1 addition & 1 deletion ballsdex/packages/countryballs/countryball.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def generate_random_name():
return "".join(random.choices(source, k=15))

extension = self.model.wild_card.split(".")[-1]
file_location = "." + self.model.wild_card
file_location = "../admin_panel/media" + self.model.wild_card
file_name = f"nt_{generate_random_name()}.{extension}"
try:
permissions = channel.permissions_for(channel.guild.me)
Expand Down
2 changes: 1 addition & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ cachetools = "^5.5.0"
pre-commit = "^3.7.1"
black = {version = "^24.8.0", allow-prereleases = true}
flake8-pyproject = "^1.2.3"
pyright = "^1.1.335"
pyright = "^1.1.390"
isort = "^5.13.2"
django-debug-toolbar = "^4.4.6"

Expand Down Expand Up @@ -75,3 +75,5 @@ line_length = 99
[tool.pyright]
extraPaths = ["./admin_panel"]
pythonVersion = "3.13"
reportIncompatibleMethodOverride = "warning"
reportIncompatibleVariableOverride = "warning"

0 comments on commit 5e44962

Please sign in to comment.