random_article.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # -*- coding: utf-8 -*-
  2. """
  3. Random Article Plugin For Pelican
  4. ========================
  5. This plugin generates a html file which redirect to a random article
  6. using javascript's window.location. The generated html file is
  7. saved at SITEURL.
  8. """
  9. from __future__ import unicode_literals
  10. import os.path
  11. from logging import info
  12. from codecs import open
  13. from pelican import signals
  14. HTML_TOP = """
  15. <!DOCTYPE html>
  16. <head>
  17. <title>random</title>
  18. <script type="text/javascript">
  19. function redirect(){
  20. var urls = [
  21. """
  22. HTML_BOTTOM = """
  23. ""];
  24. var index = Math.floor(Math.random() * (urls.length-1));
  25. window.location = urls[index];
  26. }
  27. </script>
  28. <body onload="redirect()">
  29. </body>
  30. </html>
  31. """
  32. ARTICLE_URL = """ "{0}/{1}",
  33. """
  34. class RandomArticleGenerator(object):
  35. """
  36. The structure is derived from sitemap plugin
  37. """
  38. def __init__(self, context, settings, path, theme, output_path, *null):
  39. self.output_path = output_path
  40. self.context = context
  41. self.siteurl = settings.get('SITEURL')
  42. self.randomurl = settings.get('RANDOM')
  43. def write_url(self, article, fd):
  44. if getattr(article, 'status', 'published') != 'published':
  45. return
  46. page_path = os.path.join(self.output_path, article.url)
  47. if not os.path.exists(page_path):
  48. return
  49. fd.write(ARTICLE_URL.format(self.siteurl, article.url))
  50. def generate_output(self, writer):
  51. path = os.path.join(self.output_path, self.randomurl)
  52. articles = self.context['articles']
  53. info('writing {0}'.format(path))
  54. if len(articles) == 0:
  55. return
  56. with open(path, 'w', encoding='utf-8') as fd:
  57. fd.write(HTML_TOP)
  58. for art in articles:
  59. self.write_url(art, fd)
  60. fd.write(HTML_BOTTOM)
  61. def get_generators(generators):
  62. return RandomArticleGenerator
  63. def register():
  64. signals.get_generators.connect(get_generators)