Fix dictionary auto-tagging
[redakcja.git] / apps / filebrowser / views.py
index b507a75..6c1c92d 100644 (file)
@@ -1,8 +1,7 @@
 # coding: utf-8
 
 # general imports
 # coding: utf-8
 
 # general imports
-import os, re, locale
-from time import gmtime, strftime
+import re
 
 # django imports
 from django.shortcuts import render_to_response, HttpResponse
 
 # django imports
 from django.shortcuts import render_to_response, HttpResponse
@@ -16,20 +15,27 @@ from django import forms
 from django.core.urlresolvers import reverse
 from django.core.exceptions import ImproperlyConfigured
 from django.dispatch import Signal
 from django.core.urlresolvers import reverse
 from django.core.exceptions import ImproperlyConfigured
 from django.dispatch import Signal
+from django.views.decorators.csrf import csrf_exempt
 
 
-from django.utils.encoding import smart_unicode
+from django.utils.encoding import smart_unicode, smart_str
 
 # filebrowser imports
 from filebrowser.fb_settings import *
 
 # filebrowser imports
 from filebrowser.fb_settings import *
-from filebrowser.functions import _url_to_path, _path_to_url, _get_path, _get_file, _get_version_path, _get_breadcrumbs, _get_filterdate, _get_settings_var, _handle_file_upload, _get_file_type, _url_join, _convert_filename
+
+from filebrowser.functions import (
+        _url_to_path, _path_to_url, _get_path, _get_file, _get_version_path,
+        _get_breadcrumbs, _get_filterdate, _get_settings_var, _handle_file_upload,
+        _get_file_type, _url_join, _convert_filename)
+
 from filebrowser.templatetags.fb_tags import query_helper
 from filebrowser.base import FileObject
 from filebrowser.decorators import flash_login_required
 
 # Precompile regular expressions
 filter_re = []
 from filebrowser.templatetags.fb_tags import query_helper
 from filebrowser.base import FileObject
 from filebrowser.decorators import flash_login_required
 
 # Precompile regular expressions
 filter_re = []
+
 for exp in EXCLUDE:
 for exp in EXCLUDE:
-   filter_re.append(re.compile(exp))
+    filter_re.append(re.compile(exp))
 for k, v in VERSIONS.iteritems():
     exp = (r'_%s.(%s)') % (k, '|'.join(EXTENSION_LIST))
     filter_re.append(re.compile(exp))
 for k, v in VERSIONS.iteritems():
     exp = (r'_%s.(%s)') % (k, '|'.join(EXTENSION_LIST))
     filter_re.append(re.compile(exp))
@@ -47,25 +53,25 @@ def browse(request):
 
     if path is None:
         msg = _('Directory/File does not exist.')
 
     if path is None:
         msg = _('Directory/File does not exist.')
-        request.user.message_set.create(message = msg)
+        request.user.message_set.create(message=msg)
         if directory is None:
             # The DIRECTORY does not exist, raise an error to prevent eternal redirecting.
         if directory is None:
             # The DIRECTORY does not exist, raise an error to prevent eternal redirecting.
-            raise ImproperlyConfigured, _("Error finding upload directory. Maybe it does not exist?")
+            raise ImproperlyConfigured(_("Error finding upload directory: %s. Maybe it does not exist?" % os.path.join(MEDIA_ROOT, DIRECTORY)))
         redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
         return HttpResponseRedirect(redirect_url)
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
 
     # INITIAL VARIABLES
         redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
         return HttpResponseRedirect(redirect_url)
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
 
     # INITIAL VARIABLES
-    results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0 }
+    results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0}
     counter = {}
     for k, v in EXTENSIONS.iteritems():
         counter[k] = 0
 
     dir_list = os.listdir(abs_path)
     files = []
     counter = {}
     for k, v in EXTENSIONS.iteritems():
         counter[k] = 0
 
     dir_list = os.listdir(abs_path)
     files = []
-    print "LISTING FILES: ", dir_list
+    print "LISTING FILES: ", dir_list
     for file in dir_list:
     for file in dir_list:
-        print repr(file)
+        print repr(file)
         # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
         filtered = file.startswith('.')
         for re_prefix in filter_re:
         # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
         filtered = file.startswith('.')
         for re_prefix in filter_re:
@@ -76,7 +82,7 @@ def browse(request):
         results_var['results_total'] += 1
 
         # CREATE FILEOBJECT
         results_var['results_total'] += 1
 
         # CREATE FILEOBJECT
-        fileobject = FileObject(os.path.join(DIRECTORY, path, file))
+        fileobject = FileObject(os.path.join(smart_str(DIRECTORY), smart_str(path), smart_str(file)))
 
         # FILTER / SEARCH
         append = False
 
         # FILTER / SEARCH
         append = False
@@ -106,7 +112,7 @@ def browse(request):
             counter[fileobject.filetype] += 1
 
     # SORTING
             counter[fileobject.filetype] += 1
 
     # SORTING
-    files.sort(key = lambda e: getattr(e, request.GET.get('o', DEFAULT_ORDER)))
+    files.sort(key=lambda e: getattr(e, request.GET.get('o', DEFAULT_ORDER)))
     if request.GET.get('ot') == "desc":
         files.reverse()
 
     if request.GET.get('ot') == "desc":
         files.reverse()
 
@@ -119,13 +125,14 @@ def browse(request):
         'title': _(u'FileBrowser'),
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, path, ''),
         'title': _(u'FileBrowser'),
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, path, ''),
-    }, context_instance = Context(request))
+    }, context_instance=Context(request))
 browse = staff_member_required(never_cache(browse))
 
 
 # mkdir signals
 browse = staff_member_required(never_cache(browse))
 
 
 # mkdir signals
-filebrowser_pre_createdir = Signal(providing_args = ["path", "dirname"])
-filebrowser_post_createdir = Signal(providing_args = ["path", "dirname"])
+filebrowser_pre_createdir = Signal(providing_args=["path", "dirname"])
+filebrowser_post_createdir = Signal(providing_args=["path", "dirname"])
+
 
 def mkdir(request):
     """
 
 def mkdir(request):
     """
@@ -139,7 +146,7 @@ def mkdir(request):
     path = _get_path(query.get('dir', ''))
     if path is None:
         msg = _('Directory/File does not exist.')
     path = _get_path(query.get('dir', ''))
     if path is None:
         msg = _('Directory/File does not exist.')
-        request.user.message_set.create(message = msg)
+        request.user.message_set.create(message=msg)
         return HttpResponseRedirect(reverse("fb_browse"))
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
 
         return HttpResponseRedirect(reverse("fb_browse"))
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
 
@@ -149,15 +156,15 @@ def mkdir(request):
             server_path = os.path.join(abs_path, form.cleaned_data['dir_name'])
             try:
                 # PRE CREATE SIGNAL
             server_path = os.path.join(abs_path, form.cleaned_data['dir_name'])
             try:
                 # PRE CREATE SIGNAL
-                filebrowser_pre_createdir.send(sender = request, path = path, dirname = form.cleaned_data['dir_name'])
+                filebrowser_pre_createdir.send(sender=request, path=path, dirname=form.cleaned_data['dir_name'])
                 # CREATE FOLDER
                 os.mkdir(server_path)
                 os.chmod(server_path, 0775)
                 # POST CREATE SIGNAL
                 # CREATE FOLDER
                 os.mkdir(server_path)
                 os.chmod(server_path, 0775)
                 # POST CREATE SIGNAL
-                filebrowser_post_createdir.send(sender = request, path = path, dirname = form.cleaned_data['dir_name'])
+                filebrowser_post_createdir.send(sender=request, path=path, dirname=form.cleaned_data['dir_name'])
                 # MESSAGE & REDIRECT
                 msg = _('The Folder %s was successfully created.') % (form.cleaned_data['dir_name'])
                 # MESSAGE & REDIRECT
                 msg = _('The Folder %s was successfully created.') % (form.cleaned_data['dir_name'])
-                request.user.message_set.create(message = msg)
+                request.user.message_set.create(message=msg)
                 # on redirect, sort by date desc to see the new directory on top of the list
                 # remove filter in order to actually _see_ the new folder
                 redirect_url = reverse("fb_browse") + query_helper(query, "ot=desc,o=date", "ot,o,filter_type,filter_date,q")
                 # on redirect, sort by date desc to see the new directory on top of the list
                 # remove filter in order to actually _see_ the new folder
                 redirect_url = reverse("fb_browse") + query_helper(query, "ot=desc,o=date", "ot,o,filter_type,filter_date,q")
@@ -176,10 +183,11 @@ def mkdir(request):
         'title': _(u'New Folder'),
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, path, _(u'New Folder')),
         'title': _(u'New Folder'),
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, path, _(u'New Folder')),
-    }, context_instance = Context(request))
+    }, context_instance=Context(request))
 mkdir = staff_member_required(never_cache(mkdir))
 
 
 mkdir = staff_member_required(never_cache(mkdir))
 
 
+@csrf_exempt
 def upload(request):
     """
     Multipe File Upload.
 def upload(request):
     """
     Multipe File Upload.
@@ -192,7 +200,7 @@ def upload(request):
     path = _get_path(query.get('dir', ''))
     if path is None:
         msg = _('Directory/File does not exist.')
     path = _get_path(query.get('dir', ''))
     if path is None:
         msg = _('Directory/File does not exist.')
-        request.user.message_set.create(message = msg)
+        request.user.message_set.create(message=msg)
         return HttpResponseRedirect(reverse("fb_browse"))
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
 
         return HttpResponseRedirect(reverse("fb_browse"))
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
 
@@ -207,10 +215,11 @@ def upload(request):
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, path, _(u'Upload')),
         'session_key': session_key,
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, path, _(u'Upload')),
         'session_key': session_key,
-    }, context_instance = Context(request))
+    }, context_instance=Context(request))
 upload = staff_member_required(never_cache(upload))
 
 
 upload = staff_member_required(never_cache(upload))
 
 
+@csrf_exempt
 def _check_file(request):
     """
     Check if file already exists on the server.
 def _check_file(request):
     """
     Check if file already exists on the server.
@@ -234,8 +243,9 @@ def _check_file(request):
 
 
 # upload signals
 
 
 # upload signals
-filebrowser_pre_upload = Signal(providing_args = ["path", "file"])
-filebrowser_post_upload = Signal(providing_args = ["path", "file"])
+filebrowser_pre_upload = Signal(providing_args=["path", "file"])
+filebrowser_post_upload = Signal(providing_args=["path", "file"])
+
 
 def _upload_file(request):
     """
 
 def _upload_file(request):
     """
@@ -253,7 +263,7 @@ def _upload_file(request):
             filedata = request.FILES['Filedata']
             filedata.name = _convert_filename(filedata.name)
             # PRE UPLOAD SIGNAL
             filedata = request.FILES['Filedata']
             filedata.name = _convert_filename(filedata.name)
             # PRE UPLOAD SIGNAL
-            filebrowser_pre_upload.send(sender = request, path = request.POST.get('folder'), file = filedata)
+            filebrowser_pre_upload.send(sender=request, path=request.POST.get('folder'), file=filedata)
             # HANDLE UPLOAD
             uploadedfile = _handle_file_upload(abs_path, filedata)
             # MOVE UPLOADED FILE
             # HANDLE UPLOAD
             uploadedfile = _handle_file_upload(abs_path, filedata)
             # MOVE UPLOADED FILE
@@ -263,19 +273,20 @@ def _upload_file(request):
                 new_file = os.path.join(abs_path, uploadedfile)
                 file_move_safe(new_file, old_file)
             # POST UPLOAD SIGNAL
                 new_file = os.path.join(abs_path, uploadedfile)
                 file_move_safe(new_file, old_file)
             # POST UPLOAD SIGNAL
-            filebrowser_post_upload.send(sender = request, path = request.POST.get('folder'), file = FileObject(os.path.join(DIRECTORY, folder, filedata.name)))
+            filebrowser_post_upload.send(sender=request, path=request.POST.get('folder'), file=FileObject(os.path.join(DIRECTORY, folder, filedata.name)))
     return HttpResponse('True')
     return HttpResponse('True')
-_upload_file = flash_login_required(_upload_file)
+_upload_file = csrf_exempt(flash_login_required(_upload_file))
 
 
 # delete signals
 
 
 # delete signals
-filebrowser_pre_delete = Signal(providing_args = ["path", "filename"])
-filebrowser_post_delete = Signal(providing_args = ["path", "filename"])
+filebrowser_pre_delete = Signal(providing_args=["path", "filename"])
+filebrowser_post_delete = Signal(providing_args=["path", "filename"])
+
 
 def delete(request):
     """
     Delete existing File/Directory.
 
 def delete(request):
     """
     Delete existing File/Directory.
-    
+
     When trying to delete a Directory, the Directory has to be empty.
     """
 
     When trying to delete a Directory, the Directory has to be empty.
     """
 
@@ -285,7 +296,7 @@ def delete(request):
     filename = _get_file(query.get('dir', ''), query.get('filename', ''))
     if path is None or filename is None:
         msg = _('Directory/File does not exist.')
     filename = _get_file(query.get('dir', ''), query.get('filename', ''))
     if path is None or filename is None:
         msg = _('Directory/File does not exist.')
-        request.user.message_set.create(message = msg)
+        request.user.message_set.create(message=msg)
         return HttpResponseRedirect(reverse("fb_browse"))
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
 
         return HttpResponseRedirect(reverse("fb_browse"))
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
 
@@ -295,7 +306,7 @@ def delete(request):
             relative_server_path = os.path.join(DIRECTORY, path, filename)
             try:
                 # PRE DELETE SIGNAL
             relative_server_path = os.path.join(DIRECTORY, path, filename)
             try:
                 # PRE DELETE SIGNAL
-                filebrowser_pre_delete.send(sender = request, path = path, filename = filename)
+                filebrowser_pre_delete.send(sender=request, path=path, filename=filename)
                 # DELETE IMAGE VERSIONS/THUMBNAILS
                 for version in VERSIONS:
                     try:
                 # DELETE IMAGE VERSIONS/THUMBNAILS
                 for version in VERSIONS:
                     try:
@@ -305,10 +316,10 @@ def delete(request):
                 # DELETE FILE
                 os.unlink(os.path.join(abs_path, filename))
                 # POST DELETE SIGNAL
                 # DELETE FILE
                 os.unlink(os.path.join(abs_path, filename))
                 # POST DELETE SIGNAL
-                filebrowser_post_delete.send(sender = request, path = path, filename = filename)
+                filebrowser_post_delete.send(sender=request, path=path, filename=filename)
                 # MESSAGE & REDIRECT
                 msg = _('The file %s was successfully deleted.') % (filename.lower())
                 # MESSAGE & REDIRECT
                 msg = _('The file %s was successfully deleted.') % (filename.lower())
-                request.user.message_set.create(message = msg)
+                request.user.message_set.create(message=msg)
                 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype")
                 return HttpResponseRedirect(redirect_url)
             except OSError:
                 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype")
                 return HttpResponseRedirect(redirect_url)
             except OSError:
@@ -317,14 +328,14 @@ def delete(request):
         else:
             try:
                 # PRE DELETE SIGNAL
         else:
             try:
                 # PRE DELETE SIGNAL
-                filebrowser_pre_delete.send(sender = request, path = path, filename = filename)
+                filebrowser_pre_delete.send(sender=request, path=path, filename=filename)
                 # DELETE FOLDER
                 os.rmdir(os.path.join(abs_path, filename))
                 # POST DELETE SIGNAL
                 # DELETE FOLDER
                 os.rmdir(os.path.join(abs_path, filename))
                 # POST DELETE SIGNAL
-                filebrowser_post_delete.send(sender = request, path = path, filename = filename)
+                filebrowser_post_delete.send(sender=request, path=path, filename=filename)
                 # MESSAGE & REDIRECT
                 msg = _('The directory %s was successfully deleted.') % (filename.lower())
                 # MESSAGE & REDIRECT
                 msg = _('The directory %s was successfully deleted.') % (filename.lower())
-                request.user.message_set.create(message = msg)
+                request.user.message_set.create(message=msg)
                 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype")
                 return HttpResponseRedirect(redirect_url)
             except OSError:
                 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype")
                 return HttpResponseRedirect(redirect_url)
             except OSError:
@@ -332,7 +343,7 @@ def delete(request):
                 msg = OSError
 
     if msg:
                 msg = OSError
 
     if msg:
-        request.user.message_set.create(message = msg)
+        request.user.message_set.create(message=msg)
 
     return render_to_response('filebrowser/index.html', {
         'dir': dir_name,
 
     return render_to_response('filebrowser/index.html', {
         'dir': dir_name,
@@ -340,18 +351,19 @@ def delete(request):
         'query': query,
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, dir_name, ''),
         'query': query,
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, dir_name, ''),
-    }, context_instance = Context(request))
+    }, context_instance=Context(request))
 delete = staff_member_required(never_cache(delete))
 
 
 # delete signals
 delete = staff_member_required(never_cache(delete))
 
 
 # delete signals
-filebrowser_pre_rename = Signal(providing_args = ["path", "filename"])
-filebrowser_post_rename = Signal(providing_args = ["path", "filename"])
+filebrowser_pre_rename = Signal(providing_args=["path", "filename"])
+filebrowser_post_rename = Signal(providing_args=["path", "filename"])
+
 
 def rename(request):
     """
     Rename existing File/Directory.
 
 def rename(request):
     """
     Rename existing File/Directory.
-    
+
     Includes renaming existing Image Versions/Thumbnails.
     """
 
     Includes renaming existing Image Versions/Thumbnails.
     """
 
@@ -363,7 +375,7 @@ def rename(request):
     filename = _get_file(query.get('dir', ''), query.get('filename', ''))
     if path is None or filename is None:
         msg = _('Directory/File does not exist.')
     filename = _get_file(query.get('dir', ''), query.get('filename', ''))
     if path is None or filename is None:
         msg = _('Directory/File does not exist.')
-        request.user.message_set.create(message = msg)
+        request.user.message_set.create(message=msg)
         return HttpResponseRedirect(reverse("fb_browse"))
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
     file_extension = os.path.splitext(filename)[1].lower()
         return HttpResponseRedirect(reverse("fb_browse"))
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
     file_extension = os.path.splitext(filename)[1].lower()
@@ -375,7 +387,7 @@ def rename(request):
             new_relative_server_path = os.path.join(DIRECTORY, path, form.cleaned_data['name'] + file_extension)
             try:
                 # PRE RENAME SIGNAL
             new_relative_server_path = os.path.join(DIRECTORY, path, form.cleaned_data['name'] + file_extension)
             try:
                 # PRE RENAME SIGNAL
-                filebrowser_pre_delete.send(sender = request, path = path, filename = filename)
+                filebrowser_pre_delete.send(sender=request, path=path, filename=filename)
                 # DELETE IMAGE VERSIONS/THUMBNAILS
                 # regenerating versions/thumbs will be done automatically
                 for version in VERSIONS:
                 # DELETE IMAGE VERSIONS/THUMBNAILS
                 # regenerating versions/thumbs will be done automatically
                 for version in VERSIONS:
@@ -386,10 +398,10 @@ def rename(request):
                 # RENAME ORIGINAL
                 os.rename(os.path.join(MEDIA_ROOT, relative_server_path), os.path.join(MEDIA_ROOT, new_relative_server_path))
                 # POST RENAME SIGNAL
                 # RENAME ORIGINAL
                 os.rename(os.path.join(MEDIA_ROOT, relative_server_path), os.path.join(MEDIA_ROOT, new_relative_server_path))
                 # POST RENAME SIGNAL
-                filebrowser_post_delete.send(sender = request, path = path, filename = filename)
+                filebrowser_post_delete.send(sender=request, path=path, filename=filename)
                 # MESSAGE & REDIRECT
                 msg = _('Renaming was successful.')
                 # MESSAGE & REDIRECT
                 msg = _('Renaming was successful.')
-                request.user.message_set.create(message = msg)
+                request.user.message_set.create(message=msg)
                 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename")
                 return HttpResponseRedirect(redirect_url)
             except OSError, (errno, strerror):
                 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename")
                 return HttpResponseRedirect(redirect_url)
             except OSError, (errno, strerror):
@@ -404,7 +416,7 @@ def rename(request):
         'title': _(u'Rename "%s"') % filename,
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, path, _(u'Rename')),
         'title': _(u'Rename "%s"') % filename,
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, path, _(u'Rename')),
-    }, context_instance = Context(request))
+    }, context_instance=Context(request))
 rename = staff_member_required(never_cache(rename))
 
 
 rename = staff_member_required(never_cache(rename))
 
 
@@ -419,7 +431,7 @@ def versions(request):
     filename = _get_file(query.get('dir', ''), query.get('filename', ''))
     if path is None or filename is None:
         msg = _('Directory/File does not exist.')
     filename = _get_file(query.get('dir', ''), query.get('filename', ''))
     if path is None or filename is None:
         msg = _('Directory/File does not exist.')
-        request.user.message_set.create(message = msg)
+        request.user.message_set.create(message=msg)
         return HttpResponseRedirect(reverse("fb_browse"))
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
 
         return HttpResponseRedirect(reverse("fb_browse"))
     abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
 
@@ -429,7 +441,6 @@ def versions(request):
         'title': _(u'Versions for "%s"') % filename,
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, path, _(u'Versions for "%s"') % filename),
         'title': _(u'Versions for "%s"') % filename,
         'settings_var': _get_settings_var(),
         'breadcrumbs': _get_breadcrumbs(query, path, _(u'Versions for "%s"') % filename),
-    }, context_instance = Context(request))
-versions = staff_member_required(never_cache(versions))
-
+    }, context_instance=Context(request))
 
 
+versions = staff_member_required(never_cache(versions))