Beispiel #1
0
 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),
         )
Beispiel #2
0
 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))
Beispiel #3
0
 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 get_directory():
    """
    Returns FB's ``DIRECTORY`` setting, appending a directory using
    the site's ID if ``MEDIA_LIBRARY_PER_SITE`` is ``True``, and also
    creating the root directory if missing.
    """
    from mezzanine.conf import settings as mezz_settings
    from mezzanine.utils.sites import current_site_id
    from mezzanine.core.request import current_request
    #from mezzanine.utils.models import get_user_model_name
    dirname = DIRECTORY
    if getattr(mezz_settings, "MEDIA_LIBRARY_PER_SITE", False):
        dirname = os.path.join(dirname, "site-%s" % current_site_id())
    request = current_request()
    username = request.user.username
    if(username=='admin'):
        fullpath = os.path.join(mezz_settings.MEDIA_ROOT, dirname)
        if not default_storage.isdir(fullpath):
            default_storage.makedirs(fullpath)
    else:
        dirname = os.path.join(dirname, "username-%s" % username)
        fullpath = os.path.join(mezz_settings.MEDIA_ROOT, dirname)
        if not default_storage.isdir(fullpath):
            default_storage.makedirs(fullpath)
    return dirname
Beispiel #5
0
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),
    )
Beispiel #6
0
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 get_directory():
    """
    Returns FB's ``DIRECTORY`` setting, appending a directory using
    the site's ID if ``MEDIA_LIBRARY_PER_SITE`` is ``True``, and also
    creating the root directory if missing.
    """
    dirname = DIRECTORY
    if getattr(mezz_settings, "MEDIA_LIBRARY_PER_SITE", False):
        dirname = os.path.join(dirname, "site-%s" % current_site_id())
    fullpath = os.path.join(mezz_settings.MEDIA_ROOT, dirname)
    if not default_storage.isdir(fullpath):
        default_storage.makedirs(fullpath)
    return dirname
def get_directory():
    """
    Returns FB's ``DIRECTORY`` setting, appending a directory using
    the site's ID if ``MEDIA_LIBRARY_PER_SITE`` is ``True``, and also
    creating the root directory if missing.
    """

    dirname = fb_settings.DIRECTORY
    if getattr(dj_settings, "MEDIA_LIBRARY_PER_SITE", False):
        dirname = os.path.join(dirname, "site-%s" % current_site_id())
    fullpath = os.path.join(dj_settings.MEDIA_ROOT, dirname)
    if not default_storage.isdir(fullpath):
        default_storage.makedirs(fullpath)
    return dirname
Beispiel #9
0
 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))
Beispiel #10
0
 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))
Beispiel #11
0
def get_directory():
    """
    Returns FB's ``DIRECTORY`` setting, appending a directory using
    the site's ID if ``MEDIA_LIBRARY_PER_SITE`` is ``True``, and also
    creating the root directory if missing.
    """
    from mezzanine.conf import settings as mezz_settings
    from mezzanine.utils.sites import current_site_id
    from mezzanine.core.request import current_request
    username = current_request().user.get_username()
    DIRECTORY = getattr(settings, "FILEBROWSER_DIRECTORY", '/' + username)
    dirname = DIRECTORY
    if getattr(mezz_settings, "MEDIA_LIBRARY_PER_SITE", False):
        dirname = os.path.join(dirname, "site-%s" % current_site_id())
    fullpath = os.path.join(mezz_settings.MEDIA_ROOT, dirname)
    if not default_storage.isdir(fullpath):
        default_storage.makedirs(fullpath)
    return dirname
Beispiel #12
0
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(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.')])
Beispiel #13
0
def thumbnail(image_url, width, height, upscale=True, quality=95, left=.5,
              top=.5, padding=False, padding_color="#fff"):
    """
    Given the URL to an image, resizes the image using the given width
    and height on the first time it is requested, and returns the URL
    to the new resized image. If width or height are zero then original
    ratio is maintained. When ``upscale`` is False, images smaller than
    the given size will not be grown to fill that size. The given width
    and height thus act as maximum dimensions.
    """

    if not image_url:
        return ""
    try:
        from PIL import Image, ImageFile, ImageOps
    except ImportError:
        return ""

    image_url = unquote(str(image_url)).split("?")[0]
    if image_url.startswith(settings.MEDIA_URL):
        image_url = image_url.replace(settings.MEDIA_URL, "", 1)
    image_dir, image_name = os.path.split(image_url)
    image_prefix, image_ext = os.path.splitext(image_name)
    filetype = {".png": "PNG", ".gif": "GIF"}.get(image_ext.lower(), "JPEG")
    thumb_name = "%s-%sx%s" % (image_prefix, width, height)
    if not upscale:
        thumb_name += "-no-upscale"
    if left != .5 or top != .5:
        left = min(1, max(0, left))
        top = min(1, max(0, top))
        thumb_name = "%s-%sx%s" % (thumb_name, left, top)
    thumb_name += "-padded-%s" % padding_color if padding else ""
    thumb_name = "%s%s" % (thumb_name, image_ext)

    # `image_name` is used here for the directory path, as each image
    # requires its own sub-directory using its own name - this is so
    # we can consistently delete all thumbnails for an individual
    # image, which is something we do in filebrowser when a new image
    # is written, allowing us to purge any previously generated
    # thumbnails that may match a new image name.
    thumb_dir = os.path.join(
        image_dir,
        settings.THUMBNAILS_DIR_NAME,
        image_name
    )
    if not default_storage.exists(thumb_dir):
        try:
            default_storage.makedirs(thumb_dir)
        except OSError:
            pass

    thumb_path = os.path.join(thumb_dir, thumb_name)
    thumb_url = "%s/%s/%s" % (settings.THUMBNAILS_DIR_NAME,
                              quote(image_name.encode("utf-8")),
                              quote(thumb_name.encode("utf-8")))
    image_url_path = os.path.dirname(image_url)
    if image_url_path:
        thumb_url = "%s/%s" % (image_url_path, thumb_url)

    try:
        thumb_exists = default_storage.exists(thumb_path)
    except UnicodeEncodeError:
        # The image that was saved to a filesystem with utf-8 support,
        # but somehow the locale has changed and the filesystem does not
        # support utf-8.
        from mezzanine.core.exceptions import FileSystemEncodingChanged
        raise FileSystemEncodingChanged()
    if thumb_exists:
        # Thumbnail exists, don't generate it.
        return thumb_url
    elif not default_storage.exists(image_url):
        # Requested image does not exist, just return its URL.
        return image_url

    f = default_storage.open(image_url)
    try:
        image = Image.open(f)
    except:
        # Invalid image format.
        return image_url

    image_info = image.info

    # Transpose to align the image to its orientation if necessary.
    # If the image is transposed, delete the exif information as
    # not all browsers support the CSS image-orientation:
    # - http://caniuse.com/#feat=css-image-orientation
    try:
        orientation = image._getexif().get(0x0112)
    except:
        orientation = None
    if orientation:
        methods = {
           2: (Image.FLIP_LEFT_RIGHT,),
           3: (Image.ROTATE_180,),
           4: (Image.FLIP_TOP_BOTTOM,),
           5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90),
           6: (Image.ROTATE_270,),
           7: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_270),
           8: (Image.ROTATE_90,)}.get(orientation, ())
        if methods:
            image_info.pop('exif', None)
            for method in methods:
                image = image.transpose(method)

    to_width = int(width)
    to_height = int(height)
    from_width = image.size[0]
    from_height = image.size[1]

    if not upscale:
        to_width = min(to_width, from_width)
        to_height = min(to_height, from_height)

    # Set dimensions.
    if to_width == 0:
        to_width = from_width * to_height // from_height
    elif to_height == 0:
        to_height = from_height * to_width // from_width
    if image.mode not in ("P", "L", "RGBA") \
            and filetype not in ("JPG", "JPEG"):
        try:
            image = image.convert("RGBA")
        except:
            return image_url
    # Required for progressive jpgs.
    ImageFile.MAXBLOCK = 2 * (max(image.size) ** 2)

    # Padding.
    if padding and to_width and to_height:
        from_ratio = float(from_width) / from_height
        to_ratio = float(to_width) / to_height
        pad_size = None
        if to_ratio < from_ratio:
            pad_height = int(to_height * (float(from_width) / to_width))
            pad_size = (from_width, pad_height)
            pad_top = (pad_height - from_height) // 2
            pad_left = 0
        elif to_ratio > from_ratio:
            pad_width = int(to_width * (float(from_height) / to_height))
            pad_size = (pad_width, from_height)
            pad_top = 0
            pad_left = (pad_width - from_width) // 2
        if pad_size is not None:
            pad_container = Image.new("RGBA", pad_size, padding_color)
            pad_container.paste(image, (pad_left, pad_top))
            image = pad_container

    # Create the thumbnail.
    to_size = (to_width, to_height)
    to_pos = (left, top)
    try:
        output = io.BytesIO()
        image = ImageOps.fit(image, to_size, Image.ANTIALIAS, 0, to_pos)
        image = image.save(output, filetype, quality=quality, **image_info)
        default_storage.save(unquote(thumb_url), File(output))
    except Exception:
        return image_url
    return thumb_url