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) 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))
def makethumb(request, dir_name=None, file_name=None): """ Make Thumbnail(s) for existing Image or Directory This is useful if someone uploads images via FTP, not using the upload functionality of the FileBrowser. """ path = _get_path(dir_name) query = _get_query(request.GET) if file_name: # MAKE THUMB FOR SINGLE IMAGE file_path = os.path.join(PATH_SERVER, path, file_name) if os.path.isfile(file_path): _make_image_thumbnail(PATH_SERVER, path, file_name) else: # MAKE THUMBS FOR WHOLE DIRECTORY dir_path = os.path.join(PATH_SERVER, path) dir_list = os.listdir(dir_path) for file in dir_list: if os.path.isfile(os.path.join(PATH_SERVER, path, file)) and not os.path.isfile(os.path.join(PATH_SERVER, path, THUMB_PREFIX + file)) and not re.compile(THUMB_PREFIX, re.M).search(file) and _get_file_type(file) == "Image": _make_image_thumbnail(PATH_SERVER, path, file) # MESSAGE & REDIRECT msg = _('Thumbnail creation successful.') request.user.message_set.create(message=msg) return HttpResponseRedirect(URL_ADMIN + path + query['query_str_total']) return render_to_response('filebrowser/index.html', { 'dir': dir_name, 'query': query, 'settings_var': _get_settings_var(request.META['HTTP_HOST'], path), 'breadcrumbs': _get_breadcrumbs(_get_query(request.GET), dir_name, '') }, context_instance=Context(request))
def makethumb(request, dir_name=None, file_name=None): """ Make Thumbnail(s) for existing Image or Directory This is useful if someone uploads images via FTP, not using the upload functionality of the FileBrowser. """ path = _get_path(request, dir_name) query = _get_query(request.GET) if file_name: # MAKE THUMB FOR SINGLE IMAGE file_path = os.path.join(PATH_SERVER, path, file_name) if os.path.isfile(file_path): _make_image_thumbnail(PATH_SERVER, path, file_name) else: # MAKE THUMBS FOR WHOLE DIRECTORY dir_path = os.path.join(PATH_SERVER, path) dir_list = os.listdir(dir_path) for file in dir_list: if os.path.isfile(os.path.join(PATH_SERVER, path, file)) and not os.path.isfile(os.path.join(PATH_SERVER, path, THUMB_PREFIX + file)) and not re.compile(THUMB_PREFIX, re.M).search(file) and _get_file_type(file) == "Image": _make_image_thumbnail(PATH_SERVER, path, file) # MESSAGE & REDIRECT msg = _('Thumbnail creation successful.') request.user.message_set.create(message=msg) return HttpResponseRedirect(URL_ADMIN + path + query['query_str_total']) return render_to_response('filebrowser/index.html', { 'dir': dir_name, 'query': query, 'settings_var': _get_settings_var(request.META['HTTP_HOST'], path), 'breadcrumbs': _get_breadcrumbs(_get_query(request.GET), dir_name, ''), 'root_path': URL_HOME, }, context_instance=Context(request))
def delete(request): """ Delete existing File/Directory. 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) return HttpResponseRedirect(reverse("fb_browse")) abs_path = os.path.join(settings.MEDIA_ROOT, DIRECTORY, path) msg = "" if request.GET: if request.GET.get('filetype') != "Folder": relative_server_path = os.path.join(DIRECTORY, path, filename) try: # DELETE IMAGE VERSIONS/THUMBNAILS for version in VERSIONS: try: os.unlink(os.path.join(MEDIA_ROOT, _get_version_path(relative_server_path, version))) except: pass # DELETE FILE os.unlink(os.path.join(abs_path, filename)) msg = _('The file %s was successfully deleted.') % (filename.lower()) 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 else: try: os.rmdir(os.path.join(abs_path, filename)) msg = _('The directory %s was successfully deleted.') % (filename.lower()) 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) 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))
def upload(request, dir_name=None): """ Multipe Upload. """ from django.forms.formsets import formset_factory path = _get_path(request, dir_name) query = _get_query(request.GET) # PIL's Error "Suspension not allowed here" work around: # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html if STRICT_PIL: from PIL import ImageFile else: try: from PIL import ImageFile except ImportError: import ImageFile ImageFile.MAXBLOCK = IMAGE_MAXBLOCK # default is 64k UploadFormSet = formset_factory(UploadForm, formset=BaseUploadFormSet, extra=5) if request.method == 'POST': formset = UploadFormSet(data=request.POST, files=request.FILES, path_server=PATH_SERVER, path=path) if formset.is_valid(): for cleaned_data in formset.cleaned_data: if cleaned_data: # UPLOAD FILE _handle_file_upload(PATH_SERVER, path, cleaned_data['file']) if _get_file_type(cleaned_data['file'].name) == "Image": # MAKE THUMBNAIL _make_image_thumbnail(PATH_SERVER, path, cleaned_data['file'].name) # IMAGE GENERATOR if FORCE_GENERATOR or (cleaned_data['use_image_generator'] and (IMAGE_GENERATOR_LANDSCAPE != "" or IMAGE_GENERATOR_PORTRAIT != "")): _image_generator(PATH_SERVER, path, cleaned_data['file'].name) # GENERATE CROPPED/RECTANGULAR IMAGE if FORCE_GENERATOR or (cleaned_data['use_image_generator'] and IMAGE_CROP_GENERATOR != ""): _image_crop_generator(PATH_SERVER, path, cleaned_data['file'].name) # MESSAGE & REDIRECT msg = _('Upload successful.') request.user.message_set.create(message=msg) # on redirect, sort by date desc to see the uploaded files on top of the list redirect_url = URL_ADMIN + path + "?&ot=desc&o=3&" + query['pop'] return HttpResponseRedirect(redirect_url) else: formset = UploadFormSet(path_server=PATH_SERVER, path=path) return render_to_response('filebrowser/upload.html', { 'formset': formset, 'dir': dir_name, 'query': _get_query(request.GET), 'settings_var': _get_settings_var(request.META['HTTP_HOST'], path), 'breadcrumbs': _get_breadcrumbs(_get_query(request.GET), dir_name, _(u'Upload')), 'title': _(u'Select files to upload'), 'root_path': URL_HOME, }, context_instance=Context(request))
def upload(request, dir_name=None): """ Multipe Upload. """ from django.forms.formsets import formset_factory path = _get_path(dir_name) query = _get_query(request.GET) # PIL's Error "Suspension not allowed here" work around: # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html import ImageFile ImageFile.MAXBLOCK = 1000000 # default is 64k UploadFormSet = formset_factory(UploadForm, formset=BaseUploadFormSet, extra=5) if request.method == 'POST': formset = UploadFormSet(data=request.POST, files=request.FILES, path_server=PATH_SERVER, path=path) if formset.is_valid(): for cleaned_data in formset.cleaned_data: if cleaned_data: # UPLOAD FILE _handle_file_upload(PATH_SERVER, path, cleaned_data['file']) if _get_file_type(cleaned_data['file'].name) == "Image": # MAKE THUMBNAIL _make_image_thumbnail(PATH_SERVER, path, cleaned_data['file'].name) # IMAGE GENERATOR if cleaned_data['use_image_generator'] and (IMAGE_GENERATOR_LANDSCAPE != "" or IMAGE_GENERATOR_PORTRAIT != ""): _image_generator(PATH_SERVER, path, cleaned_data['file'].name) # GENERATE CROPPED/RECTANGULAR IMAGE if cleaned_data['use_image_generator'] and IMAGE_CROP_GENERATOR != "": _image_crop_generator(PATH_SERVER, path, cleaned_data['file'].name) # MESSAGE & REDIRECT msg = _('Upload successful.') request.user.message_set.create(message=msg) # on redirect, sort by date desc to see the uploaded files on top of the list redirect_url = URL_ADMIN + path + "?&ot=desc&o=3&" + query['pop'] return HttpResponseRedirect(redirect_url) else: formset = UploadFormSet(path_server=PATH_SERVER, path=path) return render_to_response('filebrowser/upload.html', { 'formset': formset, 'dir': dir_name, 'query': _get_query(request.GET), 'settings_var': _get_settings_var(request.META['HTTP_HOST'], path), 'breadcrumbs': _get_breadcrumbs(_get_query(request.GET), dir_name, 'Multiple Upload'), 'title': _('Select files to upload'), }, context_instance=Context(request))
def generateimages(request, dir_name=None, file_name=None): """ Generate Image Versions for existing singe Image or a whole Directory. This is useful if someone uploads images via FTP, not using the upload functionality of the FileBrowser. """ path = _get_path(dir_name) query = request.GET if file_name: # GENERATE IMAGES if IMAGE_GENERATOR_LANDSCAPE != "" or IMAGE_GENERATOR_PORTRAIT != "": _image_generator(PATH_SERVER, path, file_name) # GENERATE CROPPED/RECTANGULAR IMAGE if IMAGE_CROP_GENERATOR != "": _image_crop_generator(PATH_SERVER, path, file_name) else: # GENERATE IMAGES FOR WHOLE DIRECTORY dir_path = os.path.join(PATH_SERVER, path) dir_list = os.listdir(dir_path) for file in dir_list: if os.path.isfile( os.path.join(PATH_SERVER, path, file)) and _get_file_type(file) == "Image": # GENERATE IMAGES if IMAGE_GENERATOR_LANDSCAPE != "" or IMAGE_GENERATOR_PORTRAIT != "": _image_generator(PATH_SERVER, path, file) # GENERATE CROPPED/RECTANGULAR IMAGE if IMAGE_CROP_GENERATOR != "": _image_crop_generator(PATH_SERVER, path, file) # MESSAGE & REDIRECT msg = _('Successfully generated Images.') request.user.message_set.create(message=msg) return HttpResponseRedirect(URL_ADMIN + path + query_helper(query, "", "")) return render_to_response( 'filebrowser/index.html', { 'dir': dir_name, 'query': query, 'settings_var': _get_settings_var(), 'breadcrumbs': _get_breadcrumbs(query, dir_name, ''), 'root_path': URL_HOME, }, context_instance=Context(request))
def generateimages(request, dir_name=None, file_name=None): """ Generate Image Versions for existing singe Image or a whole Directory. This is useful if someone uploads images via FTP, not using the upload functionality of the FileBrowser. """ path = _get_path(request, dir_name) query = _get_query(request.GET) if file_name: # GENERATE IMAGES if IMAGE_GENERATOR_LANDSCAPE != "" or IMAGE_GENERATOR_PORTRAIT != "": _image_generator(PATH_SERVER, path, file_name) # GENERATE CROPPED/RECTANGULAR IMAGE if IMAGE_CROP_GENERATOR != "": _image_crop_generator(PATH_SERVER, path, file_name) else: # GENERATE IMAGES FOR WHOLE DIRECTORY dir_path = os.path.join(PATH_SERVER, path) dir_list = os.listdir(dir_path) for file in dir_list: if os.path.isfile(os.path.join(PATH_SERVER, path, file)) and not re.compile(THUMB_PREFIX, re.M).search(file) and _get_file_type(file) == "Image": # GENERATE IMAGES if IMAGE_GENERATOR_LANDSCAPE != "" or IMAGE_GENERATOR_PORTRAIT != "": _image_generator(PATH_SERVER, path, file) # GENERATE CROPPED/RECTANGULAR IMAGE if IMAGE_CROP_GENERATOR != "": _image_crop_generator(PATH_SERVER, path, file) # MESSAGE & REDIRECT msg = _('Successfully generated Images.') request.user.message_set.create(message=msg) return HttpResponseRedirect(URL_ADMIN + path + query['query_str_total']) return render_to_response('filebrowser/index.html', { 'dir': dir_name, 'query': query, 'settings_var': _get_settings_var(request.META['HTTP_HOST'], path), 'breadcrumbs': _get_breadcrumbs(_get_query(request.GET), dir_name, ''), 'root_path': URL_HOME, }, context_instance=Context(request))
def upload(request): """ Multipe File Upload. """ # 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) return HttpResponseRedirect(reverse("fb_browse")) abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path) 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')), }, context_instance=Context(request))
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) 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))
msg = _('The directory %s was successfully created.') % (form.cleaned_data['dir_name'].lower()) request.user.message_set.create(message=msg) # on redirect, sort by date desc to see the new directory on top of the list return HttpResponseRedirect(URL_ADMIN + path + "?&ot=desc&o=3&" + query['pop']) 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 directory.')]) else: form = MakeDirForm(PATH_SERVER, path) return render_to_response('filebrowser/makedir.html', { 'form': form, 'query': query, 'settings_var': _get_settings_var(request.META['HTTP_HOST'], path), 'breadcrumbs': _get_breadcrumbs(_get_query(request.GET), dir_name, 'Make Directory'), 'title': _('Make directory'), }, context_instance=Context(request)) mkdir = staff_member_required(never_cache(mkdir)) def upload(request, dir_name=None): """ Multipe Upload. """ from django.forms.formsets import formset_factory path = _get_path(dir_name) query = _get_query(request.GET)
def delete(request, dir_name=None): """ Delete existing File/Directory. If file is an Image, also delete thumbnail. When trying to delete a directory, the directory has to be empty. """ path = _get_path(request, dir_name) query = _get_query(request.GET) msg = "" if request.GET: if request.GET.get('type') != "Folder": server_path = os.path.join(PATH_SERVER, path, request.GET.get('filename')) try: # DELETE FILE os.unlink(server_path) # TRY DELETING THUMBNAIL path_thumb = os.path.join(PATH_SERVER, path, THUMB_PREFIX + request.GET.get('filename')) try: os.unlink(path_thumb) except OSError: pass # TRY DELETING IMAGE_VERSIONS versions_path = os.path.join(PATH_SERVER, path, request.GET.get('filename').replace(".", "_").lower() + IMAGE_GENERATOR_DIRECTORY) try: dir_list = os.listdir(versions_path) for file in dir_list: file_path = os.path.join(versions_path, file) os.unlink(file_path) os.rmdir(versions_path) except OSError: pass # MESSAGE & REDIRECT msg = _('The file %s was successfully deleted.') % (request.GET.get('filename').lower()) request.user.message_set.create(message=msg) return HttpResponseRedirect(URL_ADMIN + path + query['query_nodelete']) except OSError: # todo: define error message msg = OSError else: server_path = os.path.join(PATH_SERVER, path, request.GET.get('filename')) try: os.rmdir(server_path) # MESSAGE & REDIRECT msg = _('The directory %s was successfully deleted.') % (request.GET.get('filename').lower()) request.user.message_set.create(message=msg) return HttpResponseRedirect(URL_ADMIN + path + query['query_nodelete']) except OSError: # todo: define error message msg = OSError if 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(request.META['HTTP_HOST'], path), 'breadcrumbs': _get_breadcrumbs(_get_query(request.GET), dir_name, ''), 'root_path': URL_HOME, }, context_instance=Context(request))
query, "ot=desc,o=date", "ot,o,filter_type,filter_data")) 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 directory.')]) else: form = MakeDirForm(PATH_SERVER, path) return render_to_response( 'filebrowser/makedir.html', { 'form': form, 'query': query, 'settings_var': _get_settings_var(), 'breadcrumbs': _get_breadcrumbs(query, dir_name, _(u'New Folder')), 'title': _(u'New Folder'), 'root_path': URL_HOME, }, context_instance=Context(request)) mkdir = staff_member_required(never_cache(mkdir)) def upload(request, dir_name=None): """ Multipe Upload. """
def index(request, dir_name=None): """ Show list of files on a server-directory. """ path = _get_path(dir_name) query = request.GET # INITIAL VARIABLES results_var = { 'results_total': 0, 'results_current': 0, 'delete_total': 0, 'thumbs_total': 0, 'generator_total': 0, 'select_total': 0 } counter = {} for k, v in EXTENSIONS.iteritems(): counter[k] = 0 dir_list = os.listdir(os.path.join(PATH_SERVER, path)) files = [] for file in dir_list: # EXCLUDE FILES MATCHING THUMB_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 # only increment results_total if file is not filtered results_var['results_total'] += 1 # CREATE FILEOBJECT fileobject = FileObject(file, path, request.GET.get('type', '')) # COUNTER/RESULTS if fileobject.filetype: counter[fileobject.filetype] += 1 if fileobject.filetype == 'Image' and fileobject.image_is_generated( ) == False: results_var['generator_total'] += 1 if fileobject.filetype == 'Image': results_var['thumbs_total'] += 1 if fileobject.filetype != 'Folder': results_var['delete_total'] += 1 elif fileobject.filetype == 'Folder' and fileobject.folder_is_empty(): results_var['delete_total'] += 1 # 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) results_var['results_current'] += 1 # SORTING files = _sort_by_attr(files, request.GET.get('o', 'date')) if request.GET.get('ot') == "desc": files.reverse() return render_to_response( 'filebrowser/index.html', { 'dir': dir_name, 'files': files, 'results_var': results_var, 'query': query, 'counter': counter, 'settings_var': _get_settings_var(), 'breadcrumbs': _get_breadcrumbs(query, dir_name, ''), 'title': _(u'FileBrowser'), 'root_path': URL_HOME, }, context_instance=Context(request))
results_var['results_current'] = len(file_list) for file in file_dict: if file['file_type'] == 'Image': results_var['change_total'] += 1 if file['file_type'] != 'Folder': results_var['delete_total'] += 1 elif file['file_type'] == 'Folder' and file['flag_deletedir'] == True: results_var['delete_total'] += 1 return render_to_response('filebrowser/index.html', { 'dir': dir_name, 'file_dict': file_dict, 'results_var': results_var, 'query': query, 'counter': counter, 'settings_var': _get_settings_var(request.META['HTTP_HOST'], path), 'breadcrumbs': _get_breadcrumbs(_get_query(request.GET), dir_name, ''), 'title': _(u'FileBrowser'), 'root_path': URL_HOME, 'popmode': request.GET.get('pop'), }, context_instance=Context(request)) index = staff_member_required(never_cache(index)) def mkdir(request, dir_name=None): """ Make directory """ path = _get_path(request, dir_name) query = _get_query(request.GET)
def index(request, dir_name=None): """ Show list of files on a server-directory. """ path = _get_path(dir_name) query = _get_query(request.GET) # INITIAL VARIABLES results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'change_total': 0, 'imagegenerator_total': 0 } counter = {} for k,v in EXTENSIONS.iteritems(): counter[k] = 0 dir_list = os.listdir(os.path.join(PATH_SERVER, path)) file_list = [] for file in dir_list: # VARIABLES var_filesize_long = '' # filesize var_filesize_str = '' # filesize in B, kB, MB var_date = '' # YYYY-MM-dd var_path_thumb = '' # path to thumbnail var_link = '' # link to file (using URL_WWW), link to folder (using URL_ADMIN) var_select_link = '' # link to file (using URL_WWW) var_save_path = '' # Path to file relative to MEDIA_ROOT var_file_extension = '' # see EXTENSIONS in fb_settings.py var_file_type = '' # Folder, Image, Video, Document, Sound, Code, ... var_image_dimensions = '' # Image Dimensions (width, height) var_thumb_dimensions = '' # Thumbnail Dimensions (width, height) var_flag_makethumb = False # True, if Image has no Thumbnail. var_flag_deletedir = False # True, if Directory is empty. var_image_version = False # True, if Image is generated with ImageGenerator. # DON'T DISPLAY FILES STARTING WITH %THUMB_PREFIX% OR "." if re.compile(THUMB_PREFIX, re.M).search(file) or \ file.startswith('.'): # ... or with a '.' \ continue else: results_var['results_total'] += 1 # SIZE var_filesize_long = os.path.getsize(os.path.join(PATH_SERVER, path, file)) var_filesize_str = _get_filesize(var_filesize_long) # DATE / TIME date_time = os.path.getmtime(os.path.join(PATH_SERVER, path, file)) var_date = strftime("%Y-%m-%d", gmtime(date_time)) # EXTENSION / FLAG_EMPTYDIR / DELETE_TOTAL fn = os.path.join(PATH_SERVER, path, file) var_select_link = var_link = "%s%s%s" % (URL_WWW, path, file) if os.path.isfile(fn): # file var_file_extension = os.path.splitext(file)[1].lower() elif os.path.isdir(fn): # folder var_link = "%s%s%s" % (URL_ADMIN, path, file) if not os.listdir(os.path.join(PATH_SERVER, path, file)): var_flag_deletedir = True # only empty directories are allowed to be deleted # DETERMINE MEDIA SAVE PATH var_save_path = var_select_link if not SAVE_FULL_URL: var_save_path = var_save_path.replace(settings.MEDIA_URL, '').lstrip('/') # FILETYPE / COUNTER var_file_type = _get_file_type(file) if var_file_type: counter[var_file_type] += 1 # DIMENSIONS / MAKETHUMB / SELECT if var_file_type == 'Image': try: im = Image.open(os.path.join(PATH_SERVER, path, file)) var_image_dimensions = im.size var_path_thumb = "%s%s%s%s" % (URL_WWW, path, THUMB_PREFIX, file) try: thumb = Image.open(os.path.join(PATH_SERVER, path, THUMB_PREFIX + file)) var_thumb_dimensions = thumb.size except: # if thumbnail does not exist, show makethumb-Icon instead. var_path_thumb = settings.URL_FILEBROWSER_MEDIA + 'img/filebrowser_Thumb.gif' var_flag_makethumb = True except: # if image is corrupt, change filetype to not defined var_file_type = '' # check, if image is generated with ImageGenerator var_image_version = _is_image_version(file) if var_image_version == False: results_var['imagegenerator_total'] += 1 # FILTER / SEARCH flag_extend = False if query['filter_type'] != '' and query['filter_date'] != '' and var_file_type == query['filter_type'] and _get_filterdate(query['filter_date'], date_time): flag_extend = True elif query['filter_type'] != '' and query['filter_date'] == '' and var_file_type == query['filter_type']: flag_extend = True elif query['filter_type'] == '' and query['filter_date'] != '' and _get_filterdate(query['filter_date'], date_time): flag_extend = True elif query['filter_type'] == '' and query['filter_date'] == '': flag_extend = True if query['q'] and not re.compile(query['q'].lower(), re.M).search(file.lower()): flag_extend = False # APPEND FILE_LIST if flag_extend == True: file_list.append([file, var_filesize_long, var_filesize_str, var_date, var_path_thumb, var_link, var_select_link, var_save_path, var_file_extension, var_file_type, var_image_dimensions, var_thumb_dimensions, file.lower(), var_flag_makethumb, var_flag_deletedir, var_image_version]) # SORT LIST file_list.sort(lambda x, y: cmp(x[int(query['o'])], y[int(query['o'])])) if query['ot'] == "desc": file_list.reverse() # MAKE DICTIONARY (for better readability in the templates) file_dict = _make_filedict(file_list) # RESULTS results_var['results_current'] = len(file_list) for file in file_dict: if file['file_type'] == 'Image': results_var['change_total'] += 1 if file['file_type'] != 'Folder': results_var['delete_total'] += 1 elif file['file_type'] == 'Folder' and file['flag_deletedir'] == True: results_var['delete_total'] += 1 return render_to_response('filebrowser/index.html', { 'dir': dir_name, 'file_dict': file_dict, 'results_var': results_var, 'query': query, 'counter': counter, 'settings_var': _get_settings_var(request.META['HTTP_HOST'], path), 'breadcrumbs': _get_breadcrumbs(_get_query(request.GET), dir_name, ''), 'title': _(u'FileBrowser'), 'root_path': URL_HOME, }, context_instance=Context(request))
def delete(request, dir_name=None): """ Delete existing File/Directory. If file is an Image, also delete thumbnail. When trying to delete a directory, the directory has to be empty. """ path = _get_path(dir_name) query = _get_query(request.GET) msg = "" if request.GET: if request.GET.get('type') != "Folder": server_path = os.path.join(PATH_SERVER, path, request.GET.get('filename')) try: # DELETE FILE os.unlink(server_path) # TRY DELETING THUMBNAIL path_thumb = os.path.join(PATH_SERVER, path, THUMB_PREFIX + request.GET.get('filename')) try: os.unlink(path_thumb) except OSError: pass # TRY DELETING IMAGE_VERSIONS versions_path = os.path.join(PATH_SERVER, path, request.GET.get('filename').replace(".", "_").lower() + IMAGE_GENERATOR_DIRECTORY) try: dir_list = os.listdir(versions_path) for file in dir_list: file_path = os.path.join(versions_path, file) os.unlink(file_path) os.rmdir(versions_path) except OSError: pass # MESSAGE & REDIRECT msg = _('The file %s was successfully deleted.') % (request.GET.get('filename').lower()) request.user.message_set.create(message=msg) return HttpResponseRedirect(URL_ADMIN + path + query['query_nodelete']) except OSError: # todo: define error message msg = OSError else: server_path = os.path.join(PATH_SERVER, path, request.GET.get('filename')) try: os.rmdir(server_path) # MESSAGE & REDIRECT msg = _('The directory %s was successfully deleted.') % (request.GET.get('filename').lower()) request.user.message_set.create(message=msg) return HttpResponseRedirect(URL_ADMIN + path + query['query_nodelete']) except OSError: # todo: define error message msg = OSError if 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(request.META['HTTP_HOST'], path), 'breadcrumbs': _get_breadcrumbs(_get_query(request.GET), dir_name, '') }, context_instance=Context(request))
def upload(request, dir_name=None): """ Multipe Upload. """ from django.forms.formsets import formset_factory path = _get_path(dir_name) query = request.GET # PIL's Error "Suspension not allowed here" work around: # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html if STRICT_PIL: from PIL import ImageFile else: try: from PIL import ImageFile except ImportError: import ImageFile ImageFile.MAXBLOCK = IMAGE_MAXBLOCK # default is 64k UploadFormSet = formset_factory(UploadForm, formset=BaseUploadFormSet, extra=5) if request.method == 'POST': formset = UploadFormSet(data=request.POST, files=request.FILES, path_server=PATH_SERVER, path=path) if formset.is_valid(): for cleaned_data in formset.cleaned_data: if cleaned_data: # UPLOAD FILE _handle_file_upload(PATH_SERVER, path, cleaned_data['file']) if _get_file_type(cleaned_data['file'].name) == "Image": # IMAGE GENERATOR if FORCE_GENERATOR or ( cleaned_data['use_image_generator'] and (IMAGE_GENERATOR_LANDSCAPE != "" or IMAGE_GENERATOR_PORTRAIT != "")): _image_generator(PATH_SERVER, path, cleaned_data['file'].name) # GENERATE CROPPED/RECTANGULAR IMAGE if FORCE_GENERATOR or ( cleaned_data['use_image_generator'] and IMAGE_CROP_GENERATOR != ""): _image_crop_generator(PATH_SERVER, path, cleaned_data['file'].name) # MESSAGE & REDIRECT msg = _('Upload successful.') request.user.message_set.create(message=msg) # on redirect, sort by date desc to see the uploaded files on top of the list # remove filter in order to actually _see_ the uploaded file(s) return HttpResponseRedirect(URL_ADMIN + path + query_helper( query, "ot=desc,o=date", "ot,o,filter_type,filter_data")) else: formset = UploadFormSet(path_server=PATH_SERVER, path=path) return render_to_response( 'filebrowser/upload.html', { 'formset': formset, 'dir': dir_name, 'query': query, 'settings_var': _get_settings_var(), 'breadcrumbs': _get_breadcrumbs(query, dir_name, _(u'Upload')), 'title': _(u'Select files to upload'), 'root_path': URL_HOME, }, context_instance=Context(request))
# 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") 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 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)) mkdir = staff_member_required(never_cache(mkdir)) @csrf_exempt def upload(request): """ Multipe File Upload. """ from django.http import parse_cookie # QUERY / PATH CHECK query = request.GET
def index(request, dir_name=None): """ Show list of files on a server-directory. """ path = _get_path(dir_name) query = _get_query(request.GET) # INITIAL VARIABLES results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'change_total': 0, 'imagegenerator_total': 0 } counter = {} for k,v in EXTENSIONS.iteritems(): counter[k] = 0 dir_list = os.listdir(os.path.join(PATH_SERVER, path)) file_list = [] for file in dir_list: # VARIABLES var_filesize_long = '' # filesize var_filesize_str = '' # filesize in B, kB, MB var_date = '' # YYYY-MM-dd var_path_thumb = '' # path to thumbnail var_link = '' # link to file (using URL_WWW), link to folder (using URL_ADMIN) var_select_link = '' # link to file (using URL_WWW) var_file_extension = '' # see EXTENSIONS in fb_settings.py var_file_type = '' # Folder, Image, Video, Document, Sound, Code, ... var_image_dimensions = '' # Image Dimensions (width, height) var_thumb_dimensions = '' # Thumbnail Dimensions (width, height) var_flag_makethumb = False # True, if Image has no Thumbnail. var_flag_deletedir = False # True, if Directory is empty. var_image_version = False # True, if Image is generated with ImageGenerator. # DON'T DISPLAY FILES STARTING WITH %THUMB_PREFIX% OR "." if re.compile(THUMB_PREFIX, re.M).search(file) or \ file.startswith('.'): # ... or with a '.' \ continue else: results_var['results_total'] += 1 # SIZE var_filesize_long = os.path.getsize(os.path.join(PATH_SERVER, path, file)) var_filesize_str = _get_filesize(var_filesize_long) # DATE / TIME date_time = os.path.getmtime(os.path.join(PATH_SERVER, path, file)) var_date = strftime("%Y-%m-%d", gmtime(date_time)) # EXTENSION / FLAG_EMPTYDIR / DELETE_TOTAL if os.path.isfile(os.path.join(PATH_SERVER, path, file)): # file var_file_extension = os.path.splitext(file)[1].lower() var_select_link = var_link = "%s%s%s" % (URL_WWW, path, file) elif os.path.isdir(os.path.join(PATH_SERVER, path, file)): # folder var_link = "%s%s%s" % (URL_ADMIN, path, file) var_select_link = "%s%s%s/" % (URL_WWW, path, file) if not os.listdir(os.path.join(PATH_SERVER, path, file)): var_flag_deletedir = True # only empty directories are allowed to be deleted # FILETYPE / COUNTER var_file_type = _get_file_type(file) if var_file_type: counter[var_file_type] += 1 # DIMENSIONS / MAKETHUMB / SELECT if var_file_type == 'Image': try: im = Image.open(os.path.join(PATH_SERVER, path, file)) var_image_dimensions = im.size var_path_thumb = "%s%s%s%s" % (URL_WWW, path, THUMB_PREFIX, file) try: thumb = Image.open(os.path.join(PATH_SERVER, path, THUMB_PREFIX + file)) var_thumb_dimensions = thumb.size except: # if thumbnail does not exist, show makethumb-Icon instead. var_path_thumb = settings.ADMIN_MEDIA_PREFIX + 'filebrowser/img/filebrowser_Thumb.gif' var_flag_makethumb = True except: # if image is corrupt, change filetype to not defined var_file_type = '' # check, if image is generated with ImageGenerator var_image_version = _is_image_version(file) if var_image_version == False: results_var['imagegenerator_total'] += 1 # FILTER / SEARCH flag_extend = False if query['filter_type'] != '' and query['filter_date'] != '' and file_type == query['filter_type'] and _get_filterdate(query['filter_date'], date_time): flag_extend = True elif query['filter_type'] != '' and query['filter_date'] == '' and var_file_type == query['filter_type']: flag_extend = True elif query['filter_type'] == '' and query['filter_date'] != '' and _get_filterdate(query['filter_date'], date_time): flag_extend = True elif query['filter_type'] == '' and query['filter_date'] == '': flag_extend = True if query['q'] and not re.compile(query['q'].lower(), re.M).search(file.lower()): flag_extend = False # APPEND FILE_LIST if flag_extend == True: file_list.append([file, var_filesize_long, var_filesize_str, var_date, var_path_thumb, var_link, var_select_link, var_file_extension, var_file_type, var_image_dimensions, var_thumb_dimensions, file.lower(), var_flag_makethumb, var_flag_deletedir, var_image_version]) # SORT LIST file_list.sort(lambda x, y: cmp(x[int(query['o'])], y[int(query['o'])])) if query['ot'] == "desc": file_list.reverse() # MAKE DICTIONARY (for better readability in the templates) file_dict = _make_filedict(file_list) # RESULTS results_var['results_current'] = len(file_list) for file in file_dict: if file['file_type'] == 'Image': results_var['change_total'] += 1 if file['file_type'] != 'Folder': results_var['delete_total'] += 1 elif file['file_type'] == 'Folder' and file['flag_deletedir'] == True: results_var['delete_total'] += 1 return render_to_response('filebrowser/index.html', { 'dir': dir_name, 'file_dict': file_dict, 'results_var': results_var, 'query': query, 'counter': counter, 'settings_var': _get_settings_var(request.META['HTTP_HOST'], path), 'breadcrumbs': _get_breadcrumbs(_get_query(request.GET), dir_name, ''), 'title': _('FileBrowser'), }, context_instance=Context(request))
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) if directory is None: # The DIRECTORY does not exist, raise an error to prevent eternal redirecting. raise ImproperlyConfigured(_("Error finding upload directory: %s. Maybe it does not exist?" % os.path.join(MEDIA_ROOT, DIRECTORY))) redirect_url = reverse("fb_browse") + query_helper(query, "", "dir") return HttpResponseRedirect(redirect_url) abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path) # INITIAL VARIABLES 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 = [] # print "LISTING FILES: ", dir_list for file in dir_list: # print repr(file) # 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(smart_str(DIRECTORY), smart_str(path), smart_str(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) results_var['results_current'] += 1 # 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 # COUNTER/RESULTS if fileobject.filetype: counter[fileobject.filetype] += 1 # SORTING 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, 'results_var': results_var, 'counter': counter, 'query': query, 'title': _(u'FileBrowser'), 'settings_var': _get_settings_var(), 'breadcrumbs': _get_breadcrumbs(query, path, ''), }, context_instance=Context(request))