def test_get_version_path_do_not_check_file(self): for version in settings.FILEBROWSER_VERSIONS: path = get_version_path("3/rss.gif", version, check_file=False) ends = "3/rss_" + version + ".gif" print("Path [%s] have to ends with [%s], version [%s]\n" % (path, ends, version)) self.assertTrue(path.endswith(ends), "Path [%s] is not ends with [%s]" % (path, ends,)) for version2 in settings.FILEBROWSER_VERSIONS: path2 = get_version_path(path, version2, check_file=False) ends = "3/rss_" + version2 + ".gif" print("Path [%s] have to ends with [%s], version [%s->%s]\n" % (path2, ends, version, version2)) self.assertTrue(path2.endswith(ends), "Path [%s] is not ends with [%s]" % (path2, ends,)) ends = "3/rss.gif" orig_path = get_version_path(path, version_prefix='', check_file=False) print("Path [%s] have to ends with [%s], version [%s->]\n" % (orig_path, ends, version)) self.assertTrue(orig_path.endswith(ends), "Path [%s] is not ends with [%s]" % (path2, ends,)) orig_path = get_version_path(path, check_file=False) print("Path [%s] have to ends with [%s], version [%s->]\n" % (orig_path, ends, version)) self.assertTrue(orig_path.endswith(ends), "Path [%s] is not ends with [%s]" % (path2, ends,))
def test_get_version_path(self): for version in settings.FILEBROWSER_VERSIONS: version_generator("2/rss.gif", version) for version in settings.FILEBROWSER_VERSIONS: path = get_version_path("2/rss.gif", version) ends = "rss_" + version + ".gif" print("Path [%s] have to ends with [%s], version [%s]\n" % (path, ends, version)) self.assertTrue(path.endswith(ends), "Path [%s] is not ends with [%s]" % (path, ends,)) for version2 in settings.FILEBROWSER_VERSIONS: path2 = get_version_path(path, version2) ends = "rss_" + version2 + ".gif" print("Path [%s] have to ends with [%s], version [%s->%s]\n" % (path2, ends, version, version2)) self.assertTrue(path2.endswith(ends), "Path [%s] is not ends with [%s]" % (path2, ends,)) ends = "rss.gif" orig_path = get_version_path(path, None) print("Path [%s] have to ends with [%s], version [%s->]\n" % (orig_path, ends, version)) self.assertTrue(orig_path.endswith(ends), "Path [%s] is not ends with [%s]" % (path2, ends,)) orig_path = get_version_path(path) print("Path [%s] have to ends with [%s], version [%s->]\n" % (orig_path, ends, version)) self.assertTrue(orig_path.endswith(ends), "Path [%s] is not ends with [%s]" % (path2, ends,))
def test_detail(test): """ Check the detail view and version generation. Check also renaming of files. """ url = reverse('%s:fb_detail' % test.site_name) response = test.c.get(url, {'dir': test.testfile.folder, 'filename': test.testfile.filename}) # Check we get an OK response for the detail view test.assertTrue(response.status_code == 200) # At this moment all versions should be generated. Check that. for version_suffix in VERSIONS: path = get_version_path(test.testfile.path, version_suffix, site=test.site) test.assertTrue(test.site.storage.exists(path)) # Attemp renaming the file url = '?'.join([url, urlencode({'dir': test.testfile.folder, 'filename': test.testfile.filename})]) response = test.c.post(url, {'name': 'testpic.jpg'}) # Check we get 302 response for renaming test.assertTrue(response.status_code == 302) # Check the file was renamed correctly: test.assertTrue(test.site.storage.exists(os.path.join(test.testfile.head, 'testpic.jpg'))) # Store the renamed file test.testfile = FileObject(os.path.join(test.testfile.head, 'testpic.jpg'), site=test.site) # Check all versions were deleted (after renaming): for version_suffix in VERSIONS: path = get_version_path(test.testfile.path, version_suffix, site=test.site) test.assertFalse(test.site.storage.exists(path))
def test_detail(test): """ Check the detail view and version generation. Check also renaming of files. """ url = reverse('%s:fb_detail' % test.site_name) response = test.c.get(url, { 'dir': test.testfile.folder, 'filename': test.testfile.filename }) # Check we get an OK response for the detail view test.assertTrue(response.status_code == 200) # At this moment all versions should be generated. Check that. for version_suffix in VERSIONS: path = get_version_path(test.testfile.path, version_suffix, site=test.site) print 'PATH=%s' % path test.assertTrue(test.site.storage.exists(path)) # Attemp renaming the file url = '?'.join([ url, urlencode({ 'dir': test.testfile.folder, 'filename': test.testfile.filename }) ]) response = test.c.post(url, {'name': 'testpic.jpg'}) # Check we get 302 response for renaming test.assertTrue(response.status_code == 302) # Check the file was renamed correctly: test.assertTrue( test.site.storage.exists( os.path.join(test.testfile.head, 'testpic.jpg'))) # Store the renamed file test.testfile = FileObject(os.path.join(test.testfile.head, 'testpic.jpg'), site=test.site) # Check all versions were deleted (after renaming): for version_suffix in VERSIONS: path = get_version_path(test.testfile.path, version_suffix, site=test.site) test.assertFalse(test.site.storage.exists(path))
def test_browse(self): response = self.client.get(reverse('fb_browse')) self.assertEqual(response.status_code, 200) value = os.path.join(self.working_dir, self.image_name) version_filename = get_version_path(value, fb_settings.ADMIN_THUMBNAIL) os.remove(version_filename)
def version_generate(self, version_suffix): version_path = get_version_path(self.path, version_suffix, site=self.site) if not self.site.storage.isfile(version_path): version_path = version_generator(self.path, version_suffix, site=self.site) elif self.site.storage.modified_time(self.path) > self.site.storage.modified_time(version_path): version_path = version_generator(self.path, version_suffix, force=True, site=self.site) return FileObject(version_path, site=self.site)
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 site = context.get('site', get_default_site()) directory = site.directory try: if isinstance(source, FileObject): site = source.site source = source.path source = force_unicode(source) version_path = get_version_path(source, version_prefix, site=site) if not site.storage.isfile(version_path): version_path = version_generator(source, version_prefix, site=site) elif site.storage.modified_time(source) > site.storage.modified_time(version_path): version_path = version_generator(source, version_prefix, force=True, site=site) return site.storage.url(version_path) except: return ""
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 site = context.get('filebrowser_site', get_default_site()) directory = site.directory try: if isinstance(source, FileObject): site = source.site source = source.path if isinstance(source, File): source = source.name source = force_unicode(source) if FORCE_PLACEHOLDER: source = PLACEHOLDER elif SHOW_PLACEHOLDER and not site.storage.isfile(source): source = PLACEHOLDER version_path = get_version_path(source, version_prefix, site=site) if not site.storage.isfile(version_path): version_path = version_generator(source, version_prefix, site=site) elif site.storage.modified_time(source) > site.storage.modified_time(version_path): version_path = version_generator(source, version_prefix, force=True, site=site) context[self.var_name] = FileObject(version_path, site=site) except: context[self.var_name] = "" return ''
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: if isinstance(source, FileObject): source = source.path source = force_unicode(source) version_path = get_version_path(source, version_prefix) if not os.path.isfile(version_path): version_path = version_generator(source, version_prefix) elif os.path.getmtime(source) > os.path.getmtime(version_path): version_path = version_generator(source, version_prefix, force=True) context[self.var_name] = FileObject(version_path) except: context[self.var_name] = "" return ''
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: source = force_unicode(source) version_path = get_version_path(url_to_path(source), version_prefix) if not os.path.isfile(smart_str(os.path.join(MEDIA_ROOT, version_path))): # create version version_path = version_generator(url_to_path(source), version_prefix) elif os.path.getmtime(smart_str(os.path.join(MEDIA_ROOT, url_to_path(source)))) > os.path.getmtime(smart_str(os.path.join(MEDIA_ROOT, version_path))): # recreate version if original image was updated version_path = version_generator(url_to_path(source), version_prefix, force=True) context[self.var_name] = FileObject(version_path) except: context[self.var_name] = "" return ''
def version_generate(self, version_suffix): version_path = get_version_path(self.path, version_suffix, media_root=self.media_root) if not os.path.isfile(version_path): version_path = version_generator(self.path, version_suffix, media_root=self.media_root) elif os.path.getmtime(self.path) > os.path.getmtime(version_path): version_path = version_generator(self.path, version_suffix, force=True, media_root=self.media_root) return FileObject(version_path, media_root=self.media_root, media_url=self.media_url)
def _save_crop(self, org_path, version=None, **size_args): tmpfile = File(NamedTemporaryFile()) try: f = self.storage.open(org_path) im = Image.open(f) try: version_path = functions.get_version_path(org_path, version, site=self) except AttributeError: # modern filebrowser from filebrowser.base import FileObject version_path = FileObject(org_path).version_path(version) root, ext = os.path.splitext(version_path) size_args.update({ 'width' : VERSIONS[version].get('width'), 'height' : VERSIONS[version].get('height') }) im = self._do_crop(im, **size_args) try: im.save(tmpfile, format=Image.EXTENSION[ext], quality=fb_settings.VERSION_QUALITY, optimize=(ext != '.gif')) except IOError: im.save(tmpfile, format=Image.EXTENSION[ext], quality=fb_settings.VERSION_QUALITY) # Remove the old version, if there's any if version_path != self.storage.get_available_name(version_path): self.storage.delete(version_path) self.storage.save(version_path, tmpfile) finally: tmpfile.close() try: f.close() except: pass
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 site = context.get('site', get_default_site()) directory = site.directory try: if isinstance(source, FileObject): site = source.site source = source.path if isinstance(source, File): source = source.name source = force_unicode(source) if FORCE_PLACEHOLDER: source = PLACEHOLDER elif SHOW_PLACEHOLDER and not site.storage.isfile(source): source = PLACEHOLDER version_path = get_version_path(source, version_prefix, site=site) if not site.storage.isfile(version_path): version_path = version_generator(source, version_prefix, site=site) elif site.storage.modified_time(source) > site.storage.modified_time(version_path): version_path = version_generator(source, version_prefix, force=True, site=site) context[self.var_name] = FileObject(version_path, site=site) except: context[self.var_name] = "" return ''
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: source = force_unicode(source) version_path = get_version_path(url_to_path(source), version_prefix) if not os.path.isfile( smart_str(os.path.join(MEDIA_ROOT, version_path))): # create version version_path = version_generator(url_to_path(source), version_prefix) elif os.path.getmtime( smart_str(os.path.join( MEDIA_ROOT, url_to_path(source)))) > os.path.getmtime( smart_str(os.path.join(MEDIA_ROOT, version_path))): # recreate version if original image was updated version_path = version_generator(url_to_path(source), version_prefix, force=True) context[self.var_name] = FileObject(version_path) except: context[self.var_name] = "" return ''
def version_generate(self, version_suffix): version_path = get_version_path(self.path, version_suffix) if not os.path.isfile(version_path): version_path = version_generator(self.path, version_suffix) elif os.path.getmtime(self.path) > os.path.getmtime(version_path): version_path = version_generator(self.path, version_suffix, force=True) return FileObject(version_path)
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(source), version_prefix ) if not os.path.isfile(smart_str(os.path.join(fb_settings.MEDIA_ROOT, version_path))): # create version version_path = version_generator( url_to_path(source), version_prefix ) elif os.path.getmtime(smart_str(os.path.join(fb_settings.MEDIA_ROOT, url_to_path(source)))) > os.path.getmtime(smart_str(os.path.join(fb_settings.MEDIA_ROOT, version_path))): # recreate version if original image was updated version_path = version_generator( url_to_path(source), version_prefix, force=True ) return path_to_url(version_path) except: return ""
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 media_root = context.get('media_root', MEDIA_ROOT) media_url = context.get('media_url', MEDIA_URL) try: if isinstance(source, FileObject): source = source.path source = force_unicode(source) version_path = get_version_path(source, version_prefix, media_root=media_root) if not os.path.isfile(version_path): version_path = version_generator(source, version_prefix, media_root=media_root) elif os.path.getmtime(source) > os.path.getmtime(version_path): version_path = version_generator(source, version_prefix, force=True, media_root=media_root) context[self.var_name] = FileObject(version_path, media_root=media_root, media_url=media_url) except: context[self.var_name] = "" return ''
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 directory = context.get('directory', DIRECTORY) try: if isinstance(source, FileObject): source = source.path source = force_unicode(source) version_path = get_version_path(source, version_prefix, directory=directory) if not os.path.isfile(version_path): version_path = version_generator(source, version_prefix, directory=directory) elif os.path.getmtime(source) > os.path.getmtime(version_path): version_path = version_generator(source, version_prefix, force=True, directory=directory) return path_to_url(version_path) except: return ""
def _url_thumbnail(self): """ Thumbnail URL. """ if self.filetype == "Image": return u"{0}".format(url_join(fb_settings.MEDIA_URL, get_version_path(self.path, ADMIN_THUMBNAIL))) else: return ""
def generate_fb_version(image_path, version_suffix): from filebrowser.functions import get_version_path, version_generator version_path = get_version_path(image_path, version_suffix) if not os.path.isfile(version_path): version_path = version_generator(image_path, version_suffix) elif os.path.getmtime(image_path) > os.path.getmtime(version_path): version_path = version_generator(image_path, version_suffix, force=True) return version_path
def _url_thumbnail(self): """ Thumbnail URL. """ if self.filetype == "Image": return u"%s" % url_join(MEDIA_URL, get_version_path(self.path, 'fb_thumb')) else: return ""
def _upload_file(self, request): """ Upload file to the server. """ if request.method == "POST": folder = request.GET.get('folder', '') if request.is_ajax(): # Advanced (AJAX) submission filedata = ContentFile(request.raw_post_data) else: # Basic (iframe) submission if len(request.FILES) != 1: raise Http404('Invalid request! Multiple files included.') filedata = request.FILES.values()[0] try: filedata.name = convert_filename(request.GET['qqfile']) except KeyError: return HttpResponseBadRequest('Invalid request! No filename given.') fb_uploadurl_re = re.compile(r'^.*(%s)' % reverse("filebrowser:fb_upload", current_app=self.name)) folder = fb_uploadurl_re.sub('', folder) path = os.path.join(self.directory, folder) file_name = os.path.join(path, filedata.name) file_already_exists = self.storage.exists(file_name) # Check for name collision with a directory if file_already_exists and self.storage.isdir(file_name): ret_json = {'success': False, 'filename': filedata.name} return HttpResponse(json.dumps(ret_json)) signals.filebrowser_pre_upload.send(sender=request, path=request.POST.get('folder'), file=filedata, site=self) uploadedfile = handle_file_upload(path, filedata, site=self) if file_already_exists and OVERWRITE_EXISTING: old_file = smart_unicode(file_name) new_file = smart_unicode(uploadedfile) self.storage.move(new_file, old_file, allow_overwrite=True) else: file_name = smart_unicode(uploadedfile) fobj = FileObject(smart_unicode(file_name), site=self) signals.filebrowser_post_upload.send(sender=request, path=request.POST.get('folder'), file=fobj, site=self) if fobj.filetype == "Image": version_path = get_version_path(fobj.path,ADMIN_THUMBNAIL,site=self) if not self.storage.isfile(version_path): version_path = version_generator(fobj.path, ADMIN_THUMBNAIL, site=self) thumbnail_path = self.storage.url(version_path) else: thumbnail_path = '' # let Ajax Upload know whether we saved it or not ret_json = {'success': True, 'filename': filedata.name, 'path': fobj.path, 'url': fobj.url, 'thumbnail': thumbnail_path, 'filetype': fobj.filetype } return HttpResponse(json.dumps(ret_json))
def rename(request): """ Rename existing File/Directory. Includes renaming existing Image Versions/Thumbnails. """ from filebrowser.forms import RenameForm # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) if 'pop' in query: is_popup = True else: is_popup = False filename = get_file(query.get('dir', ''), 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.warning(request, message=msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = _check_access(request, 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(fb_settings.DIRECTORY, path, filename) new_filename = form.cleaned_data['name'] + file_extension new_relative_server_path = os.path.join(fb_settings.DIRECTORY, path, new_filename) try: # PRE RENAME SIGNAL filebrowser_pre_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) # DELETE IMAGE VERSIONS/THUMBNAILS # regenerating versions/thumbs will be done automatically for version in VERSIONS: try: os.unlink(os.path.join(fb_settings.MEDIA_ROOT, get_version_path(relative_server_path, version))) except: pass # RENAME ORIGINAL os.rename(os.path.join(fb_settings.MEDIA_ROOT, relative_server_path), os.path.join(fb_settings.MEDIA_ROOT, 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.success(request, message=msg) redirect_url = reverse("fb_browse") + query_helper(query, "", "filename") return HttpResponseRedirect(redirect_url) except OSError, (errno, strerror): form.errors['name'] = forms.util.ErrorList([_('Error.')])
def test_version_object(self): url = '{0}?filename={1}'.format(reverse('fb_versions'), self.image_name) self.client.get(url) for version in fb_settings.ADMIN_VERSIONS: value = os.path.join(self.working_dir, self.image_name) version_filename = get_version_path(value, version) self.assertTrue(os.path.isfile(version_filename)) os.remove(version_filename)
def _url_thumbnail(self): """ Thumbnail URL. """ if self.filetype == "Image": return u"%s" % url_join( fb_settings.MEDIA_URL, get_version_path(self.path, ADMIN_THUMBNAIL)) else: return ""
def get_image_version(source, version_prefix): source = force_unicode(source) version_path = get_version_path(url_to_path(source), version_prefix) if not os.path.isfile(smart_str(os.path.join(MEDIA_ROOT, version_path))): # create version version_path = version_generator(url_to_path(source), version_prefix) elif os.path.getmtime(smart_str(os.path.join(MEDIA_ROOT, url_to_path(source)))) > os.path.getmtime(smart_str(os.path.join(MEDIA_ROOT, version_path))): # recreate version if original image was updated version_path = version_generator(url_to_path(source), version_prefix, force=True) return path_to_url(version_path)
def rename(request, root_directory=DIRECTORY): """ Rename existing File/Directory. Includes renaming existing Image Versions/Thumbnails. """ from filebrowser.forms import RenameForm # QUERY / PATH CHECK query = request.GET path = get_path(query.get("dir", ""), root_directory) filename = get_file(query.get("dir", ""), query.get("filename", ""), root_directory) 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.") _message(request, msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = os.path.join(MEDIA_ROOT, root_directory, path) file_extension = os.path.splitext(filename)[1].lower() if request.method == "POST": form = RenameForm(abs_path, file_extension, request.POST) if form.is_valid(): relative_server_path = os.path.join(root_directory, path, filename) new_filename = form.cleaned_data["name"] + file_extension new_relative_server_path = os.path.join(root_directory, path, new_filename) try: # PRE RENAME SIGNAL filebrowser_pre_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) # DELETE IMAGE VERSIONS/THUMBNAILS # regenerating versions/thumbs will be done automatically for version in VERSIONS: try: os.unlink(os.path.join(MEDIA_ROOT, get_version_path(relative_server_path, version))) except: pass # RENAME ORIGINAL os.rename( os.path.join(MEDIA_ROOT, relative_server_path), os.path.join(MEDIA_ROOT, new_relative_server_path) ) # POST RENAME SIGNAL filebrowser_post_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) # MESSAGE & REDIRECT msg = _("Renaming was successful.") _message(request, msg) redirect_url = reverse("fb_browse") + query_helper(request.GET, "", "filename") return HttpResponseRedirect(redirect_url) except OSError, (errno, strerror): form.errors["name"] = forms.util.ErrorList([_("Error.")])
def url_of_image_version(self, image_path, version): """ :type image_path: basestring :type version: basestring :return: unicode """ if not image_path or not isinstance(image_path, basestring): raise ValueError('image_path is null or not string') location = fbfunctions.get_version_path(fbfunctions.url_to_path(image_path), '') gallery_path = fbfunctions.version_generator(location, version) if not gallery_path: raise ValueError("invalid image %s" % (image_path,)) return self.full_url(fbfunctions.path_to_url(gallery_path))
def rename(request): """ Rename existing File/Directory. Includes renaming existing Image Versions/Thumbnails. """ from filebrowser.forms import RenameForm # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) filename = get_file(query.get('dir', ''), query.get('filename', '')) if path is None or filename is None: if path is None: msg = _('The requested Folder does not exist.') else: msg = _('The requested 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) 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(DIRECTORY, path, filename) new_filename = form.cleaned_data['name'] + file_extension new_relative_server_path = os.path.join(DIRECTORY, path, new_filename) try: # PRE RENAME SIGNAL filebrowser_pre_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) # DELETE IMAGE VERSIONS/THUMBNAILS # regenerating versions/thumbs will be done automatically for version in VERSIONS: try: os.unlink(os.path.join(MEDIA_ROOT, get_version_path(relative_server_path, version))) except: pass # RENAME ORIGINAL os.rename(os.path.join(MEDIA_ROOT, relative_server_path), os.path.join(MEDIA_ROOT, new_relative_server_path)) # POST RENAME SIGNAL filebrowser_post_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) # MESSAGE & REDIRECT msg = _('Renaming was successful.') request.user.message_set.create(message=msg) redirect_url = reverse("fb_browse") + query_helper(query, "", "filename") return HttpResponseRedirect(redirect_url) except OSError, (errno, strerror): form.errors['name'] = forms.util.ErrorList([_('Error.')])
def test_version_setting(self): url = '{0}?filename={1}'.format(reverse('fb_versions'), self.image_name) response = self.client.get(url) for version in fb_settings.ADMIN_VERSIONS: value = os.path.join(self.working_dir, self.image_name) version_filename = get_version_path(value, version) version_prefix = fb_settings.VERSIONS[version]['verbose_name'] needle = '<strong>{0}</strong>'.format(version_prefix) self.assertInHTML(needle, response.content.decode('utf-8')) os.remove(version_filename)
def make_certificado_inscricao(self, request, queryset): response = HttpResponse(mimetype='application/zip') response['Content-Disposition'] = 'filename=Certificados.zip' buffer = StringIO() zip = zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) try: certificado = Certificado.objects.get(tipo_inscricao=queryset[0].tipo_inscricao) except: self.message_user(request, u'Ainda não há um certificado cadastrado para esse tipo de inscrição!') return campos = CampoCertificado.objects.filter(certificado=certificado) inscricoes = queryset for inscricao in inscricoes: template = Image.open(settings.MEDIA_ROOT+"/"+get_version_path(certificado.template.path, 'template_certificado')) draw = ImageDraw.Draw(template) for campo in campos: try: texto = DadosInscricao.objects.get(inscricao=inscricao, campo=campo.campo).resposta except: self.message_user(request, 'Erro! Verifique se o campo \"'+str(campo.campo)+'\" da Inscrição Nº '+str(inscricao.id)+' foi preenchido!') return if campo.tipo == 'MA': texto = texto.upper() posicao = campo.x, (campo.y-campo.tamanho)-campo.tamanho/2 fonte = ImageFont.truetype(settings.MEDIA_ROOT+"/"+campo.fonte.fonte.path, campo.tamanho) draw.text(posicao, texto, font=fonte, fill=campo.cor) if campos: local = settings.MEDIA_ROOT+'/certificados/tmp/' nome = remove_sc(str(inscricao.evento))+' - '+remove_sc(str(queryset[0].tipo_inscricao))+' - '+remove_sc(DadosInscricao.objects.filter(inscricao=inscricao)[0].resposta)+'.png' template.save(local+nome) zip.write(local+nome, nome) os.remove(local+nome) else: self.message_user(request, u'Erro! Verifique se há certificados sem campos e/ou tipos de inscrições sem dados cadastrais!') return zip.close() buffer.flush() ret_zip = buffer.getvalue() buffer.close() response.write(ret_zip) return response
def version_generate(self, version_suffix): path = self.path if FORCE_PLACEHOLDER or ( SHOW_PLACEHOLDER and not self.site.storage.isfile(path)): path = PLACEHOLDER version_path = get_version_path(path, version_suffix, site=self.site) if not self.site.storage.isfile(version_path): version_path = version_generator(path, version_suffix, site=self.site) elif self.site.storage.modified_time(path) > self.site.storage.modified_time(version_path): version_path = version_generator(path, version_suffix, force=True, site=self.site) return FileObject(version_path, site=self.site)
def version_generate(self, version_suffix): version_path = get_version_path(self.path, version_suffix, site=self.site) if not self.site.storage.isfile(version_path): version_path = version_generator(self.path, version_suffix, site=self.site) elif self.site.storage.modified_time( self.path) > self.site.storage.modified_time(version_path): version_path = version_generator(self.path, version_suffix, force=True, site=self.site) return FileObject(version_path, site=self.site)
def rename(request): """ Rename existing File/Directory. Includes renaming existing Image Versions/Thumbnails. """ from filebrowser.forms import RenameForm # QUERY / PATH CHECK result = _get_path_and_filename(request) if isinstance(result, HttpResponse): # path or filename doesn't exist return result path, filename, abs_path = result 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(DIRECTORY, path, filename) new_filename = form.cleaned_data['name'] + file_extension new_relative_server_path = os.path.join(DIRECTORY, path, new_filename) try: # PRE RENAME SIGNAL filebrowser_pre_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) # DELETE IMAGE VERSIONS/THUMBNAILS # regenerating versions/thumbs will be done automatically for version in VERSIONS: try: os.unlink(os.path.join(MEDIA_ROOT, get_version_path(relative_server_path, version))) except: pass # RENAME ORIGINAL os.rename(os.path.join(MEDIA_ROOT, relative_server_path), os.path.join(MEDIA_ROOT, new_relative_server_path)) # POST RENAME SIGNAL filebrowser_post_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) # MESSAGE & REDIRECT msg = _('Renaming was successful.') request.user.message_set.create(message=msg) redirect_url = reverse("fb_browse") + query_helper(request.GET, "", "filename") return HttpResponseRedirect(redirect_url) except OSError, (errno, strerror): form.errors['name'] = forms.util.ErrorList([_('Error.')])
def get_all_filebrowse_values(self): versions = getattr(settings, 'FILEBROWSER_VERSIONS', fb_settings.VERSIONS) files = [] for model, fields in self.get_all_models().items(): for record in model.objects.values(*fields): for field, value in record.items(): if value: file_obj = FileObject(value.replace(settings.MEDIA_URL, '')) files.append(file_obj.path_full) for version in versions: version_path = get_version_path(url_to_path(file_obj.url_save), version) version_file = os.path.join(settings.MEDIA_ROOT, version_path) if os.path.isfile(version_file): files.append(version_file) return files
def version_generate(self, version_suffix): path = self.path if FORCE_PLACEHOLDER or (SHOW_PLACEHOLDER and not self.site.storage.isfile(path)): path = PLACEHOLDER version_path = get_version_path(path, version_suffix, site=self.site) if not self.site.storage.isfile(version_path): version_path = version_generator(path, version_suffix, site=self.site) elif self.site.storage.modified_time( path) > self.site.storage.modified_time(version_path): version_path = version_generator(path, version_suffix, force=True, site=self.site) return FileObject(version_path, site=self.site)
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: source = force_unicode(source) version_path = get_version_path(source, version_prefix) if not os.path.isfile(version_path): version_path = version_generator(source, version_prefix) elif os.path.getmtime(source) > os.path.getmtime(version_path): version_path = version_generator(source, version_prefix, force=True) return path_to_url(version_path) except: return ""
def test_version(self): value = os.path.join(self.working_dir, self.image_name) version_filename = get_version_path(value, fb_settings.ADMIN_THUMBNAIL) self.assertTrue(os.path.isfile(version_filename)) os.remove(version_filename)
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: if path is None: msg = _('The requested Folder does not exist.') else: msg = _('The requested File does not exist.') messages.warning(request,message=msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = _check_access(request, path) msg = "" if request.GET: if request.GET.get('filetype') != "Folder": relative_server_path = os.path.join(fb_settings.DIRECTORY, path, filename) try: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # DELETE FILE os.unlink(smart_str(_check_access(request, path, filename))) # DELETE IMAGE VERSIONS/THUMBNAILS for version in VERSIONS: try: os.unlink(os.path.join(fb_settings.MEDIA_ROOT, get_version_path(relative_server_path, version))) except: pass # 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.success(request,message=msg) redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype") return HttpResponseRedirect(redirect_url) except OSError, e: # todo: define error message msg = unicode(e) else: try: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # DELETE FOLDER os.rmdir(_check_access(request, 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.success(request,message=msg) redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype") return HttpResponseRedirect(redirect_url) except OSError, e: # todo: define error message msg = unicode(e)
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: if path is None: msg = _('The requested Folder does not exist.') else: msg = _('The requested 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) msg = "" if request.GET: if request.GET.get('filetype') != "Folder": relative_server_path = os.path.join(DIRECTORY, path, filename) try: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # 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(smart_str(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()) 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: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # DELETE FOLDER os.rmdir(os.path.join(abs_path, filename)) # POST DELETE SIGNAL filebrowser_post_delete.send(sender=request, path=path, filename=filename) # MESSAGE & REDIRECT msg = _('The folder %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), 'breadcrumbs_title': "" }, context_instance=Context(request))
def _upload_file(self, request): """ Upload file to the server. """ if request.method == "POST": folder = request.GET.get('folder', '') if request.is_ajax(): # Advanced (AJAX) submission filedata = ContentFile(request.raw_post_data) else: # Basic (iframe) submission if len(request.FILES) != 1: raise Http404('Invalid request! Multiple files included.') filedata = request.FILES.values()[0] try: filedata.name = convert_filename(request.GET['qqfile']) except KeyError: return HttpResponseBadRequest( 'Invalid request! No filename given.') fb_uploadurl_re = re.compile( r'^.*(%s)' % reverse("filebrowser:fb_upload", current_app=self.name)) folder = fb_uploadurl_re.sub('', folder) path = os.path.join(self.directory, folder) file_name = os.path.join(path, filedata.name) file_already_exists = self.storage.exists(file_name) # Check for name collision with a directory if file_already_exists and self.storage.isdir(file_name): ret_json = {'success': False, 'filename': filedata.name} return HttpResponse(json.dumps(ret_json)) signals.filebrowser_pre_upload.send( sender=request, path=request.POST.get('folder'), file=filedata, site=self) uploadedfile = handle_file_upload(path, filedata, site=self) if file_already_exists and OVERWRITE_EXISTING: old_file = smart_unicode(file_name) new_file = smart_unicode(uploadedfile) self.storage.move(new_file, old_file, allow_overwrite=True) else: file_name = smart_unicode(uploadedfile) fobj = FileObject(smart_unicode(file_name), site=self) signals.filebrowser_post_upload.send( sender=request, path=request.POST.get('folder'), file=fobj, site=self) if fobj.filetype == "Image": version_path = get_version_path(fobj.path, ADMIN_THUMBNAIL, site=self) if not self.storage.isfile(version_path): version_path = version_generator(fobj.path, ADMIN_THUMBNAIL, site=self) thumbnail_path = self.storage.url(version_path) else: thumbnail_path = '' # let Ajax Upload know whether we saved it or not ret_json = { 'success': True, 'filename': filedata.name, 'path': fobj.path, 'url': fobj.url, 'thumbnail': thumbnail_path, 'filetype': fobj.filetype } return HttpResponse(json.dumps(ret_json))
def rename(request): """ Rename existing File/Directory. Includes renaming existing Image Versions/Thumbnails. """ # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) if 'pop' in query: is_popup = True else: is_popup = False filename = get_file(query.get('dir', ''), 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.warning(request, message=msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = _check_access(request, 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(fb_settings.DIRECTORY, path, filename) new_filename = form.cleaned_data['name'] + file_extension new_relative_server_path = os.path.join(fb_settings.DIRECTORY, path, new_filename) try: # PRE RENAME SIGNAL filebrowser_pre_rename.send(sender=request, path=path, filename=filename, new_filename=new_filename) # DELETE IMAGE VERSIONS/THUMBNAILS # regenerating versions/thumbs will be done automatically for version in VERSIONS: try: os.unlink( os.path.join( fb_settings.MEDIA_ROOT, get_version_path(relative_server_path, version))) except: pass # RENAME ORIGINAL os.rename( os.path.join(fb_settings.MEDIA_ROOT, relative_server_path), os.path.join(fb_settings.MEDIA_ROOT, 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.success(request, message=msg) redirect_url = reverse("fb_browse") + query_helper( query, "", "filename") return HttpResponseRedirect(redirect_url) except OSError as e: form.errors['name'] = forms.utils.ErrorList([_('Error.')]) else: form = RenameForm(abs_path, file_extension) return render( request, _template() + 'rename.html', { 'form': form, 'query': query, 'file_extension': file_extension, 'title': _(u'Rename "{0}"').format(filename), 'settings_var': get_settings_var(), 'breadcrumbs': get_breadcrumbs(query, path), 'breadcrumbs_title': _(u'Rename'), 'is_popup': is_popup })
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: if path is None: msg = _('The requested Folder does not exist.') else: msg = _('The requested File does not exist.') messages.add_message(request, messages.SUCCESS, msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path) msg = "" if request.GET: if request.GET.get('filetype') != "Folder": relative_server_path = os.path.join(DIRECTORY, path, filename) try: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # 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(smart_str(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) redirect_url = reverse("fb_browse") + query_helper( query, "", "filename,filetype") return HttpResponseRedirect(redirect_url) except OSError: # todo: define error message msg = OSError else: try: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # DELETE FOLDER os.rmdir(os.path.join(abs_path, filename)) # POST DELETE SIGNAL filebrowser_post_delete.send(sender=request, path=path, filename=filename) # MESSAGE & REDIRECT msg = _('The folder %s was successfully deleted.') % ( filename.lower()) messages.add_message(request, messages.SUCCESS, 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: messages.add_message(request, messages.SUCCESS, 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), 'breadcrumbs_title': "" }, 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: if path is None: msg = _('The requested Folder does not exist.') else: msg = _('The requested File does not exist.') messages.warning(request, message=msg) return HttpResponseRedirect(reverse("fb_browse")) abs_path = _check_access(request, path) msg = "" if request.GET: if request.GET.get('filetype') != "Folder": relative_server_path = os.path.join(fb_settings.DIRECTORY, path, filename) try: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # DELETE FILE os.unlink(smart_str(_check_access(request, path, filename))) # DELETE IMAGE VERSIONS/THUMBNAILS for version in VERSIONS: try: os.unlink( os.path.join( fb_settings.MEDIA_ROOT, get_version_path(relative_server_path, version))) except: pass # 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.success(request, message=msg) redirect_url = reverse("fb_browse") + query_helper( query, "", "filename,filetype") return HttpResponseRedirect(redirect_url) except OSError, e: # todo: define error message msg = unicode(e) else: try: # PRE DELETE SIGNAL filebrowser_pre_delete.send(sender=request, path=path, filename=filename) # DELETE FOLDER os.rmdir(_check_access(request, 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.success(request, message=msg) redirect_url = reverse("fb_browse") + query_helper( query, "", "filename,filetype") return HttpResponseRedirect(redirect_url) except OSError, e: # todo: define error message msg = unicode(e)