From a73b3d8f83229ad3ebf10115d38992ca68577b78 Mon Sep 17 00:00:00 2001 From: =?utf8?q?=C5=81ukasz=20Rekucki?= Date: Tue, 2 Mar 2010 23:14:28 +0100 Subject: [PATCH] Added setting of default order in FileBrowser. Added sort() to gallery view(). Fixes #377 --- apps/filebrowser/fb_settings.py | 22 ++--- apps/filebrowser/functions.py | 119 ++++++++++--------------- apps/filebrowser/views.py | 150 ++++++++++++++++---------------- apps/wiki/views.py | 1 + platforma/settings.py | 1 + platforma/urls.py | 20 +++-- 6 files changed, 148 insertions(+), 165 deletions(-) diff --git a/apps/filebrowser/fb_settings.py b/apps/filebrowser/fb_settings.py index 502f109f..59de8256 100755 --- a/apps/filebrowser/fb_settings.py +++ b/apps/filebrowser/fb_settings.py @@ -38,23 +38,23 @@ PATH_TINYMCE = getattr(settings, "FILEBROWSER_PATH_TINYMCE", DEFAULT_PATH_TINYMC # Therefore, if you add a category (e.g. "Misc"), you won't get an icon. EXTENSIONS = getattr(settings, "FILEBROWSER_EXTENSIONS", { 'Folder': [''], - 'Image': ['.jpg','.jpeg','.gif','.png','.tif','.tiff'], - 'Video': ['.mov','.wmv','.mpeg','.mpg','.avi','.rm'], - 'Document': ['.pdf','.doc','.rtf','.txt','.xls','.csv'], - 'Sound': ['.mp3','.mp4','.wav','.aiff','.midi','.m4p'], - 'Code': ['.html','.py','.js','.css'] + 'Image': ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff'], + 'Video': ['.mov', '.wmv', '.mpeg', '.mpg', '.avi', '.rm'], + 'Document': ['.pdf', '.doc', '.rtf', '.txt', '.xls', '.csv'], + 'Sound': ['.mp3', '.mp4', '.wav', '.aiff', '.midi', '.m4p'], + 'Code': ['.html', '.py', '.js', '.css'] }) # Define different formats for allowed selections. # This has to be a subset of EXTENSIONS. SELECT_FORMATS = getattr(settings, "FILEBROWSER_SELECT_FORMATS", { - 'File': ['Folder','Document',], + 'File': ['Folder', 'Document', ], 'Image': ['Image'], - 'Media': ['Video','Sound'], + 'Media': ['Video', 'Sound'], 'Document': ['Document'], # for TinyMCE we can also define lower-case items 'image': ['Image'], - 'file': ['Folder','Image','Document',], + 'file': ['Folder', 'Image', 'Document', ], }) # Directory to Save Image Versions (and Thumbnails). Relative to MEDIA_ROOT. @@ -72,7 +72,7 @@ VERSIONS = getattr(settings, "FILEBROWSER_VERSIONS", { 'croppedthumbnail': {'verbose_name': 'Cropped Thumbnail (140x140px)', 'width': 140, 'height': 140, 'opts': 'crop'}, }) # Versions available within the Admin-Interface. -ADMIN_VERSIONS = getattr(settings, 'FILEBROWSER_ADMIN_VERSIONS', ['thumbnail','small', 'medium','big']) +ADMIN_VERSIONS = getattr(settings, 'FILEBROWSER_ADMIN_VERSIONS', ['thumbnail', 'small', 'medium', 'big']) # Which Version should be used as Admin-thumbnail. ADMIN_THUMBNAIL = getattr(settings, 'FILEBROWSER_ADMIN_THUMBNAIL', 'fb_thumb') @@ -85,7 +85,7 @@ SAVE_FULL_URL = getattr(settings, "FILEBROWSER_SAVE_FULL_URL", True) STRICT_PIL = getattr(settings, 'FILEBROWSER_STRICT_PIL', False) # PIL's Error "Suspension not allowed here" work around: # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html -IMAGE_MAXBLOCK = getattr(settings, 'FILEBROWSER_IMAGE_MAXBLOCK', 1024*1024) +IMAGE_MAXBLOCK = getattr(settings, 'FILEBROWSER_IMAGE_MAXBLOCK', 1024 * 1024) # Exclude files matching any of the following regular expressions # Default is to exclude 'thumbnail' style naming of image-thumbnails. EXTENSION_LIST = [] @@ -97,6 +97,8 @@ MAX_UPLOAD_SIZE = getattr(settings, "FILEBROWSER_MAX_UPLOAD_SIZE", 10485760) # Convert Filename (replace spaces and convert to lowercase) CONVERT_FILENAME = getattr(settings, "FILEBROWSER_CONVERT_FILENAME", True) +DEFAULT_ORDER = getattr(settings, "FILEBROWSER_DEFAULT_ORDER", "filename_lower") + # EXTRA TRANSLATION STRINGS # The following strings are not availabe within views or templates _('Folder') diff --git a/apps/filebrowser/functions.py b/apps/filebrowser/functions.py index cef9dcd9..5f7f98f8 100755 --- a/apps/filebrowser/functions.py +++ b/apps/filebrowser/functions.py @@ -31,7 +31,7 @@ def _url_to_path(value): mediaurl_re = re.compile(r'^(%s)' % (MEDIA_URL)) value = mediaurl_re.sub('', value) return value - + def _path_to_url(value): """ @@ -43,7 +43,7 @@ def _path_to_url(value): mediaroot_re = re.compile(r'^(%s)' % (MEDIA_ROOT)) value = mediaroot_re.sub('', value) return _url_join(MEDIA_URL, value) - + def _dir_from_url(value): """ @@ -51,13 +51,13 @@ def _dir_from_url(value): URL has to be an absolute URL including MEDIA_URL or an URL relative to MEDIA_URL. """ - + mediaurl_re = re.compile(r'^(%s)' % (MEDIA_URL)) value = mediaurl_re.sub('', value) directory_re = re.compile(r'^(%s)' % (DIRECTORY)) value = directory_re.sub('', value) return os.path.split(value)[0] - + def _get_version_path(value, version_prefix): """ @@ -74,30 +74,7 @@ def _get_version_path(value, version_prefix): return os.path.join(VERSIONS_BASEDIR, path, version_filename) else: return None - -def _sort_by_attr(seq, attr): - """ - Sort the sequence of objects by object's attribute - - Arguments: - seq - the list or any sequence (including immutable one) of objects to sort. - attr - the name of attribute to sort by - - Returns: - the sorted list of objects. - """ - import operator - - # Use the "Schwartzian transform" - # Create the auxiliary list of tuples where every i-th tuple has form - # (seq[i].attr, i, seq[i]) and sort it. The second item of tuple is needed not - # only to provide stable sorting, but mainly to eliminate comparison of objects - # (which can be expensive or prohibited) in case of equal attribute values. - intermed = map(None, map(getattr, seq, (attr,)*len(seq)), xrange(len(seq)), seq) - intermed.sort() - return map(operator.getitem, intermed, (-1,) * len(intermed)) - def _url_join(*args): if args[0].startswith("http://"): @@ -114,66 +91,66 @@ def _url_join(*args): if os.path.splitext(args[-1])[1]: url = url.rstrip("/") return url - + def _get_path(path): """ Get Path. """ - + if os.path.isabs(path) or not os.path.isdir(os.path.join(MEDIA_ROOT, DIRECTORY, path)): return None return path - + def _get_file(path, filename): """ Get File. """ - + if not os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)) and not os.path.isdir(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)): return None return filename - + def _get_breadcrumbs(query, path, title): """ Get breadcrumbs. """ - + breadcrumbs = [] dir_query = "" if path: for item in path.split(os.sep): - dir_query = os.path.join(dir_query,item) - breadcrumbs.append([item,dir_query]) + dir_query = os.path.join(dir_query, item) + breadcrumbs.append([item, dir_query]) if title: - breadcrumbs.append([title,'']) + breadcrumbs.append([title, '']) return breadcrumbs - + def _get_filterdate(filterDate, dateTime): """ Get filterdate. """ - + returnvalue = '' dateYear = strftime("%Y", gmtime(dateTime)) dateMonth = strftime("%m", gmtime(dateTime)) dateDay = strftime("%d", gmtime(dateTime)) if filterDate == 'today' and int(dateYear) == int(localtime()[0]) and int(dateMonth) == int(localtime()[1]) and int(dateDay) == int(localtime()[2]): returnvalue = 'true' - elif filterDate == 'thismonth' and dateTime >= time()-2592000: returnvalue = 'true' + elif filterDate == 'thismonth' and dateTime >= time() - 2592000: returnvalue = 'true' elif filterDate == 'thisyear' and int(dateYear) == int(localtime()[0]): returnvalue = 'true' - elif filterDate == 'past7days' and dateTime >= time()-604800: returnvalue = 'true' + elif filterDate == 'past7days' and dateTime >= time() - 604800: returnvalue = 'true' elif filterDate == '': returnvalue = 'true' return returnvalue - + def _get_settings_var(): """ Get settings variables used for FileBrowser listing. """ - + settings_var = {} # Main settings_var['DEBUG'] = DEBUG @@ -199,52 +176,52 @@ def _get_settings_var(): # Convert Filenames settings_var['CONVERT_FILENAME'] = CONVERT_FILENAME return settings_var - + def _handle_file_upload(path, file): """ Handle File Upload. """ - + file_path = os.path.join(path, file.name) uploadedfile = default_storage.save(file_path, file) return uploadedfile - + def _get_file_type(filename): """ Get file type as defined in EXTENSIONS. """ - + file_extension = os.path.splitext(filename)[1].lower() file_type = '' - for k,v in EXTENSIONS.iteritems(): + for k, v in EXTENSIONS.iteritems(): for extension in v: if file_extension == extension.lower(): file_type = k return file_type - + def _is_selectable(filename, selecttype): """ Get select type as defined in FORMATS. """ - + file_extension = os.path.splitext(filename)[1].lower() select_types = [] - for k,v in SELECT_FORMATS.iteritems(): + for k, v in SELECT_FORMATS.iteritems(): for extension in v: if file_extension == extension.lower(): select_types.append(k) return select_types - -def _version_generator(value, version_prefix, force=None): + +def _version_generator(value, version_prefix, force = None): """ Generate Version for an Image. value has to be a serverpath relative to MEDIA_ROOT. """ - + # PIL's Error "Suspension not allowed here" work around: # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html if STRICT_PIL: @@ -255,7 +232,7 @@ def _version_generator(value, version_prefix, force=None): except ImportError: import ImageFile ImageFile.MAXBLOCK = IMAGE_MAXBLOCK # default is 64k - + try: im = Image.open(os.path.join(MEDIA_ROOT, value)) version_path = _get_version_path(value, version_prefix) @@ -266,38 +243,38 @@ def _version_generator(value, version_prefix, force=None): os.chmod(version_dir, 0775) version = scale_and_crop(im, VERSIONS[version_prefix]['width'], VERSIONS[version_prefix]['height'], VERSIONS[version_prefix]['opts']) try: - version.save(absolute_version_path, quality=90, optimize=1) + version.save(absolute_version_path, quality = 90, optimize = 1) except IOError: - version.save(absolute_version_path, quality=90) + version.save(absolute_version_path, quality = 90) return version_path except: return None - + def scale_and_crop(im, width, height, opts): - x, y = [float(v) for v in im.size] + x, y = [float(v) for v in im.size] if width: xr = float(width) else: - xr = float(x*height/y) + xr = float(x * height / y) if height: yr = float(height) else: - yr = float(y*width/x) - + yr = float(y * width / x) + if 'crop' in opts: - r = max(xr/x, yr/y) + r = max(xr / x, yr / y) else: - r = min(xr/x, yr/y) - + r = min(xr / x, yr / y) + if r < 1.0 or (r > 1.0 and 'upscale' in opts): - im = im.resize((int(x*r), int(y*r)), resample=Image.ANTIALIAS) - + im = im.resize((int(x * r), int(y * r)), resample = Image.ANTIALIAS) + if 'crop' in opts: - x, y = [float(v) for v in im.size] - ex, ey = (x-min(x, xr))/2, (y-min(y, yr))/2 + x, y = [float(v) for v in im.size] + ex, ey = (x - min(x, xr)) / 2, (y - min(y, yr)) / 2 if ex or ey: - im = im.crop((int(ex), int(ey), int(x-ex), int(y-ey))) + im = im.crop((int(ex), int(ey), int(x - ex), int(y - ey))) return im scale_and_crop.valid_options = ('crop', 'upscale') @@ -307,6 +284,6 @@ def _convert_filename(value): return value.replace(" ", "_").lower() else: return value - - + + diff --git a/apps/filebrowser/views.py b/apps/filebrowser/views.py index 0976f11e..3dcba4a3 100644 --- a/apps/filebrowser/views.py +++ b/apps/filebrowser/views.py @@ -19,7 +19,7 @@ from django.dispatch import Signal # filebrowser imports from filebrowser.fb_settings import * -from filebrowser.functions import _url_to_path, _path_to_url, _sort_by_attr, _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 @@ -28,7 +28,7 @@ from filebrowser.decorators import flash_login_required filter_re = [] for exp in EXCLUDE: filter_re.append(re.compile(exp)) -for k,v in VERSIONS.iteritems(): +for k, v in VERSIONS.iteritems(): exp = (r'_%s.(%s)') % (k, '|'.join(EXTENSION_LIST)) filter_re.append(re.compile(exp)) @@ -37,32 +37,32 @@ def browse(request): """ Browse Files/Directories. """ - + # QUERY / PATH CHECK query = request.GET path = _get_path(query.get('dir', '')) directory = _get_path('') - + 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. raise ImproperlyConfigured, _("Error finding upload directory. Maybe it does not exist?") 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 } counter = {} - for k,v in EXTENSIONS.iteritems(): + for k, v in EXTENSIONS.iteritems(): counter[k] = 0 - + dir_list = os.listdir(abs_path) files = [] for file in dir_list: - + # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS filtered = file.startswith('.') for re_prefix in filter_re: @@ -71,17 +71,17 @@ def browse(request): if filtered: continue results_var['results_total'] += 1 - + # CREATE FILEOBJECT fileobject = FileObject(os.path.join(DIRECTORY, path, file)) - + # FILTER / SEARCH append = False if fileobject.filetype == request.GET.get('filter_type', fileobject.filetype) and _get_filterdate(request.GET.get('filter_date', ''), fileobject.date): append = True if request.GET.get('q') and not re.compile(request.GET.get('q').lower(), re.M).search(file.lower()): append = False - + # APPEND FILE_LIST if append: files.append(fileobject) @@ -97,16 +97,16 @@ def browse(request): results_var['select_total'] += 1 elif not query.get('type'): results_var['select_total'] += 1 - + # COUNTER/RESULTS if fileobject.filetype: counter[fileobject.filetype] += 1 - + # SORTING - files = _sort_by_attr(files, request.GET.get('o', 'date')) + files.sort(key = lambda e: getattr(e, request.GET.get('o', DEFAULT_ORDER))) if request.GET.get('ot') == "desc": files.reverse() - + return render_to_response('filebrowser/index.html', { 'dir': path, 'files': files, @@ -116,45 +116,45 @@ def browse(request): '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 -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): """ Make Directory. """ - + from filebrowser.forms import MakeDirForm - + # QUERY / PATH CHECK query = request.GET 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) - + if request.method == 'POST': form = MakeDirForm(abs_path, request.POST) if form.is_valid(): 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 - 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']) - 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") @@ -166,14 +166,14 @@ def mkdir(request): form.errors['dir_name'] = forms.util.ErrorList([_('Error creating directory.')]) else: form = MakeDirForm(abs_path) - + return render_to_response('filebrowser/makedir.html', { 'form': form, 'query': query, '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)) @@ -181,30 +181,30 @@ def upload(request): """ Multipe File Upload. """ - + from django.http import parse_cookie - + # QUERY / PATH CHECK query = request.GET 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) - + # SESSION (used for flash-uploading) cookie_dict = parse_cookie(request.META.get('HTTP_COOKIE', '')) engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) session_key = cookie_dict.get(settings.SESSION_COOKIE_NAME, None) - + return render_to_response('filebrowser/upload.html', { 'query': query, 'title': _(u'Select files to upload'), '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)) @@ -212,35 +212,35 @@ def _check_file(request): """ Check if file already exists on the server. """ - + from django.utils import simplejson - + folder = request.POST.get('folder') fb_uploadurl_re = re.compile(r'^(%s)' % reverse("fb_upload")) folder = fb_uploadurl_re.sub('', folder) - + fileArray = {} if request.method == 'POST': - for k,v in request.POST.items(): + for k, v in request.POST.items(): if k != "folder": v = _convert_filename(v) if os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, folder, v)): fileArray[k] = v - + return HttpResponse(simplejson.dumps(fileArray)) # 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): """ Upload file to the server. """ - + from django.core.files.move import file_move_safe - + if request.method == 'POST': folder = request.POST.get('folder') fb_uploadurl_re = re.compile(r'^(%s)' % reverse("fb_upload")) @@ -250,7 +250,7 @@ def _upload_file(request): 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 @@ -260,14 +260,14 @@ def _upload_file(request): 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') _upload_file = flash_login_required(_upload_file) # 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): """ @@ -275,24 +275,24 @@ def delete(request): When trying to delete a Directory, the Directory has to be empty. """ - + # QUERY / PATH CHECK query = request.GET path = _get_path(query.get('dir', '')) 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) - + msg = "" if request.GET: if request.GET.get('filetype') != "Folder": 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: @@ -302,10 +302,10 @@ def delete(request): # 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()) - 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: @@ -314,36 +314,36 @@ def delete(request): 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 - 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()) - 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: # todo: define error message 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, 'file': request.GET.get('filename', ''), '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 -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): """ @@ -351,20 +351,20 @@ def rename(request): Includes renaming existing Image Versions/Thumbnails. """ - + from filebrowser.forms import RenameForm - + # QUERY / PATH CHECK query = request.GET path = _get_path(query.get('dir', '')) 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() - + if request.method == 'POST': form = RenameForm(abs_path, file_extension, request.POST) if form.is_valid(): @@ -372,7 +372,7 @@ def rename(request): 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: @@ -383,17 +383,17 @@ 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 - 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.') - 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): form.errors['name'] = forms.util.ErrorList([_('Error.')]) else: form = RenameForm(abs_path, file_extension) - + return render_to_response('filebrowser/rename.html', { 'form': form, 'query': query, @@ -401,7 +401,7 @@ def rename(request): '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)) @@ -409,24 +409,24 @@ def versions(request): """ Show all Versions for an Image according to ADMIN_VERSIONS. """ - + # QUERY / PATH CHECK query = request.GET path = _get_path(query.get('dir', '')) 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 render_to_response('filebrowser/versions.html', { 'original': _path_to_url(os.path.join(DIRECTORY, path, filename)), 'query': query, '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)) + }, context_instance = Context(request)) versions = staff_member_required(never_cache(versions)) diff --git a/apps/wiki/views.py b/apps/wiki/views.py index f9e69962..eff1f1db 100644 --- a/apps/wiki/views.py +++ b/apps/wiki/views.py @@ -41,6 +41,7 @@ def document_gallery(request, directory): try: base_dir = os.path.join(settings.MEDIA_ROOT, settings.FILEBROWSER_DIRECTORY, directory) 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')] + images.sort() return HttpResponse(json.dumps(images)) except (IndexError, OSError), e: raise Http404 diff --git a/platforma/settings.py b/platforma/settings.py index 2c4e6588..414c7130 100755 --- a/platforma/settings.py +++ b/platforma/settings.py @@ -139,6 +139,7 @@ FILEBROWSER_URL_FILEBROWSER_MEDIA = STATIC_URL + 'filebrowser/' FILEBROWSER_DIRECTORY = 'images/' FILEBROWSER_ADMIN_VERSIONS = [] FILEBROWSER_VERSIONS_BASEDIR = 'thumbnails/' +FILEBROWSER_DEFAULT_ORDER = "path_relative" # REPOSITORY_PATH = '/Users/zuber/Projekty/platforma/files/books' IMAGE_DIR = 'images' diff --git a/platforma/urls.py b/platforma/urls.py index ea9ba258..cfa23001 100755 --- a/platforma/urls.py +++ b/platforma/urls.py @@ -15,32 +15,34 @@ urlpatterns = patterns('') if 'cas_consumer' in settings.INSTALLED_APPS: urlpatterns += patterns('', # django-cas-consumer - url(r'^accounts/login/$', 'cas_consumer.views.login', name='login'), - url(r'^accounts/logout/$', 'cas_consumer.views.logout', name='logout'), + url(r'^accounts/login/$', 'cas_consumer.views.login', name = 'login'), + url(r'^accounts/logout/$', 'cas_consumer.views.logout', name = 'logout'), ) else: urlpatterns += patterns('', # Django auth - url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'redirect_field_name': 'next'}, name='login'), - url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'), + url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'redirect_field_name': 'next'}, name = 'login'), + url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name = 'logout'), ) urlpatterns += patterns('', url(r'^$', 'wiki.views.document_list'), url(r'^gallery/(?P[^/]+)$', 'wiki.views.document_gallery'), - + # Admin panel (r'^admin/filebrowser/', include('filebrowser.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/(.*)', admin.site.root), - + # Static files (should be served by Apache) url(r'^%s(?P.+)$' % settings.MEDIA_URL[1:], 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), + url(r'^%s(?P.+)$' % settings.ADMIN_MEDIA_PREFIX[1:], 'django.views.static.serve', + {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), url(r'^%s(?P.+)$' % settings.STATIC_URL[1:], 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True}), - - url(r'^(?P(.*))$', 'wiki.views.document_detail'), - + + url(r'^(?P[^/]+)$', 'wiki.views.document_detail'), + ) -- 2.20.1