store.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import os
  2. from hashlib import md5
  3. from path import Path
  4. from PIL import Image
  5. from django.utils.encoding import force_bytes
  6. from misago.conf import settings
  7. from .paths import AVATARS_STORE
  8. from .store_ import *
  9. def get_avatar_hash(user, suffix=None):
  10. avatars_dir = get_existing_avatars_dir(user)
  11. avatar_suffix = suffix or max(settings.MISAGO_AVATARS_SIZES)
  12. avatar_file = '%s_%s.png' % (user.pk, avatar_suffix)
  13. avatar_file = Path(os.path.join(avatars_dir, avatar_file))
  14. md5_hash = md5()
  15. with open(avatar_file, 'rb') as f:
  16. while True:
  17. data = f.read(128)
  18. if not data:
  19. break
  20. md5_hash.update(data)
  21. return md5_hash.hexdigest()[:8]
  22. def get_user_avatar_tokens(user):
  23. token_seeds = (user.email, user.avatar_hash, settings.SECRET_KEY)
  24. tokens = {
  25. 'org': md5(force_bytes('org:%s:%s:%s' % token_seeds)).hexdigest()[:8],
  26. 'tmp': md5(force_bytes('tmp:%s:%s:%s' % token_seeds)).hexdigest()[:8],
  27. }
  28. tokens.update({
  29. tokens['org']: 'org',
  30. tokens['tmp']: 'tmp',
  31. })
  32. return tokens
  33. def store_original_avatar(user):
  34. org_path = avatar_file_path(user, 'org')
  35. if org_path.exists():
  36. org_path.remove()
  37. avatar_file_path(user, 'tmp').rename(org_path)
  38. def avatar_file_path(user, size):
  39. avatars_dir = get_existing_avatars_dir(user)
  40. avatar_file = '%s_%s.png' % (user.pk, size)
  41. return Path(os.path.join(avatars_dir, avatar_file))
  42. def avatar_file_exists(user, size):
  43. return avatar_file_path(user, size).exists()
  44. def store_new_avatar(user, image):
  45. """
  46. Deletes old image before storing new one
  47. """
  48. delete_avatar(user)
  49. store_avatar(user, image)
  50. def get_avatars_dir_path(user=None):
  51. if user:
  52. try:
  53. user_pk = user.pk
  54. except AttributeError:
  55. user_pk = user
  56. dir_hash = md5(str(user_pk).encode()).hexdigest()
  57. hash_path = [dir_hash[0:1], dir_hash[2:3]]
  58. return Path(os.path.join(AVATARS_STORE, *hash_path))
  59. else:
  60. return Path(os.path.join(AVATARS_STORE, 'blank'))
  61. def get_existing_avatars_dir(user=None):
  62. avatars_dir = get_avatars_dir_path(user)
  63. if not avatars_dir.exists():
  64. avatars_dir.makedirs()
  65. return avatars_dir