1 # -*- coding: utf-8 -*-
4 from datetime import date
8 from librarian import html, parser, dcparser
9 from librarian import ParseError, ValidationError
11 from django.conf import settings
12 from django.contrib.auth.decorators import login_required, permission_required
14 from django.core.urlresolvers import reverse
15 from django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotFound
16 from django.utils import simplejson as json
17 from django.views.generic.simple import direct_to_template
18 from django.contrib.auth.decorators import login_required
20 from explorer import forms, models
21 from toolbar import models as toolbar_models
23 from django.forms.util import ErrorList
28 # Some useful decorators
30 def file_branch(fileid, user=None):
31 parts = fileid.split('$')
32 return ('personal_'+ user.username + '_' if user is not None else '') \
35 def file_path(fileid):
36 return 'pub_'+fileid+'.xml'
39 """Open a repository for this view"""
40 def view_with_repo(request, *args, **kwargs):
41 kwargs['repo'] = wlrepo.open_library(settings.REPOSITORY_PATH, 'hg')
42 return view(request, *args, **kwargs)
46 def ajax_login_required(view):
47 """Similar ro @login_required, but instead of redirect,
48 just return some JSON stuff with error."""
49 def view_with_auth(request, *args, **kwargs):
50 if request.user.is_authenticated():
51 return view(request, *args, **kwargs)
53 return HttpResponse( json.dumps({'result': 'access_denied', 'errors': ['Brak dostępu.']}) );
60 def file_list(request, repo):
62 from api.resources import library_resource
64 bookform = api.forms.DocumentUploadForm()
66 # short-circut the api document list
67 doctree = library_resource.handler.read(request)
68 # print "DOCTREE:", doctree['documents']
70 return direct_to_template(request, 'explorer/file_list.html', extra_context={
71 'filetree': doctree['documents'], 'bookform': bookform,
74 @permission_required('explorer.can_add_files')
76 def file_upload(request, repo):
77 from api.resources import library_resource
78 from api.forms import DocumentUploadForm
79 from django.http import HttpRequest, HttpResponseRedirect
81 response = library_resource.handler.create(request)
83 if isinstance(response, HttpResponse):
84 data = json.loads(response.content)
86 if response.status_code == 201:
87 return HttpResponseRedirect( \
88 reverse("editor_view", args=[ data['name'] ]) )
90 bookform = DocumentUploadForm(request.POST, request.FILES)
93 return direct_to_template(request, 'explorer/file_upload.html',
94 extra_context={'bookform': bookform } )
103 def file_xml(request, repo, path):
104 rpath = file_path(path)
105 if request.method == 'POST':
108 form = forms.BookForm(request.POST)
110 print 'Saving whole text.', request.user.username
112 # encode it back to UTF-8, so we can put it into repo
113 encoded_data = form.cleaned_data['content'].encode('utf-8')
116 repo._add_file(rpath, encoded_data)
117 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'),\
118 user=request.user.username)
121 # wczytaj dokument z ciągu znaków -> weryfikacja
122 document = parser.WLDocument.from_string(form.cleaned_data['content'])
123 except (ParseError, ValidationError), e:
124 warnings = [u'Niepoprawny dokument XML: ' + unicode(e.message)]
126 # save to user's branch
127 repo.in_branch(save_action, file_branch(path, request.user) );
128 except UnicodeDecodeError, e:
129 errors = [u'Błąd kodowania danych przed zapisem: ' + unicode(e.message)]
130 except hg.RepositoryException, e:
131 errors = [u'Błąd repozytorium: ' + unicode(e.message)]
134 errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
136 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok',
137 'errors': errors, 'warnings': warnings}) );
139 form = forms.BookForm()
140 data = repo.get_file(rpath, file_branch(path, request.user))
141 form.fields['content'].initial = data
142 return HttpResponse( json.dumps({'result': 'ok', 'content': data}) )
146 def file_update_local(request, path, repo):
150 wlock = repo.write_lock()
152 tipA = repo.get_branch_tip('default')
153 tipB = repo.get_branch_tip( file_branch(path, request.user) )
155 nodeA = repo.getnode(tipA)
156 nodeB = repo.getnode(tipB)
158 # do some wild checks - see file_commit() for more info
159 if (repo.common_ancestor(tipA, tipB) == nodeA) \
160 or (nodeB in nodeA.parents()):
161 result = 'nothing-to-do'
164 repo.merge_revisions(tipB, tipA, \
165 request.user.username, 'Personal branch update.')
167 except hg.UncleanMerge, e:
169 result = 'fatal-error'
170 except hg.RepositoryException, e:
172 result = 'fatal-error'
177 raise Exception("Ouch, this shouldn't happen!")
179 return HttpResponse( json.dumps({'result': result, 'errors': errors}) );
183 def file_commit(request, path, repo):
186 local_modified = False
187 if request.method == 'POST':
188 form = forms.MergeForm(request.POST)
191 wlock = repo.write_lock()
193 tipA = repo.get_branch_tip('default')
194 tipB = repo.get_branch_tip( file_branch(path, request.user) )
196 nodeA = repo.getnode(tipA)
197 nodeB = repo.getnode(tipB)
199 print repr(nodeA), repr(nodeB), repo.common_ancestor(tipA, tipB), repo.common_ancestor(tipB, tipA)
201 if repo.common_ancestor(tipB, tipA) == nodeA:
205 # * <- can also be here!
210 # The local branch has been recently updated,
211 # so we don't need to update yet again, but we need to
212 # merge down to default branch, even if there was
213 # no commit's since last update
214 repo.merge_revisions(tipA, tipB, \
215 request.user.username, form.cleaned_data['message'])
217 elif any( p.branch()==nodeB.branch() for p in nodeA.parents()):
225 # Default has no changes, to update from this branch
226 # since the last merge of local to default.
227 if nodeB not in nodeA.parents():
228 repo.merge_revisions(tipA, tipB, \
229 request.user.username, form.cleaned_data['message'])
232 result = 'nothing-to-do'
233 elif repo.common_ancestor(tipA, tipB) == nodeB:
237 # * <- this case overlaps with previos one
243 # There was a recent merge to the defaul branch and
244 # no changes to local branch recently.
246 # Use the fact, that user is prepared to see changes, to
247 # update his branch if there are any
248 if nodeB not in nodeA.parents():
249 repo.merge_revisions(tipB, tipA, \
250 request.user.username, 'Personal branch update during merge.')
251 local_modified = True
254 result = 'nothing-to-do'
256 # both branches have changes made to them, so
258 repo.merge_revisions(tipB, tipA, \
259 request.user.username, 'Personal branch update during merge.')
261 local_modified = True
264 tipB = repo.get_branch_tip( file_branch(path, request.user) )
266 # and merge back to the default
267 repo.merge_revisions(tipA, tipB, \
268 request.user.username, form.cleaned_data['message'])
270 except hg.UncleanMerge, e:
272 result = 'fatal-error'
273 except hg.RepositoryException, e:
275 result = 'fatal-error'
280 errors = [ form.errors['message'].as_text() ]
282 result = 'fatal-error'
284 return HttpResponse( json.dumps({'result': result, 'errors': errors, 'localmodified': local_modified}) );
286 return HttpResponse( json.dumps({'result': 'fatal-error', 'errors': ['No data posted']}) )
291 def file_dc(request, path, repo):
293 rpath = file_path(path)
295 if request.method == 'POST':
296 form = forms.DublinCoreForm(request.POST)
301 file_contents = repo._get_file(rpath)
303 # wczytaj dokument z repozytorium
304 document = parser.WLDocument.from_string(file_contents)
305 document.book_info.update(form.cleaned_data)
308 repo._write_file(rpath, document.serialize().encode('utf-8'))
310 message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), \
311 user=request.user.username )
314 repo.in_branch(save_action, file_branch(path, request.user) )
315 except UnicodeEncodeError, e:
316 errors = ['Bład wewnętrzny: nie można zakodować pliku do utf-8']
317 except (ParseError, ValidationError), e:
321 errors = ["Pole '%s': %s\n" % (field[0], field[1].as_text()) for field in form.errors.iteritems()]
323 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}) );
325 # this is unused currently, but may come in handy
329 fulltext = repo.get_file(rpath, file_branch(path, request.user))
330 bookinfo = dcparser.BookInfo.from_string(fulltext)
331 content = bookinfo.to_dict()
332 except (ParseError, ValidationError), e:
335 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok',
336 'errors': errors, 'content': content }) )
338 # Display the main editor view
342 def display_editor(request, path):
343 # this is the only entry point where we create an autobranch for the user
344 # if it doesn't exists. All other views SHOULD fail.
345 #def ensure_branch_exists():
346 # parent = repo.get_branch_tip('default')
347 # repo._create_branch(file_branch(path, request.user), parent)
350 # repo.with_wlock(ensure_branch_exists)
352 return direct_to_template(request, 'explorer/editor.html', extra_context={
354 'panel_list': ['lewy', 'prawy'],
355 'availble_panels': models.EditorPanel.objects.all(),
356 # 'scriptlets': toolbar_models.Scriptlet.objects.all()
359 # return direct_to_template(request, 'explorer/nofile.html', \
360 # extra_context = { 'fileid': path })
365 class panel_view(object):
367 def __new__(cls, request, name, path, **kwargs):
369 panel = models.EditorPanel.objects.get(id=name)
370 method = getattr(cls, name + '_panel', None)
371 if not panel or method is None:
372 raise HttpResponseNotFound
374 extra_context = method(request, path, panel, **kwargs)
376 if not isinstance(extra_context, dict):
379 extra_context.update({
380 'toolbar_groups': panel.toolbar_groups.all(),
381 'toolbar_extra_group': panel.toolbar_extra,
385 return direct_to_template(request, 'explorer/panels/'+name+'.html',\
386 extra_context=extra_context)
391 def xmleditor_panel(request, path, panel, repo):
392 rpath = file_path(path)
393 return {'text': repo.get_file(rpath, file_branch(path, request.user))}
397 def gallery_panel(request, path, panel):
398 return {'form': forms.ImageFoldersForm() }
403 def htmleditor_panel(request, path, panel, repo):
404 rpath = file_path(path)
405 user_branch = file_branch(path, request.user)
407 result = html.transform(repo.get_file(rpath, user_branch), is_file=False)
408 print "HTML: %r" % result
409 return {'html': result}
410 except (ParseError, ValidationError), e:
411 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
412 'fileid': path, 'exception_type': type(e).__name__, 'exception': e,
413 'panel_name': panel.display_name})
418 def dceditor_panel(request, path, panel, repo):
419 user_branch = file_branch(path, request.user)
420 rpath = file_path(path)
422 doc_text = repo.get_file(rpath, user_branch)
423 document = parser.WLDocument.from_string(doc_text)
424 form = forms.DublinCoreForm(info=document.book_info)
425 return {'form': form}
426 except (ParseError, ValidationError), e:
427 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
428 'fileid': path, 'exception_type': type(e).__name__, 'exception': e,
429 'panel_name': panel.display_name})
432 ## Editor "commands" and "dialogs"
436 def print_html(request, path, repo):
437 user_branch = file_branch(path, request.user)
438 rpath = file_path(path)
440 html.transform(repo.get_file(rpath, user_branch), is_file=False),
441 mimetype="text/html")
445 def print_xml(request, path, repo):
446 user_branch = file_branch(path, request.user)
447 rpath = file_path(path)
448 return HttpResponse( repo.get_file(rpath, user_branch), mimetype="text/plain; charset=utf-8")
450 @permission_required('explorer.can_add_files')
451 def split_text(request, path):
452 rpath = file_path(path)
454 if request.method == "POST":
455 sform = forms.SplitForm(request.POST, prefix='splitform')
456 dcform = forms.DublinCoreForm(request.POST, prefix='dcform')
458 print "validating sform"
461 # if sform.cleaned_data['autoxml']:
462 # print "validating dcform"
463 # valid = dcform.is_valid()
465 print "valid is ", valid
468 uri = path + '$' + sform.cleaned_data['partname']
469 child_rpath = file_path(uri)
470 repo = hg.Repository(settings.REPOSITORY_PATH)
472 # save the text into parent's branch
474 if repo._file_exists(child_rpath):
475 el = sform._errors.get('partname', ErrorList())
476 el.append("Part with this name already exists")
477 sform._errors['partname'] = el
480 fulltext = sform.cleaned_data['fulltext']
481 fulltext = fulltext.replace(u'<include-tag-placeholder />',
482 librarian.xinclude_forURI(u'wlrepo://'+uri) )
484 repo._write_file(rpath, fulltext.encode('utf-8'))
486 newtext = sform.cleaned_data['splittext']
487 if sform.cleaned_data['autoxml']:
488 # this is a horrible hack - really
489 bi = dcparser.BookInfo.from_element(librarian.DEFAULT_BOOKINFO.to_etree())
490 bi.update(dcform.data)
492 newtext = librarian.wrap_text(newtext, \
493 unicode(date.today()), bookinfo=bi )
495 repo._add_file(child_rpath, newtext.encode('utf-8'))
496 repo._commit(message="Split from '%s' to '%s'" % (path, uri), \
497 user=request.user.username )
500 if repo.in_branch(split_action, file_branch(path, request.user)):
501 # redirect to success
503 uri = urllib.quote( unicode(uri).encode('utf-8'))
504 return HttpResponseRedirect( reverse('split-success',\
505 kwargs={'path': path})+'?child='+uri )
507 try: # to read the current DC
508 repo = hg.Repository(settings.REPOSITORY_PATH)
509 fulltext = repo.get_file(rpath, file_branch(path, request.user))
510 bookinfo = dcparser.BookInfo.from_string(fulltext)
511 except (ParseError, ValidationError):
512 bookinfo = librarian.DEFAULT_BOOKINFO
514 sform = forms.SplitForm(prefix='splitform')
515 dcform = forms.DublinCoreForm(prefix='dcform', info=bookinfo)
517 return direct_to_template(request, 'explorer/split.html', extra_context={
518 'splitform': sform, 'dcform': dcform, 'fileid': path} )
520 def split_success(request, path):
521 return direct_to_template(request, 'explorer/split_success.html',\
522 extra_context={'fileid': path, 'cfileid': request.GET['child']} )
529 def folder_images(request, folder):
530 return direct_to_template(request, 'explorer/folder_images.html', extra_context={
531 'images': models.get_images_from_folder(folder),
534 def _add_references(message, issues):
535 return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
537 def _get_issues_for_file(fileid):
540 uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % fileid)
541 return json.loads(uf.read())
542 except urllib2.HTTPError:
550 #def pull_requests(request):
551 # return direct_to_template(request, 'manager/pull_request.html', extra_context = {
552 # 'objects': models.PullRequest.objects.all()} )