/kai/controllers/snippets.py

https://bitbucket.org/bbangert/kai/ · Python · 173 lines · 155 code · 8 blank · 10 comment · 0 complexity · 2172fdf5e8412b643970cf7b9169992d MD5 · raw file

  1. import logging
  2. import re
  3. from couchdb import ResourceConflict
  4. from formencode import htmlfill
  5. from pylons import cache, request, response, session, tmpl_context as c, url
  6. from pylons.controllers.util import abort, redirect
  7. from pylons.decorators import rest
  8. import kai.lib.pygmentsupport
  9. from kai.lib.base import BaseController, CMSObject, render
  10. from kai.lib.decorators import logged_in, validate
  11. from kai.lib.helpers import success_flash, failure_flash, rst_render
  12. from kai.lib.serialization import render_feed
  13. from kai.model import Human, Snippet, forms
  14. from kai.model.generics import all_doc_tags
  15. log = logging.getLogger(__name__)
  16. class SnippetsController(BaseController, CMSObject):
  17. def __before__(self):
  18. c.active_tab = 'Tools'
  19. c.active_sub = 'Snippets'
  20. def preview(self):
  21. data = request.POST['content']
  22. return rst_render(data)
  23. def index(self, format='html'):
  24. """ Get the snippets by date and by author"""
  25. snippets = list(Snippet.by_date(self.db, descending=True, limit=100))
  26. c.snippets = [x for x in snippets[:20] if x.content]
  27. if format in ['atom', 'rss']:
  28. response.content_type = 'application/atom+xml'
  29. return render_feed(
  30. title="PylonsHQ Snippet Feed", link=url.current(qualified=True),
  31. description="Recent PylonsHQ snippets", objects=c.snippets,
  32. pub_date='created')
  33. authors = []
  34. for snippet in c.snippets:
  35. displayname = snippet.displayname.strip()
  36. if displayname not in authors:
  37. authors.append(displayname)
  38. c.unique_authors = authors[:10]
  39. return render('/snippets/index.mako')
  40. def new(self):
  41. if not c.user:
  42. abort(401)
  43. c.tags = [row['name'] for row in list(all_doc_tags(self.db))]
  44. return render('snippets/add.mako')
  45. @validate(form=forms.snippet_form, error_handler='new')
  46. def create(self):
  47. if not c.user:
  48. abort(401)
  49. self.form_result['content'] = self.form_result.pop('snippet_form_content')
  50. snippet = Snippet(**self.form_result)
  51. snippet.human_id = c.user.id
  52. snippet.email = c.user.email
  53. snippet.displayname = c.user.displayname
  54. ## generate the slug
  55. slug = snippet.title.replace(" ", "_")
  56. slug = slug.lower()
  57. slug = re.sub('[^A-Za-z0-9_]+', '', slug)
  58. snippet.slug = slug
  59. if 'tags' in self.form_result:
  60. snippet.tags = self.form_result['tags'].replace(',', ' ').strip().split(' ')
  61. snippet.store(self.db)
  62. success_flash('Snippet has been added')
  63. redirect(url('snippets'))
  64. @logged_in
  65. def edit(self, id):
  66. slug = id.lower().strip()
  67. snippets = list(Snippet.by_slug(self.db)[slug]) or abort(404)
  68. snippet = snippets[0]
  69. if snippet.displayname:
  70. author = Human.load(self.db, snippet.human_id)
  71. is_owner = self._check_owner(snippet, c.user, check_session=True)
  72. if not is_owner:
  73. abort(401)
  74. c.snippet = snippet
  75. return render('/snippets/edit.mako')
  76. @logged_in
  77. @validate(form=forms.snippet_form, error_handler='edit')
  78. def update(self, id):
  79. slug = id.lower().strip()
  80. snippets = list(Snippet.by_slug(self.db)[slug]) or abort(404)
  81. snippet = snippets[0]
  82. if snippet.displayname:
  83. author = Human.load(self.db, snippet.human_id)
  84. is_owner = self._check_owner(snippet, c.user, check_session=True)
  85. if not is_owner:
  86. abort(401)
  87. snippet.title = self.form_result['title']
  88. snippet.content = self.form_result['content']
  89. snippet.description = self.form_result['description']
  90. ## generate the slug
  91. slug = snippet.title.replace(" ", "_")
  92. slug = slug.lower()
  93. slug = re.sub('[^A-Za-z0-9_]+', '', slug)
  94. snippet.slug = slug
  95. if 'tags' in self.form_result:
  96. snippet.tags = self.form_result['tags'].replace(',', ' ').strip().split(' ')
  97. snippet.store(self.db)
  98. success_flash('Snippet has been updated')
  99. redirect(url('snippet', id=slug))
  100. @logged_in
  101. def preview(self):
  102. """Return a HTML version of the rST content"""
  103. data = request.POST['content']
  104. return rst_render(data)
  105. def show(self, id):
  106. """Show a particular snippet
  107. Keyword arguments:
  108. id - actually a slug
  109. """
  110. slug = id.lower().strip()
  111. snippets = list(Snippet.by_slug(self.db)[slug]) or abort(404)
  112. snippet = snippets[0]
  113. c.snippet_content = rst_render(snippet.content)
  114. c.snippet = snippet
  115. if c.snippet.displayname:
  116. c.author = Human.load(self.db, c.snippet.human_id)
  117. c.is_owner = self._check_owner(c.snippet, c.user, check_session=True)
  118. return render('/snippets/view.mako')
  119. def by_author(self, id=None):
  120. """View snippets by an authors human_id.
  121. Keyword arguments:
  122. id - authors human id.
  123. """
  124. if not id:
  125. c.authors = list(Snippet.author_totals(self.db))
  126. else:
  127. snippets = list(Snippet.by_author(self.db)[id]) or abort(404)
  128. c.username = snippets[0].displayname
  129. c.snippets = snippets
  130. return render('/snippets/byauthor.mako')
  131. def by_tag(self, tag=None):
  132. """View snippets by a particular tag.
  133. Keyword arguments:
  134. tag - a tag (string)
  135. """
  136. snippets = list(Snippet.by_tag(self.db)[tag]) or abort(404)
  137. c.snippets = snippets
  138. c.tag = tag
  139. return render('/snippets/bytag.mako')
  140. def tagcloud(self):
  141. c.tag_sizes = cache.get_cache('snippets.py_tagcloud').get_value(
  142. 'snippet', createfunc=lambda: Snippet.tag_sizes(), expiretime=180)
  143. return render('/snippets/tagcloud.mako')