Dodanie opisu zmian do interfejsu zarządzania pull requestami.
[redakcja.git] / apps / api / handlers / text_handler.py
1 # -*- encoding: utf-8 -*-
2
3 __author__= "Łukasz Rekucki"
4 __date__ = "$2009-10-19 14:34:42$"
5 __doc__ = "Module documentation."
6
7 #import api.forms as forms
8 #import api.response as response
9 #
10 #from api.utils import validate_form, hglibrary
11 #from api.models import PartCache
12 #
13
14 #
15 #from piston.handler import BaseHandler
16 #
17 #from wlrepo import *
18
19 import re
20 from library_handlers import *
21
22 import librarian
23 from librarian import parser
24
25 #
26 # Document Text View
27 #
28
29 XINCLUDE_REGEXP = r"""<(?:\w+:)?include\s+[^>]*?href=("|')wlrepo://(?P<link>[^\1]+?)\1\s*[^>]*?>"""
30 #
31 #
32 #
33
34 class DocumentTextHandler(BaseHandler):
35     allowed_methods = ('GET', 'POST')
36
37     @validate_form(forms.TextRetrieveForm, 'GET')
38     @hglibrary
39     def read(self, request, form, docid, lib):
40         """Read document as raw text"""
41         try:
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']
46
47             document = lib.document_for_revision(revision)
48
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'
53                 })
54
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
59                 })
60
61             for error in check_user(request, user):
62                 return error
63
64             if not chunk:
65                 return document.data('xml')
66
67             xdoc = parser.WLDocument.from_string(document.data('xml'),\
68                 parse_dublincore=False)
69
70             xchunk = xdoc.chunk(chunk)
71
72             if xchunk is None:
73                 return response.EntityNotFound().django_response({
74                       'reason': 'no-chunk-in-document',
75                       'path': chunk
76                 })
77
78             return librarian.serialize_children(xchunk, format=format)
79
80         except librarian.ParseError, e:
81             return response.EntityNotFound().django_response({
82                 'reason': 'invalid-document-state',
83                 'exception': type(e),
84                 'message': e.message
85             })
86         except (EntryNotFound, RevisionNotFound), e:
87             return response.EntityNotFound().django_response({
88                 'reason': 'not-found',
89                 'exception': type(e), 'message': e.message
90             })
91
92     @validate_form(forms.TextUpdateForm, 'POST')
93     @hglibrary
94     def create(self, request, form, docid, lib):
95         try:
96             revision = form.cleaned_data['revision']
97             msg = form.cleaned_data['message']
98             user = form.cleaned_data['user'] or request.user.username
99
100             # do not allow changing not owned documents
101             # (for now... )
102
103
104             if user != request.user.username:
105                 return response.AccessDenied().django_response({
106                     'reason': 'insufficient-priviliges',
107                 })
108
109             current = lib.document(docid, user)
110             orig = lib.document_for_rev(revision)
111
112             if current != orig:
113                 return response.EntityConflict().django_response({
114                         "reason": "out-of-date",
115                         "provided_revision": orig.revision,
116                         "latest_revision": current.revision })
117
118             if form.cleaned_data.has_key('contents'):
119                 data = form.cleaned_data['contents']
120             else:
121                 chunks = form.cleaned_data['chunks']
122                 xdoc = parser.WLDocument.from_string(current.data('xml'))
123                 errors = xdoc.merge_chunks(chunks)
124
125                 if len(errors):
126                     return response.EntityConflict().django_response({
127                             "reason": "invalid-chunks",
128                             "message": "Unable to merge following parts into the document: %s " % ",".join(errors)
129                     })
130
131                 data = xdoc.serialize()
132
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 []) ]
136
137             log.info("INCLUDES: %s", includes)
138
139             # TODO: provide useful routines to make this simpler
140             def xml_update_action(lib, resolve):
141                 try:
142                     f = lib._fileopen(resolve('parts'), 'r')
143                     stored_includes = json.loads(f.read())
144                     f.close()
145                 except:
146                     stored_includes = []
147
148                 if stored_includes != includes:
149                     f = lib._fileopen(resolve('parts'), 'w+')
150                     f.write(json.dumps(includes))
151                     f.close()
152
153                     lib._fileadd(resolve('parts'))
154
155                     # update the parts cache
156                     PartCache.update_cache(docid, current.owner,\
157                         stored_includes, includes)
158
159                 # now that the parts are ok, write xml
160                 f = lib._fileopen(resolve('xml'), 'w+')
161                 f.write(data.encode('utf-8'))
162                 f.close()
163
164             ndoc = None
165             ndoc = current.invoke_and_commit(\
166                 xml_update_action, lambda d: (msg, user) )
167
168             try:
169                 # return the new revision number
170                 return response.SuccessAllOk().django_response({
171                     "document": ndoc.id,
172                     "user": user,
173                     "subview": "xml",
174                     "previous_revision": current.revision,
175                     "revision": ndoc.revision,
176                     'timestamp': ndoc.revision.timestamp,
177                     "url": reverse("doctext_view", args=[ndoc.id])
178                 })
179             except Exception, e:
180                 if ndoc: lib._rollback()
181                 raise e
182         except RevisionNotFound, e:
183             return response.EntityNotFound(mimetype="text/plain").\
184                 django_response(e.message)