def browse(request):
    """
    Browse Files/Directories.
    """

    query = request.GET.copy()
    abs_path = u'%s' % os.path.join(MEDIA_ROOT, DIRECTORY, query.get(
        'dir', ''))
    filelisting = FileListing(abs_path,
                              filter_func=filter_browse,
                              sorting_by=query.get('o', DEFAULT_SORTING_BY),
                              sorting_order=query.get('ot',
                                                      DEFAULT_SORTING_ORDER))

    files = []
    if SEARCH_TRAVERSE and query.get("q"):
        listing = filelisting.files_walk_filtered()
    else:
        listing = filelisting.files_listing_filtered()
    for fileobject in listing:
        # date/type filter
        append = False
        if fileobject.filetype == query.get(
                'filter_type', fileobject.filetype) and get_filterdate(
                    query.get('filter_date', ''), fileobject.date or 0):
            append = True
        # search
        if query.get("q") and not re.compile(query.get("q").lower(),
                                             re.M).search(
                                                 fileobject.filename.lower()):
            append = False
        # append
        if append:
            files.append(fileobject)
    filelisting.results_total = filelisting.results_listing_filtered
    filelisting.results_current = len(files)

    p = Paginator(files, LIST_PER_PAGE)
    page_nr = request.GET.get('p', '1')
    try:
        page = p.page(page_nr)
    except (EmptyPage, InvalidPage):
        page = p.page(p.num_pages)

    return render_to_response(
        'filebrowser/index.html', {
            'p': p,
            'page': page,
            'filelisting': filelisting,
            'query': query,
            'title': _(u'FileBrowser'),
            'settings_var': get_settings_var(),
            'breadcrumbs': get_breadcrumbs(query, query.get('dir', '')),
            'breadcrumbs_title': ""
        },
        context_instance=Context(request))
Exemple #2
0
def browse(request):
    """
    Browse Files/Directories.
    """
    
    query = request.GET.copy()
    user = request.user.username
    abs_path = u'%s' % os.path.join(MEDIA_ROOT, DIRECTORY, user, query.get('dir', ''))
    if not abs_path.startswith(request.user.get_profile().media_path) and \
            not request.user.is_superuser:
        raise Http403("You may not access this directory")
    filelisting = FileListing(abs_path,
        filter_func=filter_browse,
        sorting_by=query.get('o', DEFAULT_SORTING_BY),
        sorting_order=query.get('ot', DEFAULT_SORTING_ORDER))
    
    files = []
    if SEARCH_TRAVERSE and query.get("q"):
        listing = filelisting.files_walk_filtered()
    else:
        listing = filelisting.files_listing_filtered()
    for fileobject in listing:
        # date/type filter
        append = False
        if fileobject.filetype == query.get('filter_type', fileobject.filetype) and get_filterdate(query.get('filter_date', ''), fileobject.date or 0):
            append = True
        # search
        if query.get("q") and not re.compile(query.get("q").lower(), re.M).search(fileobject.filename.lower()):
            append = False
        # append
        if append:
            files.append(fileobject)
    filelisting.results_total = filelisting.results_listing_filtered
    filelisting.results_current = len(files)
    
    p = Paginator(files, LIST_PER_PAGE)
    page_nr = request.GET.get('p', '1')
    try:
        page = p.page(page_nr)
    except (EmptyPage, InvalidPage):
        page = p.page(p.num_pages)
    
    return render_to_response('filebrowser/index.html', {
        'p': p,
        'page': page,
        'filelisting': filelisting,
        'query': query,
        'title': _(u'FileBrowser'),
        'settings_var': get_settings_var(),
        'breadcrumbs': get_breadcrumbs(query, query.get('dir', '')),
        'breadcrumbs_title': ""
    }, context_instance=Context(request))
Exemple #3
0
def browse(request):
    """
    Browse Files/Directories.
    """
    # QUERY / PATH CHECK
    query = request.GET.copy()
    path = get_path(query.get('dir', ''))
    directory = get_path('')

    if 'pop' in query:
        is_popup = True
    else:
        is_popup = False

    if path is not None:
        abs_path = _check_access(request, path)

    if path is None:
        msg = _('The requested Folder does not exist.')
        messages.warning(request,message=msg)
        if directory is None:
            # The DIRECTORY does not exist, raise an error to prevent eternal redirecting.
            raise ImproperlyConfigured, _("Error finding Upload-Folder. Maybe it does not exist?")
        redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
        return HttpResponseRedirect(redirect_url)
    
    # INITIAL VARIABLES
    results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0 }
    counter = {}
    for k,v in EXTENSIONS.iteritems():
        counter[k] = 0
    
    dir_list = os.listdir(abs_path)
    files = []
    for file in dir_list:
        
        # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
        filtered = file.startswith('.')
        for re_prefix in filter_re:
            if re_prefix.search(file):
                filtered = True
        if filtered:
            continue
        results_var['results_total'] += 1
        
        # CREATE FILEOBJECT
        fileobject = FileObject(os.path.join(fb_settings.DIRECTORY, path.decode('utf-8'), file.decode('utf-8')))
        
        # FILTER / SEARCH
        append = False
        if fileobject.filetype == request.GET.get('filter_type', fileobject.filetype) and get_filterdate(request.GET.get('filter_date', ''), fileobject.date):
            append = True
        if request.GET.get('q') and not re.compile(request.GET.get('q').lower(), re.M).search(file.lower()):
            append = False
        
        # APPEND FILE_LIST
        if append:
            _type = query.get('type')
            try:
                # COUNTER/RESULTS
                if fileobject.filetype == 'Image':
                    results_var['images_total'] += 1
                if fileobject.filetype != 'Folder':
                    results_var['delete_total'] += 1
                elif fileobject.filetype == 'Folder' and fileobject.is_empty:
                    results_var['delete_total'] += 1
                if _type and _type in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[_type]:
                    results_var['select_total'] += 1
                elif not _type:
                    results_var['select_total'] += 1
            except OSError:
                # Ignore items that have problems
                continue
            else:
                files.append(fileobject)
                results_var['results_current'] += 1
        
        # COUNTER/RESULTS
        if fileobject.filetype:
            counter[fileobject.filetype] += 1
    
    # SORTING
    query['o'] = request.GET.get('o', DEFAULT_SORTING_BY)
    query['ot'] = request.GET.get('ot', DEFAULT_SORTING_ORDER)
    files = sort_by_attr(files, request.GET.get('o', DEFAULT_SORTING_BY))
    if not request.GET.get('ot') and DEFAULT_SORTING_ORDER == "desc" or request.GET.get('ot') == "desc":
        files.reverse()
    
    p = Paginator(files, LIST_PER_PAGE)
    try:
        page_nr = request.GET.get('p', '1')
    except:
        page_nr = 1
    try:
        page = p.page(page_nr)
    except (EmptyPage, InvalidPage):
        page = p.page(p.num_pages)
    
    return render_to_response(_template() + 'index.html', {
        'dir': path,
        'p': p,
        'page': page,
        'results_var': results_var,
        'counter': counter,
        'query': query,
        'title': _(u'FileBrowser'),
        'settings_var': get_settings_var(),
        'breadcrumbs': get_breadcrumbs(query, path),
        'breadcrumbs_title': "",
        'is_popup': is_popup
    }, context_instance=Context(request))
    def browse(self, request):
        """
        Browse Files/Directories.
        """

        filter_re = []
        for exp in EXCLUDE:
           filter_re.append(re.compile(exp))
        for k,v in VERSIONS.iteritems():
            exp = (r'_%s(%s)') % (k, '|'.join(EXTENSION_LIST))
            filter_re.append(re.compile(exp))

        def filter_browse(item):
            filtered = item.filename.startswith('.')
            for re_prefix in filter_re:
                if re_prefix.search(item.filename):
                    filtered = True
            if filtered:
                return False
            return True
        
        query = request.GET.copy()
        path = u'%s' % os.path.join(self.directory, query.get('dir', ''))
        
        filelisting = FileListing(path,
            filter_func=filter_browse,
            sorting_by=query.get('o', DEFAULT_SORTING_BY),
            sorting_order=query.get('ot', DEFAULT_SORTING_ORDER),
            site=self)
        
        files = []
        if SEARCH_TRAVERSE and query.get("q"):
            listing = filelisting.files_walk_filtered()
        else:
            listing = filelisting.files_listing_filtered()
        
        # If we do a search, precompile the search pattern now
        do_search = query.get("q")
        if do_search:
            re_q = re.compile(query.get("q").lower(), re.M)
        
        filter_type = query.get('filter_type')
        filter_date = query.get('filter_date')
        
        for fileobject in listing:
            # date/type filter
            append = False
            if (not filter_type or fileobject.filetype == filter_type) and (not filter_date or get_filterdate(filter_date, fileobject.date or 0)):
                append = True
            # search
            if do_search and not re_q.search(fileobject.filename.lower()):
                append = False
            # append
            if append:
                files.append(fileobject)
        
        filelisting.results_total = len(listing)
        filelisting.results_current = len(files)
        
        p = Paginator(files, LIST_PER_PAGE)
        page_nr = request.GET.get('p', '1')
        try:
            page = p.page(page_nr)
        except (EmptyPage, InvalidPage):
            page = p.page(p.num_pages)
        
        return render_to_response('filebrowser/index.html', {
            'p': p,
            'page': page,
            'filelisting': filelisting,
            'query': query,
            'title': _(u'FileBrowser'),
            'is_popup': "pop" in request.REQUEST,   # ChangeList uses "pop"
            'settings_var': get_settings_var(directory=self.directory),
            'breadcrumbs': get_breadcrumbs(query, query.get('dir', '')),
            'breadcrumbs_title': "",
            'filebrowser_site': self
        }, context_instance=Context(request, current_app=self.name))
Exemple #5
0
    def browse(self, request):
        """
        Browse Files/Directories.
        """

        filter_re = []
        for exp in EXCLUDE:
            filter_re.append(re.compile(exp))
        for k, v in VERSIONS.iteritems():
            exp = (r'_%s(%s)') % (k, '|'.join(EXTENSION_LIST))
            filter_re.append(re.compile(exp))

        def filter_browse(item):
            filtered = item.filename.startswith('.')
            for re_prefix in filter_re:
                if re_prefix.search(item.filename):
                    filtered = True
            if filtered:
                return False
            return True

        query = request.GET.copy()
        path = u'%s' % os.path.join(self.directory, query.get('dir', ''))

        filelisting = FileListing(path,
                                  filter_func=filter_browse,
                                  sorting_by=query.get('o',
                                                       DEFAULT_SORTING_BY),
                                  sorting_order=query.get(
                                      'ot', DEFAULT_SORTING_ORDER),
                                  site=self)

        files = []
        if SEARCH_TRAVERSE and query.get("q"):
            listing = filelisting.files_walk_filtered()
        else:
            listing = filelisting.files_listing_filtered()

        # If we do a search, precompile the search pattern now
        do_search = query.get("q")
        if do_search:
            re_q = re.compile(query.get("q").lower(), re.M)

        filter_type = query.get('filter_type')
        filter_date = query.get('filter_date')

        for fileobject in listing:
            # date/type filter
            append = False
            if (not filter_type or fileobject.filetype == filter_type) and (
                    not filter_date
                    or get_filterdate(filter_date, fileobject.date or 0)):
                append = True
            # search
            if do_search and not re_q.search(fileobject.filename.lower()):
                append = False
            # append
            if append:
                files.append(fileobject)

        filelisting.results_total = len(listing)
        filelisting.results_current = len(files)

        p = Paginator(files, LIST_PER_PAGE)
        page_nr = request.GET.get('p', '1')
        try:
            page = p.page(page_nr)
        except (EmptyPage, InvalidPage):
            page = p.page(p.num_pages)

        return render_to_response(
            'filebrowser/index.html', {
                'p': p,
                'page': page,
                'filelisting': filelisting,
                'query': query,
                'title': _(u'FileBrowser'),
                'settings_var': get_settings_var(directory=self.directory),
                'breadcrumbs': get_breadcrumbs(query, query.get('dir', '')),
                'breadcrumbs_title': "",
                'filebrowser_site': self
            },
            context_instance=Context(request, current_app=self.name))
Exemple #6
0
def browse(request):
    """
    Browse Files/Directories.
    """

    # QUERY / PATH CHECK
    query = request.GET.copy()
    path = get_path(query.get('dir', ''))
    directory = get_path('')
    if path is None:
        msg = _('The requested Folder does not exist.')
        messages.add_message(request, messages.SUCCESS, msg)
        if directory is None:
            # The DIRECTORY does not exist, raise an error to prevent eternal redirecting.
            raise ImproperlyConfigured, _(
                "Error finding Upload-Folder. Maybe it does not exist?")
        redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
        return HttpResponseRedirect(redirect_url)
    abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)

    # INITIAL VARIABLES
    results_var = {
        'results_total': 0,
        'results_current': 0,
        'delete_total': 0,
        'images_total': 0,
        'select_total': 0
    }
    counter = {}
    for k, v in EXTENSIONS.iteritems():
        counter[k] = 0

    dir_list = os.listdir(abs_path)
    files = []
    for file in dir_list:

        # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
        filtered = file.startswith('.')
        for re_prefix in filter_re:
            if re_prefix.search(file):
                filtered = True
        if filtered:
            continue
        results_var['results_total'] += 1

        # CREATE FILEOBJECT
        fileobject = FileObject(os.path.join(DIRECTORY, path, file))

        # FILTER / SEARCH
        append = False
        if fileobject.filetype == request.GET.get(
                'filter_type', fileobject.filetype) and get_filterdate(
                    request.GET.get('filter_date', ''), fileobject.date):
            append = True
        if request.GET.get('q') and not re.compile(
                request.GET.get('q').lower(), re.M).search(file.lower()):
            append = False

        # APPEND FILE_LIST
        if append:
            try:
                # COUNTER/RESULTS
                if fileobject.filetype == 'Image':
                    results_var['images_total'] += 1
                if fileobject.filetype != 'Folder':
                    results_var['delete_total'] += 1
                elif fileobject.filetype == 'Folder' and fileobject.is_empty:
                    results_var['delete_total'] += 1
                if query.get('type') and query.get(
                        'type'
                ) in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[
                        query.get('type')]:
                    results_var['select_total'] += 1
                elif not query.get('type'):
                    results_var['select_total'] += 1
            except OSError:
                # Ignore items that have problems
                continue
            else:
                files.append(fileobject)
                results_var['results_current'] += 1

        # COUNTER/RESULTS
        if fileobject.filetype:
            counter[fileobject.filetype] += 1

    # SORTING
    query['o'] = request.GET.get('o', DEFAULT_SORTING_BY)
    query['ot'] = request.GET.get('ot', DEFAULT_SORTING_ORDER)
    files = sort_by_attr(files, request.GET.get('o', DEFAULT_SORTING_BY))
    if not request.GET.get(
            'ot') and DEFAULT_SORTING_ORDER == "desc" or request.GET.get(
                'ot') == "desc":
        files.reverse()

    p = Paginator(files, LIST_PER_PAGE)
    try:
        page_nr = request.GET.get('p', '1')
    except:
        page_nr = 1
    try:
        page = p.page(page_nr)
    except (EmptyPage, InvalidPage):
        page = p.page(p.num_pages)

    return render_to_response('filebrowser/index.html', {
        'dir': path,
        'p': p,
        'page': page,
        'results_var': results_var,
        'counter': counter,
        'query': query,
        'title': _(u'FileBrowser'),
        'settings_var': get_settings_var(),
        'breadcrumbs': get_breadcrumbs(query, path),
        'breadcrumbs_title': ""
    },
                              context_instance=Context(request))
Exemple #7
0
def browse(request):
    """
    Browse Files/Directories.
    """
    
    # QUERY / PATH CHECK
    query = request.GET.copy()
    path = get_path(query.get('dir', ''))
    directory = get_path('')
    q = request.GET.get('q')
    
    if path is None:
        msg = _('The requested Folder does not exist.')
        request.user.message_set.create(message=msg)
        if directory is None:
            # The DIRECTORY does not exist, raise an error to prevent eternal redirecting.
            raise ImproperlyConfigured, _("Error finding Upload-Folder (MEDIA_ROOT + FILEBROWSER_DIRECTORY). Maybe it does not exist?")
        redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
        return HttpResponseRedirect(redirect_url)
    abs_path = u'%s' % os.path.join(MEDIA_ROOT, DIRECTORY, path)
    
    # INITIAL VARIABLES
    results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0 }
    counter = {}
    for k,v in EXTENSIONS.iteritems():
        counter[k] = 0
    
    if q:
        m_root = os.path.normpath(MEDIA_ROOT)
        dirs = []
        for root, _subdirs, filenames in os.walk(abs_path):
            dirs_2 = []
            items = _subdirs + filenames
            for f in items:
                dirs_2.append((os.path.normpath(root)[len(m_root)+1:], f))
            # append result of every iteration to dirs
            dirs.append(dirs_2)
        dir_list = itertools.chain(*dirs)
    else:
        root = os.path.join(DIRECTORY, path)
        dir_list = ((root, f) for f in os.listdir(abs_path))
    
    files = []
    for file_dir, file in dir_list:
        # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
        filtered = file.startswith('.')
        for re_prefix in filter_re:
            if re_prefix.search(file):
                filtered = True
        if filtered:
            continue
        results_var['results_total'] += 1
        
        # CREATE FILEOBJECT
        fileobject = FileObject(os.path.join(file_dir, file))
        
        # FILTER / SEARCH
        append = False
        if fileobject.filetype == request.GET.get('filter_type', fileobject.filetype) and get_filterdate(request.GET.get('filter_date', ''), fileobject.date or 0):
            append = True
        if q and not re.compile(q.lower(), re.M).search(file.lower()):
            append = False
        
        # APPEND FILE_LIST
        if append:
            try:
                # COUNTER/RESULTS
                if fileobject.filetype == 'Image':
                    results_var['images_total'] += 1
                if fileobject.filetype != 'Folder':
                    results_var['delete_total'] += 1
                elif fileobject.filetype == 'Folder' and fileobject.is_empty:
                    results_var['delete_total'] += 1
                if query.get('type') and query.get('type') in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[query.get('type')]:
                    results_var['select_total'] += 1
                elif not query.get('type'):
                    results_var['select_total'] += 1
            except OSError:
                # Ignore items that have problems
                continue
            else:
                files.append(fileobject)
                results_var['results_current'] += 1
        
        # COUNTER/RESULTS
        if fileobject.filetype:
            counter[fileobject.filetype] += 1
    
    # SORTING
    query['o'] = request.GET.get('o', DEFAULT_SORTING_BY)
    query['ot'] = request.GET.get('ot', DEFAULT_SORTING_ORDER)
    files = sort_by_attr(files, request.GET.get('o', DEFAULT_SORTING_BY))
    if not request.GET.get('ot') and DEFAULT_SORTING_ORDER == "desc" or request.GET.get('ot') == "desc":
        files.reverse()
    
    p = Paginator(files, LIST_PER_PAGE)
    try:
        page_nr = request.GET.get('p', '1')
    except:
        page_nr = 1
    try:
        page = p.page(page_nr)
    except (EmptyPage, InvalidPage):
        page = p.page(p.num_pages)
    
    return render_to_response('filebrowser/index.html', {
        'dir': path,
        'p': p,
        'q': q,
        'page': page,
        'results_var': results_var,
        'counter': counter,
        'query': query,
        'title': _(u'FileBrowser'),
        'settings_var': get_settings_var(),
        'breadcrumbs': get_breadcrumbs(query, path),
        'breadcrumbs_title': ""
    }, context_instance=Context(request))
def browse(request):
    """
    Browse Files/Directories.
    """
    # QUERY / PATH CHECK
    query = request.GET.copy()
    path = get_path(query.get("dir", ""))
    directory = get_path("")

    if path is not None:
        abs_path = os.path.abspath(os.path.join(fb_settings.MEDIA_ROOT, fb_settings.DIRECTORY, path))
        if not abs_path.startswith(os.path.abspath(os.path.join(fb_settings.MEDIA_ROOT, fb_settings.DIRECTORY))):
            # cause any attempt to leave media root directory to fail
            raise Http404

    if path is None:
        msg = _("The requested Folder does not exist.")
        messages.warning(request, message=msg)
        if directory is None:
            # The DIRECTORY does not exist, raise an error to prevent eternal redirecting.
            raise ImproperlyConfigured, _("Error finding Upload-Folder. Maybe it does not exist?")
        redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
        return HttpResponseRedirect(redirect_url)

    # INITIAL VARIABLES
    results_var = {"results_total": 0, "results_current": 0, "delete_total": 0, "images_total": 0, "select_total": 0}
    counter = {}
    for k, v in EXTENSIONS.iteritems():
        counter[k] = 0

    dir_list = os.listdir(abs_path)
    files = []
    for file in dir_list:

        # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
        filtered = file.startswith(".")
        for re_prefix in filter_re:
            if re_prefix.search(file):
                filtered = True
        if filtered:
            continue
        results_var["results_total"] += 1

        # CREATE FILEOBJECT
        fileobject = FileObject(os.path.join(fb_settings.DIRECTORY, path, file))

        # FILTER / SEARCH
        append = False
        if fileobject.filetype == request.GET.get("filter_type", fileobject.filetype) and get_filterdate(
            request.GET.get("filter_date", ""), fileobject.date
        ):
            append = True
        if request.GET.get("q") and not re.compile(request.GET.get("q").lower(), re.M).search(file.lower()):
            append = False

        # APPEND FILE_LIST
        if append:
            try:
                # COUNTER/RESULTS
                if fileobject.filetype == "Image":
                    results_var["images_total"] += 1
                if fileobject.filetype != "Folder":
                    results_var["delete_total"] += 1
                elif fileobject.filetype == "Folder" and fileobject.is_empty:
                    results_var["delete_total"] += 1
                if (
                    query.get("type")
                    and query.get("type") in SELECT_FORMATS
                    and fileobject.filetype in SELECT_FORMATS[query.get("type")]
                ):
                    results_var["select_total"] += 1
                elif not query.get("type"):
                    results_var["select_total"] += 1
            except OSError:
                # Ignore items that have problems
                continue
            else:
                files.append(fileobject)
                results_var["results_current"] += 1

        # COUNTER/RESULTS
        if fileobject.filetype:
            counter[fileobject.filetype] += 1

    # SORTING
    query["o"] = request.GET.get("o", DEFAULT_SORTING_BY)
    query["ot"] = request.GET.get("ot", DEFAULT_SORTING_ORDER)
    files = sort_by_attr(files, request.GET.get("o", DEFAULT_SORTING_BY))
    if not request.GET.get("ot") and DEFAULT_SORTING_ORDER == "desc" or request.GET.get("ot") == "desc":
        files.reverse()

    p = Paginator(files, LIST_PER_PAGE)
    try:
        page_nr = request.GET.get("p", "1")
    except:
        page_nr = 1
    try:
        page = p.page(page_nr)
    except (EmptyPage, InvalidPage):
        page = p.page(p.num_pages)

    return render_to_response(
        "filebrowser/index.html",
        {
            "dir": path,
            "p": p,
            "page": page,
            "results_var": results_var,
            "counter": counter,
            "query": query,
            "title": _(u"FileBrowser"),
            "settings_var": get_settings_var(),
            "breadcrumbs": get_breadcrumbs(query, path),
            "breadcrumbs_title": "",
        },
        context_instance=Context(request),
    )
Exemple #9
0
def browse(request):
    """
    Browse Files/Directories.
    """
    
    # QUERY / PATH CHECK
    query = request.GET
    path = get_path(query.get('dir', ''))
    directory = get_path('')
    
    if path is None:
        msg = _('The requested Folder does not exist.')
        request.user.message_set.create(message=msg)
        if directory is None:
            # The DIRECTORY does not exist, raise an error to prevent eternal redirecting.
            raise ImproperlyConfigured, _("Error finding Upload-Folder. Maybe it does not exist?")
        redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
        return HttpResponseRedirect(redirect_url)
    abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
    
    # INITIAL VARIABLES
    results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0 }
    counter = {}
    for k,v in EXTENSIONS.iteritems():
        counter[k] = 0
    
    dir_list = os.listdir(abs_path)
    files = []
    for file in dir_list:
        
        # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
        filtered = file.startswith('.')
        for re_prefix in filter_re:
            if re_prefix.search(file):
                filtered = True
        if filtered:
            continue
        results_var['results_total'] += 1
        
        # CREATE FILEOBJECT
        fileobject = FileObject(os.path.join(DIRECTORY, path, file))
        
        # FILTER / SEARCH
        append = False
        if fileobject.filetype == request.GET.get('filter_type', fileobject.filetype) and get_filterdate(request.GET.get('filter_date', ''), fileobject.date):
            append = True
        if request.GET.get('q') and not re.compile(request.GET.get('q').lower(), re.M).search(file.lower()):
            append = False
        
        # APPEND FILE_LIST
        if append:
            files.append(fileobject)
            results_var['results_current'] += 1
            # COUNTER/RESULTS
            if fileobject.filetype == 'Image':
                results_var['images_total'] += 1
            if fileobject.filetype != 'Folder':
                results_var['delete_total'] += 1
            elif fileobject.filetype == 'Folder' and fileobject.is_empty:
                results_var['delete_total'] += 1
            if query.get('type') and query.get('type') in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[query.get('type')]:
                results_var['select_total'] += 1
            elif not query.get('type'):
                results_var['select_total'] += 1
        
        # COUNTER/RESULTS
        if fileobject.filetype:
            counter[fileobject.filetype] += 1
    
    # SORTING
    files = sort_by_attr(files, request.GET.get('o', 'date'))
    if request.GET.get('ot') == "desc":
        files.reverse()
    
    return render_to_response('filebrowser/index.html', {
        'dir': path,
        'files': files,
        'results_var': results_var,
        'counter': counter,
        'query': query,
        'title': _(u'FileBrowser'),
        'settings_var': get_settings_var(),
        'breadcrumbs': get_breadcrumbs(query, path, ''),
    }, context_instance=Context(request))
Exemple #10
0
def browse(request):
    """
    Browse Files/Directories.
    """
    
    query = request.GET.copy()
    abs_path = u'%s' % os.path.join(MEDIA_ROOT, DIRECTORY, query.get('dir', ''))

    filelisting = FileListing(abs_path,
        filter_func=filter_browse,
        sorting_by=query.get('o', DEFAULT_SORTING_BY),
        sorting_order=query.get('ot', DEFAULT_SORTING_ORDER))
    
    files = []
    if SEARCH_TRAVERSE and query.get("q"):
        listing = filelisting.files_walk_filtered()
    else:
        listing = filelisting.files_listing_filtered()

    # If we do a search, precompile the search pattern now
    do_search = query.get("q")
    if do_search:
        re_q = re.compile(query.get("q").lower(), re.M)

    filter_type = query.get('filter_type')
    filter_date = query.get('filter_date')
    
    for fileobject in listing:
        # date/type filter
        append = False
        if (not filter_type or fileobject.filetype == filter_type) and (not filter_date or get_filterdate(filter_date, fileobject.date or 0)):
            append = True
        # search
        if do_search and not re_q.search(fileobject.filename.lower()):
            append = False
        # append
        if append:
            files.append(fileobject)

    filelisting.results_total = len(listing)
    filelisting.results_current = len(files)
    
    p = Paginator(files, LIST_PER_PAGE)
    page_nr = request.GET.get('p', '1')
    try:
        page = p.page(page_nr)
    except (EmptyPage, InvalidPage):
        page = p.page(p.num_pages)

    return render_to_response('filebrowser/index.html', {
        'p': p,
        'page': page,
        'filelisting': filelisting,
        'query': query,
        'title': _(u'FileBrowser'),
        'settings_var': get_settings_var(),
        'breadcrumbs': get_breadcrumbs(query, query.get('dir', '')),
        'breadcrumbs_title': ""
    }, context_instance=Context(request))
    def browse(self, request):
        """
        Browse Files/Directories.
        """

        filter_re = []
        for exp in EXCLUDE:
            filter_re.append(re.compile(exp))
        for k, v in VERSIONS.iteritems():
            exp = (r"_%s(%s)") % (k, "|".join(EXTENSION_LIST))
            filter_re.append(re.compile(exp))

        def filter_browse(item):
            filtered = item.filename.startswith(".")
            for re_prefix in filter_re:
                if re_prefix.search(item.filename):
                    filtered = True
            if filtered:
                return False
            return True

        query = request.GET.copy()
        path = u"%s" % os.path.join(self.directory, query.get("dir", ""))

        filelisting = FileListing(
            path,
            filter_func=filter_browse,
            sorting_by=query.get("o", DEFAULT_SORTING_BY),
            sorting_order=query.get("ot", DEFAULT_SORTING_ORDER),
            site=self,
        )

        files = []
        if SEARCH_TRAVERSE and query.get("q"):
            listing = filelisting.files_walk_filtered()
        else:
            listing = filelisting.files_listing_filtered()

        # If we do a search, precompile the search pattern now
        do_search = query.get("q")
        if do_search:
            re_q = re.compile(query.get("q").lower(), re.M)

        filter_type = query.get("filter_type")
        filter_date = query.get("filter_date")

        for fileobject in listing:
            # date/type filter
            append = False
            if (not filter_type or fileobject.filetype == filter_type) and (
                not filter_date or get_filterdate(filter_date, fileobject.date or 0)
            ):
                append = True
            # search
            if do_search and not re_q.search(fileobject.filename.lower()):
                append = False
            # append
            if append:
                files.append(fileobject)

        filelisting.results_total = len(listing)
        filelisting.results_current = len(files)

        p = Paginator(files, LIST_PER_PAGE)
        page_nr = request.GET.get("p", "1")
        try:
            page = p.page(page_nr)
        except (EmptyPage, InvalidPage):
            page = p.page(p.num_pages)

        return render_to_response(
            "filebrowser/index.html",
            {
                "p": p,
                "page": page,
                "filelisting": filelisting,
                "query": query,
                "title": _(u"FileBrowser"),
                "settings_var": get_settings_var(directory=self.directory),
                "breadcrumbs": get_breadcrumbs(query, query.get("dir", "")),
                "breadcrumbs_title": "",
                "site": self,
            },
            context_instance=Context(request, current_app=self.name),
        )
Exemple #12
0
def browse(request):
    """
    Browse Files/Directories.
    """

    # QUERY / PATH CHECK
    query = request.GET.copy()
    path = get_path(query.get("dir", ""))
    directory = get_path("")
    q = request.GET.get("q")

    if path is None:
        msg = _("The requested Folder does not exist.")
        request.user.message_set.create(message=msg)
        if directory is None:
            # The DIRECTORY does not exist, raise an error to prevent eternal redirecting.
            raise ImproperlyConfigured, _(
                "Error finding Upload-Folder (MEDIA_ROOT + FILEBROWSER_DIRECTORY). Maybe it does not exist?"
            )
        redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
        return HttpResponseRedirect(redirect_url)
    abs_path = u"%s" % os.path.join(MEDIA_ROOT, DIRECTORY, path)

    # INITIAL VARIABLES
    results_var = {"results_total": 0, "results_current": 0, "delete_total": 0, "images_total": 0, "select_total": 0}
    counter = {}
    for k, v in EXTENSIONS.iteritems():
        counter[k] = 0

    if q:
        m_root = os.path.normpath(MEDIA_ROOT)
        dirs = []
        for root, _subdirs, filenames in os.walk(abs_path):
            dirs_2 = []
            items = _subdirs + filenames
            for f in items:
                dirs_2.append((os.path.normpath(root)[len(m_root) + 1 :], f))
            # append result of every iteration to dirs
            dirs.append(dirs_2)
        dir_list = itertools.chain(*dirs)
    else:
        root = os.path.join(DIRECTORY, path)
        dir_list = ((root, f) for f in os.listdir(abs_path))

    files = []
    for file_dir, file in dir_list:
        # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
        filtered = file.startswith(".")
        for re_prefix in filter_re:
            if re_prefix.search(file):
                filtered = True
        if filtered:
            continue
        results_var["results_total"] += 1

        # CREATE FILEOBJECT
        fileobject = FileObject(os.path.join(file_dir, file))

        # FILTER / SEARCH
        append = False
        if fileobject.filetype == request.GET.get("filter_type", fileobject.filetype) and get_filterdate(
            request.GET.get("filter_date", ""), fileobject.date or 0
        ):
            append = True
        if q and not re.compile(q.lower(), re.M).search(file.lower()):
            append = False

        # APPEND FILE_LIST
        if append:
            try:
                # COUNTER/RESULTS
                if fileobject.filetype == "Image":
                    results_var["images_total"] += 1
                if fileobject.filetype != "Folder":
                    results_var["delete_total"] += 1
                elif fileobject.filetype == "Folder" and fileobject.is_empty:
                    results_var["delete_total"] += 1
                if (
                    query.get("type")
                    and query.get("type") in SELECT_FORMATS
                    and fileobject.filetype in SELECT_FORMATS[query.get("type")]
                ):
                    results_var["select_total"] += 1
                elif not query.get("type"):
                    results_var["select_total"] += 1
            except OSError:
                # Ignore items that have problems
                continue
            else:
                files.append(fileobject)
                results_var["results_current"] += 1

        # COUNTER/RESULTS
        if fileobject.filetype and fileobject.filetype in counter:  # Fixes bug where folder is not in extensions
            counter[fileobject.filetype] += 1

    # SORTING
    query["o"] = request.GET.get("o", DEFAULT_SORTING_BY)
    query["ot"] = request.GET.get("ot", DEFAULT_SORTING_ORDER)
    files = sort_by_attr(files, request.GET.get("o", DEFAULT_SORTING_BY))
    if not request.GET.get("ot") and DEFAULT_SORTING_ORDER == "desc" or request.GET.get("ot") == "desc":
        files.reverse()

    p = Paginator(files, LIST_PER_PAGE)
    try:
        page_nr = request.GET.get("p", "1")
    except:
        page_nr = 1
    try:
        page = p.page(page_nr)
    except (EmptyPage, InvalidPage):
        page = p.page(p.num_pages)

    return render_to_response(
        "filebrowser/index.html",
        {
            "dir": path,
            "p": p,
            "q": q,
            "page": page,
            "results_var": results_var,
            "counter": counter,
            "query": query,
            "title": _(u"FileBrowser"),
            "settings_var": get_settings_var(),
            "breadcrumbs": get_breadcrumbs(query, path),
            "breadcrumbs_title": "",
        },
        context_instance=Context(request),
    )