Parent: [a31727] (diff)

Download this file

main.py    306 lines (261 with data), 10.3 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
#-*- python -*-
import difflib
import logging
from pprint import pformat
# Non-stdlib imports
import pkg_resources
from tg import expose, validate, redirect
from pylons import g, c, request
from formencode import validators
from ming.orm.base import mapper
# Pyforge-specific imports
from pyforge.app import Application, ConfigOption, SitemapEntry
from pyforge.lib.helpers import push_config
from pyforge.lib.search import search
from pyforge.lib.decorators import audit, react
from pyforge.lib.security import require, has_artifact_access
from pyforge.model import ProjectRole, User
# Local imports
from forgewiki import model
from forgewiki import version
log = logging.getLogger(__name__)
# Will not be needed after _dispatch is fixed in tg 2.1
from pyforge.lib.dispatch import _dispatch
class ForgeWikiApp(Application):
'''This is the Wiki app for PyForge'''
__version__ = version.__version__
permissions = [ 'configure', 'read', 'create', 'edit', 'delete', 'comment' ]
config_options = Application.config_options + [
ConfigOption('project_name', str, 'pname'),
ConfigOption('message', str, 'Custom message goes here'),
]
def __init__(self, project, config):
Application.__init__(self, project, config)
self.root = RootController()
def has_access(self, user, topic):
return user != User.anonymous()
@audit('Wiki.#')
def auditor(self, routing_key, data):
'''Attach a comment to the named page'''
log.info('Auditing data from %s (%s)',
routing_key, self.config.options.mount_point)
log.info('Headers are: %s', data['headers'])
try:
elements = routing_key.split('.')
count = len(elements)
log.info('Audit applies to page ' + elements[1])
p = model.Page.upsert(elements[1])
except:
log.info('Audit applies to page Root.')
p = model.Page.upsert('Root')
# Find ancestor comment
parent = model.Comment.query.get(message_id=data['headers'].get('In-Reply-To'))
if parent is None: parent = p
comment = parent.reply()
if 'Message-ID' in data['headers']:
comment.message_id=data['headers']['Message-ID']
comment.text = '*%s*\n\n%s' % (
data['headers'].get('Subject'),
data['payload'])
log.info('Set subject to %s', data['headers'].get('Subject'))
@react('Wiki.#')
def reactor(self, routing_key, data):
log.info('Reacting to data from %s (%s)',
routing_key, self.config.options.mount_point)
@audit('forgewiki.reply')
def auditor(self, routing_key, data):
log.info('Auditing reply from %s (%s)',
routing_key, self.config.options.mount_point)
# 'data' should be a dictionary which includes:
# destinations, text, from, subject, message_id
data['destinations'] = 'devnull@localhost'
g.publish('audit', 'forgemail.send_email',
data, serializer='yaml')
@property
def sitemap(self):
menu_id = 'ForgeWiki (%s)' % self.config.options.mount_point
with push_config(c, app=self):
pages = [
SitemapEntry(p.title, p.url())
for p in model.Page.query.find(dict(
app_config_id=self.config._id)) ]
return [
SitemapEntry(menu_id, '.')[SitemapEntry('Pages')[pages]] ]
def sidebar_menu(self):
return [
SitemapEntry(p.title, p.url())
for p in model.Page.query.find(dict(
app_config_id=self.config._id)) ]
@property
def templates(self):
return pkg_resources.resource_filename('forgewiki', 'templates')
def install(self, project):
'Set up any default permissions and roles here'
self.config.options['project_name'] = project._id
self.uninstall(project)
# Give the installing user all the permissions
pr = c.user.project_role()
for perm in self.permissions:
self.config.acl[perm] = [ pr._id ]
self.config.acl['read'].append(
ProjectRole.query.get(name='*anonymous')._id)
self.config.acl['comment'].append(
ProjectRole.query.get(name='*authenticated')._id)
p = model.Page.upsert('Root')
p.text = 'This is the root page.'
p.commit()
def uninstall(self, project):
"Remove all the plugin's artifacts from the database"
mapper(model.Page).remove(dict(project_id=c.project._id))
mapper(model.Comment).remove(dict(project_id=c.project._id))
class RootController(object):
@expose('forgewiki.templates.index')
def index(self):
redirect('Root/')
return dict(message=c.app.config.options['message'])
#Will not be needed after _dispatch is fixed in tg 2.1
def _dispatch(self, state, remainder):
return _dispatch(self, state, remainder)
#Instantiate a Page object, and continue dispatch there
def _lookup(self, pname, *remainder):
return PageController(pname), remainder
@expose()
def new_page(self, title):
redirect(title + '/')
@expose('forgewiki.templates.search')
@validate(dict(q=validators.UnicodeString(if_empty=None),
history=validators.StringBool(if_empty=False)))
def search(self, q=None, history=None):
'local wiki search'
results = []
count=0
if not q:
q = ''
else:
search_query = '''%s
AND is_history_b:%s
AND project_id_s:%s
AND mount_point_s:%s''' % (
q, history, c.project._id, c.app.config.options.mount_point)
results = search(search_query)
if results: count=results.hits
return dict(q=q, history=history, results=results or [], count=count)
class PageController(object):
def __init__(self, title):
self.title = title
self.page = model.Page.upsert(title)
self.comments = CommentController(self.page)
def get_version(self, version):
if not version: return self.page
try:
return model.Page.upsert(self.title, version=int(version))
except ValueError:
return None
@expose('forgewiki.templates.page_view')
@validate(dict(version=validators.Int(if_empty=None)))
def index(self, version=None):
require(has_artifact_access('read', self.page))
page = self.get_version(version)
if page is None:
if version: redirect('.?version=%d' % (version-1))
else: redirect('.')
cur = page.version
if cur > 1: prev = cur-1
else: prev = None
next = cur+1
return dict(page=page,
cur=cur, prev=prev, next=next)
@expose('forgewiki.templates.page_edit')
def edit(self):
if self.page.version == 1:
require(has_artifact_access('create', self.page))
else:
require(has_artifact_access('edit', self.page))
return dict(page=self.page,
example=MARKDOWN_EXAMPLE)
@expose('forgewiki.templates.page_history')
def history(self):
require(has_artifact_access('read', self.page))
pages = self.page.history()
return dict(title=self.title, pages=pages)
@expose('forgewiki.templates.page_diff')
def diff(self, v1, v2):
require(has_artifact_access('read', self.page))
p1 = self.get_version(int(v1))
p2 = self.get_version(int(v2))
t1 = p1.text
t2 = p2.text
differ = difflib.SequenceMatcher(None, p1.text, p2.text)
result = []
for tag, i1, i2, j1, j2 in differ.get_opcodes():
if tag in ('delete', 'replace'):
result += [ '<del>', t1[i1:i2], '</del>' ]
if tag in ('insert', 'replace'):
result += [ '<ins>', t2[j1:j2], '</ins>' ]
if tag == 'equal':
result += t1[i1:i2]
result = ''.join(result).replace('\n', '<br/>\n')
return dict(p1=p1, p2=p2, edits=result)
@expose(content_type='text/plain')
def raw(self):
require(has_artifact_access('read', self.page))
return pformat(self.page)
@expose()
def revert(self, version):
require(has_artifact_access('edit', self.page))
orig = self.get_version(version)
self.page.text = orig.text
self.page.commit()
redirect('.')
@expose()
def update(self, text):
require(has_artifact_access('edit', self.page))
self.page.text = text
self.page.commit()
redirect('.')
class CommentController(object):
def __init__(self, page, comment_id=None):
self.page = page
self.comment_id = comment_id
self.comment = model.Comment.query.get(_id=self.comment_id)
@expose()
def reply(self, text):
require(has_artifact_access('comment', self.page))
if self.comment_id:
c = self.comment.reply()
c.text = text
else:
c = self.page.reply()
c.text = text
email = ''
for addr in c.author().email_addresses:
email = email + ', ' + addr
data = {
# 'destinations':email,
'text':text,
'from':str(self.page),
'subject':str('reply to '+c._id),
'message_id':c._id}
g.publish('audit', 'forgewiki.reply', data,
serializer='yaml')
redirect(request.referer)
@expose()
def delete(self):
require(lambda:c.user._id == self.comment.author()._id)
self.comment.delete()
redirect(request.referer)
def _dispatch(self, state, remainder):
return _dispatch(self, state, remainder)
def _lookup(self, next, *remainder):
if self.comment_id:
return CommentController(
self.page,
self.comment_id + '/' + next), remainder
else:
return CommentController(
self.page, next), remainder
MARKDOWN_EXAMPLE='''
# First-level heading
Some *emphasized* and **strong** text
#### Fourth-level heading
'''