forked from honzakral/django-threadedcomments
-
Notifications
You must be signed in to change notification settings - Fork 1
/
threadedcommentstags.py
285 lines (259 loc) · 12.3 KB
/
threadedcommentstags.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import re
from django import template
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_str, force_unicode
from django.utils.safestring import mark_safe
from threadedcomments.models import ThreadedComment, FreeThreadedComment
from django import template
# Regular expressions for getting rid of newlines and witespace
inbetween = re.compile('>[ \r\n]+<')
newlines = re.compile('\r|\n')
def get_contenttype_kwargs(content_object):
"""
Gets the basic kwargs necessary for almost all of the following tags.
"""
kwargs = {
'content_type' : ContentType.objects.get_for_model(content_object).id,
'object_id' : getattr(content_object, 'pk', getattr(content_object, 'id')),
}
return kwargs
def get_comment_url(content_object, parent=None):
"""
Given an object and an optional parent, this tag gets the URL to POST to for the
creation of new ``ThreadedComment`` objects.
"""
kwargs = get_contenttype_kwargs(content_object)
if parent:
if not isinstance(parent, ThreadedComment):
raise template.TemplateSyntaxError, "get_comment_url requires its parent object to be of type ThreadedComment"
kwargs.update({'parent_id' : getattr(parent, 'pk', getattr(parent, 'id'))})
return reverse('tc_comment_parent', kwargs=kwargs)
else:
return reverse('tc_comment', kwargs=kwargs)
def get_comment_url_ajax(content_object, parent=None, ajax_type='json'):
"""
Given an object and an optional parent, this tag gets the URL to POST to for the
creation of new ``ThreadedComment`` objects. It returns the latest created object
in the AJAX form of the user's choosing (json or xml).
"""
kwargs = get_contenttype_kwargs(content_object)
kwargs.update({'ajax' : ajax_type})
if parent:
if not isinstance(parent, ThreadedComment):
raise template.TemplateSyntaxError, "get_comment_url_ajax requires its parent object to be of type ThreadedComment"
kwargs.update({'parent_id' : getattr(parent, 'pk', getattr(parent, 'id'))})
return reverse('tc_comment_parent_ajax', kwargs=kwargs)
else:
return reverse('tc_comment_ajax', kwargs=kwargs)
def get_comment_url_json(content_object, parent=None):
"""
Wraps ``get_comment_url_ajax`` with ``ajax_type='json'``
"""
try:
return get_comment_url_ajax(content_object, parent, ajax_type="json")
except template.TemplateSyntaxError:
raise template.TemplateSyntaxError, "get_comment_url_json requires its parent object to be of type ThreadedComment"
return ''
def get_comment_url_xml(content_object, parent=None):
"""
Wraps ``get_comment_url_ajax`` with ``ajax_type='xml'``
"""
try:
return get_comment_url_ajax(content_object, parent, ajax_type="xml")
except template.TemplateSyntaxError:
raise template.TemplateSyntaxError, "get_comment_url_xml requires its parent object to be of type ThreadedComment"
return ''
def get_free_comment_url(content_object, parent=None):
"""
Given an object and an optional parent, this tag gets the URL to POST to for the
creation of new ``FreeThreadedComment`` objects.
"""
kwargs = get_contenttype_kwargs(content_object)
if parent:
if not isinstance(parent, FreeThreadedComment):
raise template.TemplateSyntaxError, "get_free_comment_url requires its parent object to be of type FreeThreadedComment"
kwargs.update({'parent_id' : getattr(parent, 'pk', getattr(parent, 'id'))})
return reverse('tc_free_comment_parent', kwargs=kwargs)
else:
return reverse('tc_free_comment', kwargs=kwargs)
def get_free_comment_url_ajax(content_object, parent=None, ajax_type='json'):
"""
Given an object and an optional parent, this tag gets the URL to POST to for the
creation of new ``FreeThreadedComment`` objects. It returns the latest created object
in the AJAX form of the user's choosing (json or xml).
"""
kwargs = get_contenttype_kwargs(content_object)
kwargs.update({'ajax' : ajax_type})
if parent:
if not isinstance(parent, FreeThreadedComment):
raise template.TemplateSyntaxError, "get_free_comment_url_ajax requires its parent object to be of type FreeThreadedComment"
kwargs.update({'parent_id' : getattr(parent, 'pk', getattr(parent, 'id'))})
return reverse('tc_free_comment_parent_ajax', kwargs=kwargs)
else:
return reverse('tc_free_comment_ajax', kwargs=kwargs)
def get_free_comment_url_json(content_object, parent=None):
"""
Wraps ``get_free_comment_url_ajax`` with ``ajax_type='json'``
"""
try:
return get_free_comment_url_ajax(content_object, parent, ajax_type="json")
except template.TemplateSyntaxError:
raise template.TemplateSyntaxError, "get_free_comment_url_json requires its parent object to be of type FreeThreadedComment"
return ''
def get_free_comment_url_xml(content_object, parent=None):
"""
Wraps ``get_free_comment_url_ajax`` with ``ajax_type='xml'``
"""
try:
return get_free_comment_url_ajax(content_object, parent, ajax_type="xml")
except template.TemplateSyntaxError:
raise template.TemplateSyntaxError, "get_free_comment_url_xml requires its parent object to be of type FreeThreadedComment"
return ''
def auto_transform_markup(comment):
"""
Given a comment (``ThreadedComment`` or ``FreeThreadedComment``), this tag
looks up the markup type of the comment and formats the output accordingly.
It can also output the formatted content to a context variable, if a context name is
specified.
"""
try:
from django.contrib.markup.templatetags import markup
from django.utils.html import escape
from threadedcomments.models import MARKDOWN, TEXTILE, REST, PLAINTEXT
if comment.markup == MARKDOWN:
return markup.markdown(comment.comment)
elif comment.markup == TEXTILE:
return markup.textile(comment.comment)
elif comment.markup == REST:
return markup.restructuredtext(comment.comment)
# elif comment.markup == HTML:
# return mark_safe(force_unicode(comment.comment))
elif comment.markup == PLAINTEXT:
return escape(comment.comment)
except ImportError:
# Not marking safe, in case tag fails and users input malicious code.
return force_unicode(comment.comment)
def do_auto_transform_markup(parser, token):
try:
split = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag must be of format {%% %r COMMENT %%} or of format {%% %r COMMENT as CONTEXT_VARIABLE %%}" % (token.contents.split()[0], token.contents.split()[0], token.contents.split()[0])
if len(split) == 2:
return AutoTransformMarkupNode(split[1])
elif len(split) == 4:
return AutoTransformMarkupNode(split[1], context_name=split[3])
else:
raise template.TemplateSyntaxError, "Invalid number of arguments for tag %r" % split[0]
class AutoTransformMarkupNode(template.Node):
def __init__(self, comment, context_name=None):
self.comment = template.Variable(comment)
self.context_name = context_name
def render(self, context):
comment = self.comment.resolve(context)
if self.context_name:
context[self.context_name] = auto_transform_markup(comment)
return ''
else:
return auto_transform_markup(comment)
def do_get_threaded_comment_tree(parser, token):
"""
Gets a tree (list of objects ordered by preorder tree traversal, and with an
additional ``depth`` integer attribute annotated onto each ``ThreadedComment``.
"""
try:
split = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag must be of format {%% get_threaded_comment_tree for OBJECT as CONTEXT_VARIABLE %%}" % token.contents.split()[0]
return CommentTreeNode(split[2], split[4])
def do_get_free_threaded_comment_tree(parser, token):
"""
Gets a tree (list of objects ordered by traversing tree in preorder, and with an
additional ``depth`` integer attribute annotated onto each ``FreeThreadedComment.``
"""
try:
split = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag must be of format {%% get_free_threaded_comment_tree for OBJECT as CONTEXT_VARIABLE %%}" % token.contents.split()[0]
return FreeCommentTreeNode(split[2], split[4])
class CommentTreeNode(template.Node):
def __init__(self, content_object, context_name):
self.content_object = template.Variable(content_object)
self.context_name = context_name
def render(self, context):
content_object = self.content_object.resolve(context)
context[self.context_name] = ThreadedComment.public.get_tree(content_object)
return ''
class FreeCommentTreeNode(template.Node):
def __init__(self, content_object, context_name):
self.content_object = template.Variable(content_object)
self.context_name = context_name
def render(self, context):
content_object = self.content_object.resolve(context)
context[self.context_name] = FreeThreadedComment.public.get_tree(content_object)
return ''
def do_get_comment_count(parser, token):
"""
Gets a count of how many ThreadedComment objects are attached to the given
object.
"""
error_message = "%r tag must be of format {%% %r for OBJECT as CONTEXT_VARIABLE %%}" % (token.contents.split()[0], token.contents.split()[0])
try:
split = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, error_message
if split[1] != 'for' or split[3] != 'as':
raise template.TemplateSyntaxError, error_message
return ThreadedCommentCountNode(split[2], split[4])
class ThreadedCommentCountNode(template.Node):
def __init__(self, content_object, context_name):
self.content_object = template.Variable(content_object)
self.context_name = context_name
def render(self, context):
content_object = self.content_object.resolve(context)
context[self.context_name] = ThreadedComment.public.all_for_object(content_object).count()
return ''
def do_get_free_comment_count(parser, token):
"""
Gets a count of how many FreeThreadedComment objects are attached to the
given object.
"""
error_message = "%r tag must be of format {%% %r for OBJECT as CONTEXT_VARIABLE %%}" % (token.contents.split()[0], token.contents.split()[0])
try:
split = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, error_message
if split[1] != 'for' or split[3] != 'as':
raise template.TemplateSyntaxError, error_message
return FreeThreadedCommentCountNode(split[2], split[4])
class FreeThreadedCommentCountNode(template.Node):
def __init__(self, content_object, context_name):
self.content_object = template.Variable(content_object)
self.context_name = context_name
def render(self, context):
content_object = self.content_object.resolve(context)
context[self.context_name] = FreeThreadedComment.public.all_for_object(content_object).count()
return ''
def oneline(value):
"""
Takes some HTML and gets rid of newlines and spaces between tags, rendering
the result all on one line.
"""
try:
return mark_safe(newlines.sub('', inbetween.sub('><', value)))
except:
return value
register = template.Library()
register.simple_tag(get_comment_url)
register.simple_tag(get_comment_url_json)
register.simple_tag(get_comment_url_xml)
register.simple_tag(get_free_comment_url)
register.simple_tag(get_free_comment_url_json)
register.simple_tag(get_free_comment_url_xml)
register.filter('oneline', oneline)
register.tag('auto_transform_markup', do_auto_transform_markup)
register.tag('get_threaded_comment_tree', do_get_threaded_comment_tree)
register.tag('get_free_threaded_comment_tree', do_get_free_threaded_comment_tree)
register.tag('get_free_threaded_comment_tree', do_get_free_threaded_comment_tree)
register.tag('get_comment_count', do_get_comment_count)
register.tag('get_free_comment_count', do_get_free_comment_count)