share_post.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """
  2. Share Post
  3. ==========
  4. This plugin adds share URL to article. These links are textual which means no
  5. online tracking of your readers.
  6. """
  7. from bs4 import BeautifulSoup
  8. try:
  9. from urllib.parse import quote
  10. except ImportError:
  11. from urllib import quote
  12. from pelican import signals, contents
  13. from pelican.generators import ArticlesGenerator, PagesGenerator
  14. def article_title(content):
  15. main_title = BeautifulSoup(content.title, 'html.parser').get_text().strip()
  16. sub_title = ''
  17. if hasattr(content, 'subtitle'):
  18. sub_title = ' ' + BeautifulSoup(content.subtitle, 'html.parser').get_text().strip()
  19. return quote(('%s%s' % (main_title, sub_title)).encode('utf-8'))
  20. def article_url(content):
  21. site_url = content.settings['SITEURL']
  22. return quote(('%s/%s' % (site_url, content.url)).encode('utf-8'))
  23. def article_summary(content):
  24. return quote(BeautifulSoup(content.summary, 'html.parser').get_text().strip().encode('utf-8'))
  25. def share_post(content):
  26. if isinstance(content, contents.Static):
  27. return
  28. title = article_title(content)
  29. url = article_url(content)
  30. summary = article_summary(content)
  31. mail_link = 'mailto:?subject=%s&body=%s' % (title, url)
  32. diaspora_link = 'https://sharetodiaspora.github.io/?title=%s&url=%s' % (title, url)
  33. facebook_link = 'http://www.facebook.com/sharer/sharer.php?u=%s' % url
  34. gplus_link = 'https://plus.google.com/share?url=%s' % url
  35. twitter_link = 'https://twitter.com/intent/tweet?text=%s&url=%s' % (title, url)
  36. hackernews_link = 'https://news.ycombinator.com/submitlink?t=%s&u=%s' % (title, url)
  37. linkedin_link = 'https://www.linkedin.com/shareArticle?mini=true&url=%s&title=%s&summary=%s&source=%s' % (
  38. url, title, summary, url
  39. )
  40. content.share_post = {
  41. 'diaspora' : diaspora_link,
  42. 'twitter' : twitter_link,
  43. 'facebook' : facebook_link,
  44. 'google-plus': gplus_link,
  45. 'linkedin' : linkedin_link,
  46. 'hacker-news': hackernews_link,
  47. 'email' : mail_link
  48. }
  49. def run_plugin(generators):
  50. for generator in generators:
  51. if isinstance(generator, ArticlesGenerator):
  52. for article in generator.articles:
  53. share_post(article)
  54. elif isinstance(generator, PagesGenerator):
  55. for page in generator.pages:
  56. share_post(page)
  57. def register():
  58. try:
  59. signals.all_generators_finalized.connect(run_plugin)
  60. except AttributeError:
  61. # NOTE: This results in #314 so shouldn't really be relied on
  62. # https://github.com/getpelican/pelican-plugins/issues/314
  63. signals.content_object_init.connect(share_post)