avatars.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # -*- coding: utf-8 -*-
  2. """
  3. """
  4. import logging
  5. import os
  6. import hashlib
  7. logger = logging.getLogger(__name__)
  8. _log = "pelican_comment_system: avatars: "
  9. try:
  10. from identicon import identicon
  11. _identiconImported = True
  12. except ImportError as e:
  13. logger.warning(_log + "identicon deactivated: " + str(e))
  14. _identiconImported = False
  15. # Global Variables
  16. _identicon_save_path = None
  17. _identicon_output_path = None
  18. _identicon_data = None
  19. _identicon_size = None
  20. _initialized = False
  21. _authors = None
  22. _missingAvatars = []
  23. def _ready():
  24. if not _initialized:
  25. logger.warning(_log + "Module not initialized. use init")
  26. if not _identicon_data:
  27. logger.debug(_log + "No identicon data set")
  28. return _identiconImported and _initialized and _identicon_data
  29. def init(pelican_output_path, identicon_output_path, identicon_data, identicon_size, authors):
  30. global _identicon_save_path
  31. global _identicon_output_path
  32. global _identicon_data
  33. global _identicon_size
  34. global _initialized
  35. global _authors
  36. _identicon_save_path = os.path.join(pelican_output_path, identicon_output_path)
  37. _identicon_output_path = identicon_output_path
  38. _identicon_data = identicon_data
  39. _identicon_size = identicon_size
  40. _authors = authors
  41. _initialized = True
  42. def _createIdenticonOutputFolder():
  43. if not _ready():
  44. return
  45. if not os.path.exists(_identicon_save_path):
  46. os.makedirs(_identicon_save_path)
  47. def getAvatarPath(comment_id, metadata):
  48. if not _ready():
  49. return ''
  50. md5 = hashlib.md5()
  51. author = tuple()
  52. for data in _identicon_data:
  53. if data in metadata:
  54. string = str(metadata[data])
  55. md5.update(string)
  56. author += tuple([string])
  57. else:
  58. logger.warning(_log + data + " is missing in comment: " + comment_id)
  59. if author in _authors:
  60. return _authors[author]
  61. global _missingAvatars
  62. code = md5.hexdigest()
  63. if not code in _missingAvatars:
  64. _missingAvatars.append(code)
  65. return os.path.join(_identicon_output_path, '%s.png' % code)
  66. def generateAndSaveMissingAvatars():
  67. _createIdenticonOutputFolder()
  68. for code in _missingAvatars:
  69. avatar_path = '%s.png' % code
  70. avatar = identicon.render_identicon(int(code, 16), _identicon_size)
  71. avatar_save_path = os.path.join(_identicon_save_path, avatar_path)
  72. avatar.save(avatar_save_path, 'PNG')