store.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import os
  2. from path import path
  3. from PIL import Image
  4. from misago.conf import settings
  5. from misago.users.avatars.paths import AVATARS_STORE
  6. def normalize_image(image):
  7. """if image is gif, strip it of animation"""
  8. image.seek(0)
  9. return image.copy().convert('RGBA')
  10. def store_avatar(user, image):
  11. avatars_dir = get_existing_avatars_dir(user)
  12. normalize_image(image)
  13. for size in sorted(settings.MISAGO_AVATARS_SIZES, reverse=True):
  14. image = image.resize((size, size), Image.ANTIALIAS)
  15. image.save('%s/%s_%s.png' % (avatars_dir, user.pk, size), "PNG")
  16. def delete_avatar(user):
  17. avatars_dir = get_existing_avatars_dir(user)
  18. suffixes_to_delete = settings.MISAGO_AVATARS_SIZES + ('org', 'tmp')
  19. for size in suffixes_to_delete:
  20. avatar_file = path('%s/%s_%s.png' % (avatars_dir, user.pk, size))
  21. if avatar_file.exists():
  22. avatar_file.remove()
  23. def store_temporary_avatar(user, image):
  24. avatars_dir = get_existing_avatars_dir(user)
  25. normalize_image(image)
  26. image.save('%s/%s_tmp.png' % (avatars_dir, user.pk), "PNG")
  27. def store_original_avatar(user):
  28. org_path = avatar_file_path(user, 'org')
  29. if org_path.exists():
  30. org_path.remove()
  31. avatar_file_path(user, 'tmp').rename(org_path)
  32. def avatar_file_path(user, size):
  33. avatars_dir = get_existing_avatars_dir(user)
  34. return path('%s/%s_%s.png' % (avatars_dir, user.pk, size))
  35. def avatar_file_exists(user, size):
  36. return avatar_file_path(user, size).exists()
  37. def store_new_avatar(user, image):
  38. """
  39. Deletes old image before storing new one
  40. """
  41. delete_avatar(user)
  42. store_avatar(user, image)
  43. def get_existing_avatars_dir(user):
  44. date_dir = unicode(user.joined_on.strftime('%y%m'))
  45. avatars_dir = path(os.path.join(AVATARS_STORE, date_dir))
  46. if not avatars_dir.exists():
  47. avatars_dir.mkdir()
  48. return avatars_dir