libravatar.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """Libravatar plugin for Pelican"""
  2. ## Copyright (C) 2015 Rafael Laboissiere <rafael@laboissiere.net>
  3. ##
  4. ## This program is free software: you can redistribute it and/or modify it
  5. ## under the terms of the GNU General Affero Public License as published by
  6. ## the Free Software Foundation, either version 3 of the License, or (at
  7. ## your option) any later version.
  8. ##
  9. ## This program is distributed in the hope that it will be useful, but
  10. ## WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. ## Affero General Public License for more details.
  13. ##
  14. ## You should have received a copy of the GNU Affero General Public License
  15. ## along with this program. If not, see http://www.gnu.org/licenses/.
  16. import hashlib
  17. from pelican import signals
  18. def initialize (pelicanobj):
  19. """Initialize the Libravatar plugin"""
  20. pelicanobj.settings.setdefault ('LIBRAVATAR_MISSING', None)
  21. pelicanobj.settings.setdefault ('LIBRAVATAR_SIZE', None)
  22. def add_libravatar (generator, metadata):
  23. """Article generator connector for the Libravatar plugin"""
  24. missing = generator.settings.get ('LIBRAVATAR_MISSING')
  25. size = generator.settings.get ('LIBRAVATAR_SIZE')
  26. ## Check the presence of the Email header
  27. if 'email' not in metadata.keys ():
  28. try:
  29. metadata ['email'] = generator.settings.get ('AUTHOR_EMAIL')
  30. except:
  31. pass
  32. ## Add the Libravatar URL
  33. if metadata ['email']:
  34. ## Compose URL using the MD5 hash
  35. ## (the ascii encoding is necessary for Python3)
  36. email = metadata ['email'].lower ().encode ('ascii')
  37. md5 = hashlib.md5 (email).hexdigest ()
  38. url = 'http://cdn.libravatar.org/avatar/' + md5
  39. ## Add eventual "missing picture" option
  40. if missing or size:
  41. url = url + '?'
  42. if missing:
  43. url = url + 'd=' + missing
  44. if size:
  45. url = url + '&'
  46. if size:
  47. url = url + 's=' + str (size)
  48. ## Add URL to the article's metadata
  49. metadata ['author_libravatar'] = url
  50. def register ():
  51. """Register the Libravatar plugin with Pelican"""
  52. signals.initialized.connect (initialize)
  53. signals.article_generator_context.connect (add_libravatar)