Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 539 lines (464 sloc) 21.905 kB
df971c3 fix the licenses so they stop polluting all the other diffs
spez authored
1 # The contents of this file are subject to the Common Public Attribution
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
2 # License Version 1.0. (the "License"); you may not use this file except in
3 # compliance with the License. You may obtain a copy of the License at
4 # http://code.reddit.com/LICENSE. The License is based on the Mozilla Public
5 # License Version 1.1, but Sections 14 and 15 have been added to cover use of
6 # software over a computer network and provide for limited attribution for the
7 # Original Developer. In addition, Exhibit A has been modified to be consistent
8 # with Exhibit B.
2869eaf @ketralnis New features:
ketralnis authored
9 #
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
10 # Software distributed under the License is distributed on an "AS IS" basis,
11 # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
12 # the specific language governing rights and limitations under the License.
2869eaf @ketralnis New features:
ketralnis authored
13 #
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
14 # The Original Code is Reddit.
2869eaf @ketralnis New features:
ketralnis authored
15 #
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
16 # The Original Developer is the Initial Developer. The Initial Developer of the
17 # Original Code is CondeNet, Inc.
2869eaf @ketralnis New features:
ketralnis authored
18 #
19 # All portions of the code written by CondeNet are Copyright (c) 2006-2010
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
20 # CondeNet, Inc. All Rights Reserved.
21 ################################################################################
22 from utils import to36, tup, iters
2837bb3 @KeyserSosa bugfixes for caching patch
KeyserSosa authored
23 from wrapped import Wrapped, StringTemplate, CacheStub, CachedVariable, Templated
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
24 from mako.template import Template
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
25 from r2.lib.filters import spaceCompress, safemarkdown
26 import time, pytz
7fff900 @ketralnis February 2011 Merge
ketralnis authored
27 from pylons import c, g
d99dece @spladug Honor selftext-expunging in JSON API.
spladug authored
28 from pylons.i18n import _
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
29
30 def api_type(subtype = ''):
31 return 'api-' + subtype if subtype else 'api'
32
33 def is_api(subtype = ''):
34 return c.render_style and c.render_style.startswith(api_type(subtype))
68a06c5 @spladug April 2011 Merge
spladug authored
35
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
36 def get_api_subtype():
37 if is_api() and c.render_style.startswith('api-'):
38 return c.render_style[4:]
39
40 def make_typename(typ):
41 return 't%s' % to36(typ._type_id)
42
43 def make_fullname(typ, _id):
44 return '%s_%s' % (make_typename(typ), to36(_id))
45
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
46
47 class ObjectTemplate(StringTemplate):
48 def __init__(self, d):
49 self.d = d
a402d48 New features:
Mike authored
50
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
51 def update(self, kw):
52 def _update(obj):
53 if isinstance(obj, (str, unicode)):
427c1ca fix tabbing issue. update space compression in api to stop extraneou…
Christopher Slowe authored
54 return StringTemplate(obj).finalize(kw)
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
55 elif isinstance(obj, dict):
56 return dict((k, _update(v)) for k, v in obj.iteritems())
57 elif isinstance(obj, (list, tuple)):
58 return map(_update, obj)
59 elif isinstance(obj, CacheStub) and kw.has_key(obj.name):
a402d48 New features:
Mike authored
60 return kw[obj.name]
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
61 else:
62 return obj
63 res = _update(self.d)
64 return ObjectTemplate(res)
65
66 def finalize(self, kw = {}):
67 return self.update(kw).d
68
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
69 class JsonTemplate(Template):
70 def __init__(self): pass
71
72 def render(self, thing = None, *a, **kw):
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
73 return ObjectTemplate({})
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
74
bf9f43c @KeyserSosa Messaging/commenting
KeyserSosa authored
75 class TakedownJsonTemplate(JsonTemplate):
76 def render(self, thing = None, *a, **kw):
77 return thing.explanation
78
4440ccf @KeyserSosa overhaul of JS and form handling code, not based on jQuery
KeyserSosa authored
79 class TableRowTemplate(JsonTemplate):
80 def cells(self, thing):
81 raise NotImplementedError
82
83 def css_id(self, thing):
84 return ""
85
86 def css_class(self, thing):
87 return ""
88
89 def render(self, thing = None, *a, **kw):
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
90 return ObjectTemplate(dict(id = self.css_id(thing),
91 css_class = self.css_class(thing),
92 cells = self.cells(thing)))
4440ccf @KeyserSosa overhaul of JS and form handling code, not based on jQuery
KeyserSosa authored
93
94ac558 Add JSON api access to various user lists.
Max Goodman authored
94 class UserItemHTMLJsonTemplate(TableRowTemplate):
4440ccf @KeyserSosa overhaul of JS and form handling code, not based on jQuery
KeyserSosa authored
95 def cells(self, thing):
96 cells = []
97 for cell in thing.cells:
2837bb3 @KeyserSosa bugfixes for caching patch
KeyserSosa authored
98 thing.name = cell
99 r = thing.part_render('cell_type', style = "html")
4440ccf @KeyserSosa overhaul of JS and form handling code, not based on jQuery
KeyserSosa authored
100 cells.append(spaceCompress(r))
101 return cells
102
103 def css_id(self, thing):
104 return thing.user._fullname
105
106 def css_class(self, thing):
107 return "thing"
108
109
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
110 class ThingJsonTemplate(JsonTemplate):
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
111 _data_attrs_ = dict(id = "_id36",
112 name = "_fullname",
113 created = "created",
114 created_utc = "created_utc")
115
116 @classmethod
117 def data_attrs(cls, **kw):
118 d = cls._data_attrs_.copy()
119 d.update(kw)
120 return d
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
121
122 def kind(self, wrapped):
4440ccf @KeyserSosa overhaul of JS and form handling code, not based on jQuery
KeyserSosa authored
123 """
124 Returns a string literal which identifies the type of this
125 thing. For subclasses of Thing, it will be 't's + kind_id.
126 """
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
127 _thing = wrapped.lookups[0] if isinstance(wrapped, Wrapped) else wrapped
128 return make_typename(_thing.__class__)
129
130 def rendered_data(self, thing):
4440ccf @KeyserSosa overhaul of JS and form handling code, not based on jQuery
KeyserSosa authored
131 """
132 Called only when get_api_type is non-None (i.e., a JSON
133 request has been made with partial rendering of the object to
134 be returned)
135
136 Canonical Thing data representation for JS, which is currently
137 a dictionary of three elements (translated into a JS Object
138 when sent out). The elements are:
139
140 * id : Thing _fullname of thing.
141 * content : rendered representation of the thing by
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
142 calling render on it using the style of get_api_subtype().
4440ccf @KeyserSosa overhaul of JS and form handling code, not based on jQuery
KeyserSosa authored
143 """
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
144 res = dict(id = thing._fullname,
145 content = thing.render(style=get_api_subtype()))
146 return res
147
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
148 def raw_data(self, thing):
4440ccf @KeyserSosa overhaul of JS and form handling code, not based on jQuery
KeyserSosa authored
149 """
150 Complement to rendered_data. Called when a dictionary of
151 thing data attributes is to be sent across the wire.
152 """
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
153 return dict((k, self.thing_attr(thing, v))
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
154 for k, v in self._data_attrs_.iteritems())
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
155
156 def thing_attr(self, thing, attr):
4440ccf @KeyserSosa overhaul of JS and form handling code, not based on jQuery
KeyserSosa authored
157 """
158 For the benefit of subclasses, to lookup attributes which may
159 require more work than a simple getattr (for example, 'author'
160 which has to be gotten from the author_id attribute on most
161 things).
162 """
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
163 if attr == "author":
164 return thing.author.name
f429132 @rasher Add flair text and css class to json output. Respects if the users ha…
rasher authored
165 if attr == "author_flair_text":
166 if thing.author.flair_enabled_in_sr(thing.subreddit._id):
167 return getattr(thing.author,
168 'flair_%s_text' % (thing.subreddit._id),
169 None)
170 else:
171 return None
172 if attr == "author_flair_css_class":
173 if thing.author.flair_enabled_in_sr(thing.subreddit._id):
174 return getattr(thing.author,
175 'flair_%s_css_class' % (thing.subreddit._id),
176 None)
177 else:
178 return None
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
179 elif attr == "created":
180 return time.mktime(thing._date.timetuple())
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
181 elif attr == "created_utc":
c780f09 @KeyserSosa API updates:
KeyserSosa authored
182 return (time.mktime(thing._date.astimezone(pytz.UTC).timetuple())
183 - time.timezone)
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
184 elif attr == "child":
185 return CachedVariable("childlisting")
186 return getattr(thing, attr, None)
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
187
188 def data(self, thing):
189 if get_api_subtype():
190 return self.rendered_data(thing)
191 else:
192 return self.raw_data(thing)
2869eaf @ketralnis New features:
ketralnis authored
193
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
194 def render(self, thing = None, action = None, *a, **kw):
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
195 return ObjectTemplate(dict(kind = self.kind(thing),
196 data = self.data(thing)))
2869eaf @ketralnis New features:
ketralnis authored
197
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
198 class SubredditJsonTemplate(ThingJsonTemplate):
9a4271f @KeyserSosa Upgrade Instructions
KeyserSosa authored
199 _data_attrs_ = ThingJsonTemplate.data_attrs(subscribers = "_ups",
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
200 title = "title",
201 url = "path",
7fff900 @ketralnis February 2011 Merge
ketralnis authored
202 over18 = "over_18",
08c431b @KeyserSosa * Comply with the spec on 304 errors so Chrome won't barf download.g…
KeyserSosa authored
203 description = "description",
204 display_name = "name")
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
205
7fff900 @ketralnis February 2011 Merge
ketralnis authored
206 def thing_attr(self, thing, attr):
207 # Don't reveal revenue information via /r/lounge's subscribers
208 if (attr == "_ups" and g.lounge_reddit
209 and thing.name == g.lounge_reddit):
210 return 0
211 else:
212 return ThingJsonTemplate.thing_attr(self, thing, attr)
213
5df8723 Preliminary OAuth2 for new API call authentication.
Max Goodman authored
214 class IdentityJsonTemplate(ThingJsonTemplate):
b9ec9f6 @KeyserSosa updates to API: about.json on user pages to fetch link and comment ka…
KeyserSosa authored
215 _data_attrs_ = ThingJsonTemplate.data_attrs(name = "name",
216 link_karma = "safe_karma",
2869eaf @ketralnis New features:
ketralnis authored
217 comment_karma = "comment_karma",
18cdeee Add is_gold parameter to user JSON.
Max Goodman authored
218 is_gold = "gold"
a402d48 New features:
Mike authored
219 )
2869eaf @ketralnis New features:
ketralnis authored
220
5df8723 Preliminary OAuth2 for new API call authentication.
Max Goodman authored
221 class AccountJsonTemplate(IdentityJsonTemplate):
222 _data_attrs_ = IdentityJsonTemplate.data_attrs(has_mail = "has_mail",
223 has_mod_mail = "has_mod_mail",
224 is_mod = "is_mod",
225 )
226
2869eaf @ketralnis New features:
ketralnis authored
227 def thing_attr(self, thing, attr):
a402d48 New features:
Mike authored
228 from r2.models import Subreddit
2869eaf @ketralnis New features:
ketralnis authored
229 if attr == "has_mail":
230 if c.user_is_loggedin and thing._id == c.user._id:
231 return bool(c.have_messages)
232 return None
a402d48 New features:
Mike authored
233 if attr == "has_mod_mail":
234 if c.user_is_loggedin and thing._id == c.user._id:
235 return bool(c.have_mod_messages)
236 return None
237 if attr == "is_mod":
238 return bool(Subreddit.reverse_moderator_ids(thing))
2869eaf @ketralnis New features:
ketralnis authored
239 return ThingJsonTemplate.thing_attr(self, thing, attr)
b9ec9f6 @KeyserSosa updates to API: about.json on user pages to fetch link and comment ka…
KeyserSosa authored
240
2b3b061 Add /api/me resource to fetch user info + modhash.
Max Goodman authored
241 def raw_data(self, thing):
242 data = ThingJsonTemplate.raw_data(self, thing)
243 if c.user_is_loggedin and thing._id == c.user._id:
244 data["modhash"] = c.modhash
245 return data
246
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
247 class LinkJsonTemplate(ThingJsonTemplate):
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
248 _data_attrs_ = ThingJsonTemplate.data_attrs(ups = "upvotes",
249 downs = "downvotes",
250 score = "score",
251 saved = "saved",
252 clicked = "clicked",
253 hidden = "hidden",
37e2ba9 @ketralnis * Combine cassandra clusters into a single one
ketralnis authored
254 over_18 = "over_18",
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
255 likes = "likes",
256 domain = "domain",
257 title = "title",
258 url = "url",
bf9f43c @KeyserSosa Messaging/commenting
KeyserSosa authored
259 author = "author",
f429132 @rasher Add flair text and css class to json output. Respects if the users ha…
rasher authored
260 author_flair_text =
261 "author_flair_text",
262 author_flair_css_class =
263 "author_flair_css_class",
c3b894f @KeyserSosa bugfix for messages too long (now generates an error); fix of rss fee…
KeyserSosa authored
264 thumbnail = "thumbnail",
265 media = "media_object",
c780f09 @KeyserSosa API updates:
KeyserSosa authored
266 media_embed = "media_embed",
1ee32ee add rendered selftext to json responses on comment pages
spez authored
267 selftext = "selftext",
bf9f43c @KeyserSosa Messaging/commenting
KeyserSosa authored
268 selftext_html= "selftext_html",
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
269 num_comments = "num_comments",
270 subreddit = "subreddit",
67814d5 @ketralnis Features:
ketralnis authored
271 subreddit_id = "subreddit_id",
e87f520 @KeyserSosa New Features:
KeyserSosa authored
272 is_self = "is_self",
37e2ba9 @ketralnis * Combine cassandra clusters into a single one
ketralnis authored
273 permalink = "permalink",
67814d5 @ketralnis Features:
ketralnis authored
274 )
c780f09 @KeyserSosa API updates:
KeyserSosa authored
275
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
276 def thing_attr(self, thing, attr):
e87f520 @KeyserSosa New Features:
KeyserSosa authored
277 from r2.lib.scraper import get_media_embed
c780f09 @KeyserSosa API updates:
KeyserSosa authored
278 if attr == "media_embed":
279 if (thing.media_object and
280 not isinstance(thing.media_object, basestring)):
e87f520 @KeyserSosa New Features:
KeyserSosa authored
281 media_embed = get_media_embed(thing.media_object)
282 if media_embed:
283 return dict(scrolling = media_embed.scrolling,
284 width = media_embed.width,
285 height = media_embed.height,
286 content = media_embed.content)
c780f09 @KeyserSosa API updates:
KeyserSosa authored
287 return dict()
288 elif attr == 'subreddit':
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
289 return thing.subreddit.name
290 elif attr == 'subreddit_id':
291 return thing.subreddit._fullname
1ee32ee add rendered selftext to json responses on comment pages
spez authored
292 elif attr == 'selftext':
d99dece @spladug Honor selftext-expunging in JSON API.
spladug authored
293 if not thing.expunged:
294 return thing.selftext
295 else:
296 return ''
bf9f43c @KeyserSosa Messaging/commenting
KeyserSosa authored
297 elif attr == 'selftext_html':
d99dece @spladug Honor selftext-expunging in JSON API.
spladug authored
298 if not thing.expunged:
299 return safemarkdown(thing.selftext)
300 else:
06f4b9e @spladug Use [removed] instead of [deleted] for expunged.
spladug authored
301 return safemarkdown(_("[removed]"))
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
302 return ThingJsonTemplate.thing_attr(self, thing, attr)
c780f09 @KeyserSosa API updates:
KeyserSosa authored
303
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
304 def rendered_data(self, thing):
305 d = ThingJsonTemplate.rendered_data(self, thing)
306 d['sr'] = thing.subreddit._fullname
307 return d
308
309
bf9f43c @KeyserSosa Messaging/commenting
KeyserSosa authored
310 class PromotedLinkJsonTemplate(LinkJsonTemplate):
311 _data_attrs_ = LinkJsonTemplate.data_attrs(promoted = "promoted")
312 del _data_attrs_['author']
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
313
314 class CommentJsonTemplate(ThingJsonTemplate):
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
315 _data_attrs_ = ThingJsonTemplate.data_attrs(ups = "upvotes",
316 downs = "downvotes",
317 replies = "child",
318 body = "body",
319 body_html = "body_html",
320 likes = "likes",
321 author = "author",
f429132 @rasher Add flair text and css class to json output. Respects if the users ha…
rasher authored
322 author_flair_text =
323 "author_flair_text",
324 author_flair_css_class =
325 "author_flair_css_class",
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
326 link_id = "link_id",
e87f520 @KeyserSosa New Features:
KeyserSosa authored
327 subreddit = "subreddit",
328 subreddit_id = "subreddit_id",
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
329 parent_id = "parent_id",
330 )
2d1203f @KeyserSosa added links to domains and fixed comment JSON feed to include link_id…
KeyserSosa authored
331
332 def thing_attr(self, thing, attr):
c780f09 @KeyserSosa API updates:
KeyserSosa authored
333 from r2.models import Comment, Link, Subreddit
2d1203f @KeyserSosa added links to domains and fixed comment JSON feed to include link_id…
KeyserSosa authored
334 if attr == 'link_id':
335 return make_fullname(Link, thing.link_id)
e87f520 @KeyserSosa New Features:
KeyserSosa authored
336 elif attr == 'subreddit':
337 return thing.subreddit.name
338 elif attr == 'subreddit_id':
339 return thing.subreddit._fullname
2d1203f @KeyserSosa added links to domains and fixed comment JSON feed to include link_id…
KeyserSosa authored
340 elif attr == "parent_id":
5ef76b9 @KeyserSosa New features:
KeyserSosa authored
341 if getattr(thing, "parent_id", None):
2d1203f @KeyserSosa added links to domains and fixed comment JSON feed to include link_id…
KeyserSosa authored
342 return make_fullname(Comment, thing.parent_id)
5ef76b9 @KeyserSosa New features:
KeyserSosa authored
343 else:
2d1203f @KeyserSosa added links to domains and fixed comment JSON feed to include link_id…
KeyserSosa authored
344 return make_fullname(Link, thing.link_id)
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
345 elif attr == "body_html":
427c1ca fix tabbing issue. update space compression in api to stop extraneou…
Christopher Slowe authored
346 return spaceCompress(safemarkdown(thing.body))
2d1203f @KeyserSosa added links to domains and fixed comment JSON feed to include link_id…
KeyserSosa authored
347 return ThingJsonTemplate.thing_attr(self, thing, attr)
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
348
349 def kind(self, wrapped):
350 from r2.models import Comment
351 return make_typename(Comment)
352
b9ec9f6 @KeyserSosa updates to API: about.json on user pages to fetch link and comment ka…
KeyserSosa authored
353 def raw_data(self, thing):
354 d = ThingJsonTemplate.raw_data(self, thing)
355 if c.profilepage:
356 d['link_title'] = thing.link.title
357 return d
358
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
359 def rendered_data(self, wrapped):
360 d = ThingJsonTemplate.rendered_data(self, wrapped)
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
361 d['replies'] = self.thing_attr(wrapped, 'child')
77e51a3 A new submit page.
spez authored
362 d['contentText'] = self.thing_attr(wrapped, 'body')
363 d['contentHTML'] = self.thing_attr(wrapped, 'body_html')
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
364 d['link'] = self.thing_attr(wrapped, 'link_id')
365 d['parent'] = self.thing_attr(wrapped, 'parent_id')
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
366 return d
367
368 class MoreCommentJsonTemplate(CommentJsonTemplate):
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
369 _data_attrs_ = dict(id = "_id36",
60f704e @bboe List child comments in MoreCommentsJsonTemplate.
bboe authored
370 name = "_fullname",
371 children = "children")
372
348bad9 @KeyserSosa fix for failure when JSON requesting a comment page with 'more commen…
KeyserSosa authored
373 def kind(self, wrapped):
374 return "more"
375
bf9f43c @KeyserSosa Messaging/commenting
KeyserSosa authored
376 def thing_attr(self, thing, attr):
60f704e @bboe List child comments in MoreCommentsJsonTemplate.
bboe authored
377 if attr == 'children':
378 return [to36(x) for x in thing.children]
bf9f43c @KeyserSosa Messaging/commenting
KeyserSosa authored
379 if attr in ('body', 'body_html'):
380 return ""
381 return CommentJsonTemplate.thing_attr(self, thing, attr)
382
77e51a3 A new submit page.
spez authored
383 def rendered_data(self, wrapped):
bf9f43c @KeyserSosa Messaging/commenting
KeyserSosa authored
384 return CommentJsonTemplate.rendered_data(self, wrapped)
77e51a3 A new submit page.
spez authored
385
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
386 class MessageJsonTemplate(ThingJsonTemplate):
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
387 _data_attrs_ = ThingJsonTemplate.data_attrs(new = "new",
388 subject = "subject",
389 body = "body",
2869eaf @ketralnis New features:
ketralnis authored
390 replies = "child",
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
391 body_html = "body_html",
392 author = "author",
393 dest = "dest",
a402d48 New features:
Mike authored
394 subreddit = "subreddit",
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
395 was_comment = "was_comment",
9a0df9a @KeyserSosa add context param to message JSON templates
KeyserSosa authored
396 context = "context",
2869eaf @ketralnis New features:
ketralnis authored
397 created = "created",
398 parent_id = "parent_id",
399 first_message= "first_message")
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
400
401 def thing_attr(self, thing, attr):
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
402 if attr == "was_comment":
bf9f43c @KeyserSosa Messaging/commenting
KeyserSosa authored
403 return thing.was_comment
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
404 elif attr == "context":
bf9f43c @KeyserSosa Messaging/commenting
KeyserSosa authored
405 return ("" if not thing.was_comment
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
406 else thing.permalink + "?context=3")
407 elif attr == "dest":
a402d48 New features:
Mike authored
408 if thing.to_id:
409 return thing.to.name
410 else:
411 return "#" + thing.subreddit.name
412 elif attr == "subreddit":
413 if thing.sr_id:
414 return thing.subreddit.name
415 return None
c58779c @KeyserSosa updates to JSON api and responses to /api POST interface:
KeyserSosa authored
416 elif attr == "body_html":
417 return safemarkdown(thing.body)
d3f8fdb @kemitche Send ban message from SR, not mod
kemitche authored
418 elif attr == "author" and getattr(thing, "hide_author", False):
419 return None
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
420 return ThingJsonTemplate.thing_attr(self, thing, attr)
421
422 def rendered_data(self, wrapped):
423 from r2.models import Message
5ef76b9 @KeyserSosa New features:
KeyserSosa authored
424 parent_id = wrapped.parent_id
425 if parent_id:
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
426 parent_id = make_fullname(Message, parent_id)
427 d = ThingJsonTemplate.rendered_data(self, wrapped)
428 d['parent'] = parent_id
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
429 d['contentText'] = self.thing_attr(wrapped, 'body')
430 d['contentHTML'] = self.thing_attr(wrapped, 'body_html')
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
431 return d
432
433
434 class RedditJsonTemplate(JsonTemplate):
435 def render(self, thing = None, *a, **kw):
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
436 return ObjectTemplate(thing.content().render() if thing else {})
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
437
438 class PanestackJsonTemplate(JsonTemplate):
439 def render(self, thing = None, *a, **kw):
16fc8d5 @KeyserSosa updates to service monitor. fix 500 on /api/info for empty listings
KeyserSosa authored
440 res = [t.render() for t in thing.stack if t] if thing else []
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
441 res = [x for x in res if x]
442 if not res:
443 return {}
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
444 return ObjectTemplate(res if len(res) > 1 else res[0] )
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
445
446 class NullJsonTemplate(JsonTemplate):
447 def render(self, thing = None, *a, **kw):
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
448 return ""
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
449
450 class ListingJsonTemplate(ThingJsonTemplate):
cb491d8 @KeyserSosa Update listing JSON template to include explicit before/after; fix va…
KeyserSosa authored
451 _data_attrs_ = dict(children = "things",
452 after = "after",
67814d5 @ketralnis Features:
ketralnis authored
453 before = "before",
454 modhash = "modhash")
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
455
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
456 def thing_attr(self, thing, attr):
67814d5 @ketralnis Features:
ketralnis authored
457 if attr == "modhash":
458 return c.modhash
459 elif attr == "things":
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
460 res = []
461 for a in thing.things:
462 a.childlisting = False
463 r = a.render()
464 res.append(r)
465 return res
466 return ThingJsonTemplate.thing_attr(self, thing, attr)
467
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
468
469 def rendered_data(self, thing):
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
470 return self.thing_attr(thing, "things")
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
471
472 def kind(self, wrapped):
473 return "Listing"
474
94ac558 Add JSON api access to various user lists.
Max Goodman authored
475 class UserListJsonTemplate(ThingJsonTemplate):
476 _data_attrs_ = dict(children = "users")
477
478 def thing_attr(self, thing, attr):
479 if attr == "users":
480 res = []
481 for a in thing.users:
9c5d73f Return JSON including the user fullname in user lists.
Max Goodman authored
482 r = a.render()
483 res.append(r)
94ac558 Add JSON api access to various user lists.
Max Goodman authored
484 return res
485 return ThingJsonTemplate.thing_attr(self, thing, attr)
486
487 def rendered_data(self, thing):
488 return self.thing_attr(thing, "users")
489
490 def kind(self, wrapped):
491 return "UserList"
492
9c5d73f Return JSON including the user fullname in user lists.
Max Goodman authored
493 class UserTableItemJsonTemplate(ThingJsonTemplate):
494 _data_attrs_ = dict(id = "_fullname",
495 name = "name")
496
497 def thing_attr(self, thing, attr):
498 return ThingJsonTemplate.thing_attr(self, thing.user, attr)
499
500 def render(self, thing, *a, **kw):
501 return ObjectTemplate(self.data(thing))
502
4778b17 @KeyserSosa initial checkin
KeyserSosa authored
503 class OrganicListingJsonTemplate(ListingJsonTemplate):
504 def kind(self, wrapped):
505 return "OrganicListing"
969238b @KeyserSosa * add JSON api for traffic graphs.
KeyserSosa authored
506
507 class TrafficJsonTemplate(JsonTemplate):
508 def render(self, thing, *a, **kw):
509 res = {}
510 for ival in ("hour", "day", "month"):
511 if hasattr(thing, ival + "_data"):
512 res[ival] = [[time.mktime(date.timetuple())] + list(data)
513 for date, data in getattr(thing, ival+"_data")]
84c1375 @KeyserSosa Epic Caching Update. Major features (mostly in r2.lib.wrapped)
KeyserSosa authored
514 return ObjectTemplate(res)
d80dac7 Add /api/flairlist.json.
Logan Hanks authored
515
516 class FlairListJsonTemplate(JsonTemplate):
517 def render(self, thing, *a, **kw):
518 def row_to_json(row):
519 if hasattr(row, 'user'):
520 return dict(user=row.user.name, flair_text=row.flair_text,
521 flair_css_class=row.flair_css_class)
522 else:
523 # prev/next link
524 return dict(after=row.after, reverse=row.reverse)
525
526 json_rows = [row_to_json(row) for row in thing.flair]
527 result = dict(users=[row for row in json_rows if 'user' in row])
528 for row in json_rows:
529 if 'after' in row:
530 if row['reverse']:
531 result['prev'] = row['after']
532 else:
533 result['next'] = row['after']
534 return ObjectTemplate(result)
3e42bd5 Add /api/flaircsv.
Logan Hanks authored
535
536 class FlairCsvJsonTemplate(JsonTemplate):
537 def render(self, thing, *a, **kw):
538 return ObjectTemplate([l.__dict__ for l in thing.results_by_line])
Something went wrong with that request. Please try again.