This repository has been archived by the owner on Sep 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
entity.py
634 lines (575 loc) · 24.7 KB
/
entity.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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
""" slog: Simple sample tracker system.
Base entity class, with data field classes.
Per Kraulis
2011-02-08
"""
import logging, os.path, base64, quopri
from wireframe.response import *
from .dispatcher import *
from .fields import *
class Entity(Dispatcher):
"Base entity class, with data field classes."
fields = [] # List of Field instances
tool_classes = [] # List of Tool subclasses
@classmethod
def get_field(cls, name):
"Return the field instance by name."
for field in cls.fields:
if field.name == name: return field
@property
def locked(self):
return bool(self.doc.get('locked'))
def get_editable(self, user, check_lock=True):
"""Is the given user allowed to edit this page?
NOTE: First check that the entity is not locked. Then check that
the user is allowed to edit using 'get_editable_privilege'.
"""
if check_lock and self.locked: return False
return self.get_editable_privilege(user)
def check_editable(self, user, check_lock=True):
"Check that the given user is allowed to edit this page."
if check_lock and self.locked:
raise HTTP_CONFLICT("Entity '%s' is locked." % self)
if not self.get_editable(user, check_lock=False):
raise HTTP_FORBIDDEN("User '%s' may not edit page." % user['name'])
def get_editable_privilege(self, user):
"""Is the given user allowed to edit this page?
By default, only the role 'admin' is allowed to edit any page.
"""
return user.get('role') == 'admin'
def get_url(self):
"Return the absolute URL for this entity."
return configuration.get_url(self.__class__.__name__.lower(),
self.doc['name'])
def prepare(self, request, response):
super(Entity, self).prepare(request, response)
entity = self.__class__.__name__.lower()
name = request.path_named_values['name']
try:
self.doc = self.get_named_document(entity, name)
except ValueError:
raise HTTP_NOT_FOUND("entity %s %s" % (entity, name))
def GET(self, request, response):
self.check_viewable(self.user)
page = HtmlPage(self, title="%s %s" % (self.__class__.__name__,
self.get_title()))
page.header = DIV(H1(page.title),
utils.rst_to_html(self.__doc__))
page.set_context(self.doc)
# Edit mode; allow change of data
edit = request.get('edit')
if edit:
if edit == '_attachments':
self.edit_attachments(page)
elif edit == '_tags':
self.edit_tags(page)
elif edit == '_xrefs':
self.edit_xrefs(page)
else:
self.edit_data_field(page, edit)
page.log = '' # Don't clutter view with useless log
# View mode: display data
else:
self.view(page)
page.write(response)
def get_title(self):
"Return the title to represent this entity."
return self.doc['name']
def view(self, page):
"Produce the HTML page for GET."
self.view_fields(page)
self.view_attachments(page)
self.view_tools(page)
self.view_log(page)
self.view_locked(page)
self.view_tags(page)
self.view_xrefs(page)
def view_fields(self, page):
"HTML for the entity data fields."
page.append(H2('Information'))
rows = []
for field in self.fields:
rows.append(TR(TH(field.name),
TD(field.get_view(self)),
TD(field.get_edit_button(self)),
TD(field.get_description())))
page.append(TABLE(border=1, *rows))
def view_attachments(self, page):
"HTML for the attachments list."
page.append(H2('Attachments'))
cells = [TH('Attachment'),
TH('Mimetype'),
TH('Size (bytes)')]
if self.get_editable(self.user):
cells.append(TD(FORM(INPUT(type='submit', value='Edit'),
INPUT(type='hidden',
name='edit', value='_attachments'),
method='GET',
action=self.get_url())))
rows = [TR(*cells)]
stubs = self.doc.get('_attachments', dict())
for filename in sorted(stubs.keys()):
rows.append(TR(TD(A(filename,
href=configuration.get_url('attachment',
self.doc.id,
filename))),
TD(stubs[filename]['content_type']),
TD(stubs[filename]['length'])))
page.append(TABLE(border=1, *rows))
def view_tools(self, page):
"HTML for the tools list."
page.append(H2('Tools'))
rows = []
for tool_class in self.tool_classes:
tool = tool_class(self)
disabled = not tool.is_enabled(self.doc)
rows.append(TR(TH(str(tool)),
TD(FORM(INPUT(type='submit', value='Apply',
disabled=disabled),
INPUT(type='hidden', name='entity',
value=tool.get_entity_tag(self.doc)),
method='GET',
action=tool.get_url())),
TD(utils.rst_to_html(tool.__doc__))))
if not rows:
rows.append(TR(TH(I('None'))))
page.append(TABLE(*rows))
def view_log(self, page):
"HTML for the log list."
rows = [TR(TH('Action'),
TH('Account'),
TH('Timestamp'),
TH('Comment'),
TH('Log document'))]
view = self.db.view('log/docid_timestamp',
descending=True,
include_docs=True)
for result in view[[self.doc.id, 'Z']:[self.doc.id, '']]:
doc = result.doc
rows.append(TR(TD(doc['action']),
TD(A(doc['account'],
href=configuration.get_url('account',
doc['account']))),
TD(doc['timestamp']),
TD(doc.get('comment') or ''),
TD(A(doc.id,
href=configuration.get_url('doc', doc.id)))))
page.log = DIV(H2('Log'),
TABLE(border=1, *rows))
def view_locked(self, page):
if self.locked:
img = IMG(src=configuration.get_url('static', 'locked.png'),
alt='locked')
button = INPUT(type='submit', value='Unlock')
value = INPUT(type='hidden', name='locked', value='false')
else:
img = IMG(src=configuration.get_url('static', 'unlocked.png'),
alt='unlocked')
button = INPUT(type='submit', value='Lock')
value = INPUT(type='hidden', name='locked', value='true')
page.lock = TABLE(TR(TD(img),
TD(FORM(button, value,
method='POST',
action=self.get_url()))))
def view_tags(self, page):
tags = self.doc.get('tags', [])
if self.get_editable(self.user):
edit = FORM(INPUT(type='submit', value='Edit'),
INPUT(type='hidden', name='edit', value='_tags'),
method='GET',
action=self.get_url())
else:
edit = ''
if tags:
tags.sort()
first = tags[0]
else:
first = '-'
rowspan = max(1, len(tags))
rows = [TR(TH('Tags', rowspan=rowspan),
TD(first),
TD(edit, rowspan=rowspan))]
for tag in tags[1:]:
rows.append(TR(TD(tag)))
page.meta.append(DIV(TABLE(klass='tags', *rows)))
def view_xrefs(self, page):
xrefs = self.doc.get('xrefs', [])
if self.get_editable(self.user):
edit = FORM(INPUT(type='submit', value='Edit'),
INPUT(type='hidden', name='edit', value='_xrefs'),
method='GET',
action=self.get_url())
else:
edit = ''
if xrefs:
xrefs.sort()
xref = xrefs[0]
first = A(xref.get('title') or xref['uri'], href=xref['uri'])
else:
first = '-'
rows = [TR(TH('Xrefs', rowspan=len(xrefs)),
TD(first),
TD(edit, rowspan=len(xrefs)))]
for xref in xrefs[1:]:
rows.append(TR(TD(A(xref.get('title') or xref['uri'],
href=xref['uri']))))
page.meta.append(DIV(TABLE(klass='xrefs', *rows)))
def edit_attachments(self, page):
self.check_editable(self.user)
page.append(H2('Edit attachments'))
rows = [TR(TD(),
TH('Filename'),
TH('Mimetype'),
TH('Size'))]
stubs = self.doc.get('_attachments', dict())
for filename in sorted(stubs.keys()):
rows.append(TR(TD(INPUT(type='checkbox',
name='_attachment_delete',
value=filename)),
TD(A(filename,
href=configuration.get_url('attachment',
self.doc.id,
filename))),
TD(stubs[filename]['content_type']),
TD(stubs[filename]['length'])))
page.append(P(FORM(TABLE(
TR(TH('Delete'),
TD(TABLE(border=1, *rows))),
TR(TD(),
TD(INPUT(type='submit', value='Delete checked')))),
method='POST',
action=self.get_url())))
page.append(P(FORM(TABLE(
TR(TH('Attach file'),
TD(INPUT(type='file', size=40, name='_attachment'))),
TR(TD(),
TD(INPUT(type='submit', value='Upload')))),
enctype='multipart/form-data',
method='POST',
action=self.get_url())))
page.append(P(FORM(INPUT(type='submit', value='Cancel'),
method='GET',
action=self.get_url())))
def edit_tags(self, page):
self.check_editable(self.user)
page.append(H2('Edit tags'))
tags = self.doc.get('tags', [])
if tags:
tags.sort()
tag = tags[0]
rows = [TR(TH('Current tags', rowspan=len(tags)),
TD(INPUT(type='checkbox',name='_tag_remove',value=tag)),
TD(tag))]
rows.extend([TR(TD(INPUT(type='checkbox',
name='_tag_remove', value=tag)),
TD(tag)) for tag in tags[1:]])
rows.append(TR(TD(),
TD(INPUT(type='submit', value='Remove checked'),
colspan=2)))
page.append(FORM(TABLE(klass='tags', *rows),
method='POST',
action=self.get_url()))
page.append(P())
page.append(FORM(TABLE(
TR(TH('New tags'),
TD(TEXTAREA(name='_tags_add', cols=20, rows=8))),
TR(TD(),
TD(INPUT(type='submit', value='Add')))),
method='POST',
action=self.get_url()))
page.append(P(FORM(INPUT(type='submit', value='Cancel'),
method='GET',
action=self.get_url())))
def edit_xrefs(self, page):
self.check_editable(self.user)
page.append(H2('Edit xrefs'))
xrefs = self.doc.get('xrefs', [])
if xrefs:
xrefs.sort()
xref = xrefs[0]
rows = [TR(TH('Current xrefs', rowspan=len(xrefs)),
TD(INPUT(type='checkbox',
name='_xref_remove', value=xref['uri'])),
TD(A(xref.get('title') or xref['uri'],
href=xref['uri'])))]
rows.extend([TR(TD(INPUT(type='checkbox',
name='_xref_remove', value=xref['uri'])),
TD(A(xref.get('title') or xref['uri'],
href=xref['uri'])))
for xref in xrefs[1:]])
rows.append(TR(TD(),
TD(INPUT(type='submit', value='Remove checked'),
colspan=2)))
page.append(FORM(TABLE(klass='xrefs', *rows),
method='POST',
action=self.get_url()))
page.append(P())
page.append(FORM(TABLE(
TR(TH('New xref'),
TD('URI'),
TD(INPUT(type='text', name='_xref_add_uri'))),
TR(TD(),
TD('Title'),
TD(INPUT(type='text', name='_xref_add_title'))),
TR(TD(),
TD(INPUT(type='submit', value='Add')))),
method='POST',
action=self.get_url()))
page.append(P(FORM(INPUT(type='submit', value='Cancel'),
method='GET',
action=self.get_url())))
def edit_data_field(self, page, name):
for field in self.fields:
if field.name == name: break
else:
raise HTTP_BAD_REQUEST("No such editable field '%s'." % name)
self.check_editable(self.user)
field.check_editable(self, self.user)
page.append(H2('Edit information field'))
page.append(TABLE(TR(TD(field.get_edit_form(self))),
TR(TD(FORM(INPUT(type='submit', value='Cancel'),
method='GET',
action=self.get_url())))))
def POST(self, request, response):
"Modify according to which CGI inputs were provided."
# Check edit privilege
self.check_editable(self.user, check_lock=False)
self.check_revision(request)
# Save initial document state
try:
initial = dict(self.doc)
except (AttributeError, TypeError):
initial = None
modified = [] # Names of fields that were modified
try:
locked = request.cgi_fields['locked'].value.lower()
if locked not in ('false', 'true'):
raise HTTP_BAD_REQUEST("invalid 'locked' value '%s'" % locked)
except KeyError:
locked = None
if self.locked: # If locked, only 'unlock' is allowed
if locked == 'false':
self.doc['locked'] = False
modified.append('locked')
else:
raise HTTP_CONFLICT("Entity '%s' is locked." % self)
elif locked is not None: # Only 'lock' operation is relevant
if locked == 'true':
self.doc['locked'] = True
modified.append('locked')
else: # Change in data field(s)
for field in self.fields:
if not field.get_editable(self, self.user): continue
try:
self.doc[field.name] = field.get_value(self, request)
except KeyError: # No such field in CGI inputs
pass
except ValueError, msg:
raise HTTP_BAD_REQUEST(str(msg))
else:
modified.append(field.name)
if modified:
if initial is None:
action = 'created'
else:
action = "modified %s" % ', '.join(modified)
map(self.on_field_modified, modified)
id, rev = self.db.save(self.doc) # Create or update
self.doc = self.db[id] # Get fresh instance
self.log(self.doc.id, action, initial=initial)
# Delete attachments
stubs = self.doc.get('_attachments', dict())
for filename in request.cgi_fields.getlist('_attachment_delete'):
if stubs.has_key(filename):
initial = dict(self.doc)
self.db.delete_attachment(self.doc, filename)
self.doc = self.db[self.doc.id] # Get fresh instance
comment = "filename %s" % filename
self.log(self.doc.id,
'deleted attachment',
initial=initial,
comment=comment)
# Upload attachment
try:
field = request.cgi_fields['_attachment']
if not field.filename: raise KeyError
except KeyError:
pass
else:
initial = dict(self.doc)
filename = os.path.basename(field.filename)
content = field.file.read()
try:
encoding = field.headers['content-transfer-encoding'].lower()
except KeyError:
pass
else:
if encoding == 'base64':
content = base64.standard_b64decode(content)
elif encoding == 'quoted-printable':
content = quopri.decodestring(content)
self.db.put_attachment(self.doc,
content,
filename,
field.type)
self.doc = self.db[self.doc.id] # Get fresh instance
comment = "filename %s" % filename
self.log(self.doc.id,
'uploaded attachment',
initial=initial,
comment=comment)
# Remove tags
initial = dict(self.doc)
tags = set(self.doc.get('tags', []))
original = tags.copy()
for tag in request.cgi_fields.getlist('_tag_remove'):
tags.discard(tag)
if tags != original:
self.doc['tags'] = list(tags)
id, rev = self.db.save(self.doc) # Create or update
self.doc = self.db[id] # Get fresh instance
self.log(self.doc.id,
'removed tags',
initial=initial)
# Add tags
initial = dict(self.doc)
tags = set(self.doc.get('tags', []))
original = tags.copy()
try:
new = request.cgi_fields['_tags_add'].value.strip()
if not new: raise KeyError
except KeyError:
pass
else:
for tag in new.split():
tags.add(tag)
if tags != original:
self.doc['tags'] = list(tags)
id, rev = self.db.save(self.doc) # Create or update
self.doc = self.db[id] # Get fresh instance
self.log(self.doc.id,
'added tags',
initial=initial)
# Remove xrefs
initial = dict(self.doc)
xrefs = dict([(x['uri'], x.get('title'))
for x in self.doc.get('xrefs', [])])
original = xrefs.copy()
for uri in request.cgi_fields.getlist('_xref_remove'):
try:
del xrefs[uri]
except KeyError:
pass
if xrefs != original:
result = []
for uri, title in sorted(xrefs.items()):
result.append(dict(uri=uri, title=title))
self.doc['xrefs'] = result
id, rev = self.db.save(self.doc) # Create or update
self.doc = self.db[id] # Get fresh instance
self.log(self.doc.id,
'removed xrefs',
initial=initial)
# Add xrefs
initial = dict(self.doc)
xrefs = dict([(x['uri'], x.get('title'))
for x in self.doc.get('xrefs', [])])
original = xrefs.copy()
try:
uri = request.cgi_fields['_xref_add_uri'].value.strip()
if not uri: raise KeyError
except KeyError:
pass
else:
try:
title = request.cgi_fields['_xref_add_title'].value.strip()
if not title: raise KeyError
except KeyError:
title = None
xrefs[uri] = title
if xrefs != original:
result = []
for uri, title in sorted(xrefs.items()):
result.append(dict(uri=uri, title=title))
self.doc['xrefs'] = result
id, rev = self.db.save(self.doc) # Create or update
self.doc = self.db[id] # Get fresh instance
self.log(self.doc.id,
'added xref',
initial=initial)
# Perform specified actions, if any:
# The action "X" causes the method "action_X" to be executed
# with the request instance as argument. If that action modifies
# the document of the entity, then it must also save the document.
for action in request.cgi_fields.getlist('action'):
try:
method = getattr(self, "action_%s" % action)
except AttributeError:
raise HTTP_BAD_REQUEST("no such action '%s'" % action)
method(request)
# And display result
self.GET(request, response)
def on_field_modified(self, name):
"""This method is called when the field of the specified name
has been changed. This happens *before* the modification has
been saved in the entity's document."""
pass
class EntityCreate(Dispatcher):
"Base page for creating an entity instance."
entity_class = None
def get_privilege(self):
"Return True of the logged-in user is allowed to create the entity."
raise NotImplementedError
def check_privilege(self):
if not self.get_privilege():
raise HTTP_FORBIDDEN("User '%s' may not create %s."
% (self.user['name'],
self.entity_class.__name__.lower()))
def get_url(self, name=None):
return configuration.get_url(self.entity_class.__name__.lower(),
name=name)
def GET(self, request, response):
"Display the CGI form for creating the entity."
self.check_privilege()
page = HtmlPage(self,
title="Create %s" % self.entity_class.__name__.lower())
rows = []
for field in self.entity_class.fields:
rows.append(TR(TH(field.name),
TD(field.get_create_form_field(self)),
TD(I(field.required and 'required' or 'optional')),
TD(field.get_description())))
page.append(FORM(TABLE(border=1, *rows),
P(INPUT(type='submit', value='Create')),
method='POST',
action=self.get_url()))
page.write(response)
def POST(self, request, response):
"Create the entity given the CGI input fields."
self.check_privilege()
doc = dict()
for field in self.entity_class.fields:
try:
doc[field.name] = field.get_value(self, request, required=False)
except KeyError: # No such field in CGI inputs
pass
except ValueError, msg:
raise HTTP_BAD_REQUEST(str(msg))
entity = self.entity_class.__name__.lower()
try:
self.get_named_document(entity, doc['name'])
except ValueError: # Does not exist; OK
pass
else:
raise HTTP_BAD_REQUEST("%s '%s' exists already"
% (entity, doc['name']))
self.setup(doc)
doc.update(dict(_id=utils.id_uuid(),
entity=entity,
timestamp=utils.now_iso()))
id, rev = self.db.save(doc)
self.log(id, 'created', initial=None)
raise HTTP_SEE_OTHER(Location=self.get_url(doc['name']))
def setup(self, doc):
"Modify the contents of the as yet unsaved document for the new entity."
pass