Beispiel #1
0
    def get(self, request, repo_id, format=None):
        """ Get all file/folder in a library
        """

        repo = seafile_api.get_repo(repo_id)

        parent_dir = request.GET.get('parent_dir', '/')
        parent_dir = normalize_dir_path(parent_dir)
        dir_id = seafile_api.get_dir_id_by_path(repo_id, parent_dir)
        if not dir_id:
            error_msg = 'Folder %s not found.' % parent_dir
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        repo_owner = get_repo_owner(request, repo_id)

        try:
            dirs = seafile_api.list_dir_with_perm(repo_id, parent_dir, dir_id,
                                                  repo_owner, -1, -1)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return_results = {}
        return_results['repo_name'] = repo.repo_name
        return_results['repo_id'] = repo.repo_id
        return_results['is_system_library'] = True if \
            repo.id == get_system_default_repo_id() else False
        return_results['dirent_list'] = []

        for dirent in dirs:
            dirent_info = get_dirent_info(dirent)
            return_results['dirent_list'].append(dirent_info)

        return Response(return_results)
Beispiel #2
0
    def delete(self, request, repo_id, format=None):
        """ delete a library

        Permission checking:
        1. only admin can perform this action.
        """
        if get_system_default_repo_id() == repo_id:
            error_msg = _('System library can not be deleted.')
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

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

        repo_owner = seafile_api.get_repo_owner(repo_id)
        if not repo_owner:
            repo_owner = seafile_api.get_org_repo_owner(repo_id)
        related_usernames = seaserv.get_related_users_by_repo(repo_id)

        try:
            seafile_api.remove_repo(repo_id)
            repo_deleted.send(sender=None,
                              org_id=-1,
                              usernames=related_usernames,
                              repo_owner=repo_owner,
                              repo_id=repo_id,
                              repo_name=repo.name)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'success': True})
Beispiel #3
0
    def get(self, request, repo_id, format=None):
        """ Get all file/folder in a library
        """

        repo = seafile_api.get_repo(repo_id)

        parent_dir = request.GET.get('parent_dir', '/')
        parent_dir = normalize_dir_path(parent_dir)
        dir_id = seafile_api.get_dir_id_by_path(repo_id, parent_dir)
        if not dir_id:
            error_msg = 'Folder %s not found.' % parent_dir
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        repo_owner = get_repo_owner(request, repo_id)

        try:
            dirs = seafile_api.list_dir_with_perm(repo_id,
                parent_dir, dir_id, repo_owner, -1, -1)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return_results = {}
        return_results['repo_name'] = repo.repo_name
        return_results['repo_id'] = repo.repo_id
        return_results['is_system_library'] = True if \
            repo.id == get_system_default_repo_id() else False
        return_results['dirent_list'] = []

        for dirent in dirs:
            dirent_info = get_dirent_info(dirent)
            return_results['dirent_list'].append(dirent_info)

        return Response(return_results)
Beispiel #4
0
    def delete(self, request, repo_id, format=None):
        """ delete a library

        Permission checking:
        1. only admin can perform this action.
        """
        if get_system_default_repo_id() == repo_id:
            error_msg = _('System library can not be deleted.')
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            # for case of `seafile-data` has been damaged
            # no `repo object` will be returned from seafile api
            # delete the database record anyway
            try:
                seafile_api.remove_repo(repo_id)
            except Exception as e:
                logger.error(e)
                error_msg = 'Internal Server Error'
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                                 error_msg)

            return Response({'success': True})

        repo_name = repo.name
        repo_owner = seafile_api.get_repo_owner(repo_id)
        if not repo_owner:
            repo_owner = seafile_api.get_org_repo_owner(repo_id)

        try:
            related_usernames = seaserv.get_related_users_by_repo(repo_id)
            seafile_api.remove_repo(repo_id)

            # send signal for seafevents
            repo_deleted.send(sender=None,
                              org_id=-1,
                              operator=request.user.username,
                              usernames=related_usernames,
                              repo_owner=repo_owner,
                              repo_id=repo_id,
                              repo_name=repo.name)

        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        # send admin operation log signal
        admin_op_detail = {
            "id": repo_id,
            "name": repo_name,
            "owner": repo_owner,
        }
        admin_operation.send(sender=None,
                             admin_name=request.user.username,
                             operation=REPO_DELETE,
                             detail=admin_op_detail)

        return Response({'success': True})
Beispiel #5
0
def sys_repo_delete(request, repo_id):
    """Delete a repo.
    """
    next_page = request.META.get('HTTP_REFERER', None)
    if not next_page:
        next_page = HASH_URLS['SYS_REPO_ADMIN']

    if get_system_default_repo_id() == repo_id:
        messages.error(request, _('System library can not be deleted.'))
        return HttpResponseRedirect(next_page)

    repo = seafile_api.get_repo(repo_id)
    if repo:                    # Handle the case that repo is `None`.
        repo_name = repo.name
    else:
        repo_name = ''

    repo_owner = get_repo_owner(request, repo_id)
    try:
        org_id = seafile_api.get_org_id_by_repo_id(repo_id)
        usernames = get_related_users_by_repo(repo_id,
                org_id if org_id and org_id > 0 else None)
    except Exception as e:
        logger.error(e)
        org_id = -1
        usernames = []

    seafile_api.remove_repo(repo_id)
    repo_deleted.send(sender=None, org_id=org_id, operator=request.user.username,
            usernames=usernames, repo_owner=repo_owner, repo_id=repo_id,
            repo_name=repo_name)

    messages.success(request, _('Successfully deleted.'))
    return HttpResponseRedirect(next_page)
Beispiel #6
0
def repo_remove(request, repo_id):
    if not request.is_ajax():
        raise Http404

    content_type = 'application/json; charset=utf-8'
    result = {}  

    if get_system_default_repo_id() == repo_id:
        result['error'] = _(u'System library can not be deleted.')
        return HttpResponse(json.dumps(result), status=403, content_type=content_type)
        
    repo = get_repo(repo_id)
    if not repo:
        result['error'] = _(u'Library does not exist')
        return HttpResponse(json.dumps(result), status=400, content_type=content_type)
      
    user = request.user.username
    org, base_template = check_and_get_org_by_repo(repo_id, user)
    if org: 
        # Remove repo in org context, only repo owner or org staff can
        # perform this operation.
        if request.user.is_staff or org.is_staff or \
                is_org_repo_owner(org.org_id, repo_id, user):
            # Must get related useres before remove the repo
            usernames = get_related_users_by_org_repo(org.org_id, repo_id)
            seafile_api.remove_repo(repo_id)
            repo_deleted.send(sender=None,
                              org_id=org.org_id,
                              usernames=usernames,
                              repo_owner=user,
                              repo_id=repo_id,
                              repo_name=repo.name,
                          )    
            result['success'] = True
            return HttpResponse(json.dumps(result), content_type=content_type)
        else:
            result['error'] = _(u'Permission denied.')
            return HttpResponse(json.dumps(result), status=400, content_type=content_type)
    else:
        # Remove repo in personal context, only repo owner or site staff can
        # perform this operation.
        if validate_owner(request, repo_id) or request.user.is_staff:
            usernames = get_related_users_by_repo(repo_id)
            seafile_api.remove_repo(repo_id)
            repo_deleted.send(sender=None,
                              org_id=-1,
                              usernames=usernames,
                              repo_owner=user,
                              repo_id=repo_id,
                              repo_name=repo.name,
                          )
            result['success'] = True
            return HttpResponse(json.dumps(result), content_type=content_type)
        else:
            result['error'] = _(u'Permission denied.')
            return HttpResponse(json.dumps(result), status=400, content_type=content_type)
Beispiel #7
0
def sys_list_system(request):
    """List system repos.
    """
    repos = []
    sys_repo = seafile_api.get_repo(get_system_default_repo_id())
    repos.append(sys_repo)

    return render_to_response('sysadmin/sys_list_system.html', {
            'repos': repos,
            }, context_instance=RequestContext(request))
Beispiel #8
0
def sys_list_system(request):
    """List system repos.
    """
    repos = []
    sys_repo = seafile_api.get_repo(get_system_default_repo_id())
    repos.append(sys_repo)

    return render_to_response('sysadmin/sys_list_system.html', {
            'repos': repos,
            }, context_instance=RequestContext(request))
Beispiel #9
0
def can_view_sys_admin_repo(repo):
    default_repo_id = get_system_default_repo_id()
    is_default_repo = True if repo.id == default_repo_id else False

    if is_default_repo:
        return True
    elif repo.encrypted:
        return False
    elif is_pro_version() and ENABLE_SYS_ADMIN_VIEW_REPO:
        return True
    else:
        return False
Beispiel #10
0
def can_view_sys_admin_repo(repo):
    default_repo_id = get_system_default_repo_id()
    is_default_repo = True if repo.id == default_repo_id else False

    if is_default_repo:
        return True
    elif repo.encrypted:
        return False
    elif is_pro_version():
        return True
    else:
        return False
Beispiel #11
0
    def get(self, request, repo_id, format=None):
        """ get all file/folder in a library
        """

        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)

        if not can_view_sys_admin_repo(repo):
            error_msg = 'Feature disabled.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

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

        if parent_dir[-1] != '/':
            parent_dir = parent_dir + '/'

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

        if is_org_context(request):
            repo_owner = seafile_api.get_org_repo_owner(repo_id)
        else:
            repo_owner = seafile_api.get_repo_owner(repo_id)

        try:
            dirs = seafserv_threaded_rpc.list_dir_with_perm(repo_id,
                parent_dir, dir_id, repo_owner, -1, -1)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return_results = {}
        return_results['repo_name'] = repo.repo_name
        return_results['repo_id'] = repo.repo_id
        return_results['is_system_library'] = True if \
            repo.id == get_system_default_repo_id() else False
        return_results['dirent_list'] = []

        for dirent in dirs:
            dirent_info = get_dirent_info(dirent)
            return_results['dirent_list'].append(dirent_info)

        return Response(return_results)
Beispiel #12
0
    def get(self, request, repo_id, format=None):
        """ get all file/folder in a library
        """

        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)

        if not can_view_sys_admin_repo(repo):
            error_msg = 'Feature disabled.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

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

        if parent_dir[-1] != '/':
            parent_dir = parent_dir + '/'

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

        if is_org_context(request):
            repo_owner = seafile_api.get_org_repo_owner(repo_id)
        else:
            repo_owner = seafile_api.get_repo_owner(repo_id)

        try:
            dirs = seafserv_threaded_rpc.list_dir_with_perm(
                repo_id, parent_dir, dir_id, repo_owner, -1, -1)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return_results = {}
        return_results['repo_name'] = repo.repo_name
        return_results['repo_id'] = repo.repo_id
        return_results['is_system_library'] = True if \
            repo.id == get_system_default_repo_id() else False
        return_results['dirent_list'] = []

        for dirent in dirs:
            dirent_info = get_dirent_info(dirent)
            return_results['dirent_list'].append(dirent_info)

        return Response(return_results)
Beispiel #13
0
    def get(self, request, format=None):
        try:
            repo = seafile_api.get_repo(get_system_default_repo_id())
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        result = {}
        result['name'] = repo.repo_name
        result['id'] = repo.repo_id
        result['description'] = repo.desc

        return Response(result)
Beispiel #14
0
    def get(self, request, format=None):
        try:
            repo = seafile_api.get_repo(get_system_default_repo_id())
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        result = {}
        result['name'] = repo.repo_name
        result['id'] = repo.repo_id
        result['description'] = repo.desc

        return Response(result)
Beispiel #15
0
    def get(self, request, format=None):

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

        try:
            repo = seafile_api.get_repo(get_system_default_repo_id())
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        result = {}
        result['name'] = repo.repo_name
        result['id'] = repo.repo_id
        result['description'] = repo.desc

        return Response(result)
Beispiel #16
0
    def create_default_repo(self, username):

        default_repo_id = seafile_api.create_repo(name=_("My Library"),
                desc=_("My Library"), username=username, passwd=None)

        sys_repo_id = get_system_default_repo_id()
        if not sys_repo_id or not seafile_api.get_repo(sys_repo_id):
            return None

        dirents = seafile_api.list_dir_by_path(sys_repo_id, '/')
        for dirent in dirents:
            obj_name = dirent.obj_name
            seafile_api.copy_file(sys_repo_id, '/', obj_name,
                    default_repo_id, '/', obj_name, username, 0)

        UserOptions.objects.set_default_repo(username, default_repo_id)

        return default_repo_id
Beispiel #17
0
    def delete(self, request, repo_id, format=None):
        """ delete a library

        Permission checking:
        1. only admin can perform this action.
        """
        if get_system_default_repo_id() == repo_id:
            error_msg = _('System library can not be deleted.')
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            seafile_api.remove_repo(repo_id)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'success': True})
Beispiel #18
0
    def create_default_repo(self, username):

        default_repo_id = seafile_api.create_repo(name=_("My Library"),
                                                  desc=_("My Library"),
                                                  username=username)

        sys_repo_id = get_system_default_repo_id()
        if not sys_repo_id or not seafile_api.get_repo(sys_repo_id):
            return None

        dirents = seafile_api.list_dir_by_path(sys_repo_id, '/')
        for dirent in dirents:
            obj_name = dirent.obj_name
            seafile_api.copy_file(sys_repo_id, '/', obj_name, default_repo_id,
                                  '/', obj_name, username, 0)

        UserOptions.objects.set_default_repo(username, default_repo_id)

        return default_repo_id
Beispiel #19
0
    def delete(self, request, repo_id, format=None):
        """ delete a library

        Permission checking:
        1. only admin can perform this action.
        """
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            return Response({'success': True})

        if get_system_default_repo_id() == repo_id:
            error_msg = _('System library can not be deleted.')
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            seafile_api.remove_repo(repo_id)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'success': True})
Beispiel #20
0
    def get(self, request, format=None):
        """ List 'all' libraries (by name/owner/page)

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

        # search libraries (by name/owner)
        repo_name = request.GET.get('name', '')
        owner = request.GET.get('owner', '')
        repos = []
        if repo_name and owner:
            # search by name and owner
            owned_repos = seafile_api.get_owned_repo_list(owner)
            for repo in owned_repos:
                if not repo.name or repo.is_virtual:
                    continue

                if repo_name in repo.name:
                    repo_info = get_repo_info(repo)
                    repos.append(repo_info)

            return Response({"name": repo_name, "owner": owner, "repos": repos})

        elif repo_name:
            # search by name(keyword in name)
            repos_all = seafile_api.get_repo_list(-1, -1)
            for repo in repos_all:
                if not repo.name or repo.is_virtual:
                    continue

                if repo_name in repo.name:
                    repo_info = get_repo_info(repo)
                    repos.append(repo_info)

            return Response({"name": repo_name, "owner": '', "repos": repos})

        elif owner:
            # search by owner
            owned_repos = seafile_api.get_owned_repo_list(owner)
            for repo in owned_repos:
                if repo.is_virtual:
                    continue

                repo_info = get_repo_info(repo)
                repos.append(repo_info)

            return Response({"name": '', "owner": owner, "repos": repos})

        # get libraries by page
        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

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

        repos_all = seafile_api.get_repo_list(start, limit)

        if len(repos_all) > per_page:
            repos_all = repos_all[:per_page]
            has_next_page = True
        else:
            has_next_page = False

        default_repo_id = get_system_default_repo_id()
        repos_all = filter(lambda r: not r.is_virtual, repos_all)
        repos_all = filter(lambda r: r.repo_id != default_repo_id, repos_all)

        return_results = []

        for repo in repos_all:
            repo_info = get_repo_info(repo)
            return_results.append(repo_info)

        page_info = {
            'has_next_page': has_next_page,
            'current_page': current_page
        }

        return Response({"page_info": page_info, "repos": return_results})
Beispiel #21
0
    def get(self, request, format=None):
        """ List 'all' libraries (by name/owner/page)

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

        # search libraries (by name/owner)
        repo_name = request.GET.get('name', '')
        owner = request.GET.get('owner', '')
        repos = []
        if repo_name and owner:
            # search by name and owner
            owned_repos = seafile_api.get_owned_repo_list(owner)
            for repo in owned_repos:
                if not repo.name or repo.is_virtual:
                    continue

                if repo_name in repo.name:
                    repo_info = get_repo_info(repo)
                    repos.append(repo_info)

            return Response({"name": repo_name, "owner": owner, "repos": repos})

        elif repo_name:
            # search by name(keyword in name)
            repos_all = seafile_api.get_repo_list(-1, -1)
            for repo in repos_all:
                if not repo.name or repo.is_virtual:
                    continue

                if repo_name in repo.name:
                    repo_info = get_repo_info(repo)
                    repos.append(repo_info)

            return Response({"name": repo_name, "owner": '', "repos": repos})

        elif owner:
            # search by owner
            owned_repos = seafile_api.get_owned_repo_list(owner)
            for repo in owned_repos:
                if repo.is_virtual:
                    continue

                repo_info = get_repo_info(repo)
                repos.append(repo_info)

            return Response({"name": '', "owner": owner, "repos": repos})

        # get libraries by page
        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

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

        repos_all = seafile_api.get_repo_list(start, limit)

        if len(repos_all) > per_page:
            repos_all = repos_all[:per_page]
            has_next_page = True
        else:
            has_next_page = False

        default_repo_id = get_system_default_repo_id()
        repos_all = [r for r in repos_all if not r.is_virtual]
        repos_all = [r for r in repos_all if r.repo_id != default_repo_id]

        return_results = []

        for repo in repos_all:
            repo_info = get_repo_info(repo)
            return_results.append(repo_info)

        page_info = {
            'has_next_page': has_next_page,
            'current_page': current_page
        }

        return Response({"page_info": page_info, "repos": return_results})
Beispiel #22
0
def repo_remove(request, repo_id):
    if not request.is_ajax():
        raise Http404

    content_type = 'application/json; charset=utf-8'
    result = {}

    if get_system_default_repo_id() == repo_id:
        result['error'] = _(u'System library can not be deleted.')
        return HttpResponse(json.dumps(result),
                            status=403,
                            content_type=content_type)

    repo = get_repo(repo_id)
    if not repo:
        result['error'] = _(u'Library does not exist')
        return HttpResponse(json.dumps(result),
                            status=400,
                            content_type=content_type)

    user = request.user.username
    org, base_template = check_and_get_org_by_repo(repo_id, user)
    if org:
        # Remove repo in org context, only repo owner or org staff can
        # perform this operation.
        if request.user.is_staff or org.is_staff or \
                is_org_repo_owner(org.org_id, repo_id, user):
            # Must get related useres before remove the repo
            usernames = get_related_users_by_org_repo(org.org_id, repo_id)
            seafile_api.remove_repo(repo_id)
            repo_deleted.send(
                sender=None,
                org_id=org.org_id,
                usernames=usernames,
                repo_owner=user,
                repo_id=repo_id,
                repo_name=repo.name,
            )
            result['success'] = True
            return HttpResponse(json.dumps(result), content_type=content_type)
        else:
            result['error'] = _(u'Permission denied.')
            return HttpResponse(json.dumps(result),
                                status=400,
                                content_type=content_type)
    else:
        # Remove repo in personal context, only repo owner or site staff can
        # perform this operation.
        if validate_owner(request, repo_id) or request.user.is_staff:
            usernames = get_related_users_by_repo(repo_id)
            seafile_api.remove_repo(repo_id)
            repo_deleted.send(
                sender=None,
                org_id=-1,
                usernames=usernames,
                repo_owner=user,
                repo_id=repo_id,
                repo_name=repo.name,
            )
            result['success'] = True
            return HttpResponse(json.dumps(result), content_type=content_type)
        else:
            result['error'] = _(u'Permission denied.')
            return HttpResponse(json.dumps(result),
                                status=400,
                                content_type=content_type)
Beispiel #23
0
    def get(self, request, format=None):
        """ List 'all' libraries (by name/owner/page)

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

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

        order_by = request.GET.get('order_by', '').lower().strip()
        if order_by and order_by not in ('size', 'file_count'):
            error_msg = 'order_by invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # search libraries (by name/owner)
        repo_name = request.GET.get('name', '')
        owner = request.GET.get('owner', '')
        repos = []
        if repo_name and owner:
            # search by name and owner
            orgs = ccnet_api.get_orgs_by_user(owner)
            if orgs:
                org_id = orgs[0].org_id
                owned_repos = seafile_api.get_org_owned_repo_list(
                    org_id, owner)
            else:
                owned_repos = seafile_api.get_owned_repo_list(owner)

            for repo in owned_repos:
                if not repo.name or repo.is_virtual:
                    continue

                if repo_name in repo.name:
                    repo_info = get_repo_info(repo)
                    repos.append(repo_info)

            return Response({
                "name": repo_name,
                "owner": owner,
                "repos": repos
            })

        elif repo_name:
            # search by name(keyword in name)
            repos_all = seafile_api.get_repo_list(-1, -1)
            for repo in repos_all:
                if not repo.name or repo.is_virtual:
                    continue

                if repo_name in repo.name:
                    repo_info = get_repo_info(repo)
                    repos.append(repo_info)

            return Response({"name": repo_name, "owner": '', "repos": repos})

        elif owner:
            # search by owner
            orgs = ccnet_api.get_orgs_by_user(owner)
            if orgs:
                org_id = orgs[0].org_id
                owned_repos = seafile_api.get_org_owned_repo_list(
                    org_id, owner)
            else:
                owned_repos = seafile_api.get_owned_repo_list(owner)

            for repo in owned_repos:
                if repo.is_virtual:
                    continue

                repo_info = get_repo_info(repo)
                repos.append(repo_info)

            return Response({"name": '', "owner": owner, "repos": repos})

        # get libraries by page
        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

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

        if order_by:
            repos_all = seafile_api.get_repo_list(start, limit, order_by)
        else:
            repos_all = seafile_api.get_repo_list(start, limit)

        if len(repos_all) > per_page:
            repos_all = repos_all[:per_page]
            has_next_page = True
        else:
            has_next_page = False

        default_repo_id = get_system_default_repo_id()
        repos_all = [r for r in repos_all if not r.is_virtual]
        repos_all = [r for r in repos_all if r.repo_id != default_repo_id]

        return_results = []

        for repo in repos_all:
            repo_info = get_repo_info(repo)
            return_results.append(repo_info)

        page_info = {
            'has_next_page': has_next_page,
            'current_page': current_page
        }

        return Response({"page_info": page_info, "repos": return_results})
Beispiel #24
0
    def get(self, request, format=None):
        """ Search library by name.

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

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

        query_str = request.GET.get('query', '').lower().strip()
        if not query_str:
            error_msg = 'query invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        repos = seafile_api.search_repos_by_name(query_str)

        default_repo_id = get_system_default_repo_id()
        repos = [r for r in repos if not r.is_virtual]
        repos = [r for r in repos if r.repo_id != default_repo_id]

        email_dict = {}
        name_dict = {}
        contact_email_dict = {}
        for repo in repos:

            # get owner email
            repo_id = repo.repo_id
            repo_owner = seafile_api.get_repo_owner(repo_id)
            if not repo_owner:
                try:
                    org_repo_owner = seafile_api.get_org_repo_owner(repo_id)
                except Exception:
                    org_repo_owner = ''

            owner_email = repo_owner or org_repo_owner or ''
            if repo_id not in email_dict:
                email_dict[repo_id] = owner_email

            # get owner name
            if repo_id not in name_dict:

                # is department library
                if '@seafile_group' in owner_email:
                    group_id = get_group_id_by_repo_owner(owner_email)
                    owner_name = group_id_to_name(group_id)
                else:
                    owner_name = email2nickname(owner_email)

                name_dict[repo_id] = owner_name

            # get owner contact_email
            if repo_id not in contact_email_dict:

                if '@seafile_group' in owner_email:
                    owner_contact_email = ''
                else:
                    owner_contact_email = email2contact_email(owner_email)

                contact_email_dict[repo_id] = owner_contact_email

        result = []
        for repo in repos:

            info = {}
            info['id'] = repo.repo_id
            info['name'] = repo.repo_name

            info['owner_email'] = email_dict.get(repo.repo_id, '')
            info['owner_name'] = name_dict.get(repo.repo_id, '')
            info['owner_contact_email'] = contact_email_dict.get(
                repo.repo_id, '')

            info['size'] = repo.size
            info['encrypted'] = repo.encrypted
            info['file_count'] = repo.file_count
            info['status'] = normalize_repo_status_code(repo.status)

            result.append(info)

        return Response({"repo_list": result})
Beispiel #25
0
    def delete(self, request, repo_id, format=None):
        """ delete a library

        Permission checking:
        1. only admin can perform this action.
        """
        if get_system_default_repo_id() == repo_id:
            error_msg = _('System library can not be deleted.')
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        repo = seafile_api.get_repo(repo_id)
        if not repo:
            # for case of `seafile-data` has been damaged
            # no `repo object` will be returned from seafile api
            # delete the database record anyway
            try:
                seafile_api.remove_repo(repo_id)
            except Exception as e:
                logger.error(e)
                error_msg = 'Internal Server Error'
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

            return Response({'success': True})

        repo_name = repo.name
        repo_owner = seafile_api.get_repo_owner(repo_id)
        if not repo_owner:
            repo_owner = seafile_api.get_org_repo_owner(repo_id)

        try:
            seafile_api.remove_repo(repo_id)

            try:
                org_id = seafile_api.get_org_id_by_repo_id(repo_id)
                related_usernames = get_related_users_by_repo(repo_id,
                        org_id if org_id > 0 else None)
            except Exception as e:
                logger.error(e)
                org_id = -1
                related_usernames = []

            # send signal for seafevents
            repo_deleted.send(sender=None, org_id=-1, operator=request.user.username,
                    usernames=related_usernames, repo_owner=repo_owner,
                    repo_id=repo_id, repo_name=repo.name)

        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        # send admin operation log signal
        admin_op_detail = {
            "id": repo_id,
            "name": repo_name,
            "owner": repo_owner,
        }
        admin_operation.send(sender=None, admin_name=request.user.username,
                operation=REPO_DELETE, detail=admin_op_detail)

        return Response({'success': True})