Пример #1
0
def explore(request, f_path=''):
    '''
    View that returns the information of the current directory in the filesystem.
    :param request: request information.
    :param f_path: relative filepath from the URL.
    :return: an array of JSON objects that represent the characteristics of the files/directories in the current path.
    '''
    f_path = f_path.split(
        '/')  # splitting just in case the OS doesn't use unix
    current_folder_path = path.join(settings.MEDIA_ROOT, *f_path)

    # open the current folder using Django specific classes.
    current_folder = FileSystemStorage(location=current_folder_path,
                                       file_permissions_mode=0o644,
                                       directory_permissions_mode=0o644)

    # current_folder_info: [[folder1, folder2, ...], [file1, file2, ...]]
    current_folder_info = [[], []]
    try:
        current_folder_info = current_folder.listdir(path='.')
    except NotADirectoryError:
        raise Http404('Not a Directory')

    # store data of present folder
    folder_data = []
    for f_name in current_folder_info[0]:  # reading folders
        folder_data.append({
            'name':
            f_name,
            'is_folder':
            True,
            'created':
            current_folder.get_created_time(name=f_name),
            'modified':
            current_folder.get_modified_time(name=f_name),
            'accessed':
            current_folder.get_accessed_time(name=f_name),
        })

    # update file's information
    for f_name in current_folder_info[1]:  # reading files
        file_path = path.join(current_folder_path, f_name)

        ## Fetch tags
        try:
            obj = Dataset.objects.get(path=file_path)
            obj_tags = DatasetTag.objects.filter(dataset_id=obj.id)
            tags = [Tag.objects.get(id=el.tag_id).tag_name for el in obj_tags]
        except ObjectDoesNotExist:
            tags = []

        # get file type using specific library
        type_file = magic_unix.from_file(filename=file_path)
        type_file_mime = magic_unix.from_file(filename=file_path, mime=True)
        folder_data.append({
            'name':
            f_name,
            'is_folder':
            False,
            'created':
            current_folder.get_created_time(name=f_name),
            'modified':
            current_folder.get_modified_time(name=f_name),
            'accessed':
            current_folder.get_accessed_time(name=f_name),
            'size':
            current_folder.size(name=f_name),
            'type':
            type_file,
            'type/mime':
            type_file_mime,
            'tags':
            tags
        })

    return JsonResponse({'response': folder_data}, safe=True)