Merge branch 'master' of stigma.nowoczesnapolska.org.pl:platforma
authorzuber <marek@stepniowski.com>
Mon, 19 Oct 2009 10:19:45 +0000 (12:19 +0200)
committerzuber <marek@stepniowski.com>
Mon, 19 Oct 2009 10:19:45 +0000 (12:19 +0200)
13 files changed:
apps/api/admin.py [new file with mode: 0644]
apps/api/handlers/library_handlers.py
apps/api/handlers/manage_handlers.py
apps/api/models.py
lib/wlrepo/__init__.py
lib/wlrepo/mercurial_backend/__init__.py
lib/wlrepo/mercurial_backend/document.py
platforma/locale/pl/LC_MESSAGES/django.mo [new file with mode: 0644]
platforma/locale/pl/LC_MESSAGES/django.po [new file with mode: 0644]
platforma/static/js/models.js
platforma/static/js/views/gallery.js
platforma/templates/explorer/editor.html
platforma/templates/registration/head_login.html

diff --git a/apps/api/admin.py b/apps/api/admin.py
new file mode 100644 (file)
index 0000000..efa64f3
--- /dev/null
@@ -0,0 +1,6 @@
+from django.contrib import admin
+
+import api.models
+
+admin.site.register(api.models.PullRequest)
+admin.site.register(api.models.PartCache)
index f7d5784..0635861 100644 (file)
@@ -29,7 +29,7 @@ from explorer.models import GalleryForDocument
 import api.forms as forms
 import api.response as response
 from api.utils import validate_form, hglibrary, natural_order
-from api.models import PartCache
+from api.models import PartCache, PullRequest
 
 #
 import settings
@@ -38,18 +38,24 @@ import settings
 def is_prq(username):
     return username.startswith('$prq-')
 
+def prq_for_user(username):
+    try:
+        return PullRequest.objects.get(id=int(username[5:]))
+    except:
+        return None
+
 def check_user(request, user):
     log.info("user: %r, perm: %r" % (request.user, request.user.get_all_permissions()) )
     #pull request
     if is_prq(user):
-        if not request.user.has_perm('api.pullrequest.can_view'):
+        if not request.user.has_perm('api.view_prq'):
             yield response.AccessDenied().django_response({
                 'reason': 'access-denied',
                 'message': "You don't have enough priviliges to view pull requests."
             })
     # other users
     elif request.user.username != user:
-        if not request.user.has_perm('api.document.can_view_other'):
+        if not request.user.has_perm('api.view_other_document'):
             yield response.AccessDenied().django_response({
                 'reason': 'access-denied',
                 'message': "You don't have enough priviliges to view other people's document."
@@ -140,7 +146,6 @@ class LibraryHandler(BaseHandler):
                 log.info("DOCID %s", docid)
                 doc = lib.document_create(docid)
                 # document created, but no content yet
-
                 try:
                     doc = doc.quickwrite('xml', data.encode('utf-8'),
                         '$AUTO$ XML data uploaded.', user=request.user.username)
@@ -229,28 +234,28 @@ class DocumentHandler(BaseHandler):
             # the user doesn't have this document checked out
             # or some other weird error occured
             # try to do the checkout
-            if is_prq(user) or (user == request.user.username):
-                try:
+            try:
+                if user == request.user.username:
                     mdoc = lib.document(docid)
                     doc = mdoc.take(user)
-
-                    if is_prq(user):
-                        # source revision, should probably change
-                        # but there are no changes yet, so...
-                        pass
-                    
-                except RevisionNotFound, e:
+                elif is_prq(user):
+                    prq = prq_for_user(user)
+                    # commiter's document
+                    prq_doc = lib.document_for_rev(prq.source_revision)
+                    doc = prq_doc.take(user)
+                else:
                     return response.EntityNotFound().django_response({
                         'reason': 'document-not-found',
                         'message': e.message,
-                        'docid': docid
+                        'docid': docid,
+                        'user': user,
                     })
-            else:
+            except RevisionNotFound, e:
                 return response.EntityNotFound().django_response({
                     'reason': 'document-not-found',
                     'message': e.message,
                     'docid': docid,
-                    'user': user,
+                    'user': user
                 })
 
         return {
@@ -337,7 +342,7 @@ class DocumentGalleryHandler(BaseHandler):
 
             gallery = {'name': assoc.name, 'pages': []}
             
-            for file in sorted(os.listdir(dirpath)):
+            for file in os.listdir(dirpath):
                 if not isinstance(file, unicode):
                     try:
                         file = file.decode('utf-8')
@@ -363,7 +368,7 @@ class DocumentGalleryHandler(BaseHandler):
 #            gallery['pages'].sort()
             galleries.append(gallery)
 
-        return galleries                      
+        return galleries
 
 #
 # Document Text View
@@ -623,13 +628,7 @@ class MergeHandler(BaseHandler):
         if form.cleaned_data['type'] == 'update':
             # update is always performed from the file branch
             # to the user branch
-            changed, clean = base_doc.update(request.user.username)
-
-            # update user document
-            if changed:
-                user_doc_new = user_doc.latest()
-            else:
-                user_doc_new = user_doc
+            user_doc_new = base_doc.update(request.user.username)
                 
             # shared document is the same
             doc_new = doc
@@ -648,7 +647,7 @@ class MergeHandler(BaseHandler):
                     "message": "There are unresolved conflicts in your file. Fix them, and try again."
                 })
 
-            if not request.user.has_perm('api.document.can_share'):
+            if not request.user.has_perm('api.share_document'):
                 # User is not permitted to make a merge, right away
                 # So we instead create a pull request in the database
                 try:
@@ -699,8 +698,8 @@ class MergeHandler(BaseHandler):
             "revision": user_doc_new.revision,
             'timestamp': user_doc_new.revision.timestamp,
 
-            "parent_revision": user_doc_new.revision,
-            "parent_timestamp": user_doc_new.revision.timestamp,
+            "parent_revision": user_doc.revision,
+            "parent_timestamp": user_doc.revision.timestamp,
 
             "shared_revision": doc_new.revision,
             "shared_timestamp": doc_new.revision.timestamp,
index 5905724..b94ca72 100644 (file)
@@ -8,17 +8,18 @@ __date__ = "$2009-09-25 15:49:50$"
 __doc__ = "Module documentation."
 
 from piston.handler import BaseHandler
+from wlrepo import UpdateException
 
 from api.utils import hglibrary
 from api.models import PullRequest
 from api.response import *
-from datetime import datetime
+import datetime
 
 class PullRequestListHandler(BaseHandler):
     allowed_methods = ('GET',)
 
     def read(self, request):
-        if request.user.has_perm('api.pullrequest.can_change'):
+        if request.user.has_perm('change_pullrequest'):
             return PullRequest.objects.all()
         else:
             return PullRequest.objects.filter(commiter=request.user)
@@ -33,7 +34,7 @@ class PullRequestHandler(BaseHandler):
     def update(self, request, prq_id):
         """Change the status of request"""
 
-        if not request.user.has_perm('api.pullrequest.can_change'):
+        if not request.user.has_perm('change_pullrequest'):
             return AccessDenied().django_response("Insufficient priviliges")
         
         prq = PullRequest.objects.get(id=prq_id)
@@ -59,7 +60,7 @@ class PullRequestHandler(BaseHandler):
                 'message': "This pull request is alredy resolved. Can't accept."
             })
             
-        src_doc = lib.document( prq.source_revision )
+        src_doc = lib.document_for_rev( prq.source_revision )
 
         lock = lib.lock()
         try:
@@ -69,30 +70,28 @@ class PullRequestHandler(BaseHandler):
                 #
                 #  Q: where to put the updated revision ?
                 #  A: create a special user branch named prq-#prqid
-                prq_doc = src_doc.take("$prq-%d" % prd.id)
+                prq_doc = src_doc.take("$prq-%d" % prq.id)
 
                 # This could be not the first time we try this,
                 # so the prq_doc could already be there
                 # and up to date
 
-                success, changed = prq_doc.update(user.username)
-                prq.status = 'E'
-
-                if not success:
-                    prq.save()
+                try:
+                    prq_doc = prq_doc.update(user.username)
+                    prq.source_revision = str(prq_doc.revision)
+                    src_doc = prq_doc
+                except UpdateException, e:
                     # this can happen only if the merge program
                     # is misconfigured - try returning an entity conflict
                     # TODO: put some useful infor here
-                    return EntityConflict().django_response()
-
-                if changed:
-                    prq_doc = prq_doc.latest()
-
-                prq.source_revision = str(prq_doc.revision)
-                src_doc = prq_doc
+                    prq.status = 'E'
+                    prq.save()
+                    return EntityConflict().django_response({
+                        'reason': 'update-failed',
+                        'message': e.message })                
 
             # check if there are conflicts
-            if prq_doc.has_conflict_marks():
+            if src_doc.has_conflict_marks():
                 prq.status = 'E'
                 prq.save()
                 # Now, the user must resolve the conflict
@@ -111,7 +110,7 @@ class PullRequestHandler(BaseHandler):
             # sync state with repository
             prq.status = 'A'
             prq.merged_revision = str(src_doc.shared().revision)
-            prq.merged_timestamp = datetime()
+            prq.merged_timestamp = datetime.now()
             prq.save()
 
             return SuccessAllOk().django_response({
index 90f962e..8252589 100644 (file)
@@ -59,7 +59,7 @@ class PullRequest(models.Model):
 
     class Meta:
         permissions = (           
-            ("pullrequest.can_view", "Can view pull request's contents."),
+            ("view_prq", "Can view pull request's contents."),
         )
 
 
@@ -68,6 +68,6 @@ class PullRequest(models.Model):
 class Document(models.Model):
     class Meta:
         permissions = (
-            ("document.can_share", "Can share documents without pull requests."),
-            ("document.can_view_other", "Can view other's documents."),
+            ("share_document", "Can share documents without pull requests."),
+            ("view_other_document", "Can view other's documents."),
         )    
\ No newline at end of file
index 9de75a0..0f373d4 100644 (file)
@@ -105,6 +105,9 @@ class LibraryException(Exception):
         Exception.__init__(self, msg)
         self.cause = cause
 
+class UpdateException(LibraryException):
+    pass
+
 class RevisionNotFound(LibraryException):
     def __init__(self, rev):
         LibraryException.__init__(self, "Revision %r not found." % rev)
index 536d08c..22a9d52 100644 (file)
@@ -89,9 +89,9 @@ class MercurialRevision(wlrepo.Revision):
             status = self._library._merge(other._changectx.node())
             if status.isclean():
                 self._library._commit(user=user, message=message)
-                return (True, True)
+                return True
             else:
-                return (False, False)
+                return False
         finally:
             lock.release()
 
index 0883d99..3911d04 100644 (file)
@@ -116,23 +116,24 @@ class MercurialDocument(wlrepo.Document):
         try:
             if self.ismain():
                 # main revision of the document
-                return (True, False)
+                return self
             
-            if self._revision.has_children():
-                log.info('Update failed: has children.')
-                # can't update non-latest revision
-                return (False, False)
+            if self._revision.has_children():                
+                raise UpdateException("Revision has children.")
 
             sv = self.shared()
 
             if self.parentof(sv):
-                return (True, False)
+                return self
 
             if sv.ancestorof(self):
-                return (True, False)
+                return self
 
-            return self._revision.merge_with(sv._revision, user=user,
-                message="$AUTO$ Personal branch update.")
+            if self._revision.merge_with(sv._revision, user=user,\
+                message="$AUTO$ Personal branch update."):
+                return self.latest()
+            else:
+                raise UpdateException("Merge failed.")
         finally:
             lock.release()  
 
diff --git a/platforma/locale/pl/LC_MESSAGES/django.mo b/platforma/locale/pl/LC_MESSAGES/django.mo
new file mode 100644 (file)
index 0000000..a0cefb7
Binary files /dev/null and b/platforma/locale/pl/LC_MESSAGES/django.mo differ
diff --git a/platforma/locale/pl/LC_MESSAGES/django.po b/platforma/locale/pl/LC_MESSAGES/django.po
new file mode 100644 (file)
index 0000000..52d7a6d
--- /dev/null
@@ -0,0 +1,69 @@
+# Polskie tłumaczenie dla platformy wolnych lektur.
+# Copyright (C) 2009
+# This file is distributed under the same license as the 'platforma' package.
+# lrekucki@gmail.com, 2009.
+#
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: PACKAGE VERSION\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2009-10-16 10:52+0000\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: LANGUAGE <LL@li.org>\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+
+#: templates/explorer/editor.html:53
+msgid "Refresh panel"
+msgstr "Odśwież panel"
+
+#: templates/explorer/editor.html:67
+msgid "Print version"
+msgstr "Wersja do druku"
+
+#: templates/explorer/editor.html:96
+msgid "Next page"
+msgstr "Następna strona"
+
+#: templates/explorer/editor.html:100
+msgid "Zoom in"
+msgstr "Powiększ"
+
+#: templates/explorer/editor.html:103
+msgid "Zoom out"
+msgstr "Zmniejsz"
+
+#: templates/explorer/editor.html:106
+msgid "Reset zoom"
+msgstr "Oryginalny rozmiar"
+
+#: templates/explorer/editor.html:155
+msgid "History"
+msgstr "Historia"
+
+#: templates/explorer/editor.html:156
+msgid "Push"
+msgstr "Zatwierdź"
+
+#: templates/explorer/editor.html:157
+msgid "Pull"
+msgstr "Uaktualnij"
+
+#: templates/explorer/editor.html:158
+msgid "Save"
+msgstr "Zapisz"
+
+#: templates/explorer/editor.html:159
+msgid "Quick save"
+msgstr "Szybki zapis"
+
+#: templates/registration/head_login.html:5
+msgid "Log Out"
+msgstr "Wyloguj"
+
+#: templates/registration/head_login.html:9
+msgid "Log In"
+msgstr "Logowanie"
index fe42e89..c57f4f0 100644 (file)
@@ -347,7 +347,7 @@ Editor.ImageGalleryModel = Editor.Model.extend({
     data: [],
     state: 'empty',
 
-    init: function(serverURL) {
+    init: function(document, serverURL) {
         this._super();
         this.set('state', 'empty');
         this.serverURL = serverURL;
@@ -357,16 +357,22 @@ Editor.ImageGalleryModel = Editor.Model.extend({
 
     load: function(force) {
         if (force || this.get('state') == 'empty') {
+            console.log("setting state");
             this.set('state', 'loading');
+            console.log("going ajax");
             $.ajax({
                 url: this.serverURL,
                 dataType: 'json',
-                success: this.loadingSucceeded.bind(this)
+                success: this.loadingSucceeded.bind(this),
+                error: this.loadingFailed.bind(this)
             });
         }
     },
 
-    loadingSucceeded: function(data) {
+    loadingSucceeded: function(data) 
+    {
+        console.log("success");        
+        
         if (this.get('state') != 'loading') {
             alert('erroneous state:', this.get('state'));
         }
@@ -382,6 +388,16 @@ Editor.ImageGalleryModel = Editor.Model.extend({
         this.set('state', 'synced');
     },
 
+    loadingFailed: function(data) {
+        console.log("failed");
+
+        if (this.get('state') != 'loading') {
+            alert('erroneous state:', this.get('state'));
+        }       
+
+        this.set('state', 'error');
+    },
+
     set: function(property, value) {
         if (property == 'state') {
             console.log(this.description(), ':', property, '=', value);
index 7449344..176b0ab 100644 (file)
@@ -13,7 +13,7 @@ var ImageGalleryView = View.extend({
     this._super(element, model, template);
     this.parent = parent;
 
-    console.log("galley model", this.model);
+    console.log("gallery model", this.model);
        
     this.model
       .addObserver(this, 'data', this.modelDataChanged.bind(this))
@@ -85,9 +85,9 @@ var ImageGalleryView = View.extend({
   
   modelStateChanged: function(property, value) {   
     if (value == 'loading') {
-      this.parent.freeze('Ładowanie...');
+      // this.freeze('Ładowanie...');
     } else {
-      this.parent.unfreeze();
+      this.unfreeze();
     }
   },
 
@@ -102,8 +102,7 @@ var ImageGalleryView = View.extend({
     $page.hide();
     $('img', $page).unbind();
     
-    $page.empty();
-    
+    $page.empty();    
     this.setPageViewOffset($page, {x:0, y:0});
   },
 
@@ -183,7 +182,11 @@ var ImageGalleryView = View.extend({
           offset.y = vp_height-MARGIN;               
       
       $page.css({left: offset.x, top: offset.y});           
-  }, 
+  },
+
+  reload: function() {
+    this.model.load(true);
+  },
   
   renderImage: function(target) 
   {
index f55f4ec..151ffa6 100644 (file)
@@ -50,7 +50,7 @@
                        <% for (panel in panels) { %>
                        <option value="<%= panel %>"><%= panel %></option>
                        <% }; %>
-               </select> <button class="refresh">{% trans "Refresh panel" noop %}</button></p>
+               </select> <button class="refresh">{% trans "Refresh panel"  %}</button></p>
                 </div>
                <div class="content-view"></div>
        </script>
@@ -64,7 +64,7 @@
        
        <script type="text/html" charset="utf-8" id="html-view-template">
                 <div class="htmlview-toolbar">
-                    <a class="html-print-link" href="print" ui:baseref="{% url file_print fileid %}" target="_new">{% trans "Print version" noop %}</a>
+                    <a class="html-print-link" href="print" ui:baseref="{% url file_print fileid %}" target="_new">{% trans "Print version"  %}</a>
                 </div>
                 
                <div class="htmlview">
 
 
         <button type="button" class="image-gallery-next-button">
-        <img alt="{% trans 'Next page' noop %}" src="{{STATIC_URL}}/icons/go-next.png" width="16" height="16" />
+        <img alt="{% trans 'Next page'  %}" src="{{STATIC_URL}}/icons/go-next.png" width="16" height="16" />
         </button>
 
         <button type="button" class="image-gallery-zoom-in">
-            <img alt="{% trans 'Zoom in' noop %}" src="{{STATIC_URL}}/icons/zoom_in.png" width="16" height="16" />
+            <img alt="{% trans 'Zoom in'  %}" src="{{STATIC_URL}}/icons/zoom_in.png" width="16" height="16" />
         </button>
         <button type="button" class="image-gallery-zoom-out">
-            <img alt="{% trans 'Zoom out' noop %}" src="{{STATIC_URL}}/icons/zoom_out.png" width="16" height="16" />
+            <img alt="{% trans 'Zoom out'  %}" src="{{STATIC_URL}}/icons/zoom_out.png" width="16" height="16" />
         </button>
         <button type="button" class="image-gallery-zoom-reset">
-            <img alt="{% trans 'Reset zoom' noop %}" src="{{STATIC_URL}}/icons/zoom.png" width="16" height="16" />
+            <img alt="{% trans 'Reset zoom'  %}" src="{{STATIC_URL}}/icons/zoom.png" width="16" height="16" />
         </button>
         </p>
         </div>
 {% block breadcrumbs %}<a href="{% url file_list %}">Platforma</a> &gt; {{euser}} &gt; {{ fileid }}{% endblock breadcrumbs %}
 
 {% block header-toolbar %}
-    <a href="http://stigma.nowoczesnapolska.org.pl/platforma-hg/ksiazki/log/tip/{{ fileid }}.xml" target="_new" >{% trans 'History' noop %}</a>
-       <button id="action-merge">{% trans 'Push' noop %}</button>
-        <button id="action-update">{% trans 'Pull' noop %}</button>
-        <button id="action-commit">{% trans 'Save' noop %}</button>
-        <button id="action-quick-save">{% trans 'Quick save' noop %}</button>
+    <a href="http://stigma.nowoczesnapolska.org.pl/platforma-hg/ksiazki/log/tip/{{ fileid }}.xml" target="_new" >{% trans 'History'  %}</a>
+       <button id="action-merge">{% trans 'Push' %}</button>
+        <button id="action-update">{% trans 'Pull' %}</button>
+        <button id="action-commit">{% trans 'Save' %}</button>
+        <button id="action-quick-save">{% trans 'Quick save' %}</button>
 {% endblock %}
 
 {% block maincontent %}    
index 19c9c12..560ae72 100644 (file)
@@ -2,10 +2,10 @@
 
 {% if user.is_authenticated %}
 <span class="user_name">{{ user.username }}</span> | 
-<a href='{% url logout %}?next={{request.get_full_path}}'>{% trans "Log Out" noop %}</a>
+<a href='{% url logout %}?next={{request.get_full_path}}'>{% trans "Log Out" %}</a>
 {% else %}
 {% url login as login_url %}
 {% ifnotequal login_url request.path %}
-    <a href='{{ login_url }}?next={{request.get_full_path}}'>{% trans "Log In" noop %}</a>
+    <a href='{{ login_url }}?next={{request.get_full_path}}'>{% trans "Log In" %}</a>
 {% endifnotequal %}
 {% endif %}