Skip to content

Commit 07ba884

Browse files
authored
Merge pull request #203 from PROCOLLAB-github/dev
Миграция по сжатию аватарок
2 parents 191ab57 + 6f910cf commit 07ba884

34 files changed

Lines changed: 2276 additions & 25 deletions

README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
### Run project
2727

2828
🚀 Run project via `python manage.py runserver`
29-
3029
## For developers
3130

3231
### Install pre-commit hooks
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Generated by Django 4.2.3 on 2023-09-30 09:44
2+
3+
from django.db import migrations
4+
5+
6+
class Migration(migrations.Migration):
7+
8+
dependencies = [
9+
("files", "0005_alter_userfile_options"),
10+
]
11+
12+
operations = [
13+
migrations.AlterModelOptions(
14+
name="userfile",
15+
options={
16+
"ordering": ["datetime_uploaded"],
17+
"verbose_name": "Файл",
18+
"verbose_name_plural": "Файлы",
19+
},
20+
),
21+
]
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# Generated by Django 4.2.3 on 2023-09-29 14:27
2+
3+
from io import BytesIO
4+
from django.db import migrations
5+
import requests
6+
import webp
7+
from typing import Optional
8+
9+
from PIL import Image
10+
11+
from files.service import SelectelSwiftStorage
12+
13+
14+
def convert_image_to_webp(pil_image: Image, quality: int) -> Optional[BytesIO]:
15+
"""
16+
Convert a PIL Image to WebP format.
17+
18+
Parameters:
19+
- pil_image (PIL.Image): A PIL Image object to be converted.
20+
- quality (int): The quality of the converted WebP image, 0 to 100.
21+
22+
Returns:
23+
- bytes: The converted WebP image in bytes, or None if the conversion fails.
24+
"""
25+
try:
26+
config = webp.WebPConfig.new(preset=webp.WebPPreset.PHOTO, quality=quality)
27+
webp_data = webp.WebPPicture.from_pil(pil_image).encode(config=config)
28+
return BytesIO(webp_data.buffer())
29+
except Exception as e:
30+
print(f"An error occurred: {e}")
31+
return None
32+
33+
34+
def migration(apps, schema_editor):
35+
UserFile = apps.get_model("files", "UserFile")
36+
files = UserFile.objects.all()
37+
storage = SelectelSwiftStorage()
38+
for i in files:
39+
# get all files that end in a .png or .jpg
40+
if i.link.endswith(".png") or i.link.endswith(".jpg"):
41+
old_link = i.link
42+
# convert .png/.jpg to .webp
43+
# download file and convert it to PIL image
44+
file = requests.get(i.link)
45+
pil_image = Image.open(BytesIO(file.content))
46+
# make image be 512 by 512. cut coreners if needed
47+
# if hasattr(pil_image, '_getexif'):
48+
# # noinspection PyProtectedMember
49+
# orientation = pil_image._getexif().get(0x112, 1)
50+
# if orientation in (3, 6, 8):
51+
# pil_image = pil_image.rotate(90 * (orientation - 2))
52+
53+
pil_image.thumbnail((512, 512), Image.ANTIALIAS)
54+
# convert image to webp
55+
webp_file = convert_image_to_webp(pil_image, quality=80)
56+
# delete old file
57+
storage.delete(i.link)
58+
59+
new_url = str(i.link).rsplit(".", 1)[0] + ".webp"
60+
token = storage._get_auth_token()
61+
requests.put(
62+
new_url,
63+
headers={
64+
"X-Auth-Token": token,
65+
"Content-Type": "image/webp",
66+
},
67+
data=webp_file,
68+
)
69+
i.link = new_url
70+
i.extension = "webp"
71+
i.mime_type = "image/webp"
72+
i.save()
73+
# delete the one with the old url
74+
UserFile.objects.get(link=old_link).delete()
75+
76+
77+
class Migration(migrations.Migration):
78+
dependencies = [
79+
("files", "0006_alter_userfile_options"),
80+
]
81+
82+
operations = [
83+
# FIXME
84+
# migrations.RunPython(migration, migrations.RunPython.noop),
85+
]

mailing/__init__.py

Whitespace-only changes.

mailing/admin.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from django.contrib import admin
2+
from .models import MailingSchema
3+
4+
5+
@admin.register(MailingSchema)
6+
class MailingSchemaAdmin(admin.ModelAdmin):
7+
list_display = (
8+
"id",
9+
"name",
10+
)
11+
list_display_links = (
12+
"id",
13+
"name",
14+
)
15+
search_fields = (
16+
"id",
17+
"name",
18+
)

mailing/apps.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from django.apps import AppConfig
2+
3+
4+
class MailingConfig(AppConfig):
5+
default_auto_field = "django.db.models.BigAutoField"
6+
name = "mailing"
7+
verbose_name = "Рассылка"

mailing/constants.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
def get_default_mailing_schema() -> dict[str, dict[str, str]]:
2+
return {
3+
"title": {
4+
"title": "Заголовок письма",
5+
"default": "Рассылка | Procollab",
6+
},
7+
"text": {"title": "Основной текст письма"},
8+
"button_text": {"title": "Текст кнопки", "default": "Кнопка"},
9+
}

mailing/migrations/0001_initial.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Generated by Django 4.2.3 on 2023-09-30 09:44
2+
3+
import django.core.validators
4+
from django.db import migrations, models
5+
import mailing.models
6+
7+
8+
class Migration(migrations.Migration):
9+
10+
initial = True
11+
12+
dependencies = []
13+
14+
operations = [
15+
migrations.CreateModel(
16+
name="MailingSchema",
17+
fields=[
18+
(
19+
"id",
20+
models.BigAutoField(
21+
auto_created=True,
22+
primary_key=True,
23+
serialize=False,
24+
verbose_name="ID",
25+
),
26+
),
27+
("name", models.CharField(max_length=100)),
28+
("schema", models.JSONField()),
29+
(
30+
"template",
31+
models.FileField(
32+
upload_to=mailing.models.get_template_path,
33+
validators=[
34+
django.core.validators.FileExtensionValidator(
35+
allowed_extensions=["html"]
36+
)
37+
],
38+
),
39+
),
40+
],
41+
),
42+
]
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Generated by Django 4.2.3 on 2023-09-30 09:49
2+
3+
from django.db import migrations, models
4+
5+
6+
class Migration(migrations.Migration):
7+
8+
dependencies = [
9+
("mailing", "0001_initial"),
10+
]
11+
12+
operations = [
13+
migrations.AlterField(
14+
model_name="mailingschema",
15+
name="schema",
16+
field=models.JSONField(default=None, null=True),
17+
),
18+
]
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Generated by Django 4.2.3 on 2023-09-30 09:50
2+
3+
from django.db import migrations, models
4+
5+
6+
class Migration(migrations.Migration):
7+
8+
dependencies = [
9+
("mailing", "0002_alter_mailingschema_schema"),
10+
]
11+
12+
operations = [
13+
migrations.AlterField(
14+
model_name="mailingschema",
15+
name="schema",
16+
field=models.JSONField(blank=True, default="", null=True),
17+
),
18+
]

0 commit comments

Comments
 (0)