Exemplo n.º 1
0
    def get(self, request, repo_id, format=None):
        """List all users who can view this library.

        Not support public repo
        """
        # 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)

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

        # org check
        org_id = None
        if is_org_context(request):
            org_id = request.user.org.org_id

        # main
        user_list = list()

        try:
            related_user_list = get_related_users_by_repo(repo_id, org_id)

            for email in related_user_list:
                user_info = get_user_common_info(email)
                user_list.append(user_info)
        except Exception as e:
            logger.error(e)
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal Server Error')

        return Response({'user_list': user_list})
Exemplo n.º 2
0
    def post(self, request, group_id, format=None):
        """Post a group discussion. Only group members can perform this op.
        """
        content = request.data.get('content', '')
        if not content:
            return api_error(status.HTTP_400_BAD_REQUEST, 'Content can not be empty.')

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

        username = request.user.username
        msg = GroupMessage.objects.create(group_id=group_id,
                                              from_email=username,
                                              message=content)
        # send signal
        grpmsg_added.send(sender=GroupMessage, group_id=group_id,
                from_email=username, message=content)

        info = get_user_common_info(username, avatar_size)

        isoformat_timestr = datetime_to_isoformat_timestr(msg.timestamp)
        return Response({
            "id": msg.pk,
            "group_id": group_id,
            "user_name": info["name"],
            "user_email": info["email"],
            "user_contact_email": info["contact_email"],
            "avatar_url": request.build_absolute_uri(info["avatar_url"]),
            "content": msg.message,
            "created_at": isoformat_timestr
        }, status=201)
Exemplo n.º 3
0
    def get(self, request):
        dtable_uuid = request.GET.get('dtable_uuid')
        # permission check
        auth = request.META.get('HTTP_AUTHORIZATION', '').split()
        if not is_valid_jwt(auth, dtable_uuid):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)
        # resource check
        dtable = DTables.objects.get_dtable_by_uuid(dtable_uuid)
        if not dtable:
            error_msg = 'dtable %s not found.' % dtable_uuid
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        workspace = Workspaces.objects.get_workspace_by_id(dtable.workspace.id)
        if not workspace:
            error_msg = 'Workspace not found.'
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        user_list = []
        try:
            email_list = list_dtable_related_users(workspace, dtable)

            for email in email_list:
                user_info = get_user_common_info(email)
                user_list.append(user_info)
        except Exception as e:
            logger.error(e)
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                             'Internal Server Error')

        return Response({'user_list': user_list})
Exemplo n.º 4
0
    def get(self, request, workspace_id, name):
        """list dtable related users
        """
        table_name = name
        table_file_name = table_name + FILE_TYPE

        # resource check
        workspace = Workspaces.objects.get_workspace_by_id(workspace_id)
        if not workspace:
            error_msg = 'Workspace %s not found.' % workspace_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        if '@seafile_group' in workspace.owner:
            group_id = workspace.owner.split('@')[0]
            group = seaserv.get_group(group_id)
            if not group:
                error_msg = 'Group %s not found.' % group_id
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        repo_id = workspace.repo_id
        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)

        dtable = DTables.objects.get_dtable(workspace, table_name)
        if not dtable:
            error_msg = 'dtable %s not found.' % table_name
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        table_path = normalize_file_path(table_file_name)
        table_file_id = seafile_api.get_file_id_by_path(repo_id, table_path)
        if not table_file_id:
            error_msg = 'file %s not found.' % table_file_name
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        username = request.user.username
        owner = workspace.owner
        if not check_dtable_permission(username, owner) and \
                not check_dtable_share_permission(dtable, username):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # main
        user_list = list()

        try:
            email_list = list_dtable_related_users(workspace, dtable)

            for email in email_list:
                user_info = get_user_common_info(email)
                user_list.append(user_info)
        except Exception as e:
            logger.error(e)
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, 'Internal Server Error')

        return Response({'user_list': user_list})
Exemplo n.º 5
0
    def get(self, request, group_id, format=None):
        """List all group discussions. Only group members can perform this op.
        """
        # 1 <= page, defaults to 1
        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1
        if page < 0:
            page = 1

        # 1 <= per_page <= 100, defaults to 20
        try:
            per_page = int(request.GET.get('per_page', '20'))
        except ValueError:
            per_page = 20
        if per_page < 1 or per_page > 100:
            per_page = 20

        paginator = Paginator(
            GroupMessage.objects.filter(
                group_id=group_id).order_by('-timestamp'), per_page)

        try:
            group_msgs = paginator.page(page)
        except (EmptyPage, InvalidPage):
            group_msgs = paginator.page(paginator.num_pages)

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

        msgs = []
        for msg in group_msgs:
            info = get_user_common_info(msg.from_email, avatar_size)
            isoformat_timestr = datetime_to_isoformat_timestr(msg.timestamp)
            msgs.append({
                "id": msg.pk,
                "group_id": group_id,
                "user_name": info["name"],
                "user_email": info["email"],
                "user_contact_email": info["contact_email"],
                "avatar_url": info["avatar_url"],
                "content": msg.message,
                "created_at": isoformat_timestr
            })

        return HttpResponse(json.dumps({
            "msgs": msgs,
            "current_page": page,
            "page_num": paginator.num_pages,
        }),
                            status=200,
                            content_type=json_content_type)
Exemplo n.º 6
0
    def get(self, request, group_id, format=None):
        """List all group discussions. Only group members can perform this op.
        """
        # 1 <= page, defaults to 1
        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1
        if page < 0:
            page = 1

        # 1 <= per_page <= 100, defaults to 20
        try:
            per_page = int(request.GET.get('per_page', '20'))
        except ValueError:
            per_page = 20
        if per_page < 1 or per_page > 100:
            per_page = 20

        paginator = Paginator(GroupMessage.objects.filter(
            group_id=group_id).order_by('-timestamp'), per_page)

        try:
            group_msgs = paginator.page(page)
        except (EmptyPage, InvalidPage):
            group_msgs = paginator.page(paginator.num_pages)

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

        msgs = []
        for msg in group_msgs:
            info = get_user_common_info(msg.from_email, avatar_size)
            isoformat_timestr = datetime_to_isoformat_timestr(msg.timestamp)
            msgs.append({
                "id": msg.pk,
                "group_id": group_id,
                "user_name": info["name"],
                "user_email": info["email"],
                "user_contact_email": info["contact_email"],
                "avatar_url": request.build_absolute_uri(info["avatar_url"]),
                "content": msg.message,
                "created_at": isoformat_timestr
            })

        return HttpResponse(json.dumps({
            "msgs": msgs,
            "current_page": page,
            "page_num": paginator.num_pages,
            }), status=200, content_type=json_content_type)
Exemplo n.º 7
0
    def post(self, request, repo_id, format=None):
        """Post a participant of a file.
        """
        # argument check
        path = request.data.get('path')
        if not path:
            return api_error(status.HTTP_400_BAD_REQUEST, 'path invalid.')
        path = normalize_file_path(path)

        email = request.data.get('email')
        if not email or not is_valid_username(email):
            return api_error(status.HTTP_400_BAD_REQUEST, 'email invalid.')

        # resource check
        file_id = seafile_api.get_file_id_by_path(repo_id, path)
        if not file_id:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'File %s not found.' % path)

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

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

        if not seafile_api.check_permission_by_path(repo_id, '/',
                                                    user.username):
            return api_error(status.HTTP_403_FORBIDDEN,
                             _('%s Permission denied.') % email)

        # main
        try:
            file_uuid = FileUUIDMap.objects.get_or_create_fileuuidmap_by_path(
                repo_id, path, False)

            if FileParticipant.objects.get_participant(file_uuid, email):
                return api_error(status.HTTP_409_CONFLICT,
                                 _('Participant %s already exists.') % email)

            FileParticipant.objects.add_participant(file_uuid, email)
            participant = get_user_common_info(email)
        except Exception as e:
            logger.error(e)
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                             'Internal Server Error.')

        return Response(participant, status=201)
Exemplo n.º 8
0
    def post(self, request):
        """return user_list by user_id_list
        """
        # argument check
        user_id_list = request.data.get('user_id_list')
        if not user_id_list or not isinstance(user_id_list, list):
            error_msg = 'user_id_list invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # main
        user_list = list()
        for user_id in user_id_list:
            user_info = get_user_common_info(user_id)
            user_list.append(user_info)

        return Response({'user_list': user_list})
Exemplo n.º 9
0
    def post(self, request, group_id, format=None):
        """Post a group discussion. Only group members can perform this op.
        """
        content = request.data.get('content', '')
        if not content:
            return api_error(status.HTTP_400_BAD_REQUEST,
                             'Content can not be empty.')

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

        username = request.user.username
        msg = GroupMessage.objects.create(group_id=group_id,
                                          from_email=username,
                                          message=content)
        # send signal
        grpmsg_added.send(sender=GroupMessage,
                          group_id=group_id,
                          from_email=username,
                          message=content)

        info = get_user_common_info(username, avatar_size)

        isoformat_timestr = datetime_to_isoformat_timestr(msg.timestamp)
        return Response(
            {
                "id": msg.pk,
                "group_id": group_id,
                "user_name": info["name"],
                "user_email": info["email"],
                "user_login_id": info["login_id"],
                "avatar_url": request.build_absolute_uri(info["avatar_url"]),
                "content": msg.message,
                "created_at": isoformat_timestr
            },
            status=201)
Exemplo n.º 10
0
    def get(self, request, repo_id, format=None):
        """List all participants of a file.
        """
        # argument check
        path = request.GET.get('path')
        if not path:
            return api_error(status.HTTP_400_BAD_REQUEST, 'path invalid.')
        path = normalize_file_path(path)

        # resource check
        file_id = seafile_api.get_file_id_by_path(repo_id, path)
        if not file_id:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'File %s not found.' % path)

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

        # main
        try:
            file_uuid = FileUUIDMap.objects.get_or_create_fileuuidmap_by_path(
                repo_id, path, False)

            participant_list = []
            participant_queryset = FileParticipant.objects.get_participants(
                file_uuid)

            for participant in participant_queryset:
                participant_info = get_user_common_info(participant.username)
                participant_info['avatar_url'] = request.build_absolute_uri(
                    participant_info['avatar_url'])
                participant_list.append(participant_info)
        except Exception as e:
            logger.error(e)
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                             'Internal Server Error.')

        return Response({'participant_list': participant_list})
Exemplo n.º 11
0
    def post(self, request, repo_id, format=None):
        """batch add participants of a file.
        """
        # argument check
        path = request.data.get('path')
        if not path:
            return api_error(status.HTTP_400_BAD_REQUEST, 'path invalid.')
        path = normalize_file_path(path)

        emails = request.data.get('emails')
        if not emails or not isinstance(emails, list):
            return api_error(status.HTTP_400_BAD_REQUEST, 'emails invalid.')
        emails = list(set(emails))

        # resource check
        file_id = seafile_api.get_file_id_by_path(repo_id, path)
        if not file_id:
            return api_error(status.HTTP_404_NOT_FOUND,
                             'File %s not found.' % path)

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

        # batch add
        success = list()
        failed = list()

        try:
            uuid = FileUUIDMap.objects.get_or_create_fileuuidmap_by_path(
                repo_id, path, False)
            participants_queryset = FileParticipant.objects.get_participants(
                uuid)
        except Exception as e:
            logger.error(e)
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,
                             'Internal Server Error.')

        for email in emails:
            if not is_valid_username(email):
                error_dic = {
                    'email': email,
                    'error_msg': 'email invalid.',
                    'error_code': 400
                }
                failed.append(error_dic)
                continue

            try:
                user = User.objects.get(email=email)
            except User.DoesNotExist:
                error_dic = {
                    'email': email,
                    'error_msg': 'User not found.',
                    'error_code': 404
                }
                failed.append(error_dic)
                continue

            # permission check
            if not seafile_api.check_permission_by_path(
                    repo_id, '/', user.username):
                error_dic = {
                    'email': email,
                    'error_msg': 'Permission denied.',
                    'error_code': 403
                }
                failed.append(error_dic)
                continue

            # main
            try:
                if participants_queryset.filter(uuid=uuid,
                                                username=email).count() > 0:
                    error_dic = {
                        'email': email,
                        'error_msg': 'Participant already exists.',
                        'error_code': 409
                    }
                    failed.append(error_dic)
                    continue

                FileParticipant.objects.add_participant(uuid, email)
                participant = get_user_common_info(email)
                success.append(participant)
            except Exception as e:
                logger.error(e)
                error_dic = {
                    'email': email,
                    'error_msg': 'Internal Server Error.',
                    'error_code': 500
                }
                failed.append(error_dic)
                continue

        return Response({'success': success, 'failed': failed})
Exemplo n.º 12
0
    def get(self, request, workspace_id, name):
        """list share users in dtable share
        """
        username = request.user.username
        table_name = name
        table_file_name = table_name + FILE_TYPE

        # resource check
        workspace = Workspaces.objects.get_workspace_by_id(workspace_id)
        if not workspace:
            error_msg = 'Workspace %s not found.' % workspace_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        group_id = ''
        if '@seafile_group' in workspace.owner:
            group_id = workspace.owner.split('@')[0]
            group = seaserv.get_group(group_id)
            if not group:
                error_msg = 'Group %s not found.' % group_id
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        repo_id = workspace.repo_id
        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)

        dtable = DTables.objects.get_dtable(workspace, table_name)
        if not dtable:
            error_msg = 'dtable %s not found.' % table_name
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        table_path = normalize_file_path(table_file_name)
        table_file_id = seafile_api.get_file_id_by_path(repo_id, table_path)
        if not table_file_id:
            error_msg = 'file %s not found.' % table_file_name
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        if group_id:
            if not is_group_member(group_id, username):
                error_msg = 'Permission denied.'
                return api_error(status.HTTP_403_FORBIDDEN, error_msg)
        else:
            if username != dtable.creator:
                error_msg = 'Permission denied.'
                return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # main
        try:
            share_queryset = DTableShare.objects.list_by_dtable(dtable)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error.'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        user_list = list()
        for item in share_queryset:
            user_info = get_user_common_info(item.to_user)
            user_info['permission'] = item.permission
            user_list.append(user_info)

        return Response({"user_list": user_list})
Exemplo n.º 13
0
    def get(self, request, dataset_id):
        """ return dataset contents

            param: from_dtable_id, optional
            if from_dtable_id is not given, check access permission by user through group
            if from_dtable_id is given, check access permission by dtable
        """

        # resource check
        try:
            dataset = DTableCommonDataset.objects.get(pk=dataset_id)
        except DTableCommonDataset.DoesNotExist:
            error_msg = 'dataset %s not found.' % dataset_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # perm check
        from_dtable_id = request.GET.get('from_dtable_id', '')
        if from_dtable_id:
            try:
                from_dtable = DTables.objects.get(pk=from_dtable_id)
            except DTables.DoesNotExist:
                error_msg = 'from_dtable %s not found.' % from_dtable_id
                return api_error(status.HTTP_404_NOT_FOUND, error_msg)
            if not dataset.can_access_by_dtable(from_dtable):
                error_msg = 'Permission Denied.'
                return api_error(status.HTTP_403_FORBIDDEN, error_msg)
        else:
            if not dataset.can_access_by_user_through_group(
                    request.user.username):
                error_msg = 'Permission Denied.'
                return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        # generate json web token
        dtable = DTables.objects.filter(uuid=dataset.dtable_uuid).first()
        if not dtable:
            error_msg = 'DTable %s not found.' % dataset.dtable_uuid
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        workspace = Workspaces.objects.get_workspace_by_id(dtable.workspace.id)
        if not workspace:
            error_msg = 'Workspace not found.'
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # internal usage exp 60 seconds, username = dtable-web
        payload = {
            'exp': int(time.time()) + 60,
            'dtable_uuid': dtable.uuid.hex,
            'username': '******',
            'permission': 'r',
        }
        try:
            access_token = jwt.encode(payload,
                                      DTABLE_PRIVATE_KEY,
                                      algorithm='HS256')
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        # 1. get cols from dtable-server
        url = DTABLE_SERVER_URL + 'api/v1/dtables/' + dtable.uuid.hex + '/metadata/'
        headers = {'Authorization': 'Token ' + access_token.decode('utf-8')}
        try:
            dtable_metadata = requests.get(url, headers=headers)
        except requests.HTTPError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        tables = json.loads(dtable_metadata.content)['metadata'].get(
            'tables', [])
        target_table = {}
        for table in tables:
            if table.get('_id', '') == dataset.table_id:
                target_table = table

        if not target_table:
            error_msg = _('Table %s not found.') % dataset.table_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # 2. get rows from dtable server
        url = DTABLE_SERVER_URL + 'api/v1/dtables/' + dtable.uuid.hex + '/rows/'
        headers = {'Authorization': 'Token ' + access_token.decode('utf-8')}
        query_param = {
            'table_id': dataset.table_id,
            'view_id': dataset.view_id
        }
        try:
            res = requests.get(url, headers=headers, params=query_param)
        except requests.HTTPError as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        if res.status_code == status.HTTP_404_NOT_FOUND:
            error_msg = 'table %s or view %s not found.' % (dataset.table_id,
                                                            dataset.view_id)
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        try:
            rows = json.loads(res.content).get('rows', [])
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        related_user_emails = list_dtable_related_users(workspace=workspace,
                                                        dtable=dtable)
        related_user_list = [
            get_user_common_info(email) for email in related_user_emails
        ]

        hidden_columns = []
        for view in target_table['views']:
            if dataset.view_id == view.get('_id', ''):
                hidden_columns = view.get('hidden_columns', [])

        show_cols = []
        cols = target_table.get('columns', [])
        for col in cols:
            if col['key'] in hidden_columns:
                continue
            show_cols.append(col)

        return Response({
            'rows': rows,
            'columns': show_cols,
            'related_user_list': related_user_list
        })