Пример #1
0
    def _handle_file_response(self, file, headers):
        """
        Handle response for file.

        Depending on where the file storage (e.g. filesystem, S3, etc) this could be responding with
        the file (filesystem) or a redirect (S3).

        Args:
            file (:class:`django.db.models.fields.files.FieldFile`): File to respond with
            headers (dict): A dictionary of response headers.

        Raises:
            :class:`aiohttp.web_exceptions.HTTPFound`: When we need to redirect to the file
            NotImplementedError: If file is stored in a file storage we can't handle

        Returns:
            The :class:`aiohttp.web.FileResponse` for the file.
        """
        if settings.DEFAULT_FILE_STORAGE == 'pulpcore.app.models.storage.FileSystem':
            return FileResponse(os.path.join(settings.MEDIA_ROOT, file.name),
                                headers=headers)
        elif settings.DEFAULT_FILE_STORAGE == 'storages.backends.s3boto3.S3Boto3Storage':
            raise HTTPFound(file.url, headers=headers)
        else:
            raise NotImplementedError()
Пример #2
0
    async def _handle_static_file_request(self, request):
        def _404():
            return Response(
                status=404,
                text='404: Not found',
            )

        if not self.settings.STATIC_FILES_SERVE:
            server_logger.warning(
                'Reverse proxy seems to be misconfigured: a static file request was received but STATIC_FILES_SERVE is disabled',  # NOQA
            )

            return _404()

        rel_path = request.match_info['path']

        abs_path = await self.run_function_async(
            self.static_file_loader.resolve_path,
            rel_path,
            excutor_name='static_worker',
        )

        if not abs_path:
            return _404()

        return FileResponse(abs_path)
Пример #3
0
async def get_mission(request):
    pretty = 'pretty' in request.query
    as_json = 'json' in request.query

    root_dir = request.app['dedicated_server'].missions_dir

    try:
        relative_path = request.match_info['file_path']
        absolute_path = (root_dir / relative_path)
    except Exception:
        LOG.exception("HTTP failed to get mission: incorrect input data")
        return RESTBadRequest(
            detail="incorrect input data",
            pretty=pretty,
        )

    if not absolute_path.exists():
        return RESTNotFound()

    if as_json:
        try:
            result = request.app['mission_parser'].parse(str(absolute_path))
        except Exception:
            LOG.exception(f"HTTP failed to parse mission `{absolute_path}`")
            return RESTInternalServerError(
                detail="failed to parse mission",
                pretty=pretty,
            )
        else:
            return RESTSuccess(payload=result, pretty=pretty)
    else:
        return FileResponse(absolute_path)
Пример #4
0
    async def _handle(self, request):
        rel_url = request.match_info["filename"]
        try:
            filename = Path(rel_url)
            if filename.anchor:
                # rel_url is an absolute name like
                # /static/\\machine_name\c$ or /static/D:\path
                # where the static dir is totally different
                raise HTTPForbidden()
            filepath = self._directory.joinpath(filename).resolve()
            if not self._follow_symlinks:
                filepath.relative_to(self._directory)
        except (ValueError, FileNotFoundError) as error:
            # relatively safe
            raise HTTPNotFound() from error
        except Exception as error:
            # perm error or other kind!
            request.app.logger.exception(error)
            raise HTTPNotFound() from error

        # on opening a dir, load its contents if allowed
        if filepath.is_dir():
            return await super()._handle(request)
        if filepath.is_file():
            return FileResponse(filepath,
                                chunk_size=self._chunk_size,
                                headers=CACHE_HEADERS)
        raise HTTPNotFound
Пример #5
0
    def _serve_content_artifact(self, content_artifact, headers):
        """
        Handle response for a Content Artifact with the file present.

        Depending on where the file storage (e.g. filesystem, S3, etc) this could be responding with
        the file (filesystem) or a redirect (S3).

        Args:
            content_artifact (:class:`pulpcore.app.models.ContentArtifact`): The Content Artifact to
                respond with.
            headers (dict): A dictionary of response headers.

        Raises:
            :class:`aiohttp.web_exceptions.HTTPFound`: When we need to redirect to the file
            NotImplementedError: If file is stored in a file storage we can't handle

        Returns:
            The :class:`aiohttp.web.FileResponse` for the file.
        """
        if settings.DEFAULT_FILE_STORAGE == 'pulpcore.app.models.storage.FileSystem':
            filename = content_artifact.artifact.file.name
            return FileResponse(os.path.join(settings.MEDIA_ROOT, filename), headers=headers)
        elif (settings.DEFAULT_FILE_STORAGE == 'storages.backends.s3boto3.S3Boto3Storage' or
              settings.DEFAULT_FILE_STORAGE == 'storages.backends.azure_storage.AzureStorage'):
            artifact_file = content_artifact.artifact.file
            content_disposition = f'attachment;filename={content_artifact.relative_path}'
            parameters = {"ResponseContentDisposition": content_disposition}
            url = artifact_file.storage.url(artifact_file.name, parameters=parameters)
            raise HTTPFound(url)
        else:
            raise NotImplementedError()
Пример #6
0
 def serve_static(template: str, path=DefaultPaths.STATIC_TEMPLATES):
     """
     Serve static files easily
     :param template: template file name
     :param path: path to directory
     :return: file response
     """
     return FileResponse(path=path / template)
Пример #7
0
    async def handle_frontend_request(self, request):
        # websocket
        if (request.method == 'GET'
                and request.headers.get('upgrade', '').lower() == 'websocket'):

            return await self.handle_frontend_websocket(request)

        response = FileResponse(FRONTENT_HTML)

        return response
Пример #8
0
async def interface_handle(request):
    interface_name = request.match_info["interface"]
    local_directory = join(dirname(__file__), "web_interfaces", interface_name)
    index_file = join(local_directory, "index.html")

    if not isfile(index_file):
        index_file = join(local_directory, "build", "index.html")

    if isfile(index_file):
        return FileResponse(index_file)
    return HTTPNotFound()
Пример #9
0
 async def post(self, request):
     """Retrieve the file."""
     try:
         data = await request.json()
     except ValueError:
         return self.json_message("Invalid JSON", HTTPStatus.BAD_REQUEST)
     file_path = data["filePath"]
     if file_path == "/data/data/pl.sviete.dom/files/home/AIS/ais_welcome.txt":
         if not os.path.isfile(file_path):
             # create empty file
             os.mknod(file_path)
     response = FileResponse(path=file_path)
     return response
Пример #10
0
    async def _serve_content_artifact(self, content_artifact, headers,
                                      request):
        """
        Handle response for a Content Artifact with the file present.

        Depending on where the file storage (e.g. filesystem, S3, etc) this could be responding with
        the file (filesystem) or a redirect (S3).

        Args:
            content_artifact (:class:`pulpcore.app.models.ContentArtifact`): The Content Artifact to
                respond with.
            headers (dict): A dictionary of response headers.
            request(:class:`~aiohttp.web.Request`): The request to prepare a response for.

        Raises:
            :class:`aiohttp.web_exceptions.HTTPFound`: When we need to redirect to the file
            NotImplementedError: If file is stored in a file storage we can't handle

        Returns:
            The :class:`aiohttp.web.FileResponse` for the file.
        """
        artifact_file = content_artifact.artifact.file
        artifact_name = artifact_file.name

        if settings.DEFAULT_FILE_STORAGE == "pulpcore.app.models.storage.FileSystem":
            return FileResponse(os.path.join(settings.MEDIA_ROOT,
                                             artifact_name),
                                headers=headers)
        elif settings.DEFAULT_FILE_STORAGE == "storages.backends.s3boto3.S3Boto3Storage":
            content_disposition = f"attachment;filename={content_artifact.relative_path}"
            parameters = {"ResponseContentDisposition": content_disposition}
            if headers.get("Content-Type"):
                parameters["ResponseContentType"] = headers.get("Content-Type")
            url = URL(
                artifact_file.storage.url(artifact_file.name,
                                          parameters=parameters,
                                          http_method=request.method),
                encoded=True,
            )
            raise HTTPFound(url)
        elif settings.DEFAULT_FILE_STORAGE == "storages.backends.azure_storage.AzureStorage":
            content_disposition = f"attachment;filename={artifact_name}"
            parameters = {"content_disposition": content_disposition}
            if headers.get("Content-Type"):
                parameters["content_type"] = headers.get("Content-Type")
            url = URL(artifact_file.storage.url(artifact_name,
                                                parameters=parameters),
                      encoded=True)
            raise HTTPFound(url)
        else:
            raise NotImplementedError()
Пример #11
0
        def gen_response(content):
            # 404
            if not content:
                self.logger.debug('404: not found')

                return Response(text='404: not found', status=404)

            # file response
            if isinstance(content, str):
                return FileResponse(content)

            # content response
            output = self.context.render(content)

            return Response(text=output, content_type='text/html')
Пример #12
0
    async def handle_static_file_request(self, request):
        def find_static_file():
            rel_path = request.match_info['path']

            abs_path = os.path.join(STATIC_ROOT, rel_path)
            file_exists = os.path.exists(abs_path)

            return file_exists, abs_path

        file_exists, path = await self.run_function_async(find_static_file, )

        if not file_exists:
            return Response(
                status=404,
                text='404: Not found',
            )

        return FileResponse(path)
Пример #13
0
    def _render_response(self, response_dict):
        if response_dict['file']:
            return FileResponse(response_dict['file'])

        if response_dict['redirect']:
            return HTTPFound(response_dict['redirect'])

        if response_dict['http_redirect']:
            return HTTPFound(response_dict['http_redirect'])

        response = Response(
            status=response_dict['status'],
            content_type=response_dict['content_type'],
            text=response_dict['text'],
        )

        response.headers[
            'Cache-Control'] = 'no-cache, no-store, must-revalidate'  # NOQA

        return response
Пример #14
0
    async def get(  # pylint: disable=no-self-use
        self,
        request: Request,
        slug: str,
    ) -> FileResponse | Response:
        """Download a backup file."""
        if not request["hass_user"].is_admin:
            return Response(status=HTTPStatus.UNAUTHORIZED)

        manager: BackupManager = request.app["hass"].data[DOMAIN]
        backup = await manager.get_backup(slug)

        if backup is None or not backup.path.exists():
            return Response(status=HTTPStatus.NOT_FOUND)

        return FileResponse(
            path=backup.path.as_posix(),
            headers={
                CONTENT_DISPOSITION: f"attachment; filename={slugify(backup.name)}.tar"
            },
        )
Пример #15
0
    async def get(self, request):
        _raw_path = request.rel_url.raw_path
        # _log_info(request.rel_url)
        if _raw_path == self.url:
            # 提示地址
            _tips_location = '/' + DOMAIN + '/' + VERSION + '/dist/tips.html?msg='
            if 'key' in request.query:
                _key = request.query['key']
                global API_KEY_LIST
                if _key in API_KEY_LIST:
                    # 如果Key超过一天,则提示过期
                    if (API_KEY_LIST[_key] -
                            datetime.datetime.now()).seconds < 3600 * 60 * 24:
                        # 这里执行删除key的操作
                        del API_KEY_LIST[_key]
                        # 这里解析服务
                        _action = urllib.parse.unquote(request.query['action'])
                        arr = _action.split('.', 1)
                        if arr[0] == 'script':
                            await HASS.services.async_call(
                                'script', str(arr[1]))
                        elif arr[0] == 'automation':
                            await HASS.services.async_call(
                                'automation', 'trigger',
                                {'entity_id': _action})
                        return web.HTTPFound(location=_tips_location +
                                             '执行成功&id=' + _action)
                    else:
                        return web.HTTPFound(location=_tips_location +
                                             '通信密钥已过期')
                else:
                    return web.HTTPFound(location=_tips_location +
                                         '该操作【已执行】或者【已过期】')
            #a = urllib.parse.unquote(_api)

        _path = os.path.dirname(__file__) + _raw_path.replace(
            '/' + DOMAIN + '/' + VERSION, '')
        return FileResponse(_path)
Пример #16
0
 async def get(self, request):
     # _LOGGER.info(request.rel_url.raw_path)
     return FileResponse(
         os.path.dirname(__file__) +
         request.rel_url.raw_path.replace(self.url, ''))
Пример #17
0
 async def handler(request: Request) -> FileResponse:
     filters = json.loads(request.query.get('filter'))
     start, end = filters.get('filters')[0].get('values')
     return FileResponse(f"test/resources/server/{report}_{start}_{end}.xml")
Пример #18
0
async def index_handler(request):
    '''
    send static index file
    '''
    return FileResponse('./static/index.html')
Пример #19
0
async def setup(request):
    return FileResponse("./static/index.html")
Пример #20
0
 async def get(self):
     return FileResponse(path=this_path + '/static/favicon.ico', status=200)
Пример #21
0
 async def index(self, request):
     ''' index response '''
     return FileResponse(os.path.join(self.path, "index.html"))
Пример #22
0
 async def get(self, request):
     _raw_path = request.rel_url.raw_path
     _path = os.path.dirname(__file__) + '/more-info-shbus.js'
     return FileResponse(_path)
Пример #23
0
async def robots(request):
    return FileResponse(ROBOTS_TXT)
Пример #24
0
 async def get(self, request):
     return FileResponse('app/data/schools.json')
Пример #25
0
async def index(request: Request):
    return FileResponse('index.html')
Пример #26
0
async def get_index(request: Request) -> FileResponse:
    return FileResponse(assets_path / 'pages' / 'index.html')
Пример #27
0
 async def get(self):
     return FileResponse(path=this_path + '/index.html', status=200)
Пример #28
0
    async def _match_and_stream(self, path, request):
        """
        Match the path and stream results either from the filesystem or by downloading new data.

        Args:
            path (str): The path component of the URL.
            request(:class:`~aiohttp.web.Request`): The request to prepare a response for.

        Raises:
            PathNotResolved: The path could not be matched to a published file.
            PermissionError: When not permitted.

        Returns:
            :class:`aiohttp.web.StreamResponse` or :class:`aiohttp.web.FileResponse`: The response
                streamed back to the client.
        """
        distribution = Handler._match_distribution(path)
        self._permit(request, distribution)
        publication = distribution.publication
        if not publication:
            raise PathNotResolved(path)
        rel_path = path.lstrip('/')
        rel_path = rel_path[len(distribution.base_path):]
        rel_path = rel_path.lstrip('/')

        # published artifact
        try:
            pa = publication.published_artifact.get(relative_path=rel_path)
            ca = pa.content_artifact
        except ObjectDoesNotExist:
            pass
        else:
            if ca.artifact:
                return FileResponse(ca.artifact.file.name)
            else:
                return await self._stream_content_artifact(
                    request, StreamResponse(), ca)

        # published metadata
        try:
            pm = publication.published_metadata.get(relative_path=rel_path)
        except ObjectDoesNotExist:
            pass
        else:
            return FileResponse(pm.file.name)

        # pass-through
        if publication.pass_through:
            try:
                ca = ContentArtifact.objects.get(
                    content__in=publication.repository_version.content,
                    relative_path=rel_path)
            except MultipleObjectsReturned:
                log.error(_('Multiple (pass-through) matches for {b}/{p}'), {
                    'b': distribution.base_path,
                    'p': rel_path,
                })
                raise
            except ObjectDoesNotExist:
                pass
            else:
                if ca.artifact:
                    return FileResponse(ca.artifact.file.name)
                else:
                    return await self._stream_content_artifact(
                        request, StreamResponse(), ca)
        raise PathNotResolved(path)
Пример #29
0
 async def _logoAddon(self, request: Request):
     await self._verifyHeader(request)
     return FileResponse(
         'hassio-google-drive-backup/backup/static/images/logo.png')
Пример #30
0
async def index(request):
    # for development:
    # path = build_index()
    # return Response(body=path.read_bytes(), content_type='text/html')
    return FileResponse(request.app['index_path'])