Skip to content

Commit

Permalink
Merge pull request #806 from ae-utbm/taiste
Browse files Browse the repository at this point in the history
Bugfixes
  • Loading branch information
imperosol authored Sep 1, 2024
2 parents b4749f2 + 6918e30 commit 878ee99
Show file tree
Hide file tree
Showing 16 changed files with 298 additions and 383 deletions.
18 changes: 0 additions & 18 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,21 +44,3 @@ jobs:
poetry run ./manage.py compilemessages
sudo systemctl restart uwsgi
sentry:
runs-on: ubuntu-latest
environment: production
timeout-minutes: 30
needs: deployment
steps:
- uses: actions/checkout@v3

- name: Sentry Release
uses: getsentry/[email protected]
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
SENTRY_URL: ${{ secrets.SENTRY_URL }}
with:
environment: production
18 changes: 0 additions & 18 deletions .github/workflows/taiste.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,3 @@ jobs:
poetry run ./manage.py compilemessages
sudo systemctl restart uwsgi
sentry:
runs-on: ubuntu-latest
environment: taiste
timeout-minutes: 30
needs: deployment
steps:
- uses: actions/checkout@v3

- name: Sentry Release
uses: getsentry/[email protected]
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
SENTRY_URL: ${{ secrets.SENTRY_URL }}
with:
environment: taiste
2 changes: 0 additions & 2 deletions com/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
from django.utils.translation import gettext_lazy as _

from club.models import Club
from core import utils
from core.models import Notification, Preferences, RealGroup, User


Expand All @@ -44,7 +43,6 @@ class Sith(models.Model):
alert_msg = models.TextField(_("alert message"), default="", blank=True)
info_msg = models.TextField(_("info message"), default="", blank=True)
weekmail_destinations = models.TextField(_("weekmail destinations"), default="")
version = utils.get_git_revision_short_hash()

def __str__(self):
return "⛩ Sith ⛩"
Expand Down
24 changes: 12 additions & 12 deletions core/management/commands/populate.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,10 +234,10 @@ def handle(self, *args, **options):
skia_profile = SithFile(
parent=profiles_root,
name=name,
file=resize_image(Image.open(BytesIO(f.read())), 400, "JPEG"),
file=resize_image(Image.open(BytesIO(f.read())), 400, "WEBP"),
owner=skia,
is_folder=False,
mime_type="image/jpeg",
mime_type="image/webp",
size=skia_profile_path.stat().st_size,
)
skia_profile.file.name = name
Expand Down Expand Up @@ -368,10 +368,10 @@ def handle(self, *args, **options):
richard_profile = SithFile(
parent=profiles_root,
name=name,
file=resize_image(Image.open(BytesIO(f.read())), 400, "JPEG"),
file=resize_image(Image.open(BytesIO(f.read())), 400, "WEBP"),
owner=richard,
is_folder=False,
mime_type="image/jpeg",
mime_type="image/webp",
size=richard_profile_path.stat().st_size,
)
richard_profile.file.name = name
Expand Down Expand Up @@ -853,10 +853,10 @@ def handle(self, *args, **options):
sli_profile = SithFile(
parent=profiles_root,
name=name,
file=resize_image(Image.open(BytesIO(f.read())), 400, "JPEG"),
file=resize_image(Image.open(BytesIO(f.read())), 400, "WEBP"),
owner=sli,
is_folder=False,
mime_type="image/jpeg",
mime_type="image/webp",
size=sli_profile_path.stat().st_size,
)
sli_profile.file.name = name
Expand Down Expand Up @@ -887,10 +887,10 @@ def handle(self, *args, **options):
krophil_profile = SithFile(
parent=profiles_root,
name=name,
file=resize_image(Image.open(BytesIO(f.read())), 400, "JPEG"),
file=resize_image(Image.open(BytesIO(f.read())), 400, "WEBP"),
owner=krophil,
is_folder=False,
mime_type="image/jpeg",
mime_type="image/webp",
size=krophil_profile_path.stat().st_size,
)
krophil_profile.file.name = name
Expand Down Expand Up @@ -1217,13 +1217,13 @@ def handle(self, *args, **options):
parent=album,
name=p.name,
file=resize_image(
Image.open(BytesIO(p.read_bytes())), 1000, "JPEG"
Image.open(BytesIO(p.read_bytes())), 1000, "WEBP"
),
owner=root,
is_folder=False,
is_in_sas=True,
is_moderated=True,
mime_type="image/jpeg",
mime_type="image/webp",
size=p.stat().st_size,
)
pict.file.name = p.name
Expand Down Expand Up @@ -1252,10 +1252,10 @@ def handle(self, *args, **options):
skia_profile = SithFile(
parent=profiles_root,
name=name,
file=resize_image(Image.open(BytesIO(f.read())), 400, "JPEG"),
file=resize_image(Image.open(BytesIO(f.read())), 400, "WEBP"),
owner=skia,
is_folder=False,
mime_type="image/jpeg",
mime_type="image/webp",
size=skia_profile_path.stat().st_size,
)
skia_profile.file.name = name
Expand Down
5 changes: 0 additions & 5 deletions core/templates/core/base.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -290,11 +290,6 @@
</a>
{% endblock %}
<br>
<code class="version">
{% cache 1000 "sith_version" %}
{% trans %}Sith version:{% endtrans %}&nbsp;{{ get_sith().version }}
{% endcache %}
</code>
</footer>
{% endif %}

Expand Down
2 changes: 1 addition & 1 deletion core/templates/core/macros.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
</div>
{% endif %}
</div>
{% if user.promo %}
{% if user.promo and user.promo_has_logo() %}
<div class="user_mini_profile_promo">
<img src="{{ static('core/img/promo_%02d.png' % user.promo) }}" title="Promo {{ user.promo }}" alt="Promo {{ user.promo }}" class="promo_pict" />
</div>
Expand Down
7 changes: 4 additions & 3 deletions core/templates/core/user_edit.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
<p>
{{ form[field_name].label }}
</p>
{{ form[field_name].errors }}
{%- else -%}
<em>{% trans %}To edit your profile picture, ask a member of the AE{% endtrans %}</em>
{%- endif -%}
Expand Down Expand Up @@ -163,16 +164,16 @@
/* Stop camera */
this.video.pause()
this.video.srcObject.getTracks().forEach((track) => {
if (track.readyState == 'live') {
if (track.readyState === 'live') {
track.stop();
}
});
canvas.toBlob((blob) => {
let file = new File(
[blob],
"{% trans %}captured{% endtrans %}.png",
{ type: "image/jpeg" },
"{% trans %}captured{% endtrans %}.webp",
{ type: "image/webp" },
);
let list = new DataTransfer();
Expand Down
5 changes: 0 additions & 5 deletions core/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,6 @@
UserUpdateProfileView.as_view(),
name="user_edit",
),
path(
"user/<int:user_id>/profile_upload/",
UserUploadProfilePictView.as_view(),
name="user_profile_upload",
),
path("user/<int:user_id>/clubs/", UserClubView.as_view(), name="user_clubs"),
path(
"user/<int:user_id>/prefs/",
Expand Down
22 changes: 7 additions & 15 deletions core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
#
#

import subprocess
from datetime import date

# Image utils
Expand All @@ -29,17 +28,6 @@
from PIL.Image import Resampling


def get_git_revision_short_hash() -> str:
"""Return the short hash of the current commit."""
try:
output = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"])
if isinstance(output, bytes):
return output.decode("ascii").strip()
return output.strip()
except subprocess.CalledProcessError:
return ""


def get_start_of_semester(today: Optional[date] = None) -> date:
"""Return the date of the start of the semester of the given date.
If no date is given, return the start date of the current semester.
Expand Down Expand Up @@ -102,13 +90,17 @@ def scale_dimension(width, height, long_edge):
def resize_image(im, edge, img_format):
(w, h) = im.size
(width, height) = scale_dimension(w, h, long_edge=edge)
img_format = img_format.upper()
content = BytesIO()
# use the lanczos filter for antialiasing and discard the alpha channel
im = im.resize((width, height), Resampling.LANCZOS).convert("RGB")
im = im.resize((width, height), Resampling.LANCZOS)
if img_format == "JPEG":
# converting an image with an alpha channel to jpeg would cause a crash
im = im.convert("RGB")
try:
im.save(
fp=content,
format=img_format.upper(),
format=img_format,
quality=90,
optimize=True,
progressive=True,
Expand All @@ -117,7 +109,7 @@ def resize_image(im, edge, img_format):
PIL.ImageFile.MAXBLOCK = im.size[0] * im.size[1]
im.save(
fp=content,
format=img_format.upper(),
format=img_format,
quality=90,
optimize=True,
progressive=True,
Expand Down
23 changes: 11 additions & 12 deletions core/views/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# OR WITHIN THE LOCAL FILE "LICENSE"
#
#
import mimetypes
from urllib.parse import quote, urljoin

# This file contains all the views that concern the page model
Expand Down Expand Up @@ -58,30 +59,28 @@ def send_file(
if not can_view(f, request.user) and not is_logged_in_counter(request):
raise PermissionDenied
name = getattr(f, file_attr).name
filepath = settings.MEDIA_ROOT / name

# check if file exists on disk
if not filepath.exists():
raise Http404

response = HttpResponse(
headers={"Content-Disposition": f'inline; filename="{quote(name)}"'}
)
if not settings.DEBUG:
# When receiving a response with the Accel-Redirect header,
# the reverse proxy will automatically handle the file sending.
# This is really hard to test (thus isn't tested)
# so please do not mess with this.
response = HttpResponse(status=200)
response["Content-Type"] = ""
response["Content-Type"] = "" # automatically set by nginx
response["X-Accel-Redirect"] = quote(urljoin(settings.MEDIA_URL, name))
return response

filepath = settings.MEDIA_ROOT / name
# check if file exists on disk
if not filepath.exists():
raise Http404
with open(filepath, "rb") as filename:
wrapper = FileWrapper(filename)
response = HttpResponse(wrapper, content_type=f.mime_type)
response.content = FileWrapper(filename)
response["Content-Type"] = mimetypes.guess_type(filepath)[0]
response["Last-Modified"] = http_date(f.date.timestamp())
response["Content-Length"] = filepath.stat().st_size
response["Content-Disposition"] = ('inline; filename="%s"' % f.name).encode(
"utf-8"
)
return response


Expand Down
43 changes: 23 additions & 20 deletions core/views/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,10 +201,7 @@ class Meta:


class UserProfileForm(forms.ModelForm):
"""Form handling the user profile, managing the files
This form is actually pretty bad and was made in the rush before the migration. It should be refactored.
TODO: refactor this form.
"""
"""Form handling the user profile, managing the files"""

class Meta:
model = User
Expand Down Expand Up @@ -237,24 +234,30 @@ class Meta:
]
widgets = {
"date_of_birth": SelectDate,
"profile_pict": forms.ClearableFileInput,
"avatar_pict": forms.ClearableFileInput,
"scrub_pict": forms.ClearableFileInput,
"phone": RegionalPhoneNumberWidget,
"parent_phone": RegionalPhoneNumberWidget,
"quote": forms.Textarea,
}
labels = {
"profile_pict": _(

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

# Image fields are injected here to override the file field provided by the model
# This would be better if we could have a SithImage sort of model input instead of a generic SithFile
self.fields["profile_pict"] = forms.ImageField(
required=False,
label=_(
"Profile: you need to be visible on the picture, in order to be recognized (e.g. by the barmen)"
),
"avatar_pict": _("Avatar: used on the forum"),
"scrub_pict": _("Scrub: let other know how your scrub looks like!"),
}

def generate_name(self, field_name, f):
field_name = field_name[:-4]
return field_name + str(self.instance.id) + "." + f.content_type.split("/")[-1]
)
self.fields["avatar_pict"] = forms.ImageField(
required=False,
label=_("Avatar: used on the forum"),
)
self.fields["scrub_pict"] = forms.ImageField(
required=False,
label=_("Scrub: let other know how your scrub looks like!"),
)

def process(self, files):
avatar = self.instance.avatar_pict
Expand All @@ -271,11 +274,11 @@ def process(self, files):
im = Image.open(BytesIO(f.read()))
new_file = SithFile(
parent=parent,
name=self.generate_name(field, f),
file=resize_image(im, 400, f.content_type.split("/")[-1]),
name=f"{field.removesuffix('_pict')}_{self.instance.id}.webp",
file=resize_image(im, 400, "webp"),
owner=self.instance,
is_folder=False,
mime_type=f.content_type,
mime_type="image/wepb",
size=f.size,
moderator=self.instance,
is_moderated=True,
Expand Down Expand Up @@ -305,7 +308,7 @@ def process(self, files):
% {
"file_name": f,
"msg": _(
"Bad image format, only jpeg, png, and gif are accepted"
"Bad image format, only jpeg, png, webp and gif are accepted"
),
},
)
Expand Down
Loading

0 comments on commit 878ee99

Please sign in to comment.