Wydzielanie utworów. Closes #79 Closes #98
authorŁukasz Rekucki <lrekucki@gmail.com>
Fri, 11 Sep 2009 14:12:18 +0000 (16:12 +0200)
committerŁukasz Rekucki <lrekucki@gmail.com>
Fri, 11 Sep 2009 14:12:18 +0000 (16:12 +0200)
apps/explorer/forms.py
apps/explorer/views.py
project/static/js/editor.js
project/static/js/editor.ui.js
project/templates/explorer/editor.html
project/templates/explorer/file_list.html
project/templates/explorer/panels/xmleditor.html
project/templates/explorer/split.html
project/templates/explorer/split_success.html
project/urls.py

index 9541cb0..c6aa09d 100644 (file)
@@ -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)
index 2930d98..52ff963 100644 (file)
@@ -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'<include-tag-placeholder />',
+                    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()} )
index 46d3941..cee04db 100644 (file)
@@ -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("<p>Wystapił błąd podczas wczytywania panelu.");
+            $(self.contentDiv).html("<p>Wystapił błąd podczas wczytywania panelu.</p>");
         }
     });
 }
@@ -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);
 
index 59c3f75..41025fa 100755 (executable)
@@ -104,7 +104,7 @@ Editor.prototype.setupUI = function() {
 \r
     panel_root.bind('hpanel:panel-resize-start', resize_start);\r
     self.rootDiv.bind('stopResize', function() {\r
-        self.savePanelOptions()\r
+        self.savePanelOptions();      \r
     });\r
     \r
     /*\r
@@ -127,11 +127,17 @@ Editor.prototype.setupUI = function() {
             function() {\r
                 panel.refresh();\r
             } );\r
+\r
+        self.rootDiv.bind('stopResize', function() {\r
+            panel.callHook('toolbarResized');\r
+        });\r
     });\r
 \r
     $(document).bind('panel:contentChanged', function() {\r
         self.onContentChanged.apply(self, arguments)\r
     });\r
+    \r
+    \r
 \r
     /*\r
      * Connect various buttons\r
@@ -206,8 +212,8 @@ Editor.prototype.loadSplitDialog = function(hash)
         // put the form into the window\r
         $('div.container-box', hash.w).html(data);\r
         $("div.loading-box", hash.w).hide();\r
-        $('form input[name=splittext]', hash.w).val(hash.t.selection);\r
-        $('form input[name=fulltext]', hash.w).val(hash.t.fulltext);\r
+        $('form input[name=splitform-splittext]', hash.w).val(hash.t.selection);\r
+        $('form input[name=splitform-fulltext]', hash.w).val(hash.t.fulltext);\r
         $('div.container-box', hash.w).show();\r
 \r
         // connect buttons\r
@@ -225,6 +231,19 @@ Editor.prototype.loadSplitDialog = function(hash)
         $('#split-dialog-button-dismiss').click(function() {\r
             hash.w.jqmHide();\r
             $('div.container-box', hash.w).html('');\r
+            hash.t.success();\r
+        });\r
+\r
+        if($('#id_splitform-autoxml').is(':checked'))\r
+            $('#split-form-dc-subform').show();\r
+        else\r
+            $('#split-form-dc-subform').hide();\r
+\r
+        $('#id_splitform-autoxml').change(function() {            \r
+            if( $(this).is(':checked') )\r
+                $('#split-form-dc-subform').show();\r
+            else\r
+                $('#split-form-dc-subform').hide();\r
         });\r
     };   \r
 \r
@@ -250,8 +269,11 @@ Editor.prototype.refreshPanels = function() {
         else\r
             panel.refresh();\r
     });\r
-};\r
 \r
+    $('#toolbar-button-save').attr('disabled', 'disabled');\r
+    $('#toolbar-button-commit').removeAttr('disabled');\r
+    $('#toolbar-button-update').removeAttr('disabled');\r
+};\r
 \r
 /*\r
  * Pop-up messages\r
index b37d5be..6ee1cf8 100644 (file)
@@ -28,7 +28,9 @@
     </script>
 {% endblock extrabody %}
 
-{% block breadcrumbs %}<a href="{% url file_list %}">Platforma Redakcyjna</a> &gt; plik {{ fileid }}{% endblock breadcrumbs %}
+ {% load explorer_tags %}
+
+{% block breadcrumbs %}<a href="{% url file_list %}">Platforma Redakcyjna</a> &gt; {{ fileid|bookname }}{% endblock breadcrumbs %}
 
 {% block header-toolbar %}
 
index d47a158..48be7f5 100644 (file)
@@ -38,8 +38,9 @@ $(function() {
     </p>
     </form>
     <div id="file-list">
+    {% load explorer_tags %}
     {% for file in files %}
-    <p title="{{file}}"><a href="{% url editor_view file %}">{{ file }}</a></p>
+    <p title="{{file|bookname}}"><a href="{% url editor_view file %}">{{ file|bookname }}</a></p>
     {% endfor %}
     </div>
 </div>
index 7691269..3f74017 100644 (file)
@@ -35,6 +35,7 @@ panel_hooks = {
 
         $(texteditor.frame).css({width: '100%', height: '100%'});    
         this.texteditor = texteditor;
+        self._endload();       
     },
 
        unload: function() { 
index 0fb9064..b39c58d 100755 (executable)
@@ -2,26 +2,25 @@
     <fieldset>\r
         <legend>Split options</legend>\r
         {% for field in splitform %}\r
+        {% if field.is_hidden %}\r
+        {{ field}}\r
+        {% else %}\r
         {{ field.errors }}\r
         {% ifequal field.html_name 'splitform-autoxml' %}\r
         <p><label>{{ field }} {{ field.label }}</label></p>\r
         {% else %}\r
         <p><label>{{ field.label }}: {{ field }}</label></p>\r
         {% endifequal %}\r
-\r
-        {% endfor %}\r
-\r
+        {% endif %}\r
+        {% endfor %}        \r
     </fieldset>\r
 \r
     <fieldset id="split-form-dc-subform" style="display: none;">\r
     <legend>Dublin Core</legend>\r
     {{ dcform.as_p }}\r
-    </fieldset>\r
-\r
-    <input type="hidden" name="splittext" />\r
-    <input type="hidden" name="fulltext" />\r
+    </fieldset>    \r
     <p>\r
         <button type="submit" id="split-dialog-button-accept">Split</button>\r
         <button type="button" id="split-dialog-button-close">Close</button>\r
     </p>\r
-</form>
\ No newline at end of file
+</form>\r
index 69c19c3..4f3a57b 100755 (executable)
@@ -1,3 +1,3 @@
 <p>Split successful. You can edit the new part here:\r
-<a href="{% url editor_view cfileid %}">{% url editor_view cfileid %}</a></p>\r
+<a href="{% url editor_view cfileid %}" target="_new">{% url editor_view cfileid %}</a></p>\r
 <p><button type="button" id="split-dialog-button-dismiss">Close</button></p>
\ No newline at end of file
index b357688..ae7a636 100644 (file)
@@ -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')),