Ejemplo n.º 1
0
    def get(self, request):
        # is search supported
        if not HAS_FILE_SEARCH:
            error_msg = 'Search not supported.'
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # argument check
        keyword = request.GET.get('q', None)
        if not keyword:
            error_msg = 'q invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        repo_id = request.GET.get('repo_id', None)
        if not is_valid_repo_id_format(repo_id):
            error_msg = 'repo_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # recourse check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        wiki = Wiki.objects.filter(repo_id=repo_id)[0]
        if not wiki.has_read_perm(request):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        try:
            current_page = int(request.GET.get('page', '1'))
            per_page = int(request.GET.get('per_page', '10'))
            if per_page > 100:
                per_page = 100
        except ValueError:
            current_page = 1
            per_page = 10

        start = (current_page - 1) * per_page
        size = per_page
        if start < 0 or size < 0:
            error_msg = 'page or per_page invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        repo_id_map = {}
        map_id = repo.origin_repo_id if repo.origin_repo_id else repo_id
        repo_id_map[map_id] = repo
        # search file
        try:
            results, total = search_files(
                repo_id_map, None, keyword, None, start, size, org_id=None
            )
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        for result in results:
            result.pop('repo', None)
            result.pop('exists', None)
            result.pop('last_modified_by', None)
            result.pop('name_highlight', None)
            result.pop('score', None)
            result['repo_type'] = 'public'

        has_more = True if total > current_page * per_page else False

        return Response({
            "total": total,
            "results": results,
            "has_more": has_more
        })
Ejemplo n.º 2
0
    def get(self, request):
        """ Get smart link of a file/dir.
        """

        # argument check
        repo_id = request.GET.get('repo_id', None)
        if not repo_id or not is_valid_repo_id_format(repo_id):
            error_msg = 'repo_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        is_dir = request.GET.get('is_dir', None)
        if not is_dir:
            error_msg = 'is_dir invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        is_dir = is_dir.lower()
        if is_dir not in ('true', 'false'):
            error_msg = "is_dir can only be 'true' or 'false'."
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # resource check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        is_dir = to_python_boolean(is_dir)
        if is_dir:
            if not seafile_api.get_dir_id_by_path(repo_id, normalize_dir_path(path)):
                error_msg = 'Folder %s not found.' % path
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)
        else:
            if not seafile_api.get_file_id_by_path(repo_id, normalize_file_path(path)):
                error_msg = 'File %s not found.' % path
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        if not check_folder_permission(request, repo_id, '/'):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # make sure path:
        # 1. starts with '/'
        # 2. NOT ends with '/'
        path = normalize_file_path(path)
        parent_dir = os.path.dirname(path)
        dirent_name = os.path.basename(path)

        # get file/dir uuid
        if repo.is_virtual:
            repo_id = repo.origin_repo_id
            path = posixpath.join(repo.origin_path, path.strip('/'))

            path = normalize_file_path(path)
            parent_dir = os.path.dirname(path)
            dirent_name = os.path.basename(path)

        try:
            uuid_map = FileUUIDMap.objects.get_or_create_fileuuidmap(repo_id,
                    parent_dir, dirent_name, is_dir)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        dirent_uuid = uuid_map.uuid
        smart_link = gen_smart_link(dirent_uuid, dirent_name)

        result = {}
        result['smart_link'] = smart_link
        result['smart_link_token'] = dirent_uuid

        return Response(result)
Ejemplo n.º 3
0
def simple_search(request):
    custom_search = False
    invalid_argument = False
    need_return_custom_search = False
    invalid_info = {
        'error': True,
        'error_msg': _(u'Invalid argument.'),
    }

    # Check GET parameters
    username = request.user.username
    org_id = request.user.org.org_id if is_org_context(request) else None
    keyword = request.GET.get('q', None)
    current_page = get_int(request.GET.get('page', '1'), 1)
    per_page = get_int(request.GET.get('per_page', '25'), 25)
    start = (current_page - 1) * per_page
    size = per_page
    if start < 0 or size < 0:
        invalid_argument = True

    search_repo = request.GET.get('search_repo', 'all')  # 'all' or repo_id
    search_repo = search_repo.lower()
    if not is_valid_repo_id_format(search_repo) and search_repo != 'all':
        invalid_argument = True

    search_path = request.GET.get('search_path', None)
    if search_path is not None and search_path[0] != '/':
        search_path = "/{0}".format(search_path)

    search_ftypes = request.GET.get('search_ftypes',
                                    'all')  # 'all' or 'custom'
    search_ftypes = search_ftypes.lower()
    if search_ftypes not in ('all', 'custom'):
        invalid_argument = True

    time_from = request.GET.get('time_from', '')
    time_to = request.GET.get('time_to', '')
    size_from = request.GET.get('size_from', '')
    size_to = request.GET.get('size_to', '')

    date_from = request.GET.get('date_from', '')
    date_to = request.GET.get('date_to', '')
    size_from_mb = request.GET.get('size_from_mb', '')
    size_to_mb = request.GET.get('size_to_mb', '')

    if time_from:
        if not is_valid_date(time_from) and not invalid_argument:
            need_return_custom_search = True
            invalid_argument = True
            invalid_info['error_msg'] = _(u'Invalid date.')
    else:
        time_from = None

    if time_to:
        if not is_valid_date(time_to) and not invalid_argument:
            need_return_custom_search = True
            invalid_argument = True
            invalid_info['error_msg'] = _(u'Invalid date.')
    else:
        time_to = None

    if size_from:
        if not is_valid_size(size_from) and not invalid_argument:
            need_return_custom_search = True
            invalid_argument = True
            invalid_info['error_msg'] = _(u'Invalid file size.')
    else:
        size_from = None

    if size_to:
        if not is_valid_size(size_to) and not invalid_argument:
            need_return_custom_search = True
            invalid_argument = True
            invalid_info['error_msg'] = _(u'Invalid file size.')
    else:
        size_to = None

    if size_to and size_from and size_to < size_from and not invalid_argument:
        invalid_argument = True
        need_return_custom_search = True
        invalid_info['error_msg'] = _(u'Invalid file size range.')

    if time_to and time_from and time_to < time_from and not invalid_argument:
        invalid_argument = True
        need_return_custom_search = True
        invalid_info['error_msg'] = _(u'Invalid date range.')

    time_range = (time_from, time_to)
    size_range = (size_from, size_to)
    suffixes = None
    custom_ftypes = request.GET.getlist('ftype')
    input_fileexts = request.GET.get('input_fexts', '')
    if search_ftypes == 'custom':
        suffixes = []
        if len(custom_ftypes) > 0:
            for ftp in custom_ftypes:
                if ftp in SEARCH_FILEEXT:
                    for ext in SEARCH_FILEEXT[ftp]:
                        suffixes.append(ext)

        if input_fileexts:
            input_fexts = input_fileexts.split(',')
            for i_ext in input_fexts:
                i_ext = i_ext.strip()
                if i_ext:
                    suffixes.append(i_ext)

    range_args = [time_from, time_to, size_from, size_to]
    if search_repo != 'all' or search_ftypes == 'custom' or any(
            e for e in range_args):
        custom_search = True

    if invalid_argument:
        if need_return_custom_search:
            invalid_info['keyword'] = keyword
            invalid_info['search_repo'] = search_repo
            invalid_info['search_ftypes'] = search_ftypes
            invalid_info['custom_ftypes'] = custom_ftypes
            invalid_info['input_fileexts'] = input_fileexts
            invalid_info['custom_search'] = custom_search
            invalid_info['date_from'] = date_from
            invalid_info['date_to'] = date_to
            invalid_info['size_from_mb'] = size_from_mb
            invalid_info['size_to_mb'] = size_to_mb
        return render(request, 'simple_search/search_results.html',
                      invalid_info)

    repo_id_map = {}
    # Check recourse and permission when search in a single repo
    if is_valid_repo_id_format(search_repo):
        repo_id = search_repo
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            data = {
                'error': True,
                'error_msg': _(u'Library %s not found.') % repo_id
            }
            return render(request, 'simple_search/search_results.html', data)

        # Check folder permissions
        if not check_folder_permission(request, repo_id, '/'):
            data = {'error': True, 'error_msg': _(u'Permission denied.')}
            return render(request, 'simple_search/search_results.html', data)
        map_id = repo.origin_repo_id if repo.origin_repo_id else repo_id
        repo_id_map[map_id] = repo
    else:
        repo_id_map, repo_type_map = get_search_repos_map(
            search_repo, username, org_id)

    obj_desc = {
        'suffixes': suffixes,
        'time_range': time_range,
        'size_range': size_range
    }

    # Search file
    try:
        if keyword:
            results, total = search_files(repo_id_map, search_path, keyword,
                                          obj_desc, start, size, org_id)
        else:
            results, total, keyword = [], 0, ''
    except Exception as e:
        logger.error(e)
        data = {'error': True, 'error_msg': _(u'Internal Server Error')}
        return render(request, 'simple_search/search_results.html', data)

    has_more = True if total > current_page * per_page else False

    return render(
        request, 'simple_search/search_results.html', {
            'repo': repo if is_valid_repo_id_format(search_repo) else None,
            'keyword': keyword,
            'results': results,
            'total': total,
            'has_more': has_more,
            'current_page': current_page,
            'prev_page': current_page - 1,
            'next_page': current_page + 1,
            'per_page': per_page,
            'search_repo': search_repo,
            'search_ftypes': search_ftypes,
            'custom_ftypes': custom_ftypes,
            'input_fileexts': input_fileexts,
            'error': False,
            'enable_thumbnail': ENABLE_THUMBNAIL,
            'thumbnail_size': THUMBNAIL_SIZE_FOR_GRID,
            'date_from': date_from,
            'date_to': date_to,
            'size_from_mb': size_from_mb,
            'size_to_mb': size_to_mb,
            'custom_search': custom_search
        })
Ejemplo n.º 4
0
def search(request):

    custom_search = False
    invalid_argument = False
    need_return_custom_search = False
    invalid_info = {
        'error': True,
        'error_msg': _(u'Invalid argument.'),
    }

    # argument check
    username = request.user.username
    org_id = request.user.org.org_id if is_org_context(request) else None
    keyword = request.GET.get('q', None)

    try:
        current_page = int(request.GET.get('page', '1'))
        per_page = int(request.GET.get('per_page', '25'))
    except ValueError:
        current_page = 1
        per_page = 25

    start = (current_page - 1) * per_page
    size = per_page
    if start < 0 or size < 0:
        invalid_argument = True

    search_repo = request.GET.get('search_repo',
                                  'all')  # val: 'all' or 'repo_id'
    search_repo = search_repo.lower()
    if not is_valid_repo_id_format(search_repo) and search_repo != 'all':
        invalid_argument = True

    search_path = request.GET.get('search_path', None)
    if search_path is not None and search_path[0] != '/':
        search_path = "/{0}".format(search_path)

    search_ftypes = request.GET.get('search_ftypes',
                                    'all')  # val: 'all' or 'custom'
    search_ftypes = search_ftypes.lower()
    if search_ftypes not in ('all', 'custom'):
        invalid_argument = True

    time_from = request.GET.get('time_from', '')
    time_to = request.GET.get('time_to', '')
    size_from = request.GET.get('size_from', '')
    size_to = request.GET.get('size_to', '')

    date_from = request.GET.get('date_from', '')
    date_to = request.GET.get('date_to', '')
    size_from_mb = request.GET.get('size_from_mb', '')
    size_to_mb = request.GET.get('size_to_mb', '')

    if time_from:
        if not is_valid_date_type(time_from) and not invalid_argument:
            need_return_custom_search = True
            invalid_argument = True
            invalid_info['error_msg'] = _(u'Invalid date.')
    else:
        time_from = None

    if time_to:
        if not is_valid_date_type(time_to) and not invalid_argument:
            need_return_custom_search = True
            invalid_argument = True
            invalid_info['error_msg'] = _(u'Invalid date.')
    else:
        time_to = None

    if size_from:
        if not is_valid_size_type(size_from) and not invalid_argument:
            need_return_custom_search = True
            invalid_argument = True
            invalid_info['error_msg'] = _(u'Invalid file size.')
    else:
        size_from = None

    if size_to:
        if not is_valid_size_type(size_to) and not invalid_argument:
            need_return_custom_search = True
            invalid_argument = True
            invalid_info['error_msg'] = _(u'Invalid file size.')
    else:
        size_to = None

    if size_to and size_from and size_to < size_from and not invalid_argument:
        invalid_argument = True
        need_return_custom_search = True
        invalid_info['error_msg'] = _(u'Invalid file size range.')

    if time_to and time_from and time_to < time_from and not invalid_argument:
        invalid_argument = True
        need_return_custom_search = True
        invalid_info['error_msg'] = _(u'Invalid date range.')

    time_range = (time_from, time_to)
    size_range = (size_from, size_to)
    suffixes = None
    custom_ftypes = request.GET.getlist(
        'ftype')  # types like 'Image', 'Video'... same in utils/file_types.py
    input_fileexts = request.GET.get('input_fexts',
                                     '')  # file extension input by the user
    if search_ftypes == 'custom':
        suffixes = []
        if len(custom_ftypes) > 0:
            for ftp in custom_ftypes:
                if SEARCH_FILEEXT.has_key(ftp):
                    for ext in SEARCH_FILEEXT[ftp]:
                        suffixes.append(ext)

        if input_fileexts:
            input_fexts = input_fileexts.split(',')
            for i_ext in input_fexts:
                i_ext = i_ext.strip()
                if i_ext:
                    suffixes.append(i_ext)

    range_args = [time_from, time_to, size_from, size_to]
    if search_repo != 'all' or search_ftypes == 'custom' or any(
            e for e in range_args):
        custom_search = True

    if invalid_argument:
        if need_return_custom_search:
            invalid_info['keyword'] = keyword
            invalid_info['search_repo'] = search_repo
            invalid_info['search_ftypes'] = search_ftypes
            invalid_info['custom_ftypes'] = custom_ftypes
            invalid_info['input_fileexts'] = input_fileexts
            invalid_info['custom_search'] = custom_search
            invalid_info['date_from'] = date_from
            invalid_info['date_to'] = date_to
            invalid_info['size_from_mb'] = size_from_mb
            invalid_info['size_to_mb'] = size_to_mb
        return render(request, 'search_results.html', invalid_info)

    repo_id_map = {}
    # check recourse and permissin when search in a single repo
    if is_valid_repo_id_format(search_repo):
        repo_id = search_repo
        repo = seafile_api.get_repo(repo_id)
        # recourse check
        if not repo:
            data = {
                'error': True,
                'error_msg': _(u'Library %s not found.') % repo_id
            }
            return render(request, 'search_results.html', data)

        # permission check
        if not check_folder_permission(request, repo_id, '/'):
            data = {'error': True, 'error_msg': _(u'Permission denied.')}
            return render(request, 'search_results.html', data)
        map_id = repo.origin_repo_id if repo.origin_repo_id else repo_id
        repo_id_map[map_id] = repo
    else:
        shared_from = request.GET.get('shared_from', None)
        not_shared_from = request.GET.get('not_shared_from', None)
        repo_id_map, repo_type_map = get_search_repos_map(
            search_repo, username, org_id, shared_from, not_shared_from)

    obj_desc = {
        'suffixes': suffixes,
        'time_range': time_range,
        'size_range': size_range
    }
    # search file
    try:
        if keyword:
            results, total = search_files(repo_id_map, search_path, keyword,
                                          obj_desc, start, size, org_id)
        else:
            results, total, keyword = [], 0, ''
    except Exception as e:
        logger.error(e)
        data = {'error': True, 'error_msg': _(u'Internal Server Error')}
        return render(request, 'search_results.html', data)

    has_more = True if total > current_page * per_page else False
    for r in results:
        r['parent_dir'] = os.path.dirname(r['fullpath'].rstrip('/'))

    response_dict = {
        'repo': repo if is_valid_repo_id_format(search_repo) else None,
        'keyword': keyword,
        'results': results,
        'total': total,
        'has_more': has_more,
        'current_page': current_page,
        'prev_page': current_page - 1,
        'next_page': current_page + 1,
        'per_page': per_page,
        'search_repo': search_repo,
        'search_ftypes': search_ftypes,
        'custom_ftypes': custom_ftypes,
        'input_fileexts': input_fileexts,
        'error': False,
        'enable_thumbnail': ENABLE_THUMBNAIL,
        'thumbnail_size': THUMBNAIL_SIZE_FOR_GRID,
        'date_from': date_from,
        'date_to': date_to,
        'size_from_mb': size_from_mb,
        'size_to_mb': size_to_mb,
        'custom_search': custom_search
    }

    # Whether use new index page
    use_new_page = True
    if request.GET.get('_old', None):
        use_new_page = False

    if use_new_page:
        return render(request, 'search_results_react.html', response_dict)

    return render(request, 'search_results.html', response_dict)
Ejemplo n.º 5
0
    def get(self, request):
        # Check GET parameters
        keyword = request.GET.get('q', None)
        if not keyword:
            error_msg = 'q invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            current_page = int(request.GET.get('page', '1'))
            per_page = int(request.GET.get('per_page', '10'))
        except ValueError:
            current_page = 1
            per_page = 10

        start = (current_page - 1) * per_page
        size = per_page
        if start < 0 or size < 0:
            error_msg = 'page or per_page invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        search_repo = request.GET.get('search_repo', 'all')  # scope or repo_id
        search_repo = search_repo.lower()
        if not is_valid_repo_id_format(search_repo) and \
                search_repo not in ('all', 'mine', 'shared', 'group', 'public'):
            error_msg = 'search_repo invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        search_path = request.GET.get('search_path', None)
        if search_path:
            search_path = normalize_dir_path(search_path)
            if not is_valid_repo_id_format(search_repo):
                error_msg = 'search_repo invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

            dir_id = seafile_api.get_dir_id_by_path(search_repo, search_path)
            if not dir_id:
                error_msg = 'Folder %s not found.' % search_path
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        obj_type = request.GET.get('obj_type', None)
        if obj_type:
            obj_type = obj_type.lower()

        if obj_type and obj_type not in ('dir', 'file'):
            error_msg = 'obj_type invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        search_ftypes = request.GET.get('search_ftypes',
                                        'all')  # val: 'all' or 'custom'
        search_ftypes = search_ftypes.lower()
        if search_ftypes not in ('all', 'custom'):
            error_msg = 'search_ftypes invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        with_permission = request.GET.get('with_permission', 'false')
        with_permission = with_permission.lower()
        if with_permission not in ('true', 'false'):
            error_msg = 'with_permission invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        time_from = request.GET.get('time_from', None)
        time_to = request.GET.get('time_to', None)
        if time_from is not None:
            try:
                time_from = int(time_from)
            except:
                error_msg = 'time_from invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if time_to is not None:
            try:
                time_to = int(time_to)
            except:
                error_msg = 'time_to invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        size_from = request.GET.get('size_from', None)
        size_to = request.GET.get('size_to', None)
        if size_from is not None:
            try:
                size_from = int(size_from)
            except:
                error_msg = 'size_from invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if size_to is not None:
            try:
                size_to = int(size_to)
            except:
                error_msg = 'size_to invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        time_range = (time_from, time_to)
        size_range = (size_from, size_to)

        suffixes = None
        custom_ftypes = request.GET.getlist(
            'ftype'
        )  # types like 'Image', 'Video'... same in utils/file_types.py
        input_fileexts = request.GET.get(
            'input_fexts', '')  # file extension input by the user
        if search_ftypes == 'custom':
            suffixes = []
            if len(custom_ftypes) > 0:
                for ftp in custom_ftypes:
                    if SEARCH_FILEEXT.has_key(ftp):
                        for ext in SEARCH_FILEEXT[ftp]:
                            suffixes.append(ext)

            if input_fileexts:
                input_fexts = input_fileexts.split(',')
                for i_ext in input_fexts:
                    i_ext = i_ext.strip()
                    if i_ext:
                        suffixes.append(i_ext)

        username = request.user.username
        org_id = request.user.org.org_id if is_org_context(request) else None
        repo_id_map = {}
        # Check recourse and permissin when search in a single repo
        if is_valid_repo_id_format(search_repo):
            repo_id = search_repo
            repo = seafile_api.get_repo(repo_id)
            # recourse check
            if not repo:
                error_msg = 'Library %s not found.' % repo_id
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

            # permission check
            if not check_folder_permission(request, repo_id, '/'):
                error_msg = 'Permission denied.'
                return api_error(status.HTTP_403_FORBIDDEN, error_msg)
            map_id = repo.origin_repo_id if repo.origin_repo_id else repo_id
            repo_id_map[map_id] = repo
            repo_type_map = {}
        else:
            repo_id_map, repo_type_map = get_search_repos_map(
                search_repo, username, org_id)

        obj_desc = {
            'obj_type': obj_type,
            'suffixes': suffixes,
            'time_range': time_range,
            'size_range': size_range
        }

        # Search files
        try:
            results, total = search_files(repo_id_map, search_path, keyword,
                                          obj_desc, start, size, org_id)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        for e in results:
            e.pop('repo', None)
            e.pop('exists', None)
            e.pop('last_modified_by', None)
            e.pop('name_highlight', None)
            e.pop('score', None)

            repo_id = e['repo_id']

            if with_permission.lower() == 'true':
                permission = check_folder_permission(request, repo_id, '/')
                if not permission:
                    continue
                e['permission'] = permission

            # get repo type
            if repo_type_map.has_key(repo_id):
                e['repo_type'] = repo_type_map[repo_id]
            else:
                e['repo_type'] = ''

        has_more = True if total > current_page * per_page else False

        return Response({
            "total": total,
            "results": results,
            "has_more": has_more
        })
Ejemplo n.º 6
0
Archivo: logs.py Proyecto: cytec/seahub
    def get(self, request):
        """ Get all file access logs.

        Permission checking:
        1. only admin can perform this action.
        """
        try:
            current_page = int(request.GET.get('page', '1'))
            per_page = int(request.GET.get('per_page', '100'))
        except ValueError:
            current_page = 1
            per_page = 100

        user_selected = request.GET.get('email', None)
        if user_selected and not is_valid_email(user_selected):
            error_msg = 'email %s invalid.' % user_selected
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        repo_id_selected = request.GET.get('repo_id', None)
        if repo_id_selected and not is_valid_repo_id_format(repo_id_selected):
            error_msg = 'repo_id %s invalid.' % repo_id_selected
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        start = per_page * (current_page - 1)
        limit = per_page

        # org_id = 0, show all file audit
        events = get_file_audit_events(user_selected, 0, repo_id_selected,
                                       start, limit) or []

        has_next_page = True if len(events) == per_page else False

        # Use dict to reduce memcache fetch cost in large for-loop.
        nickname_dict = {}
        contact_email_dict = {}
        repo_dict = {}
        user_email_set = set()
        repo_id_set = set()

        for event in events:
            user_email_set.add(event.user)
            repo_id_set.add(event.repo_id)

        for e in user_email_set:
            if e not in nickname_dict:
                nickname_dict[e] = email2nickname(e)
            if e not in contact_email_dict:
                contact_email_dict[e] = email2contact_email(e)
        for e in repo_id_set:
            if e not in repo_dict:
                repo_dict[e] = seafile_api.get_repo(e)

        events_info = []
        for ev in events:
            data = {}
            user_email = ev.user
            data['email'] = user_email
            data['name'] = nickname_dict.get(user_email, '')
            data['contact_email'] = contact_email_dict.get(user_email, '')

            data['ip'] = ev.ip
            data['event_type'], data[
                'device'] = generate_file_audit_event_type(ev)
            data['time'] = utc_datetime_to_isoformat_timestr(ev.timestamp)

            repo_id = ev.repo_id
            data['repo_id'] = repo_id
            repo = repo_dict.get(repo_id, None)
            data['repo_name'] = repo.name if repo else ''

            if ev.file_path.endswith('/'):
                data[
                    'file_or_dir_name'] = '/' if ev.file_path == '/' else os.path.basename(
                        ev.file_path.rstrip('/'))
            else:
                data['file_or_dir_name'] = os.path.basename(ev.file_path)
            events_info.append(data)

        resp = {
            'file_access_log_list': events_info,
            'has_next_page': has_next_page,
        }

        return Response(resp)
Ejemplo n.º 7
0
Archivo: logs.py Proyecto: cytec/seahub
    def get(self, request):
        """ Get all share permissions logs.

        Permission checking:
        1. only admin can perform this action.
        """
        try:
            current_page = int(request.GET.get('page', '1'))
            per_page = int(request.GET.get('per_page', '100'))
        except ValueError:
            current_page = 1
            per_page = 100

        user_selected = request.GET.get('email', None)
        if user_selected and not is_valid_email(user_selected):
            error_msg = 'email %s invalid.' % user_selected
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        repo_id_selected = request.GET.get('repo_id', None)
        if repo_id_selected and not is_valid_repo_id_format(repo_id_selected):
            error_msg = 'repo_id %s invalid.' % repo_id_selected
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        start = per_page * (current_page - 1)
        limit = per_page

        # org_id = 0, show all file audit
        events = get_perm_audit_events(user_selected, 0, repo_id_selected,
                                       start, limit) or []

        has_next_page = True if len(events) == per_page else False

        # Use dict to reduce memcache fetch cost in large for-loop.
        from_nickname_dict = {}
        from_contact_email_dict = {}
        to_nickname_dict = {}
        to_contact_email_dict = {}
        repo_dict = {}
        from_user_email_set = set()
        to_user_email_set = set()
        repo_id_set = set()

        for event in events:
            from_user_email_set.add(event.from_user)
            to_user_email_set.add(event.to)
            repo_id_set.add(event.repo_id)

        for e in from_user_email_set:
            if e not in from_nickname_dict:
                from_nickname_dict[e] = email2nickname(e)
            if e not in from_contact_email_dict:
                from_contact_email_dict[e] = email2contact_email(e)
        for e in to_user_email_set:
            if e not in to_nickname_dict:
                to_nickname_dict[e] = email2nickname(e)
            if e not in to_contact_email_dict:
                to_contact_email_dict[e] = email2contact_email(e)
        for e in repo_id_set:
            if e not in repo_dict:
                repo_dict[e] = seafile_api.get_repo(e)

        events_info = []
        for ev in events:
            data = {}
            from_user_email = ev.from_user
            to_user_email = ev.to
            data['from_user_email'] = from_user_email
            data['from_user_name'] = from_nickname_dict.get(
                from_user_email, '')
            data['from_user_contact_email'] = from_contact_email_dict.get(
                from_user_email, '')
            data['to_user_email'] = to_user_email
            data['to_user_name'] = to_nickname_dict.get(to_user_email, '')
            data['to_user_contact_email'] = to_contact_email_dict.get(
                to_user_email, '')

            data['etype'] = ev.etype
            data['permission'] = ev.permission

            repo_id = ev.repo_id
            data['repo_id'] = repo_id
            repo = repo_dict.get(repo_id, None)
            data['repo_name'] = repo.name if repo else ''

            data['folder'] = '/' if ev.file_path == '/' else os.path.basename(
                ev.file_path.rstrip('/'))
            data['date'] = utc_datetime_to_isoformat_timestr(ev.timestamp)
            events_info.append(data)

        resp = {
            'share_permission_log_list': events_info,
            'has_next_page': has_next_page,
        }

        return Response(resp)
Ejemplo n.º 8
0
    def get(self, request):
        """ Get all file update logs.

        Permission checking:
        1. only admin can perform this action.
        """

        if not request.user.admin_permissions.can_view_user_log():
            return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')

        try:
            current_page = int(request.GET.get('page', '1'))
            per_page = int(request.GET.get('per_page', '100'))
        except ValueError:
            current_page = 1
            per_page = 100

        user_selected = request.GET.get('email', None)
        if user_selected and not is_valid_email(user_selected):
            error_msg = 'email %s invalid.' % user_selected
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        repo_id_selected = request.GET.get('repo_id', None)
        if repo_id_selected and not is_valid_repo_id_format(repo_id_selected):
            error_msg = 'repo_id %s invalid.' % repo_id_selected
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        start = per_page * (current_page - 1)
        limit = per_page

        # org_id = 0, show all file audit
        events = get_file_update_events(user_selected, 0, repo_id_selected,
                                        start, limit) or []

        has_next_page = True if len(events) == per_page else False

        # Use dict to reduce memcache fetch cost in large for-loop.
        nickname_dict = {}
        contact_email_dict = {}
        repo_dict = {}
        user_email_set = set()
        repo_id_set = set()

        for event in events:
            user_email_set.add(event.user)
            repo_id_set.add(event.repo_id)

        for e in user_email_set:
            if e not in nickname_dict:
                nickname_dict[e] = email2nickname(e)
            if e not in contact_email_dict:
                contact_email_dict[e] = email2contact_email(e)
        for e in repo_id_set:
            if e not in repo_dict:
                repo_dict[e] = seafile_api.get_repo(e)

        events_info = []
        for ev in events:
            data = {}
            user_email = ev.user
            data['email'] = user_email
            data['name'] = nickname_dict.get(user_email, '')
            data['contact_email'] = contact_email_dict.get(user_email, '')
            data['time'] = utc_datetime_to_isoformat_timestr(ev.timestamp)

            repo_id = ev.repo_id
            data['repo_id'] = repo_id
            repo = repo_dict.get(repo_id, None)
            data['repo_name'] = repo.name if repo else ''
            data['repo_encrypted'] = repo.encrypted if repo else None

            data['file_operation'] = ev.file_oper
            data['commit_id'] = ev.commit_id
            events_info.append(data)

        resp = {
            'file_update_log_list': events_info,
            'has_next_page': has_next_page,
        }

        return Response(resp)
Ejemplo n.º 9
0
    def get(self, request):
        """ Get smart link of a file/dir.
        """

        # argument check
        repo_id = request.GET.get('repo_id', None)
        if not repo_id or not is_valid_repo_id_format(repo_id):
            error_msg = 'repo_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        path = request.GET.get('path', None)
        if not path:
            error_msg = 'path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        is_dir = request.GET.get('is_dir', None)
        if not is_dir:
            error_msg = 'is_dir invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        is_dir = is_dir.lower()
        if is_dir not in ('true', 'false'):
            error_msg = "is_dir can only be 'true' or 'false'."
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # resource check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        is_dir = to_python_boolean(is_dir)
        if is_dir:
            if not seafile_api.get_dir_id_by_path(repo_id, normalize_dir_path(path)):
                error_msg = 'Folder %s not found.' % path
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)
        else:
            if not seafile_api.get_file_id_by_path(repo_id, normalize_file_path(path)):
                error_msg = 'File %s not found.' % path
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        if not check_folder_permission(request, repo_id, '/'):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # make sure path:
        # 1. starts with '/'
        # 2. NOT ends with '/'
        path = normalize_file_path(path)
        parent_dir = os.path.dirname(path)
        dirent_name = os.path.basename(path)

        # get file/dir uuid
        if repo.is_virtual:
            repo_id = repo.origin_repo_id
            path = posixpath.join(repo.origin_path, path.strip('/'))

            path = normalize_file_path(path)
            parent_dir = os.path.dirname(path)
            dirent_name = os.path.basename(path)

        try:
            uuid_map = FileUUIDMap.objects.get_or_create_fileuuidmap(repo_id,
                    parent_dir, dirent_name, is_dir)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        dirent_uuid = uuid_map.uuid
        smart_link = gen_smart_link(dirent_uuid)

        result = {}
        result['smart_link'] = smart_link
        result['smart_link_token'] = dirent_uuid
        result['name'] = dirent_name

        return Response(result)