def render(self, context): try: source = self.src.resolve(context) except VariableDoesNotExist: return None if self.version_prefix: version_prefix = self.version_prefix else: try: version_prefix = self.version_prefix_var.resolve(context) except VariableDoesNotExist: return None try: version_path = get_version_path(url_to_path(str(source)), version_prefix) if not os.path.isfile(os.path.join(MEDIA_ROOT, version_path)): # create version version_path = version_generator(url_to_path(str(source)), version_prefix) elif os.path.getmtime( os.path.join(MEDIA_ROOT, url_to_path( str(source)))) > os.path.getmtime( os.path.join(MEDIA_ROOT, version_path)): # recreate version if original image was updated version_path = version_generator(url_to_path(str(source)), version_prefix, force=True) context[self.var_name] = FileObject(version_path) except: context[self.var_name] = "" return ''
def _upload_file(request): """ Upload file to the server. """ if request.method == 'POST': folder = request.POST.get('folder') fb_uploadurl_re = re.compile(r'^.*(%s)' % reverse("fb_upload")) folder = fb_uploadurl_re.sub('', folder) if request.FILES: filedata = request.FILES['Filedata'] abs_path = os.path.join(DIRECTORY, folder, filedata.name) # PRE UPLOAD SIGNAL filebrowser_pre_upload.send(sender=request, path=request.POST.get('folder'), file=filedata) # HANDLE UPLOAD exists = default_storage.exists( os.path.join(DIRECTORY, folder, filedata.name)) uploadedfile = default_storage.save(abs_path, filedata) if exists: default_storage.move(uploadedfile, filedata.name, allow_overwrite=True) # POST UPLOAD SIGNAL filebrowser_post_upload.send( sender=request, path=request.POST.get('folder'), file=FileObject(os.path.join(DIRECTORY, folder, filedata.name))) return HttpResponse('True')
def _upload_file(request): """ Upload file to the server. """ if request.method == "POST": folder = request.POST.get("folder") fb_uploadurl_re = re.compile(r"^.*(%s)" % reverse("fb_upload")) folder = fb_uploadurl_re.sub("", folder) if "." in folder: return HttpResponseBadRequest("") if request.FILES: filedata = request.FILES["Filedata"] directory = get_directory() # Validate file against EXTENSIONS setting. if not get_file_type(filedata.name): return HttpResponseBadRequest("") # PRE UPLOAD SIGNAL filebrowser_pre_upload.send( sender=request, path=request.POST.get("folder"), file=filedata ) # Try and remove both original and normalised thumb names, # in case files were added programmatically outside FB. file_path = os.path.join(directory, folder, filedata.name) remove_thumbnails(file_path) filedata.name = convert_filename(filedata.name) file_path = os.path.join(directory, folder, filedata.name) remove_thumbnails(file_path) if ( "." in file_path and file_path.split(".")[-1].lower() in fb_settings.ESCAPED_EXTENSIONS ): filedata = ContentFile(escape(filedata.read()), name=filedata.name) # HANDLE UPLOAD uploadedfile = default_storage.save(file_path, filedata) if default_storage.exists(file_path) and file_path != uploadedfile: default_storage.move( smart_text(uploadedfile), smart_text(file_path), allow_overwrite=True, ) # POST UPLOAD SIGNAL filebrowser_post_upload.send( sender=request, path=request.POST.get("folder"), file=FileObject(smart_text(file_path)), ) get_params = request.POST.get("get_params") if get_params: return HttpResponseRedirect(reverse("fb_browse") + get_params) return HttpResponse("True")
def _upload_file(request): """ Upload file to the server. """ if request.method == 'POST': folder = request.POST.get('folder') fb_uploadurl_re = re.compile(r'^.*(%s)' % reverse("fb_upload")) folder = fb_uploadurl_re.sub('', folder) if ".." in folder: return HttpResponseBadRequest("") if request.FILES: filedata = request.FILES['Filedata'] directory = get_directory() # Validate file against EXTENSIONS setting. if not get_file_type(filedata.name): return HttpResponseBadRequest("") # PRE UPLOAD SIGNAL filebrowser_pre_upload.send(sender=request, path=request.POST.get('folder'), file=filedata) # Try and remove both original and normalised thumb names, # in case files were added programmatically outside FB. file_path = os.path.join(directory, folder, filedata.name) remove_thumbnails(file_path) filedata.name = convert_filename(filedata.name) # this won't work with windows and s3 - replace the "\" file_path = os.path.join(directory, folder, filedata.name).replace("\\", "/") remove_thumbnails(file_path) if "." in file_path and file_path.split( ".")[-1].lower() in ESCAPED_EXTENSIONS: filedata = ContentFile(escape(filedata.read()), name=filedata.name) # HANDLE UPLOAD uploadedfile = default_storage.save(file_path, filedata) if default_storage.exists(file_path) and file_path != uploadedfile: default_storage.move(smart_text(uploadedfile), smart_text(file_path), allow_overwrite=True) # POST UPLOAD SIGNAL filebrowser_post_upload.send(sender=request, path=request.POST.get('folder'), file=FileObject( smart_text(file_path))) get_params = request.POST.get('get_params') if get_params: return HttpResponseRedirect(reverse('fb_browse') + get_params) return HttpResponse('True')
def _upload_file(request): """ Upload file to the server. Implement unicode handlers - https://github.com/sehmaschine/django-filebrowser/blob/master/filebrowser/sites.py#L471 """ if request.method == 'POST': folder = request.POST.get('folder') fb_uploadurl_re = re.compile(r'^.*(%s)' % reverse("fb_upload")) folder = fb_uploadurl_re.sub('', folder) if "." in folder: return HttpResponseBadRequest("") if request.FILES: filedata = request.FILES['Filedata'] directory = get_directory() # Validate file against EXTENSIONS setting. if not get_file_type(filedata.name): return HttpResponseBadRequest("") # PRE UPLOAD SIGNAL filebrowser_pre_upload.send(sender=request, path=request.POST.get('folder'), file=filedata) # Try and remove both original and normalised thumb names, # in case files were added programmatically outside FB. file_path = os.path.join(directory, folder, filedata.name) remove_thumbnails(file_path) filedata.name = convert_filename(filedata.name) file_path = os.path.join(directory, folder, filedata.name) remove_thumbnails(file_path) # HANDLE UPLOAD uploadedfile = default_storage.save(file_path, filedata) if default_storage.exists(file_path) and file_path != uploadedfile: default_storage.move(smart_text(uploadedfile), smart_text(file_path), allow_overwrite=True) # POST UPLOAD SIGNAL filebrowser_post_upload.send(sender=request, path=request.POST.get('folder'), file=FileObject( smart_text(file_path))) get_params = request.POST.get('get_params') if get_params: return HttpResponseRedirect(reverse('fb_browse') + get_params) return HttpResponse('True')
def _upload_file(request): """ Upload file to the server. Implement unicode handlers - https://github.com/sehmaschine/django-filebrowser/blob/master/filebrowser/sites.py#L471 """ if request.method == 'POST': folder = request.POST.get('folder') fb_uploadurl_re = re.compile(r'^.*(%s)' % reverse("fb_upload")) folder = fb_uploadurl_re.sub('', folder) if request.FILES: filedata = request.FILES['Filedata'] # PRE UPLOAD SIGNAL filebrowser_pre_upload.send(sender=request, path=request.POST.get('folder'), file=filedata) filedata.name = convert_filename(filedata.name) # HANDLE UPLOAD exists = default_storage.exists( os.path.join(get_directory(), folder, filedata.name)) abs_path = os.path.join(get_directory(), folder, filedata.name) uploadedfile = default_storage.save(abs_path, filedata) path = os.path.join(get_directory(), folder) file_name = os.path.join(path, filedata.name) if exists: default_storage.move(smart_text(uploadedfile), smart_text(file_name), allow_overwrite=True) # POST UPLOAD SIGNAL filebrowser_post_upload.send(sender=request, path=request.POST.get('folder'), file=FileObject( smart_text(file_name))) return HttpResponse('True')
def scan_path(self, path='', parent=None, out_start=''): abs_path = os.path.join(get_directory(), path) dir_list, file_list = default_storage.listdir(abs_path) for file in dir_list + file_list: if not file or file.startswith('.'): continue url_path = "/".join([ s.strip("/") for s in [get_directory(), path, file] if s.strip("/") ]) fileobject = FileObject(url_path) if not FileBrowserItem.objects.filter(filename=fileobject.filename, parent=parent).exists(): fb_item = FileBrowserItem.objects.create( filename=fileobject.filename, parent=parent, path=fileobject.path, path_relative_directory=fileobject.path_relative_directory, url=fileobject.url, extension=fileobject.extension, filetype=fileobject.filetype.lower(), filesize=fileobject.filesize, datetime=fileobject.datetime) status = 'created' else: fb_item = FileBrowserItem.objects.get( filename=fileobject.filename, parent=parent) status = 'exists' self.stdout.write('%s|--%s (%s)' % (out_start, file, status)) if fileobject.filetype == 'Folder': self.scan_path(fileobject.path_relative_directory, fb_item, out_start + "\t")
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")) folder = fb_uploadurl_re.sub('', folder) abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, folder) if request.FILES: 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) # HANDLE UPLOAD uploadedfile = handle_file_upload(abs_path, filedata) # MOVE UPLOADED FILE # if file already exists if os.path.isfile( os.path.join(MEDIA_ROOT, DIRECTORY, folder, filedata.name)): old_file = os.path.join(abs_path, filedata.name) 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))) return HttpResponse('True')
def to_python(self, value): if not value or isinstance(value, FileObject): return value return FileObject(url_to_path(value))
def browse(request): """ Browse Files/Directories. """ # QUERY / PATH CHECK query = request.GET.copy() path = get_path(query.get('dir', '')) directory = get_path('') if path is None: msg = _('The requested Folder does not exist.') messages.add_message(request, messages.ERROR, msg) if directory is None: # The directory returned by get_directory() does not exist, raise an error to prevent eternal redirecting. raise ImproperlyConfigured( _("Error finding Upload-Folder. Maybe it does not exist?")) redirect_url = reverse("fb_browse") + query_helper(query, "", "dir") return HttpResponseRedirect(redirect_url) abs_path = os.path.join(get_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.items(): counter[k] = 0 dir_list, file_list = default_storage.listdir(abs_path) files = [] for file in dir_list + file_list: # EXCLUDE FILES MATCHING ANY OF THE EXCLUDE PATTERNS filtered = not file or file.startswith('.') for re_prefix in filter_re: if re_prefix.search(file): filtered = True if filtered: continue results_var['results_total'] += 1 # CREATE FILEOBJECT url_path = "/".join([ s.strip("/") for s in [get_directory(), path.replace("\\", "/"), file] if s.strip("/") ]) fileobject = FileObject(url_path) # 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: try: # COUNTER/RESULTS results_var['delete_total'] += 1 if fileobject.filetype == 'Image': results_var['images_total'] += 1 if query.get('type') and query.get( 'type' ) in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[ query.get('type')]: results_var['select_total'] += 1 elif not query.get('type'): results_var['select_total'] += 1 except OSError: # Ignore items that have problems continue else: files.append(fileobject) results_var['results_current'] += 1 # COUNTER/RESULTS if fileobject.filetype: counter[fileobject.filetype] += 1 # SORTING query['o'] = request.GET.get('o', DEFAULT_SORTING_BY) query['ot'] = request.GET.get('ot', DEFAULT_SORTING_ORDER) defaultValue = '' if query['o'] in ['date', 'filesize']: defaultValue = 0.0 files = sorted(files, key=lambda f: getattr(f, query['o']) or defaultValue) if not request.GET.get( 'ot') and DEFAULT_SORTING_ORDER == "desc" or request.GET.get( 'ot') == "desc": files.reverse() p = Paginator(files, LIST_PER_PAGE) try: page_nr = request.GET.get('p', '1') except: page_nr = 1 try: page = p.page(page_nr) except (EmptyPage, InvalidPage): page = p.page(p.num_pages) return render( request, 'filebrowser/index.html', { 'dir': path, 'p': p, 'page': page, 'results_var': results_var, 'counter': counter, 'query': query, 'title': _(u'Media Library'), 'settings_var': get_settings_var(), 'breadcrumbs': get_breadcrumbs(query, path), 'breadcrumbs_title': "" })
def browse(request): """ Browse Files/Directories. """ # QUERY / PATH CHECK query = request.GET.copy() path = get_path(query.get('dir', '')) directory = get_path('') if path is None: msg = _('The requested Folder does not exist.') messages.add_message(request, messages.ERROR, msg) if directory is None: # The directory returned by get_directory() does not exist, raise an error to prevent eternal redirecting. raise ImproperlyConfigured, _("Error finding Upload-Folder. Maybe it does not exist?") redirect_url = reverse("fb_browse") + query_helper(query, "", "dir") return HttpResponseRedirect(redirect_url) abs_path = os.path.join(get_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(): counter[k] = 0 dir_list, file_list = default_storage.listdir(abs_path) files = [] for file in dir_list + file_list: # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS filtered = not file or file.startswith('.') for re_prefix in filter_re: if re_prefix.search(file): filtered = True if filtered: continue results_var['results_total'] += 1 # CREATE FILEOBJECT fileobject = FileObject(os.path.join(get_directory(), path, file)) # Strip leading slash in dirnames for MEDIA_LIBRARY_PER_SITE fileobject.path_relative_directory = fileobject.path_relative_directory.lstrip("/") # 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: try: # COUNTER/RESULTS if fileobject.filetype == 'Image': results_var['images_total'] += 1 if fileobject.filetype != 'Folder': results_var['delete_total'] += 1 elif fileobject.filetype == 'Folder' and fileobject.is_empty: results_var['delete_total'] += 1 if query.get('type') and query.get('type') in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[query.get('type')]: results_var['select_total'] += 1 elif not query.get('type'): results_var['select_total'] += 1 except OSError: # Ignore items that have problems continue else: files.append(fileobject) results_var['results_current'] += 1 # COUNTER/RESULTS if fileobject.filetype: counter[fileobject.filetype] += 1 # SORTING query['o'] = request.GET.get('o', DEFAULT_SORTING_BY) query['ot'] = request.GET.get('ot', DEFAULT_SORTING_ORDER) files = sort_by_attr(files, request.GET.get('o', DEFAULT_SORTING_BY)) if not request.GET.get('ot') and DEFAULT_SORTING_ORDER == "desc" or request.GET.get('ot') == "desc": files.reverse() p = Paginator(files, LIST_PER_PAGE) try: page_nr = request.GET.get('p', '1') except: page_nr = 1 try: page = p.page(page_nr) except (EmptyPage, InvalidPage): page = p.page(p.num_pages) return render_to_response('filebrowser/index.html', { 'dir': path, 'p': p, 'page': page, 'results_var': results_var, 'counter': counter, 'query': query, 'title': _(u'Media Library'), 'settings_var': get_settings_var(), 'breadcrumbs': get_breadcrumbs(query, path), 'breadcrumbs_title': "" }, context_instance=Context(request))
def browse(request): """ Browse Files/Directories. """ # QUERY / PATH CHECK query = request.GET.copy() path = get_path(query.get("dir", "")) directory = get_path("") if path is None: msg = _("The requested Folder does not exist.") messages.add_message(request, messages.ERROR, msg) if directory is None: # The directory returned by get_directory() does not exist, raise an error # to prevent eternal redirecting. raise ImproperlyConfigured( _("Error finding Upload-Folder. Maybe it does not exist?")) redirect_url = reverse("fb_browse") + query_helper(query, "", "dir") return HttpResponseRedirect(redirect_url) abs_path = os.path.join(get_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 fb_settings.EXTENSIONS.items(): counter[k] = 0 dir_list, file_list = default_storage.listdir(abs_path) files = [] for file in dir_list + file_list: # EXCLUDE FILES MATCHING ANY OF THE EXCLUDE PATTERNS filtered = not file or file.startswith(".") for re_prefix in filter_re: if re_prefix.search(file): filtered = True if filtered: continue results_var["results_total"] += 1 # CREATE FILEOBJECT url_path = "/".join([ s.strip("/") for s in [get_directory(), path.replace("\\", "/"), file] if s.strip("/") ]) fileobject = FileObject(url_path) # FILTER / SEARCH append = False if (fileobject.filetype == request.GET.get("filter_type", fileobject.filetype) and fileobject.filetype == "Folder"): append = True elif 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: try: # COUNTER/RESULTS results_var["delete_total"] += 1 if fileobject.filetype == "Image": results_var["images_total"] += 1 if (query.get("type") and query.get("type") in fb_settings.SELECT_FORMATS and fileobject.filetype in fb_settings.SELECT_FORMATS[query.get("type")]): results_var["select_total"] += 1 elif not query.get("type"): results_var["select_total"] += 1 except OSError: # Ignore items that have problems continue else: files.append(fileobject) results_var["results_current"] += 1 # COUNTER/RESULTS if fileobject.filetype: counter[fileobject.filetype] += 1 # SORTING query["o"] = request.GET.get("o", fb_settings.DEFAULT_SORTING_BY) query["ot"] = request.GET.get("ot", fb_settings.DEFAULT_SORTING_ORDER) defaultValue = "" if query["o"] in ["date", "filesize"]: defaultValue = 0.0 files = sorted(files, key=lambda f: getattr(f, query["o"]) or defaultValue) if (not request.GET.get("ot") and fb_settings.DEFAULT_SORTING_ORDER == "desc" or request.GET.get("ot") == "desc"): files.reverse() p = Paginator(files, fb_settings.LIST_PER_PAGE) try: page_nr = request.GET.get("p", "1") except: # noqa page_nr = 1 try: page = p.page(page_nr) except (EmptyPage, InvalidPage): page = p.page(p.num_pages) return render( request, "filebrowser/index.html", { "dir": path, "p": p, "page": page, "results_var": results_var, "counter": counter, "query": query, "title": _("Media Library"), "settings_var": get_settings_var(), "breadcrumbs": get_breadcrumbs(query, path), "breadcrumbs_title": "", }, )
def rename(request): """ Rename existing File/Directory. Includes renaming existing Image Versions/Thumbnails. """ from filebrowser_safe.forms import RenameForm # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) filename = query.get('filename', '') if path is None or filename is None: if path is None: msg = _('The requested Folder does not exist.') else: msg = _('The requested File does not exist.') messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = os.path.join(MEDIA_ROOT, get_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(): relative_server_path = os.path.join(get_directory(), path, filename) new_filename = form.cleaned_data['name'] + file_extension new_relative_server_path = os.path.join(get_directory(), path, new_filename) try: # PRE RENAME SIGNAL filebrowser_pre_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) # RENAME ORIGINAL remove_thumbnails(new_relative_server_path) default_storage.move(relative_server_path, new_relative_server_path) # POST RENAME SIGNAL filebrowser_post_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) fileobject = FileObject(new_relative_server_path) FileBrowserItem.objects.filter( path=relative_server_path).update( filename=fileobject.filename, path=fileobject.path, path_relative_directory=fileobject. path_relative_directory, url=fileobject.url, ) # MESSAGE & REDIRECT msg = _('Renaming was successful.') messages.add_message(request, messages.SUCCESS, msg) redirect_url = reverse("fb_browse") + query_helper( query, "", "filename") return HttpResponseRedirect(redirect_url) except OSError as xxx_todo_changeme1: (errno, strerror) = xxx_todo_changeme1.args 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, 'file_extension': file_extension, 'title': _(u'Rename "%s"') % filename, 'settings_var': get_settings_var(), 'breadcrumbs': get_breadcrumbs(query, path), 'breadcrumbs_title': _(u'Rename') }, context_instance=Context(request))
def mkdir(request): """ Make Directory. """ from filebrowser_safe.forms import MakeDirForm # QUERY / PATH CHECK query = request.GET path_relative = query.get('dir', '') path = '' parent = None if path_relative: parent_query = FileBrowserItem.objects.filter( path_relative_directory=path_relative, filetype='folder') if not parent_query.exists(): msg = _('The requested Folder does not exist.') messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse("fb_browse")) else: parent = parent_query.first() path = path_relative abs_path = os.path.join(get_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']) # CREATE FOLDER default_storage.makedirs(server_path) # POST CREATE SIGNAL filebrowser_post_createdir.send( sender=request, path=path, dirname=form.cleaned_data['dir_name']) fileobject = FileObject(server_path) FileBrowserItem.objects.create( filename=fileobject.filename, parent=parent, path=fileobject.path, path_relative_directory=fileobject.path_relative_directory, url=fileobject.url, extension=fileobject.extension, filetype=fileobject.filetype.lower(), filesize=fileobject.filesize, datetime=fileobject.datetime) # MESSAGE & REDIRECT msg = _('The Folder %s was successfully created.') % ( form.cleaned_data['dir_name']) messages.add_message(request, messages.SUCCESS, 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 # remove pagination redirect_url = reverse("fb_browse") + query_helper( query, "ot=desc,o=date", "ot,o,filter_type,filter_date,q,p") return HttpResponseRedirect(redirect_url) except OSError as xxx_todo_changeme: (errno, strerror) = xxx_todo_changeme.args if errno == 13: form.errors['dir_name'] = forms.utils.ErrorList( [_('Permission denied.')]) else: form.errors['dir_name'] = forms.utils.ErrorList( [_('Error creating folder.')]) 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), 'breadcrumbs_title': _(u'New Folder') }, context_instance=Context(request))
def browse(request): """ Browse Files/Directories. """ # QUERY / PATH CHECK query = request.GET.copy() path = get_path(query.get('dir', '')) directory = get_path('') if path is None: msg = _('The requested Folder does not exist.') 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-Folder. 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(): 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: if re_prefix.search(file): filtered = True 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: try: # COUNTER/RESULTS if fileobject.filetype == 'Image': results_var['images_total'] += 1 if fileobject.filetype != 'Folder': results_var['delete_total'] += 1 elif fileobject.filetype == 'Folder' and fileobject.is_empty: results_var['delete_total'] += 1 if query.get('type') and query.get( 'type' ) in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[ query.get('type')]: results_var['select_total'] += 1 elif not query.get('type'): results_var['select_total'] += 1 except OSError: # Ignore items that have problems continue else: files.append(fileobject) results_var['results_current'] += 1 # COUNTER/RESULTS if fileobject.filetype: counter[fileobject.filetype] += 1 # SORTING query['o'] = request.GET.get('o', DEFAULT_SORTING_BY) query['ot'] = request.GET.get('ot', DEFAULT_SORTING_ORDER) files = sort_by_attr(files, request.GET.get('o', DEFAULT_SORTING_BY)) if not request.GET.get( 'ot') and DEFAULT_SORTING_ORDER == "desc" or request.GET.get( 'ot') == "desc": files.reverse() p = Paginator(files, LIST_PER_PAGE) try: page_nr = request.GET.get('p', '1') except: page_nr = 1 try: page = p.page(page_nr) except (EmptyPage, InvalidPage): page = p.page(p.num_pages) return render_to_response('filebrowser/index.html', { 'dir': path, 'p': p, 'page': page, 'results_var': results_var, 'counter': counter, 'query': query, 'title': _(u'FileBrowser'), 'settings_var': get_settings_var(), 'breadcrumbs': get_breadcrumbs(query, path), 'breadcrumbs_title': "" }, context_instance=Context(request))