Ejemplo n.º 1
0
    def put(self, request, repo_id, org_id, format=None):
        """ Update repo group share permission.

        Permission checking:
        1. is group admin
        """

        # parameter check
        to_group_id = request.data.get('group_id', None)
        if not to_group_id:
            error_msg = 'group_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            to_group_id = int(to_group_id)
        except ValueError:
            error_msg = 'group_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        permission = request.data.get('permission', PERMISSION_READ)
        if permission not in [PERMISSION_READ, PERMISSION_READ_WRITE]:
            error_msg = 'permission invalid.'
            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)

        repo_owner = get_repo_owner(request, repo_id)
        group_id = get_group_id_by_repo_owner(repo_owner)
        if not ccnet_api.get_group(group_id):
            error_msg = 'Group %s not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if not ccnet_api.get_group(to_group_id):
            error_msg = 'Group %s not found.' % to_group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

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

        # permission check
        username = request.user.username
        if not is_group_admin(group_id, username):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        update_group_dir_permission(
            repo_id, path, repo_owner, to_group_id, permission, org_id)

        send_perm_audit_msg('modify-repo-perm',
                username, to_group_id, repo_id, path, permission)

        return Response({'success': True})
Ejemplo n.º 2
0
    def put(self, request, repo_id, org_id, format=None):
        """ Update repo group share permission.

        Permission checking:
        1. is group admin
        """

        # parameter check
        to_group_id = request.data.get('group_id', None)
        if not to_group_id:
            error_msg = 'group_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            to_group_id = int(to_group_id)
        except ValueError:
            error_msg = 'group_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        permission = request.data.get('permission', PERMISSION_READ)
        if permission not in [PERMISSION_READ, PERMISSION_READ_WRITE]:
            error_msg = 'permission invalid.'
            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)

        repo_owner = get_repo_owner(request, repo_id)
        group_id = get_group_id_by_repo_owner(repo_owner)
        if not ccnet_api.get_group(group_id):
            error_msg = 'Group %s not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if not ccnet_api.get_group(to_group_id):
            error_msg = 'Group %s not found.' % to_group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

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

        # permission check
        username = request.user.username
        if not is_group_admin(group_id, username):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        update_group_dir_permission(
            repo_id, path, repo_owner, to_group_id, permission, org_id)

        send_perm_audit_msg('modify-repo-perm',
                username, to_group_id, repo_id, path, permission)

        return Response({'success': True})
Ejemplo n.º 3
0
    def format_repo_share_to_group_msg(self, notice):
        d = json.loads(notice.detail)

        repo_id = d['repo_id']
        repo = seafile_api.get_repo(repo_id)
        group_id = d['group_id']
        group = ccnet_api.get_group(group_id)
        org_id = d.get('org_id', None)

        path = d['path']
        if path == '/':
            shared_type = 'library'
        else:
            shared_type = 'folder'
            if org_id:
                owner = seafile_api.get_org_repo_owner(repo_id)
                repo = seafile_api.get_org_virtual_repo(
                    org_id, repo_id, path, owner)
            else:
                owner = seafile_api.get_repo_owner(repo_id)
                repo = seafile_api.get_virtual_repo(repo_id, path, owner)

        notice.repo_url = HASH_URLS["VIEW_COMMON_LIB_DIR"] % {
            'repo_id': repo_id,
            'path': ''
        }
        notice.notice_from = escape(email2nickname(d['share_from']))
        notice.repo_name = repo.name
        notice.avatar_src = self.get_avatar_src(d['share_from'])
        notice.group_url = HASH_URLS['GROUP_INFO'] % {'group_id': group.id}
        notice.group_name = group.group_name
        notice.shared_type = shared_type

        return notice
Ejemplo n.º 4
0
    def list_group_shared_items(self, request, repo_id, path):

        repo_owner = seafile_api.get_repo_owner(repo_id)
        if path == '/':
            share_items = seafile_api.list_repo_shared_group_by_user(repo_owner, repo_id)
        else:
            share_items = seafile_api.get_shared_groups_for_subdir(repo_id,
                    path, repo_owner)

        ret = []
        for item in share_items:

            group_id = item.group_id
            group = ccnet_api.get_group(group_id)

            if not group:
                if path == '/':
                    seafile_api.unset_group_repo(repo_id, group_id,
                            repo_owner)
                else:
                    seafile_api.unshare_subdir_for_group(
                            repo_id, path, repo_owner, group_id)
                continue

            ret.append({
                "group_id": group_id,
                "group_name": group.group_name,
                "permission": item.perm,
            })
        return ret
Ejemplo n.º 5
0
    def format_add_user_to_group(self):
        """

        Arguments:
        - `self`:
        """
        try:
            d = json.loads(self.detail)
        except Exception as e:
            logger.error(e)
            return _(u"Internal error")

        group_staff = d['group_staff']
        group_id = d['group_id']

        group = ccnet_api.get_group(group_id)
        if group is None:
            self.delete()
            return None

        msg = _(
            u"User <a href='%(user_profile)s'>%(group_staff)s</a> has added you to group <a href='%(href)s'>%(group_name)s</a>"
        ) % {
            'user_profile': reverse('user_profile', args=[group_staff]),
            'group_staff': group_staff,
            'href': reverse('group_info', args=[group_id]),
            'group_name': escape(group.group_name)
        }
        return msg
Ejemplo n.º 6
0
def get_group_member_info(request, group_id, email, avatar_size=AVATAR_DEFAULT_SIZE):
    p = Profile.objects.get_profile_by_user(email)
    if p:
        login_id = p.login_id if p.login_id else ''
    else:
        login_id = ''

    try:
        avatar_url, is_default, date_uploaded = api_avatar_url(email, avatar_size)
    except Exception as e:
        logger.error(e)
        avatar_url = get_default_avatar_url()

    role = 'Member'
    group = ccnet_api.get_group(int(group_id))
    is_admin = bool(ccnet_api.check_group_staff(int(group_id), email))
    if email == group.creator_name:
        role = 'Owner'
    elif is_admin:
        role = 'Admin'

    member_info = {
        'group_id': group_id,
        "name": email2nickname(email),
        'email': email,
        "contact_email": Profile.objects.get_contact_email_by_user(email),
        "login_id": login_id,
        "avatar_url": request.build_absolute_uri(avatar_url),
        "is_admin": is_admin,
        "role": role,
    }

    return member_info
Ejemplo n.º 7
0
    def delete(self, request, group_id):
        """ Dismiss a specific group
        """

        group_id = int(group_id)
        group = ccnet_api.get_group(group_id)
        if not group:
            return Response({'success': True})

        group_owner = group.creator_name
        group_name = group.group_name

        try:
            ccnet_api.remove_group(group_id)
            seafile_api.remove_group_repos(group_id)
        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": group_id,
            "name": group_name,
            "owner": group_owner,
        }
        admin_operation.send(sender=None, admin_name=request.user.username,
                operation=GROUP_DELETE, detail=admin_op_detail)

        return Response({'success': True})
Ejemplo n.º 8
0
    def format_group_message_title(self):
        """

        Arguments:
        - `self`:
        """
        try:
            d = self.group_message_detail_to_dict()
        except self.InvalidDetailError as e:
            logger.error(e)
            return _(u"Internal error")

        group_id = d.get('group_id')
        group = ccnet_api.get_group(group_id)
        if group is None:
            self.delete()
            return None

        msg_from = d.get('msg_from')

        if msg_from is None:
            msg = _(u"<a href='%(href)s'>%(group_name)s</a> has a new discussion.") % {
                'href': HASH_URLS['GROUP_DISCUSS'] % {'group_id': group.id},
                'group_name': group.group_name}
        else:
            msg = _(u"%(user)s posted a new discussion in <a href='%(href)s'>%(group_name)s</a>.") % {
                'href': HASH_URLS['GROUP_DISCUSS'] % {'group_id': group.id},
                'user': escape(email2nickname(msg_from)),
                'group_name': escape(group.group_name)
            }
        return msg
Ejemplo n.º 9
0
    def delete(self, request, group_id):
        """ Dismiss a specific group
        """

        group_id = int(group_id)
        group = ccnet_api.get_group(group_id)
        if not group:
            return Response({'success': True})

        group_owner = group.creator_name
        group_name = group.group_name

        try:
            ccnet_api.remove_group(group_id)
            seafile_api.remove_group_repos(group_id)
        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": group_id,
            "name": group_name,
            "owner": group_owner,
        }
        admin_operation.send(sender=None, admin_name=request.user.username,
                operation=GROUP_DELETE, detail=admin_op_detail)

        return Response({'success': True})
Ejemplo n.º 10
0
    def format_group_join_request(self):
        """

        Arguments:
        - `self`:
        """
        try:
            d = json.loads(self.detail)
        except Exception as e:
            logger.error(e)
            return _(u"Internal error")

        username = d['username']
        group_id = d['group_id']
        join_request_msg = d['join_request_msg']

        group = ccnet_api.get_group(group_id)
        if group is None:
            self.delete()
            return None

        msg = _(u"User <a href='%(user_profile)s'>%(username)s</a> has asked to join group <a href='%(href)s'>%(group_name)s</a>, verification message: %(join_request_msg)s") % {
            'user_profile': reverse('user_profile', args=[username]),
            'username': username,
            'href': HASH_URLS['GROUP_MEMBERS'] % {'group_id': group_id},
            'group_name': escape(group.group_name),
            'join_request_msg': escape(join_request_msg),
            }
        return msg
Ejemplo n.º 11
0
def get_group_info(request, group_id, avatar_size=GROUP_AVATAR_DEFAULT_SIZE):
    group = ccnet_api.get_group(group_id)
    try:
        avatar_url, is_default, date_uploaded = api_grp_avatar_url(group.id, avatar_size)
    except Exception as e:
        logger.error(e)
        avatar_url = get_default_group_avatar_url()

    isoformat_timestr = timestamp_to_isoformat_timestr(group.timestamp)
    group_info = {
        "id": group.id,
        "parent_group_id": group.parent_group_id,
        "name": group.group_name,
        "owner": group.creator_name,
        "created_at": isoformat_timestr,
        "avatar_url": request.build_absolute_uri(avatar_url),
        "admins": get_group_admins(group.id),
    }
    # parent_group_id = 0: non department group
    # parent_group_id = -1: top department group
    # parent_group_id = n(n > 0):  sub department group, n is parent group's id
    if group.parent_group_id != 0:
        group_info['group_quota'] = seafile_api.get_group_quota(group_id)

    group_info['group_quota_usage'] = ''
    if is_pro_version():
        if is_org_context(request):
            org_id = request.user.org.org_id
            group_info['group_quota_usage'] = seafile_api.org_get_group_quota_usage(org_id, group_id)
        else:
            group_info['group_quota_usage'] = seafile_api.get_group_quota_usage(group_id)

    return group_info
Ejemplo n.º 12
0
    def _get_address_book_group_memeber_info(self, request, group_member_obj, avatar_size):

        email = group_member_obj.user_name
        try:
            avatar_url, is_default, date_uploaded = api_avatar_url(email, avatar_size)
        except Exception as e:
            logger.error(e)
            avatar_url = get_default_avatar_url()

        group_id = group_member_obj.group_id
        group = ccnet_api.get_group(group_member_obj.group_id)

        role = 'Member'
        is_admin = bool(group_member_obj.is_staff)
        if email == group.creator_name:
            role = 'Owner'
        elif is_admin:
            role = 'Admin'

        member_info = {
            'group_id': group_id,
            'group_name': group.group_name,
            'email': email,
            "name": email2nickname(email),
            "contact_email": email2contact_email(email),
            "avatar_url": request.build_absolute_uri(avatar_url),
            "is_admin": is_admin,
            "role": role,
        }

        return member_info
Ejemplo n.º 13
0
    def format_add_user_to_group(self):
        """

        Arguments:
        - `self`:
        """
        try:
            d = json.loads(self.detail)
        except Exception as e:
            logger.error(e)
            return _(u"Internal error")

        group_staff = d['group_staff']
        group_id = d['group_id']

        group = ccnet_api.get_group(group_id)
        if group is None:
            self.delete()
            return None

        msg = _(u"User <a href='%(user_profile)s'>%(group_staff)s</a> has added you to group <a href='%(href)s'>%(group_name)s</a>") % {
            'user_profile': reverse('user_profile', args=[group_staff]),
            'group_staff': escape(email2nickname(group_staff)),
            'href': reverse('group', args=[group_id]),
            'group_name': escape(group.group_name)}
        return msg
Ejemplo n.º 14
0
    def format_group_join_request(self):
        """

        Arguments:
        - `self`:
        """
        try:
            d = json.loads(self.detail)
        except Exception as e:
            logger.error(e)
            return _(u"Internal error")

        username = d['username']
        group_id = d['group_id']
        join_request_msg = d['join_request_msg']

        group = ccnet_api.get_group(group_id)
        if group is None:
            self.delete()
            return None

        msg = _(
            u"User <a href='%(user_profile)s'>%(username)s</a> has asked to join group <a href='%(href)s'>%(group_name)s</a>, verification message: %(join_request_msg)s"
        ) % {
            'user_profile': reverse('user_profile', args=[username]),
            'username': username,
            'href': reverse('group_members', args=[group_id]),
            'group_name': escape(group.group_name),
            'join_request_msg': escape(join_request_msg),
        }
        return msg
Ejemplo n.º 15
0
def show_members(group_id):
    print("group %s (%d):" %
          (ccnet_api.get_group(group_id).group_name, group_id))
    gusers = ccnet_api.get_group_members(group_id)
    for guser in gusers:
        print("%s" % (guser.user_name))
    print("")
Ejemplo n.º 16
0
    def get(self, request, repo_id):
        """ List repo user share info.

        Permission checking:
        1. is group admin
        """

        # 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)

        repo_owner = get_repo_owner(request, repo_id)
        group_id = get_group_id_by_repo_owner(repo_owner)
        if not ccnet_api.get_group(group_id):
            error_msg = 'Group %s not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

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

        # permission check
        username = request.user.username
        if not is_group_admin(group_id, username):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        result = self.list_user_shared_items(request, repo_id, path)
        return Response(result)
Ejemplo n.º 17
0
def get_group_member_info(request,
                          group_id,
                          email,
                          avatar_size=AVATAR_DEFAULT_SIZE):
    p = Profile.objects.get_profile_by_user(email)
    if p:
        login_id = p.login_id if p.login_id else ''
    else:
        login_id = ''

    avatar_url, is_default, date_uploaded = api_avatar_url(email, avatar_size)

    role = 'Member'
    group = ccnet_api.get_group(int(group_id))
    is_admin = bool(ccnet_api.check_group_staff(int(group_id), email))
    if email == group.creator_name:
        role = 'Owner'
    elif is_admin:
        role = 'Admin'

    member_info = {
        'group_id': group_id,
        "name": email2nickname(email),
        'email': email,
        "contact_email": Profile.objects.get_contact_email_by_user(email),
        "login_id": login_id,
        "avatar_url": avatar_url,
        "is_admin": is_admin,
        "role": role,
    }

    return member_info
Ejemplo n.º 18
0
    def put(self, request, group_id):
        """ Admin transfer a group

        Permission checking:
        1. Admin user;
        """

        # argument check
        new_owner = request.data.get('new_owner', None)
        if not new_owner or not is_valid_username(new_owner):
            error_msg = 'new_owner %s invalid.' % new_owner
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # recourse check
        group_id = int(group_id) # Checked by URL Conf
        group = ccnet_api.get_group(group_id)
        if not group:
            error_msg = 'Group %d not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # check if new_owner exists,
        # NOT need to check old_owner for old_owner may has been deleted.
        try:
            User.objects.get(email=new_owner)
        except User.DoesNotExist:
            error_msg = 'User %s not found.' % new_owner
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        old_owner = group.creator_name
        if new_owner == old_owner:
            error_msg = _(u'User %s is already group owner.') % new_owner
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # transfer a group
        try:
            if not is_group_member(group_id, new_owner):
                ccnet_api.group_add_member(group_id, old_owner, new_owner)

            if not is_group_admin(group_id, new_owner):
                ccnet_api.group_set_admin(group_id, new_owner)

            ccnet_api.set_group_creator(group_id, new_owner)
            ccnet_api.group_unset_admin(group_id, old_owner)
        except SearpcError 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": group_id,
            "name": group.group_name,
            "from": old_owner,
            "to": new_owner,
        }
        admin_operation.send(sender=None, admin_name=request.user.username,
                operation=GROUP_TRANSFER, detail=admin_op_detail)

        group_info = get_group_info(group_id)
        return Response(group_info)
Ejemplo n.º 19
0
    def format_repo_share_to_group_msg(self, notice):
        d = json.loads(notice.detail)

        repo_id = d['repo_id']
        repo = seafile_api.get_repo(repo_id)
        group_id = d['group_id']
        group = ccnet_api.get_group(group_id)
        org_id = d.get('org_id', None)

        path = d['path']
        if path == '/':
            shared_type = 'library'
        else:
            shared_type = 'folder'
            if org_id:
                owner = seafile_api.get_org_repo_owner(repo_id)
                repo = seafile_api.get_org_virtual_repo(
                    org_id, repo_id, path, owner)
            else:
                owner = seafile_api.get_repo_owner(repo_id)
                repo = seafile_api.get_virtual_repo(repo_id, path, owner)

        repo_url = reverse('lib_view', args=[repo_id, repo.name, ''])
        notice.repo_url = repo_url
        notice.notice_from = escape(email2nickname(d['share_from']))
        notice.repo_name = repo.name
        notice.avatar_src = self.get_avatar_src(d['share_from'])
        notice.group_url = reverse('group', args=[group.id])
        notice.group_name = group.group_name
        notice.shared_type = shared_type

        return notice
Ejemplo n.º 20
0
def get_group_info(group_id, show_size=False):
    group = ccnet_api.get_group(group_id)
    isoformat_timestr = timestamp_to_isoformat_timestr(group.timestamp)
    group_info = {
        "id": group.id,
        "name": group.group_name,
        "owner": group.creator_name,
        "owner_name": email2nickname(group.creator_name),
        "created_at": isoformat_timestr,
        "quota":
        seafile_api.get_group_quota(group_id) if is_pro_version() else 0,
        "parent_group_id": group.parent_group_id if is_pro_version() else 0
    }
    if ccnet_api.is_org_group(group_id):
        org_id = ccnet_api.get_org_id_by_group(group_id)
        group_info['org_id'] = org_id
        if org_id:
            org = ccnet_api.get_org_by_id(org_id)
            if org:
                group_info['org_name'] = org.org_name

    if show_size:
        owner = '%s@seafile_group' % group_id
        workspace = Workspaces.objects.get_workspace_by_owner(owner)
        if workspace:
            repo = seafile_api.get_repo(workspace.repo_id)
            group_info['size'] = repo.size

    return group_info
Ejemplo n.º 21
0
    def get(self, request, format=None):
        """ List all shared out folders.

        Permission checking:
        1. all authenticated user can perform this action.
        """

        shared_repos = []
        username = request.user.username

        try:
            if is_org_context(request):
                org_id = request.user.org.org_id
                shared_repos += seafile_api.get_org_share_out_repo_list(org_id, username, -1, -1)
                shared_repos += seaserv.seafserv_threaded_rpc.get_org_group_repos_by_owner(org_id, username)
            else:
                shared_repos += seafile_api.get_share_out_repo_list(username, -1, -1)
                shared_repos += seafile_api.get_group_repos_by_owner(username)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        returned_result = []
        shared_repos.sort(lambda x, y: cmp(x.repo_name, y.repo_name))
        for repo in shared_repos:
            if not repo.is_virtual:
                    continue

            result = {}
            result['repo_id'] = repo.origin_repo_id
            result['repo_name'] = repo.origin_repo_name
            result['path'] = repo.origin_path
            result['folder_name'] = repo.name
            result['share_type'] = repo.share_type
            result['share_permission'] = repo.permission

            if repo.share_type == 'personal':
                result['user_name'] = email2nickname(repo.user)
                result['user_email'] = repo.user
                result['contact_email'] = Profile.objects.get_contact_email_by_user(repo.user)

            if repo.share_type == 'group':
                group = ccnet_api.get_group(repo.group_id)

                if not group:
                    if is_org_context(request):
                        seafile_api.org_unshare_subdir_for_group(org_id,
                                repo.repo_id, repo.origin_path, username, repo.group_id)
                    else:
                        seafile_api.unshare_subdir_for_group(
                                repo.repo_id, repo.origin_path, username, repo.group_id)
                    continue

                result['group_id'] = repo.group_id
                result['group_name'] = group.group_name

            returned_result.append(result)

        return Response(returned_result)
Ejemplo n.º 22
0
    def get(self, request, repo_id):
        """ List repo user share info.

        Permission checking:
        1. is group admin
        """

        # 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)

        repo_owner = get_repo_owner(request, repo_id)
        group_id = get_group_id_by_repo_owner(repo_owner)
        if not ccnet_api.get_group(group_id):
            error_msg = 'Group %s not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

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

        # permission check
        username = request.user.username
        if not is_group_admin(group_id, username):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        result = self.list_user_shared_items(request, repo_id, path)
        return Response(result)
Ejemplo n.º 23
0
    def format_group_message_title(self):
        """

        Arguments:
        - `self`:
        """
        try:
            d = self.group_message_detail_to_dict()
        except self.InvalidDetailError as e:
            logger.error(e)
            return _(u"Internal error")

        group_id = d.get('group_id')
        group = ccnet_api.get_group(group_id)
        if group is None:
            self.delete()
            return None

        msg_from = d.get('msg_from')

        if msg_from is None:
            msg = _(u"<a href='%(href)s'>%(group_name)s</a> has a new discussion.") % {
                'href': reverse('group_discuss', args=[group.id]),
                'group_name': group.group_name}
        else:
            msg = _(u"%(user)s posted a new discussion in <a href='%(href)s'>%(group_name)s</a>.") % {
                'href': reverse('group_discuss', args=[group.id]),
                'user': escape(email2nickname(msg_from)),
                'group_name': escape(group.group_name)
            }
        return msg
Ejemplo n.º 24
0
    def format_repo_share_to_group_msg(self, notice):
        d = json.loads(notice.detail)

        repo_id = d['repo_id']
        repo = seafile_api.get_repo(repo_id)
        group_id = d['group_id']
        group = ccnet_api.get_group(group_id)
        org_id = d.get('org_id', None)

        path = d['path']
        if path == '/':
            shared_type = 'library'
        else:
            shared_type = 'folder'
            if org_id:
                owner = seafile_api.get_org_repo_owner(repo_id)
                repo = seafile_api.get_org_virtual_repo(
                    org_id, repo_id, path, owner)
            else:
                owner = seafile_api.get_repo_owner(repo_id)
                repo = seafile_api.get_virtual_repo(repo_id, path, owner)

        repo_url = reverse('lib_view', args=[repo.id, repo.name, ''])
        notice.repo_url = repo_url
        notice.notice_from = escape(email2nickname(d['share_from']))
        notice.repo_name = repo.name
        notice.avatar_src = self.get_avatar_src(d['share_from'])
        notice.group_url = reverse('group', args=[group.id])
        notice.group_name = group.group_name
        notice.shared_type = shared_type

        return notice
Ejemplo n.º 25
0
    def get(self, request, org_id, group_id):
        """get org group info
        """
        # resource check
        org_id = int(org_id)
        if not ccnet_api.get_org_by_id(org_id):
            error_msg = 'Organization %s not found.' % org_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        group_id = int(group_id)
        if get_org_id_by_group(group_id) != org_id:
            error_msg = 'Group %s not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # main
        group = ccnet_api.get_group(group_id)

        group_info = {
            "id": group.id,
            "group_name": group.group_name,
            "ctime": timestamp_to_isoformat_timestr(group.timestamp),
            "creator_email": group.creator_name,
            "creator_name": email2nickname(group.creator_name),
            'creator_contact_email': email2contact_email(group.creator_name),
        }

        return Response(group_info)
Ejemplo n.º 26
0
    def delete(self, request, group_id, repo_id, format=None):
        """ Unshare repo from group

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

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

        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)

        group_id = int(group_id)
        group = ccnet_api.get_group(group_id)
        if not group:
            error_msg = 'Group %d not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        try:
            if is_org_context(request):
                org_id = request.user.org.org_id
                seaserv.del_org_group_repo(repo_id, org_id, group_id)
            else:
                repo_owner = seafile_api.get_repo_owner(repo_id)
                seafile_api.unset_group_repo(repo_id, group_id, repo_owner)
        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})
Ejemplo n.º 27
0
    def get(self, request, group_id, format=None):
        """ List all group repos

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

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

        group_id = int(group_id)
        group = ccnet_api.get_group(group_id)
        if not group:
            error_msg = 'Group %d not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if is_org_context(request):
            org_id = request.user.org.org_id
            repos = seafile_api.get_org_group_repos(org_id, group_id)
        else:
            repos = seafile_api.get_repos_by_group(group_id)

        group_repos_info = []
        for repo in repos:
            repo_info = get_group_repo_info(repo)
            group_repos_info.append(repo_info)

        group_libraries = {
            'group_id': group_id,
            'group_name': group.group_name,
            'libraries': group_repos_info
        }

        return Response(group_libraries)
Ejemplo n.º 28
0
    def _get_address_book_group_memeber_info(self, request, group_member_obj,
                                             avatar_size):

        email = group_member_obj.user_name
        try:
            avatar_url, is_default, date_uploaded = api_avatar_url(
                email, avatar_size)
        except Exception as e:
            logger.error(e)
            avatar_url = get_default_avatar_url()

        group_id = group_member_obj.group_id
        group = ccnet_api.get_group(group_member_obj.group_id)

        role = 'Member'
        is_admin = bool(group_member_obj.is_staff)
        if email == group.creator_name:
            role = 'Owner'
        elif is_admin:
            role = 'Admin'

        member_info = {
            'group_id': group_id,
            'group_name': group.group_name,
            'email': email,
            "name": email2nickname(email),
            "contact_email": email2contact_email(email),
            "avatar_url": request.build_absolute_uri(avatar_url),
            "is_admin": is_admin,
            "role": role,
        }

        return member_info
Ejemplo n.º 29
0
    def format_repo_share_to_group_msg(self):
        """

        Arguments:
        - `self`:
        """
        try:
            d = json.loads(self.detail)
        except Exception as e:
            logger.error(e)
            return _(u"Internal error")

        share_from = email2nickname(d['share_from'])
        repo_id = d['repo_id']
        group_id = d['group_id']
        path = d.get('path', '/')
        org_id = d.get('org_id', None)

        repo = None
        try:
            group = ccnet_api.get_group(group_id)
            if path == '/':
                repo = seafile_api.get_repo(repo_id)
            else:
                if org_id:
                    owner = seafile_api.get_org_repo_owner(repo_id)
                    repo = seafile_api.get_org_virtual_repo(
                        org_id, repo_id, path, owner)
                else:
                    owner = seafile_api.get_repo_owner(repo_id)
                    repo = seafile_api.get_virtual_repo(repo_id, path, owner)
        except Exception as e:
            logger.error(e)
            return None

        if not repo or not group:
            self.delete()
            return None

        if path == '/':
            tmpl = 'notifications/notice_msg/repo_share_to_group_msg.html'
        else:
            tmpl = 'notifications/notice_msg/folder_share_to_group_msg.html'

        msg = render_to_string(
            tmpl, {
                'user': share_from,
                'lib_url': HASH_URLS["VIEW_COMMON_LIB_DIR"] % {
                    'repo_id': repo.id,
                    'path': ''
                },
                'lib_name': repo.name,
                'group_url': HASH_URLS['GROUP_INFO'] % {
                    'group_id': group.id
                },
                'group_name': group.group_name,
            })

        return msg
Ejemplo n.º 30
0
    def delete(self, request, group_id):
        """ Delete an address book group.
        """
        group_id = int(group_id)
        group = ccnet_api.get_group(group_id)
        if not group:
            return Response({'success': True})

        org_id = None
        if is_org_context(request):
            # request called by org admin
            org_id = request.user.org.org_id

        try:
            if org_id:
                has_repo = seafile_api.org_if_group_has_group_owned_repo(
                    org_id, group_id)
            else:
                has_repo = seafile_api.if_group_has_group_owned_repo(group_id)

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

        if has_repo:
            error_msg = _('There are libraries in this department.')
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if len(child_groups) > 0:
            error_msg = _('There are sub-departments in this department.')
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

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

        if ret_code == -1:
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        # send admin operation log signal
        group_owner = group.creator_name
        group_name = group.group_name
        admin_op_detail = {
            "id": group_id,
            "name": group_name,
            "owner": group_owner,
        }
        admin_operation.send(sender=None,
                             admin_name=request.user.username,
                             operation=GROUP_DELETE,
                             detail=admin_op_detail)

        return Response({'success': True})
Ejemplo n.º 31
0
    def test_can_clean_department_repo_trash(self):
        if not LOCAL_PRO_DEV_ENV:
            return

        # create a department
        group_id = ccnet_api.create_group('department_test',
                                          'system admin',
                                          parent_group_id=-1)
        seafile_api.set_group_quota(group_id, -2)
        repo_id = seafile_api.add_group_owned_repo(group_id, 'dep_test', 'rw')
        repo_owner = seafile_api.get_repo_owner(repo_id)
        assert '@seafile_group' in repo_owner
        group_repos = seafile_api.get_repos_by_group(group_id)
        assert len(group_repos) == 1
        group = ccnet_api.get_group(group_id)

        # department add user
        ccnet_api.group_add_member(group_id, group.creator_name,
                                   self.user_name)
        ccnet_api.group_add_member(group_id, group.creator_name,
                                   self.tmp_user.username)
        ccnet_api.group_set_admin(group_id, self.user_name)
        ccnet_api.group_unset_admin(group_id, self.tmp_user.username)
        assert is_group_admin(group_id, self.user_name)
        assert not is_group_admin(group_id, self.tmp_user.username)

        file_name = 'dep_test.txt'
        self.create_file(repo_id=repo_id,
                         parent_dir='/',
                         filename=file_name,
                         username=self.user_name)

        # delete a file first
        seafile_api.del_file(repo_id, '/', file_name, self.user_name)

        # get trash item count
        self.login_as(self.user)
        resp = self.client.get(reverse('api-v2.1-repo-trash', args=[repo_id]))
        json_resp = json.loads(resp.content)
        assert len(json_resp['data']) > 0

        # department member can not clean trash
        self.logout()
        self.login_as(self.tmp_user)
        resp = self.client.delete(self.url)
        self.assertEqual(403, resp.status_code)

        # department admin can clean library trash
        self.logout()
        self.login_as(self.user)
        ccnet_api.group_set_admin(group_id, self.user_name)
        resp = self.client.delete(self.url)
        self.assertEqual(200, resp.status_code)

        # get trash item count again
        resp = self.client.get(self.url)
        json_resp = json.loads(resp.content)
        assert len(json_resp['data']) == 0
Ejemplo n.º 32
0
    def post(self, request, group_id):
        """
        Bulk add group members.

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

        # argument check
        group_id = int(group_id)
        group = ccnet_api.get_group(group_id)
        if not group:
            error_msg = 'Group %d not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        emails = request.POST.getlist('email', '')
        if not emails:
            error_msg = 'Email invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        result = {}
        result['failed'] = []
        result['success'] = []
        emails_need_add = []

        for email in emails:
            try:
                User.objects.get(email=email)
            except User.DoesNotExist:
                result['failed'].append({
                    'email': email,
                    'error_msg': 'User %s not found.' % email
                    })
                continue

            if ccnet_api.is_group_user(group_id, email):
                result['failed'].append({
                    'email': email,
                    'error_msg': 'User %s is already a group member.' % email
                    })
                continue

            emails_need_add.append(email)

        # Add user to group.
        for email in emails_need_add:
            try:
                ccnet_api.group_add_member(group_id, group.creator_name, email)
                member_info = get_group_member_info(request, group_id, email)
                result['success'].append(member_info)
            except Exception as e:
                logger.error(e)
                result['failed'].append({
                    'email': email,
                    'error_msg': 'Internal Server Error'
                    })

        return Response(result)
Ejemplo n.º 33
0
def sys_log_perm_audit(request):
    """
    """
    if not EVENTS_ENABLED:
        raise Http404

    # Make sure page request is an int. If not, deliver first 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

    user_selected = request.GET.get('email', None)
    repo_selected = request.GET.get('repo_id', None)

    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_selected, start,
                                   limit)

    if events:
        for ev in events:
            if ev.to.isdigit():
                group = ccnet_api.get_group(int(ev.to))
                ev.perm_group_name = group.group_name if group else None

            ev.repo = seafile_api.get_repo(ev.repo_id)
            ev.folder_name = os.path.basename(ev.file_path)
            ev.time = utc_to_local(ev.timestamp)

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

    else:
        page_next = False

    extra_href = ''
    if user_selected:
        extra_href += "&email=%s" % user_selected

    if repo_selected:
        extra_href += "&repo_id=%s" % repo_selected

    return render(
        request, 'sys_perm_audit.html', {
            'events': events,
            'user_selected': user_selected,
            'repo_selected': repo_selected,
            'extra_href': extra_href,
            'current_page': current_page,
            'prev_page': current_page - 1,
            'next_page': current_page + 1,
            'per_page': per_page,
            'page_next': page_next,
        })
Ejemplo n.º 34
0
    def list_group_shared_items(self, request, repo_id, path):
        if is_org_context(request):
            # when calling seafile API to share authority related functions, change the uesrname to repo owner.
            repo_owner = seafile_api.get_org_repo_owner(repo_id)
            org_id = request.user.org.org_id
            if path == '/':
                share_items = seafile_api.list_org_repo_shared_group(
                    org_id, repo_owner, repo_id)
            else:
                share_items = seafile_api.get_org_shared_groups_for_subdir(
                    org_id, repo_id, path, repo_owner)
        else:
            repo_owner = seafile_api.get_repo_owner(repo_id)
            if path == '/':
                share_items = seafile_api.list_repo_shared_group_by_user(
                    repo_owner, repo_id)
            else:
                share_items = seafile_api.get_shared_groups_for_subdir(
                    repo_id, path, repo_owner)
        ret = []
        # change is_admin to True if user in admin groups.
        admin_groups = ExtraGroupsSharePermission.objects.get_admin_groups_by_repo(
            repo_id)
        for item in share_items:

            if '@seafile_group' in repo_owner and \
                    repo_owner.split('@')[0] == str(item.group_id):
                continue

            group_id = item.group_id
            group = ccnet_api.get_group(group_id)
            if not group:
                if is_org_context(request):
                    if path == '/':
                        seafile_api.del_org_group_repo(repo_id, org_id,
                                                       group_id)
                    else:
                        seafile_api.org_unshare_subdir_for_group(
                            org_id, repo_id, path, repo_owner, group_id)
                else:
                    if path == '/':
                        seafile_api.unset_group_repo(repo_id, group_id,
                                                     repo_owner)
                    else:
                        seafile_api.unshare_subdir_for_group(
                            repo_id, path, repo_owner, group_id)
                continue

            ret.append({
                "share_type": "group",
                "group_info": {
                    "id": group_id,
                    "name": group.group_name,
                },
                "permission": item.perm,
                "is_admin": group_id in admin_groups,
            })
        return ret
Ejemplo n.º 35
0
    def post(self, request, group_id):
        """
        Bulk add group members.

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

        # argument check
        group_id = int(group_id)
        group = ccnet_api.get_group(group_id)
        if not group:
            error_msg = 'Group %d not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        emails = request.POST.getlist('email', '')
        if not emails:
            error_msg = 'Email invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        result = {}
        result['failed'] = []
        result['success'] = []
        emails_need_add = []

        for email in emails:
            try:
                User.objects.get(email=email)
            except User.DoesNotExist:
                result['failed'].append({
                    'email': email,
                    'error_msg': 'User %s not found.' % email
                    })
                continue

            if is_group_member(group_id, email, in_structure=False):
                result['failed'].append({
                    'email': email,
                    'error_msg': 'User %s is already a group member.' % email2nickname(email)
                    })
                continue

            emails_need_add.append(email)

        # Add user to group.
        for email in emails_need_add:
            try:
                ccnet_api.group_add_member(group_id, group.creator_name, email)
                member_info = get_group_member_info(request, group_id, email)
                result['success'].append(member_info)
            except Exception as e:
                logger.error(e)
                result['failed'].append({
                    'email': email,
                    'error_msg': 'Internal Server Error'
                    })

        return Response(result)
Ejemplo n.º 36
0
    def delete(self, request, group_id):
        """ Delete an address book group.
        """
        group_id = int(group_id)
        group = ccnet_api.get_group(group_id)
        if not group:
            return Response({'success': True})

        try:
            has_repo = seafile_api.if_group_has_group_owned_repo(group_id)
            child_groups = ccnet_api.get_child_groups(group_id)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if has_repo:
            error_msg = _('There are libraries in this department.')
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        if len(child_groups) > 0:
            error_msg = _('There are sub-departments in this department.')
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        owner = '%s@seafile_group' % group_id
        workspace = Workspaces.objects.get_workspace_by_owner(owner)
        if workspace:
            try:
                seafile_api.remove_repo(workspace.repo_id)
                workspace.delete()
            except Exception as e:
                logger.error(e)
                error_msg = _('Internal Server Error')
                return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

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

        if ret_code == -1:
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        # send admin operation log signal
        group_owner = group.creator_name
        group_name = group.group_name
        admin_op_detail = {
            "id": group_id,
            "name": group_name,
            "owner": group_owner,
        }
        admin_operation.send(sender=None, admin_name=request.user.username,
                operation=GROUP_DELETE, detail=admin_op_detail)

        return Response({'success': True})
Ejemplo n.º 37
0
def group():
    group = create_and_get_group('test_group_{}'.format(randstring(10)),
                                 USER,
                                 gtype=None)
    try:
        yield group
    finally:
        if ccnet_api.get_group(group.id):
            ccnet_api.remove_group(group.id)
Ejemplo n.º 38
0
    def format_repo_share_to_group_msg(self):
        """

        Arguments:
        - `self`:
        """
        try:
            d = json.loads(self.detail)
        except Exception as e:
            logger.error(e)
            return _("Internal Server Error")

        share_from = email2nickname(d['share_from'])
        repo_id = d['repo_id']
        group_id = d['group_id']
        path = d.get('path', '/')
        org_id = d.get('org_id', None)

        repo = None
        try:
            group = ccnet_api.get_group(group_id)
            if path == '/':
                repo = seafile_api.get_repo(repo_id)
            else:
                if org_id:
                    owner = seafile_api.get_org_repo_owner(repo_id)
                    repo = seafile_api.get_org_virtual_repo(
                        org_id, repo_id, path, owner)
                else:
                    owner = seafile_api.get_repo_owner(repo_id)
                    repo = seafile_api.get_virtual_repo(repo_id, path, owner)
        except Exception as e:
            logger.error(e)
            return None

        if not repo or not group:
            self.delete()
            return None

        if path == '/':
            tmpl = 'notifications/notice_msg/repo_share_to_group_msg.html'
        else:
            tmpl = 'notifications/notice_msg/folder_share_to_group_msg.html'

        lib_url = reverse('lib_view', args=[repo.id, repo.name, ''])
        group_url = reverse('group', args=[group.id])
        msg = render_to_string(
            tmpl, {
                'user': share_from,
                'lib_url': lib_url,
                'lib_name': repo.name,
                'group_url': group_url,
                'group_name': group.group_name,
            })

        return msg
Ejemplo n.º 39
0
    def get(self, request, group_id):
        """List child groups and members in an address book group."""
        group_id = int(group_id)

        group = ccnet_api.get_group(group_id)
        if not group:
            error_msg = 'Group %d not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        try:
            avatar_size = int(
                request.GET.get('avatar_size', AVATAR_DEFAULT_SIZE))
        except ValueError:
            avatar_size = AVATAR_DEFAULT_SIZE

        try:
            return_ancestors = to_python_boolean(
                request.GET.get('return_ancestors', 'f'))
        except ValueError:
            return_ancestors = False

        ret_dict = address_book_group_to_dict(group)
        ret_groups = []
        ret_members = []

        groups = ccnet_api.get_child_groups(group_id)
        for group in groups:
            ret_groups.append(address_book_group_to_dict(group))

        try:
            members = ccnet_api.get_group_members(group_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 m in members:
            member_info = self._get_address_book_group_memeber_info(
                request, m, avatar_size)
            if member_info['role'] == 'Owner':
                continue
            ret_members.append(member_info)

        ret_dict['groups'] = ret_groups
        ret_dict['members'] = ret_members

        if return_ancestors:
            # get ancestor groups and remove last group which is self
            ancestor_groups = ccnet_api.get_ancestor_groups(group_id)[:-1]
            ret_dict['ancestor_groups'] = [
                address_book_group_to_dict(grp) for grp in ancestor_groups
            ]
        else:
            ret_dict['ancestor_groups'] = []

        return Response(ret_dict)
def show_share_info(user, show_groupmembers=False):
    shared_repos = seafile_api.get_share_out_repo_list(user, -1, -1)
    shared_repos += seafile_api.get_group_repos_by_owner(user)

    shown_repos = set()

    if show_groupmembers:
        groups = {}

    for repo in shared_repos:
        if repo.repo_id in shown_repos:
            continue

        shown_repos.add(repo.repo_id)

        if repo.is_virtual:
            print("Folder %s of Repo %s, shared to:" %
                  (repo.origin_path, repo.origin_repo_id))
        else:
            print("Repo %s (%s), shared to:" % (repo.repo_id, repo.name))
        sgroups = seafile_api.list_repo_shared_group(user, repo.repo_id)
        print("groups:")
        for sgroup in sgroups:
            print("%s (%d), %s" % (ccnet_api.get_group(
                sgroup.group_id).group_name, sgroup.group_id, sgroup.perm))
            if show_groupmembers:
                groups[sgroup.group_id] = sgroup
        susers = seafile_api.list_repo_shared_to(user, repo.repo_id)
        print("users:")
        for suser in susers:
            print("%s, %s" % (suser.user, suser.perm))

        print("\n")

    if show_groupmembers:
        print("\ngroup memberships:")
        for group in groups.values():
            print("group %s (%d):" % (ccnet_api.get_group(
                group.group_id).group_name, group.group_id))
            gusers = ccnet_api.get_group_members(group.group_id)
            for guser in gusers:
                print("%s" % (guser.user_name))
            print("")
Ejemplo n.º 41
0
    def format_repo_share_to_group_msg(self):
        """

        Arguments:
        - `self`:
        """
        try:
            d = json.loads(self.detail)
        except Exception as e:
            logger.error(e)
            return _(u"Internal error")

        share_from = email2nickname(d['share_from'])
        repo_id = d['repo_id']
        group_id = d['group_id']
        path = d.get('path', '/')
        org_id = d.get('org_id', None)

        repo = None
        try:
            group = ccnet_api.get_group(group_id)
            if path == '/':
                repo = seafile_api.get_repo(repo_id)
            else:
                if org_id:
                    owner = seafile_api.get_org_repo_owner(repo_id)
                    repo = seafile_api.get_org_virtual_repo(
                        org_id, repo_id, path, owner)
                else:
                    owner = seafile_api.get_repo_owner(repo_id)
                    repo = seafile_api.get_virtual_repo(repo_id, path, owner)
        except Exception as e:
            logger.error(e)
            return None

        if not repo or not group:
            self.delete()
            return None

        if path == '/':
            tmpl = 'notifications/notice_msg/repo_share_to_group_msg.html'
        else:
            tmpl = 'notifications/notice_msg/folder_share_to_group_msg.html'

        lib_url = reverse('lib_view', args=[repo.id, repo.name, ''])
        group_url = reverse('group', args=[group.id])
        msg = render_to_string(tmpl, {
            'user': share_from,
            'lib_url': lib_url,
            'lib_name': repo.name,
            'group_url': group_url,
            'group_name': group.group_name,
        })

        return msg
Ejemplo n.º 42
0
def get_group_info(group_id):
    group = ccnet_api.get_group(group_id)
    isoformat_timestr = timestamp_to_isoformat_timestr(group.timestamp)
    group_info = {
        "id": group.id,
        "name": group.group_name,
        "owner": group.creator_name,
        "created_at": isoformat_timestr,
    }

    return group_info
Ejemplo n.º 43
0
    def format_group_message(self, notice):
        d = notice.group_message_detail_to_dict()
        group_id = d['group_id']
        message = d['message']
        group = ccnet_api.get_group(int(group_id))

        notice.group_url = reverse('group_discuss', args=[group.id])
        notice.notice_from = escape(email2nickname(d['msg_from']))
        notice.group_name = group.group_name
        notice.avatar_src = self.get_avatar_src(d['msg_from'])
        notice.grp_msg = message
        return notice
Ejemplo n.º 44
0
    def format_group_message(self, notice):
        d = notice.group_message_detail_to_dict()
        group_id = d['group_id']
        message = d['message']
        group = ccnet_api.get_group(int(group_id))

        notice.group_url = HASH_URLS['GROUP_DISCUSS'] % {'group_id': group.id}
        notice.notice_from = escape(email2nickname(d['msg_from']))
        notice.group_name = group.group_name
        notice.avatar_src = self.get_avatar_src(d['msg_from'])
        notice.grp_msg = message
        return notice
Ejemplo n.º 45
0
    def get(self, request, group_id):
        """List child groups and members in an address book group."""
        group_id = int(group_id)

        group = ccnet_api.get_group(group_id)
        if not group:
            error_msg = 'Group %d not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        try:
            avatar_size = int(request.GET.get('avatar_size',
                                              AVATAR_DEFAULT_SIZE))
        except ValueError:
            avatar_size = AVATAR_DEFAULT_SIZE

        try:
            return_ancestors = to_python_boolean(request.GET.get(
                'return_ancestors', 'f'))
        except ValueError:
            return_ancestors = False

        ret_dict = address_book_group_to_dict(group)
        ret_groups = []
        ret_members = []

        groups = ccnet_api.get_child_groups(group_id)
        for group in groups:
            ret_groups.append(address_book_group_to_dict(group))

        try:
            members = ccnet_api.get_group_members(group_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 m in members:
            member_info = self._get_address_book_group_memeber_info(request,
                    m, avatar_size)
            ret_members.append(member_info)

        ret_dict['groups'] = ret_groups
        ret_dict['members'] = ret_members

        if return_ancestors:
            # get ancestor groups and remove last group which is self
            ancestor_groups = ccnet_api.get_ancestor_groups(group_id)[:-1]
            ret_dict['ancestor_groups'] = [address_book_group_to_dict(grp)
                                           for grp in ancestor_groups]
        else:
            ret_dict['ancestor_groups'] = []

        return Response(ret_dict)
Ejemplo n.º 46
0
def address_book_group_to_dict(group):
    if isinstance(group, int):
        group = ccnet_api.get_group(group)

    return {
        "id": group.id,
        "name": group.group_name,
        "owner": group.creator_name,
        "created_at": timestamp_to_isoformat_timestr(group.timestamp),
        "parent_group_id": group.parent_group_id,
        "quota": seafile_api.get_group_quota(group.id),
    }
Ejemplo n.º 47
0
    def _get_group_folder_perm_info(self, group_id, repo_id, path, perm):
        result = {}
        if group_id and repo_id and path and perm:
            group = ccnet_api.get_group(group_id)
            result['repo_id'] = repo_id
            result['group_id'] = group_id
            result['group_name'] = group.group_name
            result['folder_path'] = path
            result['folder_name'] = path if path == '/' else os.path.basename(path.rstrip('/'))
            result['permission'] = perm

        return result
Ejemplo n.º 48
0
    def delete(self, request, repo_id):
        """ Delete repo user folder perm.

        Permission checking:
        1. is group admin
        """

        # argument check
        user = request.data.get('user_email', None)
        if not user:
            error_msg = 'user_email invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        path = request.data.get('folder_path', None)
        if not path:
            error_msg = 'folder_path invalid.'
            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)

        repo_owner = get_repo_owner(request, repo_id)
        group_id = get_group_id_by_repo_owner(repo_owner)
        if not ccnet_api.get_group(group_id):
            error_msg = 'Group %s not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        username = request.user.username
        if not is_group_admin(group_id, username):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # delete permission
        path = normalize_dir_path(path)
        permission = seafile_api.get_folder_user_perm(repo_id, path, user)
        if not permission:
            return Response({'success': True})

        try:
            seafile_api.rm_folder_user_perm(repo_id, path, user)
            send_perm_audit_msg('delete-repo-perm', username,
                    user, repo_id, path, permission)
            return Response({'success': True})
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
Ejemplo n.º 49
0
    def put(self, request, group_id):
        """ Admin transfer a group

        Permission checking:
        1. Admin user;
        """

        # argument check
        new_owner = request.data.get('new_owner', None)
        if not new_owner or not is_valid_username(new_owner):
            error_msg = 'new_owner %s invalid.' % new_owner
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # recourse check
        group_id = int(group_id) # Checked by URL Conf
        group = ccnet_api.get_group(group_id)
        if not group:
            error_msg = 'Group %d not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # check if new_owner exists,
        # NOT need to check old_owner for old_owner may has been deleted.
        try:
            User.objects.get(email=new_owner)
        except User.DoesNotExist:
            error_msg = 'User %s not found.' % new_owner
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        old_owner = group.creator_name
        if new_owner == old_owner:
            error_msg = _(u'User %s is already group owner.') % new_owner
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # transfer a group
        try:
            if not is_group_member(group_id, new_owner):
                ccnet_api.group_add_member(group_id, old_owner, new_owner)

            if not is_group_admin(group_id, new_owner):
                ccnet_api.group_set_admin(group_id, new_owner)

            ccnet_api.set_group_creator(group_id, new_owner)
            ccnet_api.group_unset_admin(group_id, old_owner)
        except SearpcError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        group_info = get_group_info(group_id)

        return Response(group_info)
Ejemplo n.º 50
0
    def format_add_user_to_group(self, notice):
        d = json.loads(notice.detail)
        group_staff = d['group_staff']
        group_id = d['group_id']

        group = ccnet_api.get_group(group_id)

        notice.notice_from = escape(email2nickname(group_staff))
        notice.avatar_src = self.get_avatar_src(group_staff)
        notice.group_staff_profile_url = reverse('user_profile',
                                                  args=[group_staff])
        notice.group_url = reverse('group', args=[group.id])
        notice.group_name = group.group_name
        return notice
Ejemplo n.º 51
0
def get_group_info(group_id):
    group = ccnet_api.get_group(group_id)
    isoformat_timestr = timestamp_to_isoformat_timestr(group.timestamp)
    group_info = {
        "id": group.id,
        "name": group.group_name,
        "owner": group.creator_name,
        "owner_name": email2nickname(group.creator_name),
        "created_at": isoformat_timestr,
        "quota": seafile_api.get_group_quota(group_id) if is_pro_version() else 0,
        "parent_group_id": group.parent_group_id if is_pro_version() else 0
    }

    return group_info
Ejemplo n.º 52
0
    def get(self, request, format=None):
        """ List all shared out repos.

        Permission checking:
        1. all authenticated user can perform this action.
        """

        shared_repos = []
        username = request.user.username
        try:
            if is_org_context(request):
                org_id = request.user.org.org_id
                shared_repos += seafile_api.get_org_share_out_repo_list(org_id, username, -1, -1)
                shared_repos += seaserv.seafserv_threaded_rpc.get_org_group_repos_by_owner(org_id, username)
                shared_repos += seaserv.seafserv_threaded_rpc.list_org_inner_pub_repos_by_owner(org_id, username)
            else:
                shared_repos += seafile_api.get_share_out_repo_list(username, -1, -1)
                shared_repos += seafile_api.get_group_repos_by_owner(username)
                if not request.cloud_mode:
                    shared_repos += seaserv.list_inner_pub_repos_by_owner(username)
        except Exception as e:
            logger.error(e)
            error_msg = "Internal Server Error"
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        returned_result = []
        shared_repos.sort(lambda x, y: cmp(x.repo_name, y.repo_name))
        for repo in shared_repos:
            if repo.is_virtual:
                continue

            result = {}
            result["repo_id"] = repo.repo_id
            result["repo_name"] = repo.repo_name
            result["share_type"] = repo.share_type
            result["share_permission"] = repo.permission

            if repo.share_type == "personal":
                result["user_name"] = email2nickname(repo.user)
                result["user_email"] = repo.user

            if repo.share_type == "group":
                group = ccnet_api.get_group(repo.group_id)
                result["group_id"] = repo.group_id
                result["group_name"] = group.group_name

            returned_result.append(result)

        return Response(returned_result)
Ejemplo n.º 53
0
    def format_repo_share_to_group_msg(self, notice):
        d = json.loads(notice.detail)

        repo_id = d['repo_id']
        repo = seafile_api.get_repo(repo_id)
        group_id = d['group_id']
        group = ccnet_api.get_group(group_id)

        notice.repo_url = reverse("view_common_lib_dir", args=[repo_id, ''])
        notice.notice_from = escape(email2nickname(d['share_from']))
        notice.repo_name = repo.name
        notice.avatar_src = self.get_avatar_src(d['share_from'])
        notice.group_url = reverse("group_info", args=[group.id])
        notice.group_name = group.group_name

        return notice
Ejemplo n.º 54
0
    def format_group_join_request(self, notice):
        d = json.loads(notice.detail)
        username = d['username']
        group_id = d['group_id']
        join_request_msg = d['join_request_msg']

        group = ccnet_api.get_group(group_id)

        notice.grpjoin_user_profile_url = reverse('user_profile',
                                                  args=[username])
        notice.grpjoin_group_url = HASH_URLS['GROUP_MEMBERS'] % {'group_id': group_id}
        notice.notice_from = escape(email2nickname(username))
        notice.grpjoin_group_name = group.group_name
        notice.grpjoin_request_msg = join_request_msg
        notice.avatar_src = self.get_avatar_src(username)
        return notice
Ejemplo n.º 55
0
    def format_group_join_request(self, notice):
        d = json.loads(notice.detail)
        username = d['username']
        group_id = d['group_id']
        join_request_msg = d['join_request_msg']

        group = ccnet_api.get_group(group_id)

        notice.grpjoin_user_profile_url = reverse('user_profile',
                                                  args=[username])
        notice.grpjoin_group_url = reverse('group_members', args=[group_id])
        notice.notice_from = username
        notice.grpjoin_group_name = group.group_name
        notice.grpjoin_request_msg = join_request_msg
        notice.avatar_src = self.get_avatar_src(username)
        return notice
Ejemplo n.º 56
0
def is_group_member(group_id, email, in_structure=None):

    group_id = int(group_id)

    if in_structure in (True, False):
        return ccnet_api.is_group_user(group_id, email, in_structure)

    group = ccnet_api.get_group(group_id)
    if group.parent_group_id == 0:
        # -1: top address book group
        #  0: group not in address book
        # >0: sub group in address book
        # if `in_structure` is False, NOT check sub groups in address book
        return ccnet_api.is_group_user(group_id, email, in_structure=False)
    else:
        return ccnet_api.is_group_user(group_id, email)
Ejemplo n.º 57
0
    def delete(self, request, group_id):
        """ Delete an address book group.
        """
        group_id = int(group_id)
        group = ccnet_api.get_group(group_id)
        if not group:
            return Response({'success': True})

        try:
            has_repo = seafile_api.if_group_has_group_owned_repo(group_id)
            child_groups = ccnet_api.get_child_groups(group_id)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if has_repo:
            error_msg = _(u'There are libraries in this department.')
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        if len(child_groups) > 0:
            error_msg = _(u'There are sub-departments in this department.')
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

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

        if ret_code == -1:
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        # send admin operation log signal
        group_owner = group.creator_name
        group_name = group.group_name
        admin_op_detail = {
            "id": group_id,
            "name": group_name,
            "owner": group_owner,
        }
        admin_operation.send(sender=None, admin_name=request.user.username,
                operation=GROUP_DELETE, detail=admin_op_detail)

        return Response({'success': True})
Ejemplo n.º 58
0
def group_id_to_name(group_id):

    group_id = str(group_id)

    key = normalize_cache_key(group_id, GROUP_ID_CACHE_PREFIX)
    cached_group_name = cache.get(key)
    if cached_group_name:
        return cached_group_name

    group = ccnet_api.get_group(int(group_id))
    if not group:
        return ''

    group_name = group.group_name
    cache.set(key, group_name, GROUP_ID_CACHE_TIMEOUT)

    return group_name
Ejemplo n.º 59
0
    def put(self, request, group_id, email, format=None):
        """ update role of a group member

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

        # argument check
        group_id = int(group_id)
        group = ccnet_api.get_group(group_id)
        if not group:
            error_msg = 'Group %d not found.' % group_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        try:
            User.objects.get(email=email)
        except User.DoesNotExist:
            error_msg = 'User %s not found.' % email
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        try:
            if not is_group_member(group_id, email):
                error_msg = 'Email %s invalid.' % email
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        is_admin = request.data.get('is_admin', '')
        try:
            # set/unset a specific group member as admin
            if is_admin.lower() == 'true':
                ccnet_api.group_set_admin(group_id, email)
            elif is_admin.lower() == 'false':
                ccnet_api.group_unset_admin(group_id, email)
            else:
                error_msg = 'is_admin invalid.'
                return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        member_info = get_group_member_info(request, group_id, email)
        return Response(member_info)