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_revision(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-chunk-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):
97 revision = form.cleaned_data['revision']
98 msg = form.cleaned_data['message']
99 user = form.cleaned_data['user'] or request.user.username
101 # 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_revision(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['contents']:
119 data = form.cleaned_data['contents']
121 chunks = form.cleaned_data['chunks']
122 data = current.data('xml')
126 xdoc = parser.WLDocument.from_string(data)
127 errors = xdoc.merge_chunks(chunks)
130 return response.EntityConflict().django_response({
131 "reason": "invalid-chunks",
132 "message": "Unable to merge following parts into the document: %s " % ",".join(errors)
135 data = xdoc.serialize()
138 # try to find any Xinclude tags
139 includes = [m.groupdict()['link'] for m in (re.finditer(\
140 XINCLUDE_REGEXP, data, flags=re.UNICODE) or []) ]
142 log.info("INCLUDES: %s", includes)
144 # TODO: provide useful routines to make this simpler
145 def xml_update_action(lib, resolve):
147 f = lib._fileopen(resolve('parts'), 'r')
148 stored_includes = json.loads(f.read())
153 if stored_includes != includes:
154 f = lib._fileopen(resolve('parts'), 'w+')
155 f.write(json.dumps(includes))
158 lib._fileadd(resolve('parts'))
160 # update the parts cache
161 PartCache.update_cache(docid, current.owner,\
162 stored_includes, includes)
164 # now that the parts are ok, write xml
165 f = lib._fileopen(resolve('xml'), 'w+')
166 f.write(data.encode('utf-8'))
170 ndoc = current.invoke_and_commit(\
171 xml_update_action, lambda d: (msg, user) )
174 # return the new revision number
175 return response.SuccessAllOk().django_response({
179 "previous_revision": current.revision,
180 "revision": ndoc.revision,
181 'timestamp': ndoc.revision.timestamp,
182 "url": reverse("doctext_view", args=[ndoc.id])
185 if ndoc: lib._rollback()
187 except RevisionNotFound, e:
188 return response.EntityNotFound(mimetype="text/plain").\
189 django_response(e.message)