Parent: [2be7cd] (diff)

Child: [58a272] (diff)

Download this file

root.py    345 lines (305 with data), 13.6 kB

  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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import json
import logging
from urllib import unquote
from itertools import imap
from tg import expose, validate, redirect, flash, response
from tg.decorators import with_trailing_slash
from pylons import tmpl_context as c, app_globals as g
from pylons import request
from formencode import validators
from webob import exc
import pymongo
from allura.lib.security import require_access, has_access, require_authenticated
from allura.lib.search import search_app
from allura.lib import helpers as h
from allura.lib.utils import AntiSpam
from allura.lib.decorators import require_post
from allura.controllers import BaseController, DispatchIndex
from allura.controllers.feed import FeedArgs, FeedController
from .forum import ForumController
from forgediscussion import import_support
from forgediscussion import model
from forgediscussion import utils
from forgediscussion import widgets as FW
from allura.lib.widgets import discuss as DW
from allura.lib.widgets.search import SearchResults, SearchHelp
from forgediscussion.widgets.admin import AddForumShort
log = logging.getLogger(__name__)
class RootController(BaseController, DispatchIndex, FeedController):
class W(object):
forum_subscription_form=FW.ForumSubscriptionForm()
new_topic=DW.NewTopicPost(submit_text='Post')
announcements_table=FW.AnnouncementsTable()
add_forum=AddForumShort()
search_results = SearchResults()
search_help = SearchHelp(comments=False, history=False)
def _check_security(self):
require_access(c.app, 'read')
@with_trailing_slash
@expose('jinja:forgediscussion:templates/discussionforums/index.html')
def index(self, new_forum=False, **kw):
c.new_topic = self.W.new_topic
c.new_topic = self.W.new_topic
c.add_forum = self.W.add_forum
c.announcements_table = self.W.announcements_table
announcements=model.ForumThread.query.find(dict(
app_config_id=c.app.config._id,
flags='Announcement',
)).all()
forums = model.Forum.query.find(dict(
app_config_id=c.app.config._id,
parent_id=None, deleted=False)).all()
forums = [f for f in forums if h.has_access(f, 'read')()]
return dict(forums=forums,
announcements=announcements,
hide_forum=(not new_forum))
@expose('jinja:forgediscussion:templates/discussionforums/index.html')
def new_forum(self, **kw):
require_access(c.app, 'configure')
return self.index(new_forum=True, **kw)
@h.vardec
@expose()
@require_post()
@validate(form=W.add_forum, error_handler=index)
def add_forum_short(self, add_forum=None, **kw):
require_access(c.app, 'configure')
f = utils.create_forum(c.app, add_forum)
redirect(f.url())
@with_trailing_slash
@expose('jinja:forgediscussion:templates/discussionforums/create_topic.html')
def create_topic(self, forum_name=None, new_forum=False, **kw):
forums = model.Forum.query.find(dict(app_config_id=c.app.config._id,
parent_id=None,
deleted=False))
c.new_topic = self.W.new_topic
my_forums = []
forum_name = h.really_unicode(unquote(forum_name)) if forum_name else None
current_forum = None
for f in forums:
if forum_name == f.shortname:
current_forum = f
if has_access(f, 'post')():
my_forums.append(f)
return dict(forums=my_forums, current_forum=current_forum)
@h.vardec
@expose()
@require_post()
@validate(W.new_topic, error_handler=create_topic)
@AntiSpam.validate('Spambot protection engaged')
def save_new_topic(self, subject=None, text=None, forum=None, **kw):
discussion = model.Forum.query.get(
app_config_id=c.app.config._id,
shortname=forum)
if discussion.deleted and not has_access(c.app, 'configure')():
flash('This forum has been removed.')
redirect(request.referrer)
require_access(discussion, 'post')
thd = discussion.get_discussion_thread(dict(
headers=dict(Subject=subject)))[0]
post = thd.post(subject, text)
flash('Message posted')
redirect(thd.url())
@with_trailing_slash
@expose('jinja:forgediscussion:templates/discussionforums/search.html')
@validate(dict(q=validators.UnicodeString(if_empty=None),
history=validators.StringBool(if_empty=False),
project=validators.StringBool(if_empty=False),
limit=validators.Int(if_empty=None),
page=validators.Int(if_empty=0)))
def search(self, q=None, history=None, project=None, limit=None, page=0, **kw):
c.search_results = self.W.search_results
c.help_modal = self.W.search_help
search_params = kw
search_params.update({
'q': q or '',
'history': history,
'project': project,
'limit': limit,
'page': page,
'allowed_types': ['Post', 'Post Snapshot', 'Discussion', 'Thread'],
})
d = search_app(**search_params)
d['search_comments_disable'] = True
return d
@expose('jinja:allura:templates/markdown_syntax.html')
def markdown_syntax(self):
'Static page explaining markdown.'
return dict()
@with_trailing_slash
@expose('jinja:allura:templates/markdown_syntax_dialog.html')
def markdown_syntax_dialog(self):
'Static dialog page about how to use markdown.'
return dict()
@expose()
def _lookup(self, id=None, *remainder):
if id:
id = unquote(id)
forum = model.Forum.query.get(
app_config_id=c.app.config._id,
shortname=id)
if forum is None:
raise exc.HTTPNotFound()
c.forum = forum
return ForumController(id), remainder
else:
raise exc.HTTPNotFound()
@h.vardec
@expose()
@validate(W.forum_subscription_form)
def subscribe(self, **kw):
require_authenticated()
forum = kw.pop('forum', [])
thread = kw.pop('thread', [])
objs = []
for data in forum:
objs.append(dict(obj=model.Forum.query.get(shortname=data['shortname'],
app_config_id=c.app.config._id),
subscribed=bool(data.get('subscribed'))))
for data in thread:
objs.append(dict(obj=model.Thread.query.get(_id=data['id']),
subscribed=bool(data.get('subscribed'))))
for obj in objs:
if obj['subscribed']:
obj['obj'].subscriptions[str(c.user._id)] = True
else:
obj['obj'].subscriptions.pop(str(c.user._id), None)
redirect(request.referer)
def get_feed(self, project, app, user):
"""Return a :class:`allura.controllers.feed.FeedArgs` object describing
the xml feed for this controller.
Overrides :meth:`allura.controllers.feed.FeedController.get_feed`.
"""
return FeedArgs(
dict(project_id=project._id, app_config_id=app.config._id),
'Recent posts to %s' % app.config.options.mount_label,
app.url)
class RootRestController(BaseController):
def _check_security(self):
require_access(c.app, 'read')
@expose()
def _lookup(self, forum, *remainder):
return ForumRestController(unquote(forum)), remainder
@expose('json:')
def index(self, limit=100, page=0, **kw):
limit, page, start = g.handle_paging(int(limit), int(page))
forums = model.Forum.query.find(dict(
app_config_id=c.app.config._id,
parent_id=None, deleted=False)
).sort([('shortname', pymongo.ASCENDING)]).skip(start).limit(limit)
count = forums.count()
json = dict(forums=[dict(_id=f._id,
name=f.name,
shortname=f.shortname,
description=f.description,
num_topics=f.num_topics,
last_post=f.last_post,
url=h.absurl('/rest' + f.url()))
for f in forums if has_access(f, 'read')])
json['limit'] = limit
json['page'] = page
json['count'] = count
return json
@expose('json:')
def validate_import(self, doc=None, username_mapping=None, **kw):
require_access(c.project, 'admin')
if username_mapping is None: username_mapping = {}
try:
doc = json.loads(doc)
warnings, doc = import_support.validate_import(doc, username_mapping)
return dict(warnings=warnings, errors=[])
except Exception, e:
raise
log.exception(e)
return dict(status=False, errors=[repr(e)])
@expose('json:')
def perform_import(
self, doc=None, username_mapping=None, default_username=None, create_users=False,
**kw):
require_access(c.project, 'admin')
if username_mapping is None: username_mapping = '{}'
if c.api_token.get_capability('import') != [c.project.neighborhood.name, c.project.shortname]:
log.error('Import capability is not enabled for %s', c.project.shortname)
raise exc.HTTPForbidden(detail='Import is not allowed')
try:
doc = json.loads(doc)
username_mapping = json.loads(username_mapping)
warnings = import_support.perform_import(
doc, username_mapping, default_username, create_users)
return dict(warnings=warnings, errors=[])
except Exception, e:
raise
log.exception(e)
return dict(status=False, errors=[str(e)])
class ForumRestController(BaseController):
def __init__(self, forum):
self.forum = model.Forum.query.get(
app_config_id=c.app.config._id,
shortname=forum)
if not self.forum or self.forum.deleted:
raise exc.HTTPNotFound()
def _check_security(self):
require_access(self.forum, 'read')
@expose('json:')
def index(self, limit=100, page=0, **kw):
limit, page, start = g.handle_paging(int(limit), int(page))
topics = model.Forum.thread_class().query.find(dict(discussion_id=self.forum._id))
topics = topics.sort([('flags', pymongo.DESCENDING),
('last_post_date', pymongo.DESCENDING)])
topics = topics.skip(start).limit(limit)
count = topics.count()
json = {}
json['forum'] = self.forum.__json__()
json['forum']['topics'] = [dict(_id=t._id,
subject=t.subject,
num_replies=t.num_replies,
num_views=t.num_views,
url=h.absurl('/rest' + t.url()),
last_post=t.last_post)
for t in topics]
json['count'] = count
json['page'] = page
json['limit'] = limit
return json
@expose()
def _lookup(self, thread, thread_id, *remainder):
if thread == 'thread':
topic = model.Forum.thread_class().query.find(dict(
app_config_id=c.app.config._id,
discussion_id=self.forum._id,
_id=unquote(thread_id))).first()
if topic:
return ForumTopicRestController(self.forum, topic), remainder
raise exc.HTTPNotFound()
class ForumTopicRestController(BaseController):
def __init__(self, forum, topic):
self.forum = forum
self.topic = topic
def _check_security(self):
require_access(self.forum, 'read')
@expose('json:')
def index(self, limit=100, page=0, **kw):
limit, page, start = g.handle_paging(int(limit), int(page))
posts = self.topic.query_posts(page=page, limit=limit, style='', status='ok')
json = {}
json['topic'] = self.topic.__json__()
json['count'] = posts.count()
json['page'] = page
json['limit'] = limit
json['topic']['posts'] = posts.all()
return json