1 # -*- encoding: utf-8 -*-
3 __author__= "Ćukasz Rekucki"
4 __date__ = "$2009-09-25 15:49:50$"
5 __doc__ = "Module documentation."
7 from piston.handler import BaseHandler, AnonymousBaseHandler
12 import api.forms as forms
13 from datetime import date
15 from django.core.urlresolvers import reverse
17 from wlrepo import RevisionNotFound, DocumentAlreadyExists
18 from librarian import dcparser
20 import api.response as response
21 from api.utils import validate_form, hglibrary
24 # Document List Handlers
26 class BasicLibraryHandler(AnonymousBaseHandler):
27 allowed_methods = ('GET',)
30 def read(self, request, lib):
31 """Return the list of documents."""
33 'url': reverse('document_view', args=[docid]),
34 'name': docid } for docid in lib.documents() ]
36 return {'documents' : document_list}
39 class LibraryHandler(BaseHandler):
40 allowed_methods = ('GET', 'POST')
41 anonymous = BasicLibraryHandler
44 def read(self, request, lib):
45 """Return the list of documents."""
48 'url': reverse('document_view', args=[docid]),
49 'name': docid } for docid in lib.documents() ]
51 return {'documents' : document_list }
53 @validate_form(forms.DocumentUploadForm, 'POST')
55 def create(self, request, form, lib):
56 """Create a new document."""
58 if form.cleaned_data['ocr_data']:
59 data = form.cleaned_data['ocr_data'].encode('utf-8')
61 data = request.FILES['ocr_file'].read().decode('utf-8')
63 if form.cleaned_data['generate_dc']:
64 data = librarian.wrap_text(data, unicode(date.today()))
66 docid = form.cleaned_data['bookname']
68 doc = lib.document_create(docid)
69 doc = doc.quickwrite('xml', data, '$AUTO$ XML data uploaded.',
70 user=request.user.username)
72 url = reverse('document_view', args=[doc.id])
74 return response.EntityCreated().django_response(\
78 'revision': doc.revision },
81 except DocumentAlreadyExists:
82 # Document is already there
83 return response.EntityConflict().django_response(\
84 {"reason": "Document %s already exists." % docid})
89 class BasicDocumentHandler(AnonymousBaseHandler):
90 allowed_methods = ('GET',)
93 def read(self, request, docid, lib):
95 doc = lib.document(docid)
96 except RevisionNotFound:
101 'html_url': reverse('dochtml_view', args=[doc.id,doc.revision]),
102 'text_url': reverse('doctext_view', args=[doc.id,doc.revision]),
103 'dc_url': reverse('docdc_view', args=[doc.id,doc.revision]),
104 'public_revision': doc.revision,
112 class DocumentHandler(BaseHandler):
113 allowed_methods = ('GET', 'PUT')
114 anonymous = BasicDocumentHandler
117 def read(self, request, docid, lib):
118 """Read document's meta data"""
120 doc = lib.document(docid)
121 udoc = doc.take(request.user.username)
122 except RevisionNotFound:
123 return request.EnityNotFound().django_response()
125 # is_shared = udoc.ancestorof(doc)
126 # is_uptodate = is_shared or shared.ancestorof(document)
130 'html_url': reverse('dochtml_view', args=[doc.id,doc.revision]),
131 'text_url': reverse('doctext_view', args=[doc.id,doc.revision]),
132 'dc_url': reverse('docdc_view', args=[doc.id,doc.revision]),
133 'user_revision': udoc.revision,
134 'public_revision': doc.revision,
140 def update(self, request, docid, lib):
141 """Update information about the document, like display not"""
147 class DocumentHTMLHandler(BaseHandler):
148 allowed_methods = ('GET', 'PUT')
151 def read(self, request, docid, revision, lib):
152 """Read document as html text"""
154 if revision == 'latest':
155 document = lib.document(docid)
157 document = lib.document_for_rev(revision)
159 return librarian.html.transform(document.data('xml'))
160 except RevisionNotFound:
161 return response.EntityNotFound().django_response()
166 class DocumentTextHandler(BaseHandler):
167 allowed_methods = ('GET', 'PUT')
170 def read(self, request, docid, revision, lib):
171 """Read document as raw text"""
173 if revision == 'latest':
174 document = lib.document(docid)
176 document = lib.document_for_rev(revision)
178 # TODO: some finer-grained access control
179 return document.data('xml')
180 except RevisionNotFound:
181 return response.EntityNotFound().django_response()
184 def update(self, request, docid, revision, lib):
186 data = request.PUT['contents']
188 if request.PUT.has_key('message'):
189 msg = u"$USER$ " + request.PUT['message']
191 msg = u"$AUTO$ XML content update."
193 current = lib.document(docid, request.user.username)
194 orig = lib.document_for_rev(revision)
197 return response.EntityConflict().django_response({
198 "reason": "out-of-date",
199 "provided_revision": orig.revision,
200 "latest_revision": current.revision })
202 ndoc = doc.quickwrite('xml', data, msg)
204 # return the new revision number
208 "previous_revision": prev,
209 "updated_revision": ndoc.revision
212 except (RevisionNotFound, KeyError):
213 return response.EntityNotFound().django_response()
216 # Dublin Core handlers
218 # @requires librarian
220 class DocumentDublinCoreHandler(BaseHandler):
221 allowed_methods = ('GET', 'PUT')
224 def read(self, request, docid, revision, lib):
225 """Read document as raw text"""
227 if revision == 'latest':
228 document = lib.document(docid)
230 document = lib.document_for_rev(revision)
232 bookinfo = dcparser.BookInfo.from_string(doc.data('xml'))
233 return bookinfo.serialize()
234 except RevisionNotFound:
235 return response.EntityNotFound().django_response()
238 def update(self, request, docid, revision, lib):
240 bi_json = request.PUT['contents']
241 if request.PUT.has_key('message'):
242 msg = u"$USER$ " + request.PUT['message']
244 msg = u"$AUTO$ Dublin core update."
246 current = lib.document(docid, request.user.username)
247 orig = lib.document_for_rev(revision)
250 return response.EntityConflict().django_response({
251 "reason": "out-of-date",
252 "provided": orig.revision,
253 "latest": current.revision })
255 xmldoc = parser.WLDocument.from_string(current.data('xml'))
256 document.book_info = dcparser.BookInfo.from_json(bi_json)
259 ndoc = current.quickwrite('xml', \
260 document.serialize().encode('utf-8'),\
261 message=msg, user=request.user.username)
266 "previous_revision": prev,
267 "updated_revision": ndoc.revision
269 except (RevisionNotFound, KeyError):
270 return response.EntityNotFound().django_response()
273 class MergeHandler(BaseHandler):
274 allowed_methods = ('POST',)
276 @validate_form(forms.MergeRequestForm)
278 def create(self, request, form, docid, lib):
279 """Create a new document revision from the information provided by user"""