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 delete(request): """ Delete existing File/Directory. When trying to delete a Directory, the Directory has to be empty. """ if request.method != "POST": return HttpResponseRedirect(reverse("fb_browse")) # 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(get_directory(), path) normalized = os.path.normpath(os.path.join(get_directory(), path, filename)) if not normalized.startswith(get_directory()) or ".." in normalized: msg = _("An error occurred") messages.add_message(request, messages.ERROR, msg) elif request.GET.get('filetype') != "Folder": relative_server_path = os.path.join(get_directory(), path, filename) try: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # DELETE FILE default_storage.delete(os.path.join(abs_path, filename)) # POST DELETE SIGNAL filebrowser_post_delete.send(sender=request, path=path, filename=filename) # MESSAGE & REDIRECT msg = _('The file %s was successfully deleted.') % (filename.lower()) messages.add_message(request, messages.SUCCESS, msg) except OSError: msg = _("An error occurred") messages.add_message(request, messages.ERROR, msg) else: try: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # DELETE FOLDER default_storage.rmtree(os.path.join(abs_path, filename)) # POST DELETE SIGNAL filebrowser_post_delete.send(sender=request, path=path, filename=filename) # MESSAGE & REDIRECT msg = _('The folder %s was successfully deleted.') % (filename.lower()) messages.add_message(request, messages.SUCCESS, msg) except OSError: msg = _("An error occurred") messages.add_message(request, messages.ERROR, msg) qs = query_helper(query, "", "filename,filetype") return HttpResponseRedirect(reverse("fb_browse") + qs)
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) # 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: file_basename = os.path.splitext(filename)[0] form = RenameForm(abs_path, file_extension, initial={'name': file_basename}) return render(request, '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') })
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) # 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 _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'] directory = get_directory() # 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): 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))) return HttpResponse('True')
def render(self, name, value, attrs=None): if value is None: value = "" directory = self.directory if self.directory: if callable(self.directory): directory = self.directory() directory = os.path.normpath( datetime.datetime.now().strftime(directory)) fullpath = os.path.join(get_directory(), directory) if not default_storage.isdir(fullpath): default_storage.makedirs(fullpath) final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) final_attrs[ 'search_icon'] = URL_FILEBROWSER_MEDIA + 'img/filebrowser_icon_show.gif' final_attrs['directory'] = directory final_attrs['extensions'] = self.extensions final_attrs['format'] = self.format final_attrs['ADMIN_THUMBNAIL'] = ADMIN_THUMBNAIL final_attrs['DEBUG'] = DEBUG if value != "": try: final_attrs['directory'] = os.path.split( value.path_relative_directory)[0] except: pass return render_to_string("filebrowser/custom_field.html", dict(locals(), MEDIA_URL=MEDIA_URL))
def render(self, name, value, attrs=None, renderer=None): if value is None: value = "" directory = self.directory if self.directory: if callable(self.directory): directory = self.directory() directory = os.path.normpath( datetime.datetime.now().strftime(directory)) fullpath = os.path.join(get_directory(), directory) if not default_storage.isdir(fullpath): default_storage.makedirs(fullpath) final_attrs = dict(type=self.input_type, name=name, **attrs) final_attrs["search_icon"] = (fb_settings.URL_FILEBROWSER_MEDIA + "img/filebrowser_icon_show.gif") final_attrs["directory"] = directory final_attrs["extensions"] = self.extensions final_attrs["format"] = self.format final_attrs["DEBUG"] = fb_settings.DEBUG if renderer is not None: return mark_safe( renderer.render( "filebrowser/custom_field.html", dict(locals(), MEDIA_URL=fb_settings.MEDIA_URL), )) else: return render_to_string( "filebrowser/custom_field.html", dict(locals(), MEDIA_URL=fb_settings.MEDIA_URL), )
def render(self, name, value, attrs=None): if value is None: value = "" directory = self.directory if self.directory: instance = attrs.pop('instance', None) if callable(self.directory): if instance and instance.id: directory = self.directory(instance) else: directory = self.directory() directory = os.path.normpath(datetime.datetime.now().strftime(directory)) fullpath = os.path.join(get_directory(), directory) if not default_storage.isdir(fullpath): default_storage.makedirs(fullpath) final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) final_attrs['search_icon'] = URL_FILEBROWSER_MEDIA + 'img/filebrowser_icon_show.gif' final_attrs['directory'] = directory final_attrs['extensions'] = self.extensions final_attrs['format'] = self.format final_attrs['ADMIN_THUMBNAIL'] = ADMIN_THUMBNAIL final_attrs['DEBUG'] = DEBUG if value != "": try: final_attrs['directory'] = os.path.split(value.path_relative_directory)[0] except: pass return render_to_string("filebrowser/custom_field.html", dict(locals(), MEDIA_URL=MEDIA_URL))
def mkdir(request): """ Make Directory. """ from filebrowser_safe.forms import MakeDirForm # QUERY / PATH CHECK query = request.GET path = get_path(query.get("dir", "")) if path is None: msg = _("The requested Folder does not exist.") messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse("fb_browse")) 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"]) # 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.util.ErrorList([_("Permission denied.")]) else: form.errors["dir_name"] = forms.util.ErrorList([_("Error creating folder.")]) else: form = MakeDirForm(abs_path) return render_to_response( "filebrowser/makedir.html", { "form": form, "query": query, "title": _("New Folder"), "settings_var": get_settings_var(), "breadcrumbs": get_breadcrumbs(query, path), "breadcrumbs_title": _("New Folder"), }, context_instance=Context(request), )
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 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 mkdir(request): """ Make Directory. """ from filebrowser_safe.forms import MakeDirForm # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) if path is None: msg = _('The requested Folder does not exist.') messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse("fb_browse")) 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']) # 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(request, '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') })
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 _check_file(request): """ Check if file already exists on the server. """ 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 list(request.POST.items()): if k != "folder": if default_storage.exists(os.path.join(get_directory(), folder, v)): fileArray[k] = v return HttpResponse(dumps(fileArray))
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. """ 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 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 render(self, name, value, attrs=None): if value is None: value = "" directory = self.directory if self.directory: if callable(self.directory): directory = self.directory() directory = os.path.normpath(datetime.datetime.now().strftime(directory)) fullpath = os.path.join(get_directory(), directory) if not default_storage.isdir(fullpath): default_storage.makedirs(fullpath) final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) final_attrs["search_icon"] = URL_FILEBROWSER_MEDIA + "img/filebrowser_icon_show.gif" final_attrs["directory"] = directory final_attrs["extensions"] = self.extensions final_attrs["format"] = self.format final_attrs["DEBUG"] = DEBUG return render_to_string("filebrowser/custom_field.html", dict(locals(), MEDIA_URL=MEDIA_URL))
def render(self, name, value, attrs=None, renderer=None): if value is None: value = "" directory = self.directory if self.directory: if callable(self.directory): directory = self.directory() directory = os.path.normpath(datetime.datetime.now().strftime(directory)) fullpath = os.path.join(get_directory(), directory) if not default_storage.isdir(fullpath): default_storage.makedirs(fullpath) final_attrs = dict(type=self.input_type, name=name, **attrs) final_attrs['search_icon'] = URL_FILEBROWSER_MEDIA + 'img/filebrowser_icon_show.gif' final_attrs['directory'] = directory final_attrs['extensions'] = self.extensions final_attrs['format'] = self.format final_attrs['DEBUG'] = DEBUG return render_to_string("filebrowser/custom_field.html", dict(locals(), MEDIA_URL=MEDIA_URL))
def mkdir(request): """ Make Directory. """ from filebrowser_safe.forms import MakeDirForm # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) if path is None: msg = _('The requested Folder does not exist.') messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse("fb_browse")) 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']) # 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, (errno, strerror): if errno == 13: form.errors['dir_name'] = forms.util.ErrorList([_('Permission denied.')]) else: form.errors['dir_name'] = forms.util.ErrorList([_('Error creating folder.')])
def get_fullpapers_path(instance, filename): filename = slugify_filename(filename) upload_to = os.path.join(get_directory(), "fullpapers", filename) return upload_to
def setUpClass(cls): super(FilebrowserStaffTestCase, cls).setUpClass() cls.upload_dir = default_storage.path(get_directory())
def _path_relative_directory(self): "path relative to the path returned by get_directory()" return path_strip(self.path, get_directory()).lstrip("/")
def path_relative_directory(self): """ path relative to the path returned by get_directory() """ return path_strip(self.path, get_directory()).lstrip("/")
def setUpClass(cls): super().setUpClass() cls.upload_dir = default_storage.path(get_directory()) cls.subdir = Path(cls.upload_dir) / "TEST_DIRECTORY" cls.subdir.mkdir()
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 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 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 url_path = "/".join([s.strip("/") for s in [get_directory(), path, 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 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) 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_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 folder(self): return os.path.dirname( path_strip(os.path.join(self.head, ''), get_directory()))
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 _path_relative_directory(self): "path relative to the path returned by get_directory()" return path_strip(self.path, get_directory())
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 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 url_path = "/".join([s.strip("/") for s in [get_directory(), path, 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 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 = sorted(files, key=lambda f: getattr(f, 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": _("Media Library"), "settings_var": get_settings_var(), "breadcrumbs": get_breadcrumbs(query, path), "breadcrumbs_title": "", }, context_instance=Context(request), )
def get_abstracts_path(instance, filename): filename = slugify_filename(filename) upload_to = os.path.join(get_directory(), "abstracts", filename) return upload_to
def setUpClass(cls): super().setUpClass() cls.upload_dir = default_storage.path(get_directory())
def path_relative_directory(self): """ path relative to the path returned by get_directory() """ return path_strip(self.name, get_directory()).lstrip("/")
def directory(self): return path_strip(self.path, get_directory())
def directory(self): return path_strip(self.name, get_directory())
def _directory(self): return path_strip(self.path, get_directory())