store_.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import os
  2. from hashlib import md5
  3. from io import BytesIO
  4. from PIL import Image
  5. from django.core.files.base import ContentFile
  6. from django.db import transaction
  7. from django.utils.crypto import get_random_string
  8. from misago.conf import settings
  9. def normalize_image(image):
  10. """strip image of animation, convert to RGBA"""
  11. image.seek(0)
  12. return image.copy().convert('RGBA')
  13. def store_avatar(user, image):
  14. from ..models import Avatar
  15. image = normalize_image(image)
  16. avatars = []
  17. for size in sorted(settings.MISAGO_AVATARS_SIZES, reverse=True):
  18. image_stream = BytesIO()
  19. image = image.resize((size, size), Image.ANTIALIAS)
  20. image.save(image_stream, "PNG")
  21. avatars.append(Avatar.objects.create(
  22. user=user,
  23. size=size,
  24. image=ContentFile(image_stream.getvalue(), 'avatar')
  25. ))
  26. with transaction.atomic():
  27. user.avatars = [{'size': a.size, 'url': a.url} for a in avatars]
  28. user.save(update_fields=['avatars'])
  29. delete_avatar(user, exclude=[a.id for a in avatars])
  30. def delete_avatar(user, exclude=None):
  31. exclude = exclude or []
  32. for avatar in user.avatar_set.exclude(id__in=exclude):
  33. avatar.image.delete(False)
  34. user.avatar_set.exclude(id__in=exclude).delete()
  35. def upload_to(instance, filename):
  36. spread_path = md5(get_random_string(64).encode()).hexdigest()
  37. secret = get_random_string(32)
  38. filename_clean = '%s.png' % get_random_string(32)
  39. return os.path.join(
  40. 'avatars', spread_path[:2], spread_path[2:4], secret, filename_clean)