From: Łukasz Rekucki Date: Fri, 11 Sep 2009 14:12:18 +0000 (+0200) Subject: Wydzielanie utworów. Closes #79 Closes #98 X-Git-Url: https://git.mdrn.pl/redakcja.git/commitdiff_plain/0da45be34c7019ee362d1892e92dd53e743933b6?ds=sidebyside;hp=--cc Wydzielanie utworów. Closes #79 Closes #98 --- 0da45be34c7019ee362d1892e92dd53e743933b6 diff --git a/apps/explorer/forms.py b/apps/explorer/forms.py index 9541cb02..c6aa09d2 100644 --- a/apps/explorer/forms.py +++ b/apps/explorer/forms.py @@ -61,7 +61,7 @@ class MergeForm(forms.Form): class BookUploadForm(forms.Form): file = forms.FileField(label='Source OCR file') - bookname = forms.RegexField(regex='[\w-]+', \ + bookname = forms.RegexField(regex='[0-9\w_-]+', \ label='Publication name', help_text='Example: slowacki-beniowski') autoxml = forms.BooleanField(required=False, initial=True, label=u"Generate DublinCore template") @@ -73,9 +73,11 @@ class ImageFoldersForm(forms.Form): self.fields['folders'].choices = [('', '-- Wybierz folder z obrazkami --')] + [(fn, fn) for fn in models.get_image_folders()] class SplitForm(forms.Form): - partname = forms.RegexField(regex='[0-9\w-]+', \ + partname = forms.RegexField(regex='[0-9\w_-]+', \ label='Part name', help_text='Example: rozdział-2') - autoxml = forms.BooleanField(required=False, initial=False, label=u"Generate DublinCore") + autoxml = forms.BooleanField(required=False, initial=False, label=u"Split as new publication") + fulltext = forms.CharField(widget=forms.HiddenInput(), required=False) + splittext = forms.CharField(widget=forms.HiddenInput(), required=False) class DublinCoreForm(forms.Form): about = forms.URLField(verify_exists=False) diff --git a/apps/explorer/views.py b/apps/explorer/views.py index 2930d989..52ff9630 100644 --- a/apps/explorer/views.py +++ b/apps/explorer/views.py @@ -1,9 +1,11 @@ # -*- coding: utf-8 -*- import urllib2 -import hg +import hg, re from datetime import date -from librarian import html, parser, dcparser, wrap_text +import librarian + +from librarian import html, parser, dcparser from librarian import ParseError, ValidationError from django.conf import settings @@ -18,12 +20,18 @@ from django.contrib.auth.decorators import login_required from explorer import forms, models from toolbar import models as toolbar_models +from django.forms.util import ErrorList + # # Some useful decorators -def file_branch(path, user=None): - return ('personal_'+user.username + '_' if user is not None else '') \ - + 'file_' + path +def file_branch(fileid, user=None): + parts = fileid.split('$') + return ('personal_'+ user.username + '_' if user is not None else '') \ + + 'file_' + parts[0] + +def file_path(fileid): + return 'pub_'+fileid+'.xml' def with_repo(view): """Open a repository for this view""" @@ -50,11 +58,17 @@ def ajax_login_required(view): def file_list(request, repo): # latest_default = repo.get_branch_tip('default') - files = [ f for f in repo.repo[latest_default] if not f.startswith('.')] + + fl = [] + for file in repo.repo[latest_default]: + m = re.match(u'^pub_([\\w\\$0-9_-]+).xml$', file.decode('utf-8'), re.UNICODE) + if m is not None: + fl.append(m.group(1)) + bookform = forms.BookUploadForm() return direct_to_template(request, 'explorer/file_list.html', extra_context={ - 'files': files, 'bookform': bookform, + 'files': fl, 'bookform': bookform, }) @permission_required('explorer.can_add_files') @@ -68,21 +82,22 @@ def file_upload(request, repo): # prepare the data f = request.FILES['file'] decoded = f.read().decode('utf-8') - path = form.cleaned_data['bookname'] + fileid = form.cleaned_data['bookname'].lower() + rpath = file_path(fileid) if form.cleaned_data['autoxml']: - decoded = wrap_text(decoded, unicode(date.today()) ) + decoded = librarian.wrap_text(decoded, unicode(date.today()) ) def upload_action(): - repo._add_file(path, decoded.encode('utf-8') ) + repo._add_file(rpath, decoded.encode('utf-8') ) repo._commit(message="File %s uploaded by user %s" % \ - (path, request.user.username), user=request.user.username) + (rpath, request.user.username), user=request.user.username) repo.in_branch(upload_action, 'default') # if everything is ok, redirect to the editor return HttpResponseRedirect( reverse('editor_view', - kwargs={'path': path}) ) + kwargs={'path': fileid}) ) except hg.RepositoryException, e: other_errors.append(u'Błąd repozytorium: ' + unicode(e) ) @@ -103,6 +118,7 @@ def file_upload(request, repo): @ajax_login_required @with_repo def file_xml(request, repo, path): + rpath = file_path(path) if request.method == 'POST': errors = None warnings = None @@ -114,7 +130,7 @@ def file_xml(request, repo, path): encoded_data = form.cleaned_data['content'].encode('utf-8') def save_action(): - repo._add_file(path, encoded_data) + repo._add_file(rpath, encoded_data) repo._commit(message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'),\ user=request.user.username) @@ -138,7 +154,7 @@ def file_xml(request, repo, path): 'errors': errors, 'warnings': warnings}) ); form = forms.BookForm() - data = repo.get_file(path, file_branch(path, request.user)) + data = repo.get_file(rpath, file_branch(path, request.user)) form.fields['content'].initial = data return HttpResponse( json.dumps({'result': 'ok', 'content': data}) ) @@ -291,6 +307,7 @@ def file_commit(request, path, repo): @with_repo def file_dc(request, path, repo): errors = None + rpath = file_path(fileid) if request.method == 'POST': form = forms.DublinCoreForm(request.POST) @@ -298,14 +315,14 @@ def file_dc(request, path, repo): if form.is_valid(): def save_action(): - file_contents = repo._get_file(path) + file_contents = repo._get_file(rpath) # wczytaj dokument z repozytorium document = parser.WLDocument.from_string(file_contents) document.book_info.update(form.cleaned_data) # zapisz - repo._write_file(path, document.serialize().encode('utf-8')) + repo._write_file(rpath, document.serialize().encode('utf-8')) repo._commit( \ message=(form.cleaned_data['commit_message'] or 'Lokalny zapis platformy.'), \ user=request.user.username ) @@ -326,7 +343,7 @@ def file_dc(request, path, repo): content = [] try: - fulltext = repo.get_file(path, file_branch(path, request.user)) + fulltext = repo.get_file(rpath, file_branch(path, request.user)) bookinfo = dcparser.BookInfo.from_string(fulltext) content = bookinfo.to_dict() except (ParseError, ValidationError), e: @@ -390,7 +407,8 @@ class panel_view(object): @ajax_login_required @with_repo def xmleditor_panel(request, path, panel, repo): - return {'text': repo.get_file(path, file_branch(path, request.user))} + rpath = file_path(path) + return {'text': repo.get_file(rpath, file_branch(path, request.user))} @staticmethod @ajax_login_required @@ -401,9 +419,10 @@ class panel_view(object): @ajax_login_required @with_repo def htmleditor_panel(request, path, panel, repo): + rpath = file_path(path) user_branch = file_branch(path, request.user) try: - return {'html': html.transform(repo.get_file(path, user_branch), is_file=False)} + return {'html': html.transform(repo.get_file(rpath, user_branch), is_file=False)} except (ParseError, ValidationError), e: return direct_to_template(request, 'explorer/panels/parse_error.html', extra_context={ 'fileid': path, 'exception_type': type(e).__name__, 'exception': e, @@ -414,8 +433,9 @@ class panel_view(object): @with_repo def dceditor_panel(request, path, panel, repo): user_branch = file_branch(path, request.user) + rpath = file_path(path) try: - doc_text = repo.get_file(path, user_branch) + doc_text = repo.get_file(rpath, user_branch) document = parser.WLDocument.from_string(doc_text) form = forms.DublinCoreForm(info=document.book_info) return {'form': form} @@ -431,25 +451,25 @@ class panel_view(object): @with_repo def print_html(request, path, repo): user_branch = file_branch(path, request.user) + rpath = file_path(path) return HttpResponse( - html.transform(repo.get_file(path, user_branch), is_file=False), + html.transform(repo.get_file(rpath, user_branch), is_file=False), mimetype="text/html") @login_required @with_repo def print_xml(request, path, repo): user_branch = file_branch(path, request.user) - return HttpResponse( repo.get_file(path, user_branch), mimetype="text/plain; charset=utf-8") + rpath = file_path(path) + return HttpResponse( repo.get_file(rpath, user_branch), mimetype="text/plain; charset=utf-8") -@login_required # WARNING: we don't wont a login form inside a window -@with_repo -def split_text(request, path, repo): - user_branch = file_branch(path, request.user) - valid = False - +@permission_required('explorer.can_add_files') +def split_text(request, path): + rpath = file_path(path) + valid = False if request.method == "POST": sform = forms.SplitForm(request.POST, prefix='splitform') - dcform = forms.SplitForm(request.POST, prefix='dcform') + dcform = forms.DublinCoreForm(request.POST, prefix='dcform') print "validating sform" if sform.is_valid(): @@ -461,13 +481,52 @@ def split_text(request, path, repo): print "valid is ", valid if valid: uri = path + '$' + sform.cleaned_data['partname'] - # do something - return HttpResponseRedirect( reverse('split-success',\ - kwargs={'path': path})+'?child='+uri) + child_rpath = file_path(uri) + repo = hg.Repository(settings.REPOSITORY_PATH) + + # save the text into parent's branch + def split_action(): + if repo._file_exists(child_rpath): + el = sform._errors.get('partname', ErrorList()) + el.append("Part with this name already exists") + sform._errors['partname'] = el + return False + + fulltext = sform.cleaned_data['fulltext'] + fulltext = fulltext.replace(u'', + librarian.xinclude_forURI('wlrepo://'+uri) ) + + repo._write_file(rpath, fulltext.encode('utf-8')) + + newtext = sform.cleaned_data['splittext'] + if sform.cleaned_data['autoxml']: + # this is a horrible hack - really + bi = dcparser.BookInfo.from_element(librarian.DEFAULT_BOOKINFO.to_etree()) + bi.update(dcform.cleaned_data) + + newtext = librarian.wrap_text(newtext, \ + unicode(date.today()), bookinfo=bi ) + + repo._add_file(child_rpath, newtext.encode('utf-8')) + repo._commit(message="Split from '%s' to '%s'" % (path, uri), \ + user=request.user.username ) + return True + + if repo.in_branch(split_action, file_branch(path, request.user)): + # redirect to success + return HttpResponseRedirect( reverse('split-success',\ + kwargs={'path': path})+'?child='+uri) else: + try: # to read the current DC + repo = hg.Repository(settings.REPOSITORY_PATH) + fulltext = repo.get_file(rpath, file_branch(path, request.user)) + bookinfo = dcparser.BookInfo.from_string(fulltext) + except (ParseError, ValidationError): + bookinfo = librarian.DEFAULT_BOOKINFO + sform = forms.SplitForm(prefix='splitform') - dcform = forms.DublinCoreForm(prefix='dcform') - + dcform = forms.DublinCoreForm(prefix='dcform', info=bookinfo) + return direct_to_template(request, 'explorer/split.html', extra_context={ 'splitform': sform, 'dcform': dcform, 'fileid': path} ) @@ -485,29 +544,22 @@ def folder_images(request, folder): 'images': models.get_images_from_folder(folder), }) - def _add_references(message, issues): return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues)) -def _get_issues_for_file(path): - if not path.endswith('.xml'): - raise ValueError('Path must end with .xml') - - book_id = path[:-4] +def _get_issues_for_file(fileid): uf = None - try: - uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % book_id) + uf = urllib2.urlopen(settings.REDMINE_URL + 'publications/issues/%s.json' % fileid) return json.loads(uf.read()) except urllib2.HTTPError: return [] finally: if uf: uf.close() - # ================= # = Pull requests = # ================= -def pull_requests(request): - return direct_to_template(request, 'manager/pull_request.html', extra_context = { - 'objects': models.PullRequest.objects.all()} ) +#def pull_requests(request): +# return direct_to_template(request, 'manager/pull_request.html', extra_context = { +# 'objects': models.PullRequest.objects.all()} ) diff --git a/project/static/js/editor.js b/project/static/js/editor.js index 46d39419..cee04dbb 100644 --- a/project/static/js/editor.js +++ b/project/static/js/editor.js @@ -53,6 +53,12 @@ Panel.prototype.callHook = function() { return result; } +Panel.prototype._endload = function () { + // this needs to be here, so we + this.connectToolbar(); + this.callHook('toolbarResized'); +} + Panel.prototype.load = function (url) { // $.log('preparing xhr load: ', this.wrap); $(document).trigger('panel:unload', this); @@ -66,14 +72,12 @@ Panel.prototype.load = function (url) { panel_hooks = null; $(self.contentDiv).html(data); self.hooks = panel_hooks; - panel_hooks = null; - self.connectToolbar(); - self.callHook('load'); - self.callHook('toolbarResized'); + panel_hooks = null; + self.callHook('load'); }, error: function(request, textStatus, errorThrown) { $.log('ajax', url, this.target, 'error:', textStatus, errorThrown); - $(self.contentDiv).html("

Wystapił błąd podczas wczytywania panelu."); + $(self.contentDiv).html("

Wystapił błąd podczas wczytywania panelu.

"); } }); } @@ -377,9 +381,8 @@ Editor.prototype.saveToBranch = function(msg) } else { self.refreshPanels(); - $('#toolbar-button-save').attr('disabled', 'disabled'); - $('#toolbar-button-commit').removeAttr('disabled'); - $('#toolbar-button-update').removeAttr('disabled'); + + if(self.autosaveTimer) clearTimeout(self.autosaveTimer); diff --git a/project/static/js/editor.ui.js b/project/static/js/editor.ui.js index 59c3f754..41025fa0 100755 --- a/project/static/js/editor.ui.js +++ b/project/static/js/editor.ui.js @@ -104,7 +104,7 @@ Editor.prototype.setupUI = function() { panel_root.bind('hpanel:panel-resize-start', resize_start); self.rootDiv.bind('stopResize', function() { - self.savePanelOptions() + self.savePanelOptions(); }); /* @@ -127,11 +127,17 @@ Editor.prototype.setupUI = function() { function() { panel.refresh(); } ); + + self.rootDiv.bind('stopResize', function() { + panel.callHook('toolbarResized'); + }); }); $(document).bind('panel:contentChanged', function() { self.onContentChanged.apply(self, arguments) }); + + /* * Connect various buttons @@ -206,8 +212,8 @@ Editor.prototype.loadSplitDialog = function(hash) // put the form into the window $('div.container-box', hash.w).html(data); $("div.loading-box", hash.w).hide(); - $('form input[name=splittext]', hash.w).val(hash.t.selection); - $('form input[name=fulltext]', hash.w).val(hash.t.fulltext); + $('form input[name=splitform-splittext]', hash.w).val(hash.t.selection); + $('form input[name=splitform-fulltext]', hash.w).val(hash.t.fulltext); $('div.container-box', hash.w).show(); // connect buttons @@ -225,6 +231,19 @@ Editor.prototype.loadSplitDialog = function(hash) $('#split-dialog-button-dismiss').click(function() { hash.w.jqmHide(); $('div.container-box', hash.w).html(''); + hash.t.success(); + }); + + if($('#id_splitform-autoxml').is(':checked')) + $('#split-form-dc-subform').show(); + else + $('#split-form-dc-subform').hide(); + + $('#id_splitform-autoxml').change(function() { + if( $(this).is(':checked') ) + $('#split-form-dc-subform').show(); + else + $('#split-form-dc-subform').hide(); }); }; @@ -250,8 +269,11 @@ Editor.prototype.refreshPanels = function() { else panel.refresh(); }); -}; + $('#toolbar-button-save').attr('disabled', 'disabled'); + $('#toolbar-button-commit').removeAttr('disabled'); + $('#toolbar-button-update').removeAttr('disabled'); +}; /* * Pop-up messages diff --git a/project/templates/explorer/editor.html b/project/templates/explorer/editor.html index b37d5be6..6ee1cf85 100644 --- a/project/templates/explorer/editor.html +++ b/project/templates/explorer/editor.html @@ -28,7 +28,9 @@ {% endblock extrabody %} -{% block breadcrumbs %}Platforma Redakcyjna > plik {{ fileid }}{% endblock breadcrumbs %} + {% load explorer_tags %} + +{% block breadcrumbs %}Platforma Redakcyjna > {{ fileid|bookname }}{% endblock breadcrumbs %} {% block header-toolbar %} diff --git a/project/templates/explorer/file_list.html b/project/templates/explorer/file_list.html index d47a158a..48be7f59 100644 --- a/project/templates/explorer/file_list.html +++ b/project/templates/explorer/file_list.html @@ -38,8 +38,9 @@ $(function() {

+ {% load explorer_tags %} {% for file in files %} -

{{ file }}

+

{{ file|bookname }}

{% endfor %}
diff --git a/project/templates/explorer/panels/xmleditor.html b/project/templates/explorer/panels/xmleditor.html index 7691269b..3f74017d 100644 --- a/project/templates/explorer/panels/xmleditor.html +++ b/project/templates/explorer/panels/xmleditor.html @@ -35,6 +35,7 @@ panel_hooks = { $(texteditor.frame).css({width: '100%', height: '100%'}); this.texteditor = texteditor; + self._endload(); }, unload: function() { diff --git a/project/templates/explorer/split.html b/project/templates/explorer/split.html index 0fb9064e..b39c58db 100755 --- a/project/templates/explorer/split.html +++ b/project/templates/explorer/split.html @@ -2,26 +2,25 @@
Split options {% for field in splitform %} + {% if field.is_hidden %} + {{ field}} + {% else %} {{ field.errors }} {% ifequal field.html_name 'splitform-autoxml' %}

{% else %}

{% endifequal %} - - {% endfor %} - + {% endif %} + {% endfor %}
- - - +

- \ No newline at end of file + diff --git a/project/templates/explorer/split_success.html b/project/templates/explorer/split_success.html index 69c19c3e..4f3a57b8 100755 --- a/project/templates/explorer/split_success.html +++ b/project/templates/explorer/split_success.html @@ -1,3 +1,3 @@

Split successful. You can edit the new part here: -{% url editor_view cfileid %}

+{% url editor_view cfileid %}

\ No newline at end of file diff --git a/project/urls.py b/project/urls.py index b3576889..ae7a636c 100644 --- a/project/urls.py +++ b/project/urls.py @@ -31,7 +31,7 @@ urlpatterns = patterns('', url(r'^editor/'+PATH_SEC+'/print/xml$', 'explorer.views.print_xml'), # Task managment - url(r'^manager/pull-requests$', 'explorer.views.pull_requests'), + # url(r'^manager/pull-requests$', 'explorer.views.pull_requests'), # Admin panel url(r'^admin/doc/', include('django.contrib.admindocs.urls')),