From 317112df0a3aa6652f867da0fd8b7de504156e2b Mon Sep 17 00:00:00 2001 From: zuber Date: Wed, 20 Jan 2010 18:03:42 +0100 Subject: [PATCH] =?utf8?q?Usuni=C4=99cie=20aplikacji=20explorer.?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- apps/explorer/__init__.py | 0 apps/explorer/admin.py | 14 -- apps/explorer/context_processors.py | 11 -- apps/explorer/fields.py | 62 --------- apps/explorer/fixtures/explorer.xml | 2 - apps/explorer/forms.py | 126 ----------------- apps/explorer/middleware.py | 42 ------ apps/explorer/models.py | 71 ---------- apps/explorer/templatetags/__init__.py | 0 apps/explorer/templatetags/explorer_tags.py | 16 --- apps/explorer/views.py | 144 -------------------- apps/wiki/views.py | 15 +- platforma/settings.py | 13 +- platforma/urls.py | 18 +-- 14 files changed, 26 insertions(+), 508 deletions(-) delete mode 100644 apps/explorer/__init__.py delete mode 100644 apps/explorer/admin.py delete mode 100755 apps/explorer/context_processors.py delete mode 100644 apps/explorer/fields.py delete mode 100644 apps/explorer/fixtures/explorer.xml delete mode 100644 apps/explorer/forms.py delete mode 100644 apps/explorer/middleware.py delete mode 100644 apps/explorer/models.py delete mode 100755 apps/explorer/templatetags/__init__.py delete mode 100755 apps/explorer/templatetags/explorer_tags.py delete mode 100755 apps/explorer/views.py diff --git a/apps/explorer/__init__.py b/apps/explorer/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/apps/explorer/admin.py b/apps/explorer/admin.py deleted file mode 100644 index dd765f59..00000000 --- a/apps/explorer/admin.py +++ /dev/null @@ -1,14 +0,0 @@ -from django.contrib import admin - -import explorer.models -from explorer import forms - -admin.site.register(explorer.models.EditorSettings) -admin.site.register(explorer.models.EditorPanel) - -class GalleryAdmin(admin.ModelAdmin): - form = forms.GalleryChoiceForm - list_display = ('document', 'subpath',) - search_fields = ('document', 'subpath',) - -admin.site.register(explorer.models.GalleryForDocument, GalleryAdmin) \ No newline at end of file diff --git a/apps/explorer/context_processors.py b/apps/explorer/context_processors.py deleted file mode 100755 index eff3032c..00000000 --- a/apps/explorer/context_processors.py +++ /dev/null @@ -1,11 +0,0 @@ -# -*- coding: utf-8 -__author__="lreqc" -__date__ ="$2009-09-03 08:34:10$" - -def settings(request): - from django.conf import settings - return {'MEDIA_URL': settings.MEDIA_URL, - 'STATIC_URL': settings.STATIC_URL, - 'REDMINE_URL': settings.REDMINE_URL } - - diff --git a/apps/explorer/fields.py b/apps/explorer/fields.py deleted file mode 100644 index 5d03e68d..00000000 --- a/apps/explorer/fields.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -import datetime - -from django.conf import settings -from django.db import models -from django import forms -from django.utils import simplejson as json - - -class JSONEncoder(json.JSONEncoder): - def default(self, obj): - if isinstance(obj, datetime.datetime): - return obj.strftime('%Y-%m-%dT%H:%M:%S') - elif isinstance(obj, datetime.date): - return obj.strftime('%Y-%m-%d') - elif isinstance(obj, datetime.time): - return obj.strftime('%H:%M:%S') - return json.JSONEncoder.default(self, obj) - - -def dumps(data): - return JSONEncoder().encode(data) - - -def loads(str): - return json.loads(str, encoding=settings.DEFAULT_CHARSET) - - -class JSONFormField(forms.CharField): - widget = forms.Textarea - - def clean(self, value): - try: - loads(value) - return value - except ValueError, e: - raise forms.ValidationError('Enter a valid JSON value. Error: %s' % e) - - -class JSONField(models.TextField): - def formfield(self, **kwargs): - defaults = {'form_class': JSONFormField} - defaults.update(kwargs) - return super(JSONField, self).formfield(**defaults) - - def db_type(self): - return 'text' - - def get_internal_type(self): - return 'TextField' - - def contribute_to_class(self, cls, name): - super(JSONField, self).contribute_to_class(cls, name) - - def get_value(model_instance): - return loads(getattr(model_instance, self.attname, None)) - setattr(cls, 'get_%s_value' % self.name, get_value) - - def set_value(model_instance, json): - return setattr(model_instance, self.attname, dumps(json)) - setattr(cls, 'set_%s_value' % self.name, set_value) - diff --git a/apps/explorer/fixtures/explorer.xml b/apps/explorer/fixtures/explorer.xml deleted file mode 100644 index 3600bd76..00000000 --- a/apps/explorer/fixtures/explorer.xml +++ /dev/null @@ -1,2 +0,0 @@ - -1{"lastUpdate": 1252490221.4749999, "panels": [{"ratio": 0.484375, "name": "xmleditor"}, {"ratio": 0.515625, "name": "htmleditor"}]}Edytor HTML24Edytor XML23Dublin CoreGaleria diff --git a/apps/explorer/forms.py b/apps/explorer/forms.py deleted file mode 100644 index 33585bce..00000000 --- a/apps/explorer/forms.py +++ /dev/null @@ -1,126 +0,0 @@ -# -*- coding: utf-8 -*- -import os -from librarian import dcparser - -from django import forms -from django.conf import settings -import django.utils - -from explorer import models - - -class PersonField(forms.CharField): - def clean(self, value): - try: - return dcparser.Person.from_text( super(PersonField, self).clean(value) ) - except ValueError, e: - raise django.utils.ValidationError(e.message) - -def person_conv(value): - if isinstance(value, dcparser.Person): - return value - elif isinstance(value, basestring): - return dcparser.Person.from_text( unicode(value) ) - else: - raise ValueError("Can't convert '%s' to Person object." % value) - -class ListField(forms.Field): - def __init__(self, *args, **kwargs): - self.convert = kwargs.pop('converter', unicode) - if not kwargs.has_key('widget'): - kwargs['widget'] = forms.Textarea - super(ListField, self).__init__(*args, **kwargs) - - def _get_initial(self): - return self._initial and (u'\n'.join( ( unicode(person) for person in self._initial))) - - def _set_initial(self, value): - if value is None: - self._initial = None - elif isinstance(value, list): - self._initial = [ self.convert(e) for e in value ] - elif isinstance(value, basestring): - self._initial = [ self.convert(e) for e in value.split('\n') ] - else: - raise ValueError("Invalid value. Must be a list of dcparser.Person or string") - - initial = property(_get_initial, _set_initial) - - def clean(self, value): - super(ListField, self).clean(value) - elems = value.split('\n') - try: - return [self.convert(el) for el in elems] - except ValueError, err: - raise django.utils.ValidationError(err.message) - -class BookForm(forms.Form): - content = forms.CharField(widget=forms.Textarea) - commit_message = forms.CharField(required=False) - -class MergeForm(forms.Form): - message = forms.CharField(error_messages={'required': 'Please write a merge description.'}) - -class BookUploadForm(forms.Form): - file = forms.FileField(label='Source OCR file') - bookname = forms.RegexField(regex=r'[0-9\.\w_-]+', \ - label='Publication name', help_text='Example: slowacki-beniowski') - autoxml = forms.BooleanField(required=False, initial=True, label=u"Generate DublinCore template") - -class ImageFoldersForm(forms.Form): - folders = forms.ChoiceField(required=False) - - def __init__(self, *args, **kwargs): - super(ImageFoldersForm, self).__init__(*args, **kwargs) - 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_-]+', \ - label='Part name', help_text='Example: rozdział-2') - 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 GalleryChoiceForm(forms.ModelForm): - subpath = forms.ChoiceField(choices=()) - - def __init__(self, *args, **kwargs): - super(GalleryChoiceForm, self).__init__(*args, **kwargs) - self.fields['subpath'].choices = [(settings.IMAGE_DIR + '/' + x, x) for x in os.listdir(settings.MEDIA_ROOT + settings.IMAGE_DIR)] - - class Meta: - model = models.GalleryForDocument - fields = ('document', 'subpath',) - -class DublinCoreForm(forms.Form): - about = forms.URLField(verify_exists=False) - author = PersonField() - title = forms.CharField() - epochs = ListField() - kinds = ListField() - genres = ListField() - created_at = forms.DateField() - released_to_public_domain_at = forms.DateField(required=False) - editors = ListField(widget=forms.Textarea, required=False, converter=person_conv) - translators = ListField(widget=forms.Textarea, required=False, converter=person_conv) - technical_editors = ListField(widget=forms.Textarea, required=False, converter=person_conv) - publisher = forms.CharField() - source_name = forms.CharField(widget=forms.Textarea, required=False) - source_url = forms.URLField(verify_exists=False, required=False) - url = forms.URLField(verify_exists=False) - parts = ListField(required=False) - license = forms.CharField(required=False) - license_description = forms.CharField(widget=forms.Textarea, required=False) - - commit_message = forms.CharField(required=False, widget=forms.HiddenInput) - - def __init__(self, *args, **kwargs): - info = kwargs.pop('info', None) - super(DublinCoreForm, self).__init__(*args, **kwargs) - - if isinstance(info, dcparser.BookInfo): - vdict = info.to_dict() - for name in self.fields.keys(): - if vdict.has_key(name): - self.fields[name].initial = vdict[name] - diff --git a/apps/explorer/middleware.py b/apps/explorer/middleware.py deleted file mode 100644 index 018f1aae..00000000 --- a/apps/explorer/middleware.py +++ /dev/null @@ -1,42 +0,0 @@ -import urllib - -from django.conf import settings -from django.utils import simplejson - -from explorer import models - - -EDITOR_DEFAULT_SETTINGS_JSON = simplejson.dumps(settings.EDITOR_DEFAULT_SETTINGS) - - -class EditorSettingsMiddleware(object): - def process_request(self, request): - if request.user.is_anonymous(): - return - cookie_settings = request.COOKIES.get(settings.EDITOR_COOKIE_NAME, EDITOR_DEFAULT_SETTINGS_JSON) - - cookie_settings = simplejson.loads(urllib.unquote(cookie_settings)) - last_update = cookie_settings.get('lastUpdate', 0) - cookie_settings['lastUpdate'] = last_update - - try: - editor_settings = models.EditorSettings.objects.get(user=request.user) - except models.EditorSettings.DoesNotExist: - editor_settings = models.EditorSettings(user=request.user) - editor_settings.set_settings_value(cookie_settings) - editor_settings.save() - - # print editor_settings.get_settings_value()['lastUpdate'], '<>', last_update - if editor_settings.get_settings_value()['lastUpdate'] < last_update: - editor_settings.set_settings_value(cookie_settings) - editor_settings.save() - - request.editor_settings = editor_settings - - - def process_response(self, request, response): - if hasattr(request, 'editor_settings'): - response.set_cookie(settings.EDITOR_COOKIE_NAME, - urllib.quote(request.editor_settings.settings), max_age=7 * 60 * 60 * 24, path='/') - - return response diff --git a/apps/explorer/models.py b/apps/explorer/models.py deleted file mode 100644 index e104cda6..00000000 --- a/apps/explorer/models.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- encoding: utf-8 -*- -import os - -from django.db import models -from django.contrib.auth.models import User -from django.conf import settings -from django.utils.translation import gettext_lazy as _ - -import toolbar.models - -from explorer import fields - -class EditorSettings(models.Model): - """Ustawienia edytora dla użytkownika. - - Pole settings zawiera obiekt JSON o kluczach: - - panels - lista otwartych paneli i ich proporcje - - recentFiles - lista otwartych plików i ustawienia dla nich - - Przykład: - { - 'panels': [ - {'name': 'htmleditor', - 'ratio': 0.5}, - {'name': 'gallery', 'ratio': 0.5} - ], - 'recentFiles': [ - { - 'fileId': 'mickiewicz_pan_tadeusz.xml', - 'panels': [ - {'name': 'htmleditor', 'ratio': 0.4}, - {'name': 'gallery', 'ratio': 0.6} - ] - } - ] - } - """ - user = models.ForeignKey(User, unique=True) - settings = fields.JSONField() - - class Meta: - verbose_name, verbose_name_plural = _("editor settings"), _("editor settings") - - def __unicode__(self): - return u"Editor settings for %s" % self.user.username - -class EditorPanel(models.Model): - id = models.CharField(max_length=24, primary_key=True) - display_name = models.CharField(max_length=128) - - toolbar_groups = models.ManyToManyField(toolbar.models.ButtonGroup, blank=True) - toolbar_extra = models.ForeignKey(toolbar.models.ButtonGroup, null=True, blank=True, - unique=True, related_name='main_editor_panels') - - def __unicode__(self): - return self.display_name - - -# Yes, this is intentionally unnormalized ! -class GalleryForDocument(models.Model): - name = models.CharField(max_length=100, blank=True) - - # document associated with the gallery - document = models.CharField(max_length=255, unique=True) - - # directory containing scans under MEDIA_ROOT/ - subpath = models.CharField(max_length=255) - - def __unicode__(self): - return u"%s:%s" % (self.subpath, self.document) - diff --git a/apps/explorer/templatetags/__init__.py b/apps/explorer/templatetags/__init__.py deleted file mode 100755 index e69de29b..00000000 diff --git a/apps/explorer/templatetags/explorer_tags.py b/apps/explorer/templatetags/explorer_tags.py deleted file mode 100755 index 98af0136..00000000 --- a/apps/explorer/templatetags/explorer_tags.py +++ /dev/null @@ -1,16 +0,0 @@ -from django import template -# from toolbar import models -register = template.Library() - -from django.template.defaultfilters import stringfilter - -@register.filter(name='bookname') -@stringfilter -def bookname(fileid): - return ', '.join(\ - ' '.join(s.capitalize() for s in part.split('_'))\ - for part in fileid.split('$')) - -@register.inclusion_tag('explorer/file_tree_part.html') -def tree_part(document): - return {'document': document} \ No newline at end of file diff --git a/apps/explorer/views.py b/apps/explorer/views.py deleted file mode 100755 index c1ada7a5..00000000 --- a/apps/explorer/views.py +++ /dev/null @@ -1,144 +0,0 @@ -# -*- coding: utf-8 -*- -import urllib2 - -import logging -log = logging.getLogger('platforma.explorer.views') - -from django.conf import settings -from django.contrib.auth.decorators import login_required, permission_required - -from django.core.urlresolvers import reverse -from django.http import HttpResponse, Http404 -from django.utils import simplejson as json -from django.views.generic.simple import direct_to_template -from django.shortcuts import render_to_response -from django.template import RequestContext -from django.contrib.auth.decorators import login_required - -from explorer import forms, models -import os -# from api.models import PullRequest -from bookthemes.models import Theme - -def ajax_login_required(view): - """Similar ro @login_required, but instead of redirect, - just return some JSON stuff with error.""" - def view_with_auth(request, *args, **kwargs): - if request.user.is_authenticated(): - return view(request, *args, **kwargs) - # not authenticated - return HttpResponse( json.dumps({'result': 'access_denied', 'errors': ['Brak dostępu.']}) ); - return view_with_auth - -@login_required -def display_editor(request, path): - user = request.GET.get('user', request.user.username) - gallery_form = forms.GalleryChoiceForm() - - return render_to_response('explorer/editor.html', - # mimetype="text/html", - dictionary = { - 'fileid': path, - 'euser': user, - 'gallery_form': gallery_form, - 'available_themes': ({'first_letter': t.name[0].upper(), 'name': t.name} for t in Theme.objects.order_by('name')), - }, context_instance=RequestContext(request)) - -# -# View all files -# -def file_list(request): - from wiki.views import document_list - - # short-circut the api document list - # doctree = library_resource.handler.read(request) - # print "DOCTREE:", doctree['documents'] - - return document_list(request, 'explorer/file_list.html') - - # return direct_to_template(request, 'explorer/file_list.html', extra_context={ - # 'files': files, 'bookform': bookform, - # }) - -@permission_required('api.document.can_add') -def file_upload(request): - from api.resources import library_resource - from api.forms import DocumentUploadForm - from django.http import HttpRequest, HttpResponseRedirect - - response = library_resource.handler.create(request) - - if isinstance(response, HttpResponse): - data = json.loads(response.content) - - if response.status_code == 201: - return HttpResponseRedirect( \ - reverse("editor_view", args=[ data['name'] ]) ) - else: - bookform = DocumentUploadForm(request.POST, request.FILES) - bookform.is_valid() - - return direct_to_template(request, 'explorer/file_upload.html', - extra_context={'bookform': bookform } ) - - -@login_required -def print_html(request, **kwargs): - from api.resources import document_html_resource - - kwargs['stylesheet'] = 'legacy' - - output = document_html_resource.handler.read(request, **kwargs) - - if isinstance(output, HttpResponse): - # errors = json.loads(output.content) - output.mimetype = "text/plain" - return output - - return direct_to_template(request, 'html4print.html', - extra_context={'output': output, 'docid': kwargs['docid']}, - mimetype="text/html" ) - - -def _add_references(message, issues): - return message + " - " + ", ".join(map(lambda issue: "Refs #%d" % issue['id'], issues)) - -def _get_issues_for_file(fileid): - uf = None - try: - 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): - objects = PullRequest.objects.order_by('-status', 'timestamp') - - if not request.user.has_perm('explorer.book.can_share'): - objects = objects.filter(comitter=request.user) - - return direct_to_template(request, 'manager/pull_request.html', - extra_context = {'objects': objects} ) - - -# -# Testing -# -def renderer_test(request): - return direct_to_template(request, 'renderer.html', mimetype="text/html", - extra_context = {} ) - - -def document_gallery(request, directory): - try: - base_dir = os.path.join(settings.MEDIA_ROOT, settings.FILEBROWSER_DIRECTORY, directory) - print base_dir - images = ['%s%s%s/%s' % (settings.MEDIA_URL, settings.FILEBROWSER_DIRECTORY, directory, f) for f in os.listdir(base_dir) if os.path.splitext(f)[1].lower() in ('.jpg', '.jpeg', '.png')] - return HttpResponse(json.dumps(images)) - except (IndexError, OSError), e: - raise Http404 diff --git a/apps/wiki/views.py b/apps/wiki/views.py index 9a156a4c..ec43deea 100644 --- a/apps/wiki/views.py +++ b/apps/wiki/views.py @@ -1,5 +1,8 @@ +import os + +from django.conf import settings from django.views.generic.simple import direct_to_template -from django.http import HttpResponse +from django.http import HttpResponse, Http404 from django.utils import simplejson as json from wiki.models import storage, Document, DocumentNotFound @@ -33,3 +36,13 @@ def document_detail(request, name, template_name='wiki/document_details.html'): 'document': document, 'form': form, }) + + +def document_gallery(request, directory): + try: + base_dir = os.path.join(settings.MEDIA_ROOT, settings.FILEBROWSER_DIRECTORY, directory) + print base_dir + images = ['%s%s%s/%s' % (settings.MEDIA_URL, settings.FILEBROWSER_DIRECTORY, directory, f) for f in os.listdir(base_dir) if os.path.splitext(f)[1].lower() in ('.jpg', '.jpeg', '.png')] + return HttpResponse(json.dumps(images)) + except (IndexError, OSError), e: + raise Http404 diff --git a/platforma/settings.py b/platforma/settings.py index 19c53210..4aa2fb2f 100755 --- a/platforma/settings.py +++ b/platforma/settings.py @@ -70,7 +70,7 @@ TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", - "explorer.context_processors.settings", + "platforma.context_processors.settings", "django.core.context_processors.request", ) @@ -79,9 +79,7 @@ MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'explorer.middleware.EditorSettingsMiddleware', 'django.middleware.doc.XViewMiddleware', - 'maintenancemode.middleware.MaintenanceModeMiddleware', ) @@ -121,7 +119,7 @@ INSTALLED_APPS = ( 'piston', 'sorl.thumbnail', 'filebrowser', - 'explorer', + # 'explorer', 'toolbar', 'bookthemes', # 'api', @@ -135,13 +133,6 @@ FILEBROWSER_VERSIONS_BASEDIR = 'thumbnails/' # REPOSITORY_PATH = '/Users/zuber/Projekty/platforma/files/books' IMAGE_DIR = 'images' -EDITOR_COOKIE_NAME = 'options' -EDITOR_DEFAULT_SETTINGS = { - 'panels': [ - {'name': 'htmleditor', 'ratio': 0.5}, - {'name': 'gallery', 'ratio': 0.5} - ], -} # Python logging settings import logging diff --git a/platforma/urls.py b/platforma/urls.py index 8100a182..8d58e0e6 100755 --- a/platforma/urls.py +++ b/platforma/urls.py @@ -10,29 +10,31 @@ PATH_END = PATH_SEC + "/$" urlpatterns = patterns('', # Explorer: - url(r'^$', 'explorer.views.file_list', name='file_list'), - url(r'^file/upload', 'explorer.views.file_upload', name='file_upload'), + # url(r'^$', 'explorer.views.file_list', name='file_list'), + # url(r'^file/upload', 'explorer.views.file_upload', name='file_upload'), - url(r'^management/pull-requests$', 'explorer.views.pull_requests'), + # url(r'^management/pull-requests$', 'explorer.views.pull_requests'), # Editor panels - url(r'^editor/'+PATH_END, 'explorer.views.display_editor', name='editor_view'), - url(r'^editor/$', 'explorer.views.file_list', name='editor_base'), + # url(r'^editor/'+PATH_END, 'explorer.views.display_editor', name='editor_view'), + # url(r'^editor/$', 'explorer.views.file_list', name='editor_base'), - url(r'^file/(?P[^/]+)/print$', 'explorer.views.print_html', name="file_print"), + # url(r'^file/(?P[^/]+)/print$', 'explorer.views.print_html', name="file_print"), + url(r'^$', 'wiki.views.document_list', {'template_name': 'explorer/file_list.html'}), + # Admin panel (r'^admin/filebrowser/', include('filebrowser.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/(.*)', admin.site.root), # Theme database - url(r'themes/', include('bookthemes.urls')), + # url(r'themes/', include('bookthemes.urls')), # Our über-restful api # url(r'^api/', include('api.urls')), - url(r'^gallery/(?P[^/]+)$', 'explorer.views.document_gallery'), + url(r'^gallery/(?P[^/]+)$', 'wiki.views.document_gallery'), # Static files (should be served by Apache) url(r'^%s(?P.+)$' % settings.MEDIA_URL[1:], 'django.views.static.serve', -- 2.20.1