1 # -*- encoding: utf-8 -*-
3 __author__= "Ćukasz Rekucki"
4 __date__ = "$2009-10-19 14:34:42$"
5 __doc__ = "Module documentation."
7 #import api.forms as forms
8 #import api.response as response
10 #from api.utils import validate_form, hglibrary
11 #from api.models import PartCache
15 #from piston.handler import BaseHandler
20 from library_handlers import *
23 from librarian import parser
29 XINCLUDE_REGEXP = r"""<(?:\w+:)?include\s+[^>]*?href=("|')wlrepo://(?P<link>[^\1]+?)\1\s*[^>]*?>"""
34 class DocumentTextHandler(BaseHandler):
35 allowed_methods = ('GET', 'POST')
37 @validate_form(forms.TextRetrieveForm, 'GET')
39 def read(self, request, form, docid, lib):
40 """Read document as raw text"""
42 revision = form.cleaned_data['revision']
43 chunk = form.cleaned_data['chunk']
44 user = form.cleaned_data['user'] or request.user.username
45 format = form.cleaned_data['format']
47 document = lib.document_for_rev(revision)
49 if document.id != docid:
50 return response.BadRequest().django_response({
51 'reason': 'name-mismatch',
52 'message': 'Provided revision is not valid for this document'
55 if document.owner != user:
56 return response.BadRequest().django_response({
57 'reason': 'user-mismatch',
58 'message': "Provided revision doesn't belong to user %s" % user
61 for error in check_user(request, user):
65 return document.data('xml')
67 xdoc = parser.WLDocument.from_string(document.data('xml'),\
68 parse_dublincore=False)
70 xchunk = xdoc.chunk(chunk)
73 return response.EntityNotFound().django_response({
74 'reason': 'no-part-in-document',
78 return librarian.serialize_children(xchunk, format=format)
80 except librarian.ParseError, e:
81 return response.EntityNotFound().django_response({
82 'reason': 'invalid-document-state',
86 except (EntryNotFound, RevisionNotFound), e:
87 return response.EntityNotFound().django_response({
88 'reason': 'not-found',
89 'exception': type(e), 'message': e.message
92 @validate_form(forms.TextUpdateForm, 'POST')
94 def create(self, request, form, docid, lib):
96 revision = form.cleaned_data['revision']
97 msg = form.cleaned_data['message']
98 user = form.cleaned_data['user'] or request.user.username
100 # do not allow changing not owned documents
104 if user != request.user.username:
105 return response.AccessDenied().django_response({
106 'reason': 'insufficient-priviliges',
109 current = lib.document(docid, user)
110 orig = lib.document_for_rev(revision)
113 return response.EntityConflict().django_response({
114 "reason": "out-of-date",
115 "provided_revision": orig.revision,
116 "latest_revision": current.revision })
118 if form.cleaned_data.has_key('contents'):
119 data = form.cleaned_data['contents']
121 chunks = form.cleaned_data['chunks']
122 xdoc = parser.WLDocument.from_string(current.data('xml'))
123 errors = xdoc.merge_chunks(chunks)
126 return response.EntityConflict().django_response({
127 "reason": "invalid-chunks",
128 "message": "Unable to merge following parts into the document: %s " % ",".join(errors)
131 data = xdoc.serialize()
133 # try to find any Xinclude tags
134 includes = [m.groupdict()['link'] for m in (re.finditer(\
135 XINCLUDE_REGEXP, data, flags=re.UNICODE) or []) ]
137 log.info("INCLUDES: %s", includes)
139 # TODO: provide useful routines to make this simpler
140 def xml_update_action(lib, resolve):
142 f = lib._fileopen(resolve('parts'), 'r')
143 stored_includes = json.loads(f.read())
148 if stored_includes != includes:
149 f = lib._fileopen(resolve('parts'), 'w+')
150 f.write(json.dumps(includes))
153 lib._fileadd(resolve('parts'))
155 # update the parts cache
156 PartCache.update_cache(docid, current.owner,\
157 stored_includes, includes)
159 # now that the parts are ok, write xml
160 f = lib._fileopen(resolve('xml'), 'w+')
161 f.write(data.encode('utf-8'))
165 ndoc = current.invoke_and_commit(\
166 xml_update_action, lambda d: (msg, user) )
169 # return the new revision number
170 return response.SuccessAllOk().django_response({
174 "previous_revision": current.revision,
175 "revision": ndoc.revision,
176 'timestamp': ndoc.revision.timestamp,
177 "url": reverse("doctext_view", args=[ndoc.id])
180 if ndoc: lib._rollback()
182 except RevisionNotFound, e:
183 return response.EntityNotFound(mimetype="text/plain").\
184 django_response(e.message)