avatars.py 2.3 KB

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