avatars.py 2.3 KB

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