示例#1
0
文件: utils.py 项目: wearpants/osf.io
def get_file_object(node, path, provider, request):
    if provider == 'osfstorage':
        # Kinda like /me for a user
        # The one odd case where path is not really path
        if path == '/':
            obj = node.get_addon('osfstorage').get_root()
        else:
            obj = get_object_or_error(
                OsfStorageFileNode,
                Q('node', 'eq', node._id) &
                Q('_id', 'eq', path.strip('/')) &
                Q('is_file', 'eq', not path.endswith('/'))
            )
        return obj

    url = waterbutler_api_url_for(node._id, provider, path, meta=True)
    waterbutler_request = requests.get(
        url,
        cookies=request.COOKIES,
        headers={'Authorization': request.META.get('HTTP_AUTHORIZATION')},
    )

    if waterbutler_request.status_code == 401:
        raise PermissionDenied

    if waterbutler_request.status_code == 404:
        raise NotFound

    if is_server_error(waterbutler_request.status_code):
        raise ServiceUnavailableError(detail='Could not retrieve files information at this time.')

    try:
        return waterbutler_request.json()['data']
    except KeyError:
        raise ServiceUnavailableError(detail='Could not retrieve files information at this time.')
示例#2
0
    def get_comment(self, check_permissions=True):
        pk = self.kwargs[self.comment_lookup_url_kwarg]
        try:
            comment = Comment.find_one(Q('_id', 'eq', pk) & Q('root_target', 'ne', None))
        except NoResultsFound:
            raise NotFound

        # Deleted root targets still appear as tuples in the database and are included in
        # the above query, requiring an additional check
        if comment.root_target is None:
            raise NotFound

        if isinstance(comment.root_target, StoredFileNode):
            root_target = comment.root_target
            if root_target.provider == 'osfstorage':
                try:
                    StoredFileNode.find(
                        Q('node', 'eq', comment.node._id) &
                        Q('_id', 'eq', root_target._id) &
                        Q('is_file', 'eq', True)
                    )
                except NoResultsFound:
                    Comment.update(Q('root_target', 'eq', root_target), data={'root_target': None})
                    del comment.node.commented_files[root_target._id]
                    raise NotFound
            else:
                if root_target.provider == 'dropbox':
                    root_target = DropboxFile.load(comment.root_target._id)
                url = waterbutler_api_url_for(comment.node._id, root_target.provider, root_target.path, meta=True)
                waterbutler_request = requests.get(
                    url,
                    cookies=self.request.COOKIES,
                    headers={'Authorization': self.request.META.get('HTTP_AUTHORIZATION')},
                )

                if waterbutler_request.status_code == 401:
                    raise PermissionDenied

                if waterbutler_request.status_code == 404:
                    Comment.update(Q('root_target', 'eq', root_target), data={'root_target': None})
                    raise NotFound

                if is_server_error(waterbutler_request.status_code):
                    raise ServiceUnavailableError(detail='Could not retrieve files information at this time.')

                try:
                    waterbutler_request.json()['data']
                except KeyError:
                    raise ServiceUnavailableError(detail='Could not retrieve files information at this time.')

        if check_permissions:
            # May raise a permission denied
            self.check_object_permissions(self.request, comment)
        return comment
示例#3
0
def get_file_object(node, path, provider, request):
    # Don't bother going to waterbutler for osfstorage
    if provider == 'osfstorage':
        # Kinda like /me for a user
        # The one odd case where path is not really path
        if path == '/':
            obj = node.get_addon('osfstorage').get_root()
        else:
            if path.endswith('/'):
                model = OsfStorageFolder
            else:
                model = OsfStorageFile
            obj = get_object_or_error(model,
                                      Q(node=node.pk, _id=path.strip('/')),
                                      request)
        return obj

    if not node.get_addon(provider) or not node.get_addon(provider).configured:
        raise NotFound(
            'The {} provider is not configured for this project.'.format(
                provider))

    view_only = request.query_params.get('view_only', default=None)
    url = waterbutler_api_url_for(node._id,
                                  provider,
                                  path,
                                  _internal=True,
                                  meta=True,
                                  view_only=view_only)

    waterbutler_request = requests.get(
        url,
        cookies=request.COOKIES,
        headers={'Authorization': request.META.get('HTTP_AUTHORIZATION')},
    )

    if waterbutler_request.status_code == 401:
        raise PermissionDenied

    if waterbutler_request.status_code == 404:
        raise NotFound

    if is_server_error(waterbutler_request.status_code):
        raise ServiceUnavailableError(
            detail='Could not retrieve files information at this time.')

    try:
        return waterbutler_request.json()['data']
    except KeyError:
        raise ServiceUnavailableError(
            detail='Could not retrieve files information at this time.')
示例#4
0
 def create(self, validated_data):
     node = self.context['view'].get_node()
     auth = get_user_auth(self.context['request'])
     if validated_data.get('category', None) == 'doi':
         if node.get_identifier('doi'):
             raise exceptions.ValidationError(
                 'A DOI already exists for this resource.')
         try:
             identifiers = get_or_create_identifiers(node)
         except HTTPError:
             raise exceptions.ValidationError('Error response from client.')
         except TypeError:
             raise ServiceUnavailableError()
         for category, value in identifiers.items():
             node.set_identifier_value(category, value)
         node.add_log(
             NodeLog.EXTERNAL_IDS_ADDED,
             params={
                 'parent_node': node.parent_id,
                 'node': node._id,
                 'identifiers': identifiers,
             },
             auth=auth,
         )
         return node.identifiers.get(category='doi')
     else:
         raise exceptions.ValidationError(
             'You can only mint a DOI, not a different type of identifier.')
示例#5
0
def get_file_object(target, path, provider, request):
    # Don't bother going to waterbutler for osfstorage
    if provider == 'osfstorage':
        # Kinda like /me for a user
        # The one odd case where path is not really path
        if path == '/':
            if isinstance(target, AbstractNode):
                obj = target.get_addon('osfstorage').get_root()
            elif isinstance(target, Preprint):
                obj = target.root_folder
            else:
                obj = target
        else:
            if path.endswith('/'):
                model = OsfStorageFolder
            else:
                model = OsfStorageFile
            content_type = ContentType.objects.get_for_model(target)
            obj = get_object_or_error(
                model,
                Q(target_object_id=target.pk,
                  target_content_type=content_type,
                  _id=path.strip('/')), request)
        return obj

    if isinstance(target, AbstractNode) and not target.get_addon(
            provider) or not target.get_addon(provider).configured:
        raise NotFound(
            'The {} provider is not configured for this project.'.format(
                provider))

    view_only = request.query_params.get('view_only', default=None)
    base_url = None
    if hasattr(target, 'osfstorage_region'):
        base_url = target.osfstorage_region.waterbutler_url
    url = waterbutler_api_url_for(
        target._id,
        provider,
        path,
        _internal=True,
        base_url=base_url,
        meta=True,
        view_only=view_only,
    )

    waterbutler_request = requests.get(
        url,
        cookies=request.COOKIES,
        headers={'Authorization': request.META.get('HTTP_AUTHORIZATION')},
    )

    if waterbutler_request.status_code == 401:
        raise PermissionDenied

    if waterbutler_request.status_code == 404:
        raise NotFound

    if is_server_error(waterbutler_request.status_code):
        raise ServiceUnavailableError(
            detail='Could not retrieve files information at this time.')

    try:
        return waterbutler_request.json()['data']
    except KeyError:
        raise ServiceUnavailableError(
            detail='Could not retrieve files information at this time.')