Exemplo n.º 1
0
 def upload_file_view(self, request):
     self.init_parent_folder(request)
     if not self.has_add_permission(request):
         raise PermissionDenied
     if request.method == 'POST':
         form = UploadForm(request.POST, request.FILES)
         if form.is_valid():
             node = FileNode(file=form.cleaned_data['file'], node_type=FileNode.FILE)
             parent_folder = self.get_parent_folder(request)
             if not parent_folder.is_top_node():
                 node.parent = parent_folder
             self.save_model(request, node, None, False)
             # Respond with 'ok' for the client to verify that the upload was successful, since sometimes a failed
             # request would not result in a HTTP error and look like a successful upload.
             # For instance: When requesting the admin view without authentication, there is a redirect to the
             # login form, which to SWFUpload looks like a successful upload request.
             if request.is_ajax() or 'Adobe Flash' in request.META.get('HTTP_USER_AGENT', ''):
                 return HttpResponse("ok", mimetype="text/plain")
             else:
                 messages.info(request, _('Successfully uploaded file %s.') % node.name)
                 return HttpResponseRedirect(reverse('admin:media_tree_filenode_changelist'))
         else:
             if not settings.DEBUG:
                 raise ValidationError
                 return
     if not settings.DEBUG:
         raise ViewDoesNotExist
     else:
         # Form is rendered for troubleshooting SWFUpload. If this form works, the problem is not server-side.
         from django.template import Template, RequestContext
         if request.method != 'POST':
             form = UploadForm()
         return render_to_response('admin/media_tree/filenode/upload_form.html',
             {'form': form, 'node': self.get_parent_folder(request)}, context_instance=RequestContext(request))
Exemplo n.º 2
0
    def upload_file_view(self, request):
        try:
            if not self.has_add_permission(request):
                raise PermissionDenied

            FILE_PARAM_NAME = 'qqfile'
            self.init_parent_folder(request)

            if request.method == 'POST':

                if request.is_ajax() and request.GET.get(FILE_PARAM_NAME, None):
                    from django.core.files.base import ContentFile
                    from django.core.files.uploadedfile import UploadedFile
                    content_file = ContentFile(request.raw_post_data)
                    uploaded_file = UploadedFile(content_file, request.GET.get(FILE_PARAM_NAME), None, content_file.size)
                    form = UploadForm(request.POST, {'file': uploaded_file})
                else:
                    form = UploadForm(request.POST, request.FILES)

                if form.is_valid():
                    node = FileNode(file=form.cleaned_data['file'], node_type=FileNode.FILE)
                    parent_folder = self.get_parent_folder(request)
                    if not parent_folder.is_top_node():
                        node.parent = parent_folder
                    self.save_model(request, node, None, False)
                    # Respond with 'ok' for the client to verify that the upload was successful, since sometimes a failed
                    # request would not result in a HTTP error and look like a successful upload.
                    # For instance: When requesting the admin view without authentication, there is a redirect to the
                    # login form, which to SWFUpload looks like a successful upload request.
                    if request.is_ajax():
                        return HttpResponse('{"success": true}', mimetype="application/json")
                    else:
                        messages.info(request, _('Successfully uploaded file %s.') % node.name)
                        return HttpResponseRedirect(reverse('admin:media_tree_filenode_changelist'))
                else:
                    # invalid form data
                    if request.is_ajax():
                        return HttpResponse('{"error": "%s"}' % ' '.join(
                            [item for sublist in form.errors.values() for item in sublist]), 
                            mimetype="application/json")

            # Form is rendered for troubleshooting SWFUpload. If this form works, the problem is not server-side.
            if not settings.DEBUG:
                raise ViewDoesNotExist
            if request.method == 'GET':
                form = UploadForm()
            return render_to_response('admin/media_tree/filenode/upload_form.html', {'form': form})            

        except Exception as e:
            if request.is_ajax():
                return HttpResponse('{"error": "%s"}' % ugettext('Server Error'), 
                    mimetype="application/json")
            else:
                raise
    def upload_file_view(self, request):
        try:
            if not self.has_add_permission(request):
                raise PermissionDenied

            self.init_parent_folder(request)

            if request.method == 'POST':
                form = UploadForm(request.POST, request.FILES)
                if form.is_valid():
                    node = FileNode(file=form.cleaned_data['file'],
                                    node_type=FileNode.FILE)
                    parent_folder = self.get_parent_folder(request)
                    if not parent_folder.is_top_node():
                        node.parent = parent_folder
                    self.save_model(request, node, None, False)
                    # Respond with success
                    if request.is_ajax():
                        return HttpResponse('{"success": true}',
                                            mimetype="application/json")
                    else:
                        messages.info(
                            request,
                            _('Successfully uploaded file %s.') % node.name)
                        return HttpResponseRedirect(
                            reverse('admin:media_tree_filenode_changelist'))
                else:
                    # invalid form data
                    if request.is_ajax():
                        return HttpResponse('{"error": "%s"}' % ' '.join([
                            item for sublist in form.errors.values()
                            for item in sublist
                        ]),
                                            mimetype="application/json")

            # Form is rendered for troubleshooting XHR upload.
            # If this form works, the problem is not server-side.
            if not settings.DEBUG:
                raise ViewDoesNotExist
            if request.method == 'GET':
                form = UploadForm()
            return render_to_response(
                'admin/media_tree/filenode/upload_form.html', {'form': form},
                context_instance=RequestContext(request))

        except Exception as e:
            if request.is_ajax():
                return HttpResponse('{"error": "%s"}' %
                                    ugettext('Server Error'),
                                    mimetype="application/json")
            else:
                raise
Exemplo n.º 4
0
    def __init__(self,
                 allowed_node_types=None,
                 allowed_media_types=None,
                 allowed_extensions=None,
                 level_indicator=LEVEL_INDICATOR,
                 rel=None,
                 *args,
                 **kwargs):
        self.allowed_node_types = allowed_node_types
        self.allowed_media_types = allowed_media_types
        self.allowed_extensions = allowed_extensions
        kwargs['level_indicator'] = level_indicator
        if not kwargs.has_key('widget'):
            kwargs['widget'] = self.widget

            # TODO: FileNodeForeignKeyRawIdWidget should only be the standard widget when in admin
            # TODO: It currently does not work with move/copy form
            #kwargs['widget'] = FileNodeForeignKeyRawIdWidget(rel)

        super(FileNodeChoiceField, self).__init__(*args, **kwargs)
        # TODO there should nonetheless be an "empty item", also if not required
        if not self.required:
            self.empty_label = FileNode.get_top_node().name
        else:
            self.empty_label = '---------'
Exemplo n.º 5
0
def get_actions_context(modeladmin):
    return {
        'node': FileNode.get_top_node(), # TODO get current folder
        "opts": modeladmin.model._meta,
        "app_label": modeladmin.model._meta.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }
Exemplo n.º 6
0
def get_actions_context(modeladmin):
    return {
        'node': FileNode.get_top_node(),  # TODO get current folder
        "opts": modeladmin.model._meta,
        "app_label": modeladmin.model._meta.app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }
Exemplo n.º 7
0
    def init_parent_folder(self, request):
        folder_id = request.GET.get('folder_id', None) or  \
            request.GET.get('parent') or request.POST.get('parent', None)
        reduce_levels = request.GET.get('reduce_levels', None) or request.POST.get('reduce_levels', None)
        if folder_id or reduce_levels:
            request.GET = request.GET.copy()
            try:
                del request.GET['folder_id']
            except KeyError:
                pass
            try:
                del request.GET['reduce_levels']
            except KeyError:
                pass

        if folder_id:
            parent_folder = get_object_or_404(FileNode, pk=folder_id, node_type=FileNode.FOLDER)
        else:
            parent_folder = FileNode.get_top_node()

        if reduce_levels:
            try:
                reduce_levels = int(reduce_levels)
            except ValueError:
                reduce_levels = None

        if not reduce_levels and not request.is_ajax() and parent_folder.level >= 0:
            self.reset_expanded_folders_pk(request)
            reduce_levels = parent_folder.level + 1

        set_request_attr(request, 'parent_folder', parent_folder)
        set_request_attr(request, 'reduce_levels', reduce_levels)
Exemplo n.º 8
0
def get_current_node(form):
    selected_nodes = form.get_selected_nodes()
    if len(selected_nodes) > 0:
        current_node = selected_nodes[0].parent
    if not current_node:
        return FileNode.get_top_node()
    else:
        return current_node
Exemplo n.º 9
0
def get_current_node(form):
    selected_nodes = form.get_selected_nodes()
    if len(selected_nodes) > 0:
        current_node = selected_nodes[0].parent
    if not current_node:
        return FileNode.get_top_node()
    else:
        return current_node
def clear_cache(modeladmin, request, queryset=None):
    """
    """
    from unicodedata import normalize
    
    execute = request.POST.get('execute')
    
    files_in_storage = []
    storage = get_media_storage()

    cache_files_choices = []

    for cache_dir in get_media_backend().get_cache_paths():
        if storage.exists(cache_dir):
            files_in_dir = [storage.path(os.path.join(cache_dir, filename))  \
                for filename in storage.listdir(cache_dir)[1]]
            for file_path in files_in_dir:
                # need to normalize unicode path due to https://code.djangoproject.com/ticket/16315
                file_path = normalize('NFC', file_path)
                storage_name = os.path.join(cache_dir, os.path.basename(file_path))
                link = mark_safe('<a href="%s">%s</a>' % (
                    storage.url(storage_name), storage_name))
                cache_files_choices.append((storage_name, link))

    if not len(cache_files_choices):
        #request.user.message_set.create(message=_('There are no cache files.'))
        return HttpResponseRedirect('')

    if execute:
        form = DeleteCacheFilesForm(queryset, cache_files_choices, request.POST)
        if form.is_valid():
            form.save()
            node = FileNode.get_top_node()
            message = ungettext('Deleted %i cache file.', 'Deleted %i cache files.', len(form.success_files)) % len(form.success_files)
            if len(form.success_files) == len(cache_files_choices):
                message = '%s %s' % (_('The cache was cleared.'), message)
            #request.user.message_set.create(message=message)
            if form.error_files:
		pass                
		#request.user.message_set.create(message=_('The following files could not be deleted:')+' '+repr(form.error_files))
            return HttpResponseRedirect(node.get_admin_url())

    if not execute:
        if len(cache_files_choices) > 0:
            form = DeleteCacheFilesForm(queryset, cache_files_choices)
        else:
            form = None

    c = get_actions_context(modeladmin)
    c.update({
        'title': _('Clear cache'),
        'submit_label': _('Delete selected files'),
        'form': form,
        'select_all': 'selected_files',
    })
    return render_to_response('admin/media_tree/filenode/actions_form.html', c, context_instance=RequestContext(request))

    return HttpResponseRedirect('')
Exemplo n.º 11
0
def clear_cache(modeladmin, request, queryset=None):
    """
    Clears media cache files such as thumbnails.
    """

    execute = request.POST.get('execute')

    files_in_storage = []
    storage = get_media_storage()
    cache_files_choices = []
    for storage_name in get_cache_files():
        link = mark_safe('<a href="%s">%s</a>' %
                         (storage.url(storage_name), storage_name))
        cache_files_choices.append((storage_name, link))

    if not len(cache_files_choices):
        messages.warning(request, message=_('There are no cache files.'))
        return HttpResponseRedirect('')

    if execute:
        form = DeleteCacheFilesForm(queryset, cache_files_choices,
                                    request.POST)
        if form.is_valid():
            form.save()
            node = FileNode.get_top_node()
            message = ungettext(
                'Deleted %i cache file.', 'Deleted %i cache files.',
                len(form.success_files)) % len(form.success_files)
            if len(form.success_files) == len(cache_files_choices):
                message = '%s %s' % (_('The cache was cleared.'), message)
            messages.success(request, message=message)
            if form.error_files:
                messages.error(
                    request,
                    message=_('The following files could not be deleted:') +
                    ' ' + repr(form.error_files))
            return HttpResponseRedirect(node.get_admin_url())

    if not execute:
        if len(cache_files_choices) > 0:
            form = DeleteCacheFilesForm(queryset, cache_files_choices)
        else:
            form = None

    c = get_actions_context(modeladmin)
    c.update({
        'title': _('Clear cache'),
        'submit_label': _('Delete selected files'),
        'form': form,
        'select_all': 'selected_files',
    })
    return render_to_response('admin/media_tree/filenode/actions_form.html',
                              c,
                              context_instance=RequestContext(request))

    return HttpResponseRedirect('')
Exemplo n.º 12
0
    def upload_file_view(self, request):
        try:
            if not self.has_add_permission(request):
                raise PermissionDenied

            self.init_parent_folder(request)

            if request.method == 'POST':
                form = UploadForm(request.POST, request.FILES)
                if form.is_valid():
                    node = FileNode(file=form.cleaned_data['file'], node_type=FileNode.FILE)
                    parent_folder = self.get_parent_folder(request)
                    if not parent_folder.is_top_node():
                        node.parent = parent_folder
                    self.save_model(request, node, None, False)
                    # Respond with success
                    if request.is_ajax():
                        return HttpResponse('{"success": true}', mimetype="application/json")
                    else:
                        messages.info(request, _('Successfully uploaded file %s.') % node.name)
                        return HttpResponseRedirect(reverse('admin:media_tree_filenode_changelist'))
                else:
                    # invalid form data
                    if request.is_ajax():
                        return HttpResponse('{"error": "%s"}' % ' '.join(
                            [item for sublist in form.errors.values() for item in sublist]), 
                            mimetype="application/json")

            # Form is rendered for troubleshooting XHR upload. 
            # If this form works, the problem is not server-side.
            if not settings.DEBUG:
                raise ViewDoesNotExist
            if request.method == 'GET':
                form = UploadForm()
            return render_to_response('admin/media_tree/filenode/upload_form.html', {'form': form},
                context_instance=RequestContext(request))

        except Exception as e:
            if request.is_ajax():
                return HttpResponse('{"error": "%s"}' % ugettext('Server Error'), 
                    mimetype="application/json")
            else:
                raise
def clear_cache(modeladmin, request, queryset=None):
    """ Clears media cache files such as thumbnails. """
    
    execute = request.POST.get('execute')
    
    files_in_storage = []
    storage = get_media_storage()
    cache_files_choices = []
    for storage_name in get_cache_files():
        link = mark_safe('<a href="%s">%s</a>' % (
            storage.url(storage_name), storage_name))
        cache_files_choices.append((storage_name, link))

    if not len(cache_files_choices):
        messages.warning(request, message=_('There are no cache files.'))
        return HttpResponseRedirect('')

    if execute:
        form = DeleteCacheFilesForm(
            queryset, cache_files_choices, request.POST)
        if form.is_valid():
            form.save()
            node = FileNode.get_top_node()
            message = ungettext(
                'Deleted %i cache file.',
                'Deleted %i cache files.',
                len(form.success_files)) % len(form.success_files)
            if len(form.success_files) == len(cache_files_choices):
                message = '%s %s' % (_('The cache was cleared.'), message)
            messages.success(request, message=message)
            if form.error_files:
                messages.error(
                    request,
                    message=_('The following files could not be deleted:')
                    + ' ' + repr(form.error_files))
            return HttpResponseRedirect(node.get_admin_url())

    if not execute:
        if len(cache_files_choices) > 0:
            form = DeleteCacheFilesForm(queryset, cache_files_choices)
        else:
            form = None

    c = get_actions_context(modeladmin)
    c.update({
        'title': _('Clear cache'),
        'submit_label': _('Delete selected files'),
        'form': form,
        'select_all': 'selected_files',
    })
    return render_to_response('admin/media_tree/filenode/actions_form.html',
                              c, context_instance=RequestContext(request))

    return HttpResponseRedirect('')
def delete_orphaned_files(modeladmin, request, queryset=None):
    """
    Deletes orphaned files, i.e. media files existing in storage that are not in the database.
    """
    
    execute = request.POST.get('execute')
    
    storage = get_media_storage()
    broken_node_links = []
    orphaned_files_choices = []

    broken_nodes, orphaned_files = get_broken_media()

    for node in broken_nodes:
        link = mark_safe('<a href="%s">%s</a>' % (node.get_admin_url(), node.__unicode__()))
        broken_node_links.append(link)

    for storage_name in orphaned_files:
        file_path = storage.path(storage_name)
        link = mark_safe('<a href="%s">%s</a>' % (
            storage.url(storage_name), file_path))
        orphaned_files_choices.append((storage_name, link))

    if not len(orphaned_files_choices) and not len(broken_node_links):
        messages.success(request, message=_('There are no orphaned files.'))
        return HttpResponseRedirect('')

    if execute:
        form = DeleteOrphanedFilesForm(queryset, orphaned_files_choices, request.POST)
        if form.is_valid():
            form.save()
            node = FileNode.get_top_node()
            messages.success(request, message=ungettext('Deleted %i file from storage.', 'Deleted %i files from storage.', len(form.success_files)) % len(form.success_files))
            if form.error_files:
                messages.error(request, message=_('The following files could not be deleted from storage:')+' '+repr(form.error_files))
            return HttpResponseRedirect(node.get_admin_url())

    if not execute:
        if len(orphaned_files_choices) > 0:
            form = DeleteOrphanedFilesForm(queryset, orphaned_files_choices)
        else:
            form = None

    c = get_actions_context(modeladmin)
    c.update({
        'title': _('Orphaned files'),
        'submit_label': _('Delete selected files'),
        'form': form,
        'select_all': 'selected_files',
        'node_list_title': _('The following files in the database do not exist in storage. You should fix these media objects:'),
        'node_list': broken_node_links,
    })
    return render_to_response('admin/media_tree/filenode/actions_form.html', c, context_instance=RequestContext(request))
Exemplo n.º 15
0
    def __init__(self, allowed_node_types=None, allowed_media_types=None, allowed_extensions=None, level_indicator=LEVEL_INDICATOR, rel=None, *args, **kwargs):
        self.allowed_node_types = allowed_node_types
        self.allowed_media_types = allowed_media_types
        self.allowed_extensions = allowed_extensions
        kwargs['level_indicator'] = level_indicator;
        if not kwargs.has_key('widget'):
            kwargs['widget'] = self.widget

            # TODO: FileNodeForeignKeyRawIdWidget should only be the standard widget when in admin
            # TODO: It currently does not work with move/copy form
            #kwargs['widget'] = FileNodeForeignKeyRawIdWidget(rel)

        super(FileNodeChoiceField, self).__init__(*args, **kwargs)
        # TODO there should nonetheless be an "empty item", also if not required
        if not self.required:
            self.empty_label = FileNode.get_top_node().name
        else:
            self.empty_label = '---------'
Exemplo n.º 16
0
    def init_parent_folder(self, request):
        folder_id = request.GET.get('folder_id', None) or  \
            request.GET.get('parent') or request.POST.get('parent', None)
        reduce_levels = request.GET.get(
            'reduce_levels', None) or request.POST.get('reduce_levels', None)
        if folder_id or reduce_levels:
            request.GET = request.GET.copy()
            try:
                del request.GET['folder_id']
            except KeyError:
                pass
            try:
                del request.GET['reduce_levels']
            except KeyError:
                pass

        if folder_id:
            parent_folder = get_object_or_404(FileNode,
                                              pk=folder_id,
                                              node_type=FileNode.FOLDER)
        else:
            parent_folder = FileNode.get_top_node()

        if reduce_levels:
            try:
                reduce_levels = int(reduce_levels)
            except ValueError:
                reduce_levels = None

        if not reduce_levels and not request.is_ajax(
        ) and parent_folder.level >= 0:
            self.reset_expanded_folders_pk(request)
            reduce_levels = parent_folder.level + 1

        set_request_attr(request, 'parent_folder', parent_folder)
        set_request_attr(request, 'reduce_levels', reduce_levels)
Exemplo n.º 17
0
 def forwards(self, orm):
     for node in FileNode.objects.all():
         if not node.is_folder():
             node.mimetype = FileNode.get_mimetype(node.name, None)
             node.save()
Exemplo n.º 18
0
def save_file_in_node(obj):
    new_file_node = FileNode(file=obj.file, node_type=FileNode.FILE, has_metadata=True)

    new_file_node.name = os.path.basename(new_file_node.file.name)
    # using os.path.splitext(), foo.tar.gz would become foo.tar_2.gz instead of foo_2.tar.gz
    split = multi_splitext(new_file_node.name)
    new_file_node.make_name_unique_numbered(split[0], split[1])

    # Determine various file parameters
    # new_file_node.size = new_file_node.file.size
    new_file_node.extension = split[2].lstrip('.').lower()
    new_file_node.width, new_file_node.height = (None, None)

    new_file_node.media_type = FileNode.mimetype_to_media_type(new_file_node.name)

    new_file_node.slug = slugify(new_file_node.name)
    new_file_node.has_metadata = new_file_node.check_minimal_metadata()

    new_file_node.title = obj.title

    new_file_node.file = str(obj.file)

    super(FileNode, new_file_node).save()

    obj.file_node = new_file_node
    obj.save()
Exemplo n.º 19
0
 def forwards(self, orm):
     for node in FileNode.objects.all():
         if not node.is_folder():
             node.mimetype = FileNode.get_mimetype(node.name, None)
             node.save()
Exemplo n.º 20
0
 def forwards(self, orm):
     for node in orm.FileNode.objects.all():
         if node.node_type != media_types.FOLDER:
             node.mimetype = FileNode.get_mimetype(node.name, None)
             node.save()
def delete_orphaned_files(modeladmin, request, queryset=None):
    from unicodedata import normalize

    execute = request.POST.get("execute")
    media_subdir = app_settings.MEDIA_TREE_UPLOAD_SUBDIR

    files_in_storage = []
    storage = get_media_storage()

    files_in_db = []
    nodes_with_missing_file_links = []
    for node in FileNode.objects.filter(node_type=FileNode.FILE):
        path = node.file.path
        # need to normalize unicode path due to https://code.djangoproject.com/ticket/16315
        path = normalize("NFC", path)
        files_in_db.append(path)
        if not storage.exists(node.file):
            link = mark_safe('<a href="%s">%s</a>' % (node.get_admin_url(), node.__unicode__()))
            nodes_with_missing_file_links.append(link)

    files_in_storage = [
        storage.path(os.path.join(media_subdir, filename)) for filename in storage.listdir(media_subdir)[1]
    ]

    orphaned_files_choices = []
    for file_path in files_in_storage:
        # need to normalize unicode path due to https://code.djangoproject.com/ticket/16315
        file_path = normalize("NFC", file_path)
        if not file_path in files_in_db:
            storage_name = os.path.join(media_subdir, os.path.basename(file_path))
            link = mark_safe('<a href="%s">%s</a>' % (storage.url(storage_name), file_path))
            orphaned_files_choices.append((storage_name, link))

    if not len(orphaned_files_choices) and not len(nodes_with_missing_file_links):
        request.user.message_set.create(message=_("There are no orphaned files."))
        return HttpResponseRedirect("")

    if execute:
        form = DeleteOrphanedFilesForm(queryset, orphaned_files_choices, request.POST)
        if form.is_valid():
            form.save()
            node = FileNode.get_top_node()
            request.user.message_set.create(
                message=ungettext(
                    "Deleted %i file from storage.", "Deleted %i files from storage.", len(form.success_files)
                )
                % len(form.success_files)
            )
            if form.error_files:
                request.user.message_set.create(
                    message=_("The following files could not be deleted from storage:") + " " + repr(form.error_files)
                )
            return HttpResponseRedirect(node.get_admin_url())

    if not execute:
        if len(orphaned_files_choices) > 0:
            form = DeleteOrphanedFilesForm(queryset, orphaned_files_choices)
        else:
            form = None

    c = get_actions_context(modeladmin)
    c.update(
        {
            "title": _("Orphaned files"),
            "submit_label": _("Delete selected files"),
            "form": form,
            "select_all": "selected_files",
            "node_list_title": _(
                "The following files in the database do not exist in storage. You should fix these media objects:"
            ),
            "node_list": nodes_with_missing_file_links,
        }
    )
    return render_to_response(
        "admin/media_tree/filenode/actions_form.html", c, context_instance=RequestContext(request)
    )
Exemplo n.º 22
0
def delete_orphaned_files(modeladmin, request, queryset=None):
    """
    Deletes orphaned files, i.e. media files existing in storage that are not in the database.
    """

    execute = request.POST.get('execute')

    storage = get_media_storage()
    broken_node_links = []
    orphaned_files_choices = []

    broken_nodes, orphaned_files = get_broken_media()

    for node in broken_nodes:
        link = mark_safe('<a href="%s">%s</a>' %
                         (node.get_admin_url(), node.__unicode__()))
        broken_node_links.append(link)

    for storage_name in orphaned_files:
        file_path = storage.path(storage_name)
        link = mark_safe('<a href="%s">%s</a>' %
                         (storage.url(storage_name), file_path))
        orphaned_files_choices.append((storage_name, link))

    if not len(orphaned_files_choices) and not len(broken_node_links):
        messages.success(request, message=_('There are no orphaned files.'))
        return HttpResponseRedirect('')

    if execute:
        form = DeleteOrphanedFilesForm(queryset, orphaned_files_choices,
                                       request.POST)
        if form.is_valid():
            form.save()
            node = FileNode.get_top_node()
            messages.success(
                request,
                message=ungettext('Deleted %i file from storage.',
                                  'Deleted %i files from storage.',
                                  len(form.success_files)) %
                len(form.success_files))
            if form.error_files:
                messages.error(
                    request,
                    message=
                    _('The following files could not be deleted from storage:')
                    + ' ' + repr(form.error_files))
            return HttpResponseRedirect(node.get_admin_url())

    if not execute:
        if len(orphaned_files_choices) > 0:
            form = DeleteOrphanedFilesForm(queryset, orphaned_files_choices)
        else:
            form = None

    c = get_actions_context(modeladmin)
    c.update({
        'title':
        _('Orphaned files'),
        'submit_label':
        _('Delete selected files'),
        'form':
        form,
        'select_all':
        'selected_files',
        'node_list_title':
        _('The following files in the database do not exist in storage. You should fix these media objects:'
          ),
        'node_list':
        broken_node_links,
    })
    return render_to_response('admin/media_tree/filenode/actions_form.html',
                              c,
                              context_instance=RequestContext(request))
Exemplo n.º 23
0
def get_actions_context(modeladmin):
    return {'node': FileNode.get_top_node(), # TODO get current folder
            'opts': modeladmin.model._meta,
            'root_path': modeladmin.admin_site.root_path,
            'app_label': modeladmin.model._meta.app_label,
            'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME}
Exemplo n.º 24
0
    def upload_file_view(self, request):
        try:
            if not self.has_add_permission(request):
                raise PermissionDenied

            FILE_PARAM_NAME = 'qqfile'
            self.init_parent_folder(request)

            if request.method == 'POST':

                if request.is_ajax() and request.GET.get(
                        FILE_PARAM_NAME, None):
                    from django.core.files.base import ContentFile
                    from django.core.files.uploadedfile import UploadedFile
                    content_file = ContentFile(request.raw_post_data)
                    uploaded_file = UploadedFile(
                        content_file, request.GET.get(FILE_PARAM_NAME), None,
                        content_file.size)
                    form = UploadForm(request.POST, {'file': uploaded_file})
                else:
                    form = UploadForm(request.POST, request.FILES)

                if form.is_valid():
                    node = FileNode(file=form.cleaned_data['file'],
                                    node_type=FileNode.FILE)
                    parent_folder = self.get_parent_folder(request)
                    if not parent_folder.is_top_node():
                        node.parent = parent_folder
                    self.save_model(request, node, None, False)
                    # Respond with 'ok' for the client to verify that the upload was successful, since sometimes a failed
                    # request would not result in a HTTP error and look like a successful upload.
                    # For instance: When requesting the admin view without authentication, there is a redirect to the
                    # login form, which to SWFUpload looks like a successful upload request.
                    if request.is_ajax():
                        return HttpResponse('{"success": true}',
                                            mimetype="application/json")
                    else:
                        messages.info(
                            request,
                            _('Successfully uploaded file %s.') % node.name)
                        return HttpResponseRedirect(
                            reverse('admin:media_tree_filenode_changelist'))
                else:
                    # invalid form data
                    if request.is_ajax():
                        return HttpResponse('{"error": "%s"}' % ' '.join([
                            item for sublist in form.errors.values()
                            for item in sublist
                        ]),
                                            mimetype="application/json")

            # Form is rendered for troubleshooting SWFUpload. If this form works, the problem is not server-side.
            if not settings.DEBUG:
                raise ViewDoesNotExist
            if request.method == 'GET':
                form = UploadForm()
            return render_to_response(
                'admin/media_tree/filenode/upload_form.html', {'form': form})

        except Exception as e:
            if request.is_ajax():
                return HttpResponse('{"error": "%s"}' %
                                    ugettext('Server Error'),
                                    mimetype="application/json")
            else:
                raise
Exemplo n.º 25
0
 def __init__(self, request, *args, **kwargs):
     super(MediaTreeChangeList, self).__init__(request, *args, **kwargs)
     # self.parent_folder is set in get_queryset()
     self.title = self.parent_folder.name if self.parent_folder else FileNode.get_top_node().name
def clear_cache(modeladmin, request, queryset=None):
    """
    """
    from unicodedata import normalize

    execute = request.POST.get("execute")

    files_in_storage = []
    storage = get_media_storage()

    cache_files_choices = []

    for cache_dir in get_media_backend().get_cache_paths():
        if storage.exists(cache_dir):
            files_in_dir = [
                storage.path(os.path.join(cache_dir, filename)) for filename in storage.listdir(cache_dir)[1]
            ]
            for file_path in files_in_dir:
                # need to normalize unicode path due to https://code.djangoproject.com/ticket/16315
                file_path = normalize("NFC", file_path)
                storage_name = os.path.join(cache_dir, os.path.basename(file_path))
                link = mark_safe('<a href="%s">%s</a>' % (storage.url(storage_name), storage_name))
                cache_files_choices.append((storage_name, link))

    if not len(cache_files_choices):
        messages.warning(request, message=_("There are no cache files."))
        return HttpResponseRedirect("")

    if execute:
        form = DeleteCacheFilesForm(queryset, cache_files_choices, request.POST)
        if form.is_valid():
            form.save()
            node = FileNode.get_top_node()
            message = ungettext("Deleted %i cache file.", "Deleted %i cache files.", len(form.success_files)) % len(
                form.success_files
            )
            if len(form.success_files) == len(cache_files_choices):
                message = "%s %s" % (_("The cache was cleared."), message)
            messages.success(request, message=message)
            if form.error_files:
                messages.error(
                    request, message=_("The following files could not be deleted:") + " " + repr(form.error_files)
                )
            return HttpResponseRedirect(node.get_admin_url())

    if not execute:
        if len(cache_files_choices) > 0:
            form = DeleteCacheFilesForm(queryset, cache_files_choices)
        else:
            form = None

    c = get_actions_context(modeladmin)
    c.update(
        {
            "title": _("Clear cache"),
            "submit_label": _("Delete selected files"),
            "form": form,
            "select_all": "selected_files",
        }
    )
    return render_to_response(
        "admin/media_tree/filenode/actions_form.html", c, context_instance=RequestContext(request)
    )

    return HttpResponseRedirect("")
 def forwards(self, orm):
     for node in orm.FileNode.objects.all():
         if node.node_type != media_types.FOLDER:
             node.mimetype = FileNode.get_mimetype(node.name, None)
             node.save()