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.MercurialLibrary(settings.REPOSITORY_PATH)
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 bookform = api.forms.DocumentUploadForm()
63 return direct_to_template(request, 'explorer/file_list.html', extra_context={
64 'files': repo.documents(), 'bookform': bookform,
67 @permission_required('explorer.can_add_files')
69 def file_upload(request, repo):
71 if request.method == 'POST':
72 form = forms.BookUploadForm(request.POST, request.FILES)
76 f = request.FILES['file']
77 decoded = f.read().decode('utf-8')
78 fileid = form.cleaned_data['bookname'].lower()
79 rpath = file_path(fileid)
81 if form.cleaned_data['autoxml']:
82 decoded = librarian.wrap_text(decoded, unicode(date.today()) )
85 repo._add_file(rpath, decoded.encode('utf-8') )
86 repo._commit(message="File %s uploaded by user %s" % \
87 (rpath, request.user.username), user=request.user.username)
89 repo.in_branch(upload_action, 'default')
91 # if everything is ok, redirect to the editor
92 return HttpResponseRedirect( reverse('editor_view',
93 kwargs={'path': fileid}) )
95 except hg.RepositoryException, e:
96 other_errors.append(u'Błąd repozytorium: ' + unicode(e) )
97 #except UnicodeDecodeError, e:
98 # other_errors.append(u'Niepoprawne kodowanie pliku: ' + e.reason \
99 # + u'. Żądane kodowanie: ' + e.encoding)
103 form = forms.BookUploadForm()
104 return direct_to_template(request, 'explorer/file_upload.html',\
105 extra_context = {'form' : form, 'other_errors': other_errors})
113 def file_xml(request, repo, path):
114 rpath = file_path(path)
115 if request.method == 'POST':
118 form = forms.BookForm(request.POST)
120 print 'Saving whole text.', request.user.username
122 # encode it back to UTF-8, so we can put it into repo
123 encoded_data = form.cleaned_data['content'].encode('utf-8')
126 repo._add_file(rpath, encoded_data)
127 repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'),\
128 user=request.user.username)
131 # wczytaj dokument z ciągu znaków -> weryfikacja
132 document = parser.WLDocument.from_string(form.cleaned_data['content'])
133 except (ParseError, ValidationError), e:
134 warnings = [u'Niepoprawny dokument XML: ' + unicode(e.message)]
136 # save to user's branch
137 repo.in_branch(save_action, file_branch(path, request.user) );
138 except UnicodeDecodeError, e:
139 errors = [u'Błąd kodowania danych przed zapisem: ' + unicode(e.message)]
140 except hg.RepositoryException, e:
141 errors = [u'Błąd repozytorium: ' + unicode(e.message)]
144 errors = dict( (field[0], field[1].as_text()) for field in form.errors.iteritems() )
146 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok',
147 'errors': errors, 'warnings': warnings}) );
149 form = forms.BookForm()
150 data = repo.get_file(rpath, file_branch(path, request.user))
151 form.fields['content'].initial = data
152 return HttpResponse( json.dumps({'result': 'ok', 'content': data}) )
156 def file_update_local(request, path, repo):
160 wlock = repo.write_lock()
162 tipA = repo.get_branch_tip('default')
163 tipB = repo.get_branch_tip( file_branch(path, request.user) )
165 nodeA = repo.getnode(tipA)
166 nodeB = repo.getnode(tipB)
168 # do some wild checks - see file_commit() for more info
169 if (repo.common_ancestor(tipA, tipB) == nodeA) \
170 or (nodeB in nodeA.parents()):
171 result = 'nothing-to-do'
174 repo.merge_revisions(tipB, tipA, \
175 request.user.username, 'Personal branch update.')
177 except hg.UncleanMerge, e:
179 result = 'fatal-error'
180 except hg.RepositoryException, e:
182 result = 'fatal-error'
187 raise Exception("Ouch, this shouldn't happen!")
189 return HttpResponse( json.dumps({'result': result, 'errors': errors}) );
193 def file_commit(request, path, repo):
196 local_modified = False
197 if request.method == 'POST':
198 form = forms.MergeForm(request.POST)
201 wlock = repo.write_lock()
203 tipA = repo.get_branch_tip('default')
204 tipB = repo.get_branch_tip( file_branch(path, request.user) )
206 nodeA = repo.getnode(tipA)
207 nodeB = repo.getnode(tipB)
209 print repr(nodeA), repr(nodeB), repo.common_ancestor(tipA, tipB), repo.common_ancestor(tipB, tipA)
211 if repo.common_ancestor(tipB, tipA) == nodeA:
215 # * <- can also be here!
220 # The local branch has been recently updated,
221 # so we don't need to update yet again, but we need to
222 # merge down to default branch, even if there was
223 # no commit's since last update
224 repo.merge_revisions(tipA, tipB, \
225 request.user.username, form.cleaned_data['message'])
227 elif any( p.branch()==nodeB.branch() for p in nodeA.parents()):
235 # Default has no changes, to update from this branch
236 # since the last merge of local to default.
237 if nodeB not in nodeA.parents():
238 repo.merge_revisions(tipA, tipB, \
239 request.user.username, form.cleaned_data['message'])
242 result = 'nothing-to-do'
243 elif repo.common_ancestor(tipA, tipB) == nodeB:
247 # * <- this case overlaps with previos one
253 # There was a recent merge to the defaul branch and
254 # no changes to local branch recently.
256 # Use the fact, that user is prepared to see changes, to
257 # update his branch if there are any
258 if nodeB not in nodeA.parents():
259 repo.merge_revisions(tipB, tipA, \
260 request.user.username, 'Personal branch update during merge.')
261 local_modified = True
264 result = 'nothing-to-do'
266 # both branches have changes made to them, so
268 repo.merge_revisions(tipB, tipA, \
269 request.user.username, 'Personal branch update during merge.')
271 local_modified = True
274 tipB = repo.get_branch_tip( file_branch(path, request.user) )
276 # and merge back to the default
277 repo.merge_revisions(tipA, tipB, \
278 request.user.username, form.cleaned_data['message'])
280 except hg.UncleanMerge, e:
282 result = 'fatal-error'
283 except hg.RepositoryException, e:
285 result = 'fatal-error'
290 errors = [ form.errors['message'].as_text() ]
292 result = 'fatal-error'
294 return HttpResponse( json.dumps({'result': result, 'errors': errors, 'localmodified': local_modified}) );
296 return HttpResponse( json.dumps({'result': 'fatal-error', 'errors': ['No data posted']}) )
301 def file_dc(request, path, repo):
303 rpath = file_path(path)
305 if request.method == 'POST':
306 form = forms.DublinCoreForm(request.POST)
311 file_contents = repo._get_file(rpath)
313 # wczytaj dokument z repozytorium
314 document = parser.WLDocument.from_string(file_contents)
315 document.book_info.update(form.cleaned_data)
318 repo._write_file(rpath, document.serialize().encode('utf-8'))
320 message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), \
321 user=request.user.username )
324 repo.in_branch(save_action, file_branch(path, request.user) )
325 except UnicodeEncodeError, e:
326 errors = ['Bład wewnętrzny: nie można zakodować pliku do utf-8']
327 except (ParseError, ValidationError), e:
331 errors = ["Pole '%s': %s\n" % (field[0], field[1].as_text()) for field in form.errors.iteritems()]
333 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok', 'errors': errors}) );
335 # this is unused currently, but may come in handy
339 fulltext = repo.get_file(rpath, file_branch(path, request.user))
340 bookinfo = dcparser.BookInfo.from_string(fulltext)
341 content = bookinfo.to_dict()
342 except (ParseError, ValidationError), e:
345 return HttpResponse( json.dumps({'result': errors and 'error' or 'ok',
346 'errors': errors, 'content': content }) )
348 # Display the main editor view
352 def display_editor(request, path, repo):
354 # this is the only entry point where we create an autobranch for the user
355 # if it doesn't exists. All other views SHOULD fail.
356 def ensure_branch_exists():
357 parent = repo.get_branch_tip('default')
358 repo._create_branch(file_branch(path, request.user), parent)
361 repo.with_wlock(ensure_branch_exists)
363 return direct_to_template(request, 'explorer/editor.html', extra_context={
365 'panel_list': ['lewy', 'prawy'],
366 'availble_panels': models.EditorPanel.objects.all(),
367 'scriptlets': toolbar_models.Scriptlet.objects.all()
370 return direct_to_template(request, 'explorer/nofile.html', \
371 extra_context = { 'fileid': path })
376 class panel_view(object):
378 def __new__(cls, request, name, path, **kwargs):
380 panel = models.EditorPanel.objects.get(id=name)
381 method = getattr(cls, name + '_panel', None)
382 if not panel or method is None:
383 raise HttpResponseNotFound
385 extra_context = method(request, path, panel, **kwargs)
387 if not isinstance(extra_context, dict):
390 extra_context.update({
391 'toolbar_groups': panel.toolbar_groups.all(),
392 'toolbar_extra_group': panel.toolbar_extra,
396 return direct_to_template(request, 'explorer/panels/'+name+'.html',\
397 extra_context=extra_context)
402 def xmleditor_panel(request, path, panel, repo):
403 rpath = file_path(path)
404 return {'text': repo.get_file(rpath, file_branch(path, request.user))}
408 def gallery_panel(request, path, panel):
409 return {'form': forms.ImageFoldersForm() }
414 def htmleditor_panel(request, path, panel, repo):
415 rpath = file_path(path)
416 user_branch = file_branch(path, request.user)
418 result = html.transform(repo.get_file(rpath, user_branch), is_file=False)
419 print "HTML: %r" % result
420 return {'html': result}
421 except (ParseError, ValidationError), e:
422 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
423 'fileid': path, 'exception_type': type(e).__name__, 'exception': e,
424 'panel_name': panel.display_name})
429 def dceditor_panel(request, path, panel, repo):
430 user_branch = file_branch(path, request.user)
431 rpath = file_path(path)
433 doc_text = repo.get_file(rpath, user_branch)
434 document = parser.WLDocument.from_string(doc_text)
435 form = forms.DublinCoreForm(info=document.book_info)
436 return {'form': form}
437 except (ParseError, ValidationError), e:
438 return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={
439 'fileid': path, 'exception_type': type(e).__name__, 'exception': e,
440 'panel_name': panel.display_name})
443 ## Editor "commands" and "dialogs"
447 def print_html(request, path, repo):
448 user_branch = file_branch(path, request.user)
449 rpath = file_path(path)
451 html.transform(repo.get_file(rpath, user_branch), is_file=False),
452 mimetype="text/html")
456 def print_xml(request, path, repo):
457 user_branch = file_branch(path, request.user)
458 rpath = file_path(path)
459 return HttpResponse( repo.get_file(rpath, user_branch), mimetype="text/plain; charset=utf-8")
461 @permission_required('explorer.can_add_files')
462 def split_text(request, path):
463 rpath = file_path(path)
465 if request.method == "POST":
466 sform = forms.SplitForm(request.POST, prefix='splitform')
467 dcform = forms.DublinCoreForm(request.POST, prefix='dcform')
469 print "validating sform"
472 # if sform.cleaned_data['autoxml']:
473 # print "validating dcform"
474 # valid = dcform.is_valid()
476 print "valid is ", valid
479 uri = path + '$' + sform.cleaned_data['partname']
480 child_rpath = file_path(uri)
481 repo = hg.Repository(settings.REPOSITORY_PATH)
483 # save the text into parent's branch
485 if repo._file_exists(child_rpath):
486 el = sform._errors.get('partname', ErrorList())
487 el.append("Part with this name already exists")
488 sform._errors['partname'] = el
491 fulltext = sform.cleaned_data['fulltext']
492 fulltext = fulltext.replace(u'<include-tag-placeholder />',
493 librarian.xinclude_forURI(u'wlrepo://'+uri) )
495 repo._write_file(rpath, fulltext.encode('utf-8'))
497 newtext = sform.cleaned_data['splittext']
498 if sform.cleaned_data['autoxml']:
499 # this is a horrible hack - really
500 bi = dcparser.BookInfo.from_element(librarian.DEFAULT_BOOKINFO.to_etree())
501 bi.update(dcform.data)
503 newtext = librarian.wrap_text(newtext, \
504 unicode(date.today()), bookinfo=bi )
506 repo._add_file(child_rpath, newtext.encode('utf-8'))
507 repo._commit(message="Split from '%s' to '%s'" % (path, uri), \
508 user=request.user.username )
511 if repo.in_branch(split_action, file_branch(path, request.user)):
512 # redirect to success
514 uri = urllib.quote( unicode(uri).encode('utf-8'))
515 return HttpResponseRedirect( reverse('split-success',\
516 kwargs={'path': path})+'?child='+uri )
518 try: # to read the current DC
519 repo = hg.Repository(settings.REPOSITORY_PATH)
520 fulltext = repo.get_file(rpath, file_branch(path, request.user))
521 bookinfo = dcparser.BookInfo.from_string(fulltext)
522 except (ParseError, ValidationError):
523 bookinfo = librarian.DEFAULT_BOOKINFO
525 sform = forms.SplitForm(prefix='splitform')
526 dcform = forms.DublinCoreForm(prefix='dcform', info=bookinfo)
528 return direct_to_template(request, 'explorer/split.html', extra_context={
529 'splitform': sform, 'dcform': dcform, 'fileid': path} )
531 def split_success(request, path):
532 return direct_to_template(request, 'explorer/split_success.html',\
533 extra_context={'fileid': path, 'cfileid': request.GET['child']} )
540 def folder_images(request, folder):
541 return direct_to_template(request, 'explorer/folder_images.html', extra_context={
542 'images': models.get_images_from_folder(folder),
545 def _add_references(message, issues):
546 return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues))
548 def _get_issues_for_file(fileid):
551 uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % fileid)
552 return json.loads(uf.read())
553 except urllib2.HTTPError:
561 #def pull_requests(request):
562 # return direct_to_template(request, 'manager/pull_request.html', extra_context = {
563 # 'objects': models.PullRequest.objects.all()} )