Beispiel #1
0
    def make_request(self, method, path, query_params={}, headers=None,
                     match_info=None):
        if query_params:
            path = '%s?%s' % (path, urllib.parse.urlencode(query_params))

        # Ported from:
        # https://github.com/KeepSafe/aiohttp/blob/fa06acc2392c516491bdb25301ad3ef2b700ff5f/tests/test_web_websocket.py#L21-L45  # noqa
        self.app = mock.Mock()
        self.app._debug = False
        if headers is None:
            headers = CIMultiDict(
                {'HOST': 'server.example.com',
                 'UPGRADE': 'websocket',
                 'CONNECTION': 'Upgrade',
                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',
                 'ORIGIN': 'http://example.com',
                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',
                 'SEC-WEBSOCKET-VERSION': '13'})

        message = make_raw_request_message(method, path, headers)
        self.payload = mock.Mock()
        self.transport = mock.Mock()
        self.reader = mock.Mock()
        self.writer = mock.Mock()
        self.app.loop = self.loop
        self.app.on_response_prepare = Signal(self.app)
        req = Request(self.app, message, self.payload,
                      self.transport, self.reader, self.writer)
        req._match_info = match_info
        return req
Beispiel #2
0
def create_session(request: web.Request):
    body = yield from request.json()
    desired_capabilities = body.get("desiredCapabilities")
    request.session = Session(desired_capabilities)
    response = yield from start_session(request)
    return web.Response(
        status=response.status,
        headers=response.headers,
        body=(yield from response.read_and_close())
    )
Beispiel #3
0
def add_track_to_queue(request: web.Request):
    data = yield from request.json()
    queue_manager = yield from service_registry.get("queue_manager")
    uri = data["uri"]
    track = yield from queue_manager.add_to_queue(uri)
    logging.debug("User {} added song {} - {}".format(request.headers["X-Forwarded-For"], track.artists, track.title))
    return {"status": "ok"}
Beispiel #4
0
    def post(self, request: Request) -> Response:
        """Handle Google Assistant requests."""
        auth = request.headers.get(AUTHORIZATION, None)
        if 'Bearer {}'.format(self.access_token) != auth:
            return self.json_message(
                "missing authorization", status_code=HTTP_UNAUTHORIZED)

        data = yield from request.json()  # type: dict

        inputs = data.get('inputs')  # type: list
        if len(inputs) != 1:
            _LOGGER.error('Too many inputs in request %d', len(inputs))
            return self.json_message(
                "too many inputs", status_code=HTTP_BAD_REQUEST)

        request_id = data.get('requestId')  # type: str
        intent = inputs[0].get('intent')
        payload = inputs[0].get('payload')

        hass = request.app['hass']  # type: HomeAssistant
        res = None
        if intent == 'action.devices.SYNC':
            res = yield from self.handle_sync(hass, request_id)
        elif intent == 'action.devices.QUERY':
            res = yield from self.handle_query(hass, request_id,
                                               payload.get('devices', []))
        elif intent == 'action.devices.EXECUTE':
            res = yield from self.handle_execute(hass, request_id,
                                                 payload.get('commands', []))

        if res:
            return res

        return self.json_message(
            "invalid intent", status_code=HTTP_BAD_REQUEST)
Beispiel #5
0
    def session_extractor(request: web.Request):
        session_id = request.match_info.get("session_id")
        if session_id:
            session = Sessions.find(session_id)
        else:
            session = None

        request.session = session
        return (yield from handler(request))
    async def handler(self, request: web.Request) -> web.Response:
        lang = request.get('lang')

        try:
            posts = await self.post_service.get_all(lang)

            return self.router_service.send_success_response(self.name, posts)
        except Exception as error:
            return self.router_service.send_unexpected_error_response(
                self.name, error)
Beispiel #7
0
 def make_request(self, method, path, headers=MultiDict()):
     self.app = mock.Mock()
     message = RawRequestMessage(method, path, HttpVersion11, headers,
                                 False, False)
     self.payload = mock.Mock()
     self.transport = mock.Mock()
     self.writer = mock.Mock()
     req = Request(self.app, message, self.payload, self.transport,
                   self.writer, 15)
     return req
    def post(self, request: Request) -> Response:
        """Handle Google Assistant requests."""
        auth = request.headers.get(AUTHORIZATION, None)
        if 'Bearer {}'.format(self.access_token) != auth:
            return self.json_message("missing authorization", status_code=401)

        message = yield from request.json()  # type: dict
        result = yield from async_handle_message(request.app['hass'],
                                                 self.gass_config, message)
        return self.json(result)
Beispiel #9
0
def load_cred_request(form, schema, request: web.Request) -> dict:
    """
    Create a new credential request from a `submit-credential` form definition, fetching
    input from the client request as necessary
    """

    cred = {}
    mapping = form.get('mapping') or {}
    if mapping.get('fill_defaults', True):
        for attr in schema.attr_names:
            cred[attr] = request.get(attr)
            LOGGER.info("credential %s %s", attr, cred[attr])
    map_attr = mapping.get('attributes') or []
    # Build credential data from schema mapping
    for attribute in map_attr:
        attr_name = attribute.get('name')
        from_type = attribute.get('from', 'request')
        # Handle getting value from request data
        if from_type == 'request':
            source = attribute.get('source', attr_name)
            cred[attr_name] = request.get(source)
        # Handle getting value from helpers (function defined in config)
        elif from_type == 'helper':
            helper = getattr(helpers, attribute['source'], None)
            if not helper:
                raise Exception('Cannot find helper "%s"' %
                                attribute['source'])
            cred[attribute['name']] = helper()
        # Handle setting value with string literal or None
        elif from_type == 'literal':
            cred[attr_name] = attribute.get('source')
        # Handle getting value already set on schema skeleton
        elif from_type == 'previous':
            source = attribute.get('source')
            if source:
                try:
                    cred[attr_name] = cred[source]
                except KeyError:
                    raise ValueError('Cannot find previous value "%s"' %
                                     source)
        else:
            raise ValueError('Unkown mapping type "%s"' % attribute['from'])
    return cred
Beispiel #10
0
 async def handle_plugin_path(self, request: web.Request) -> web.StreamResponse:
     for path, app in self.plugin_routes.items():
         if request.path.startswith(path):
             request = request.clone(
                 rel_url=request.rel_url.with_path(
                     request.rel_url.path[len(path) :]
                 ).with_query(request.query_string)
             )
             return await app.handle(request)
     return web.Response(status=404)
Beispiel #11
0
async def create_user(request: web.Request) -> web.Response:
    data = await request.json()
    for field in ("first_name", "last_name"):
        if field not in data:
            raise web.HTTPBadRequest(text=f'{{"detail": "Missing `{field}`"}}')
        if not isinstance(data[field], str):
            raise web.HTTPBadRequest(text=f'{{"detail": "Invalid `{field}`"}}')
    user_id = str(uuid4())
    request.app["users"][user_id] = {**data, "id": user_id}
    return web.json_response({"id": user_id}, status=201)
Beispiel #12
0
async def logout(request: web.Request) -> web.Response:
    response = flash_response(cfg.MSG_LOGGED_OUT, "INFO")
    user_id = request.get(RQT_USERID_KEY, -1)
    client_session_id = None
    if request.can_read_body:
        body = await request.json()
        client_session_id = body.get("client_session_id", None)
    await observer.emit("SIGNAL_USER_LOGOUT", user_id, client_session_id, request.app)
    await forget(request, response)
    return response
Beispiel #13
0
def request_from_message(message, **kwargs):
    app = kwargs.get('app') or mock.Mock()
    app._debug = False
    app.on_response_prepare = signals.Signal(app)
    payload = mock.Mock()
    transport = mock.Mock()
    reader = mock.Mock()
    writer = kwargs.get('writer') or mock.Mock()
    req = Request(app, message, payload, transport, reader, writer)
    return req
Beispiel #14
0
async def create_user(request: web.Request) -> web.Response:
    data = await request.json()
    if "username" not in data:
        raise web.HTTPBadRequest(text='{"detail": "Missing `username`"}')
    if not isinstance(data["username"], str):
        raise web.HTTPBadRequest(text='{"detail": "Invalid `username`"}')
    user_id = len(request.app["users"]) + 1
    request.app["users"][user_id] = {**data, "id": user_id}
    request.app["requests_history"][user_id].append("POST")
    return web.json_response({"id": user_id}, status=201)
Beispiel #15
0
    async def _authenticate_user(self, request: Request):
        """
        If the area features membership, it invokes the methods of the underlying membership provider to authenticate
        the user, supporting anonymous authentication.

        :param request: request to authenticate.
        """
        request.user = None
        encryption_key = self.config.encryption_key
        membership = self.membership
        set_anonymous_session = False

        if self.membership:
            # does the request contains the session cookie for this area?
            session_cookie_name = self.config.session_cookie_name
            session_key = request.cookies.get(session_cookie_name)
            if session_key:
                # try to load the session
                # decrypt the session key
                success, session_guid = AesEncryptor.try_decrypt(
                    session_key, encryption_key)
                if success:
                    # try to perform login by session key
                    success, result = await membership.try_login_by_session_key(
                        session_guid)
                    if success:
                        # result is a principal object
                        request.user = result.principal
                        request.session = result.session
                    else:
                        # the login by session cookie failed: the session could be expired
                        set_anonymous_session = True
                else:
                    # session key decryption failed
                    set_anonymous_session = True
            else:
                # the request does not contain a session cookie for this area
                set_anonymous_session = True

        if set_anonymous_session:
            # initialize an anonymous session
            await self.initialize_anonymous_session(request)
        return self
Beispiel #16
0
    def post(self, request: Request) -> Response:
        """Handle Google Assistant requests."""
        auth = request.headers.get(AUTHORIZATION, None)
        if 'Bearer {}'.format(self.access_token) != auth:
            return self.json_message("missing authorization", status_code=401)

        message = yield from request.json()  # type: dict
        result = yield from async_handle_message(
            request.app['hass'], self.gass_config, message)
        return self.json(result)
Beispiel #17
0
    async def _command_proxy(
            self, path: str,
            request: web.Request) -> Union[web.Response, web.StreamResponse]:
        """Return a client request with proxy origin for Hass.io supervisor.

        This method is a coroutine.
        """
        read_timeout = _get_timeout(path)
        data = None
        headers = _init_header(request)
        if path == "snapshots/new/upload":
            # We need to reuse the full content type that includes the boundary
            headers["Content-Type"] = request._stored_content_type  # pylint: disable=protected-access

            # Snapshots are big, so we need to adjust the allowed size
            request._client_max_size = (  # pylint: disable=protected-access
                MAX_UPLOAD_SIZE)

        try:
            with async_timeout.timeout(10):
                data = await request.read()

            method = getattr(self._websession, request.method.lower())
            client = await method(
                f"http://{self._host}/{path}",
                data=data,
                headers=headers,
                timeout=read_timeout,
            )

            # Simple request
            if int(client.headers.get(CONTENT_LENGTH, 0)) < 4194000:
                # Return Response
                body = await client.read()
                return web.Response(content_type=client.content_type,
                                    status=client.status,
                                    body=body)

            # Stream response
            response = web.StreamResponse(status=client.status)
            response.content_type = client.content_type

            await response.prepare(request)
            async for data in client.content.iter_chunked(4096):
                await response.write(data)

            return response

        except aiohttp.ClientError as err:
            _LOGGER.error("Client error on api %s request %s", path, err)

        except asyncio.TimeoutError:
            _LOGGER.error("Client timeout error on API request %s", path)

        raise HTTPBadGateway()
Beispiel #18
0
def load_cred_request(form, attr_names, request: web.Request) -> dict:
    """
    Create a new credential request from a `issue-credential` form definition, fetching
    input from the client request as necessary
    """

    cred = {}
    mapping = form.get("mapping") or {}
    if mapping.get("fill_defaults", True):
        for attr in attr_names:
            cred[attr] = request.get(attr)
            LOGGER.debug("credential %s %s", attr, cred[attr])
    map_attr = mapping.get("attributes") or []
    # Build credential data from schema mapping
    for attribute in map_attr:
        attr_name = attribute.get("name")
        from_type = attribute.get("from", "request")
        # Handle getting value from request data
        if from_type == "request":
            source = attribute.get("source", attr_name)
            cred[attr_name] = request.get(source)
        # Handle getting value from helpers (function defined in config)
        elif from_type == "helper":
            helper = getattr(helpers, attribute["source"], None)
            if not helper:
                raise ValueError("Cannot find helper '{}'".format(attribute["source"]))
            cred[attribute["name"]] = helper()
        # Handle setting value with string literal or None
        elif from_type == "literal":
            cred[attr_name] = attribute.get("source")
        # Handle getting value already set on schema skeleton
        elif from_type == "previous":
            source = attribute.get("source")
            if source:
                try:
                    cred[attr_name] = cred[source]
                except KeyError:
                    raise ValueError(
                        "Cannot find previous value '{}'".format(source))
        else:
            raise ValueError("Unknown mapping type '{}'".format(attribute["from"]))
    return cred
Beispiel #19
0
	async def middlewareHandler(self, WebRequest:web.Request, handler:Callable) -> web.Response:
		WebRequest.__class__ = ExtendedRequest # people told me to never do this... well f**k it i do it anyways
		WebRequest:ExtendedRequest
		WebRequest.WebUser = None
		WebRequest.DiscordUser = None
		WebRequest.TwitchUser = None

		try:
			if str(handler.__name__) in ["_handle"]:
				raise FileNotFoundError()

			if not self.BASE.Active.web:
				return await self.Tree.Api.errors.apiNotAllowed(self, WebRequest, msg="Web is disabled and will be shutdown soon")

			if not self.BASE.Active.api and WebRequest.path.startswith("/api"):
				return await self.Tree.Api.errors.apiNotAllowed(self, WebRequest, msg="API endpoint is not enabled")

			response:web.Response = await handler(self, WebRequest)
			return response

		except web.HTTPException as HTTPEx:
			return self.response(
				body=json.dumps(dict(msg=HTTPEx.reason, status=HTTPEx.status)),
				status=HTTPEx.status,
				content_type='application/json'
			)

		except FileNotFoundError:
			if WebRequest.path.startswith("/api"):
				return await self.Tree.Api.errors.apiUnknown(self, WebRequest)
			else:
				return await self.Tree.errors.notFound(self, WebRequest)

		except Exception as e:
			tb:str = traceback.format_exc()
			self.BASE.Logger.error(f"(Web) Error in request: {str(e)}\n{tb}")
			error:str = str(e) if CliArgs.get("debug") == "all" else "Unknown error"
			return self.response(
				status=500,
				body=json.dumps(dict(msg=error, status=500)),
				content_type='application/json'
			)
Beispiel #20
0
async def post_image(request: web.Request) -> web.Response:
    """Post a job"""
    req = await request.json()
    urls = req.get('urls', None)
    if urls is None:
        return web.Response(status=400,
                            text='Bad',
                            reason='Bad Request. No `urls` field.')
    job_id = str(uuid.uuid4())
    request.app['jobs'][job_id] = _submit_job(job_id, urls)
    return web.Response(text=job_id + '\n')
Beispiel #21
0
    async def logout(self, req: Request) -> Response:
        """Log the user out by revoking tokens.

        :param req: A HTTP request instance
        :raises: HTTPBadRequest in case logout failed
        :returns: HTTPSeeOther redirect to login page
        """
        # Revoke token at AAI
        req.app["Session"]["access_token"] = None
        req.app["Session"]["user_info"] = None
        req.app["Session"]["oidc_state"] = None
        req.app["Session"] = {}
        req.app["Cookies"] = set({})

        response = web.HTTPSeeOther(f"{self.redirect}/")
        response.headers[
            "Location"] = "/" if self.redirect == self.domain else f"{self.redirect}/"
        LOG.debug("Logged out user ")

        raise response
Beispiel #22
0
    def get_error_body(self, request: web.Request, error: Exception) -> dict:

        """ Формирует и отдает словарь с телом ответа с ошибкой. Для поля оболочки id использует сохраненное в
        request значение. """
        # Так как мы знаем какая у нас оболочка ответа, сразу сделаем словарь
        # с аналогичной "схемой"
        result = dict(error_type=str(type(error)), error_message=str(error))
        response = dict(
            success=False, result=result, id=request.get(KEY_NAME_FOR_ID)
        )
        return response
Beispiel #23
0
 def make_request(self, method, path):
     self.app = mock.Mock()
     message = RawRequestMessage(method, path, HttpVersion(1, 1),
                                 CIMultiDict(), False, False)
     self.payload = mock.Mock()
     self.transport = mock.Mock()
     self.reader = mock.Mock()
     self.writer = mock.Mock()
     req = Request(self.app, message, self.payload, self.transport,
                   self.reader, self.writer)
     return req
Beispiel #24
0
    async def post(self, request: web.Request) -> web.Response:
        """Handle upload."""
        if not request["hass_user"].is_admin:
            raise Unauthorized()

        # Increase max payload
        request._client_max_size = MAX_UPLOAD_SIZE  # pylint: disable=protected-access

        try:
            data = self.schema(dict(await request.post()))
        except vol.Invalid as err:
            LOGGER.error("Received invalid upload data: %s", err)
            raise web.HTTPBadRequest() from err

        try:
            item = MediaSourceItem.from_uri(self.hass,
                                            data["media_content_id"])
        except ValueError as err:
            LOGGER.error("Received invalid upload data: %s", err)
            raise web.HTTPBadRequest() from err

        try:
            source_dir_id, location = self.source.async_parse_identifier(item)
        except Unresolvable as err:
            LOGGER.error("Invalid local source ID")
            raise web.HTTPBadRequest() from err

        uploaded_file: FileField = data["file"]

        if not uploaded_file.content_type.startswith(
            ("image/", "video/", "audio/")):
            LOGGER.error("Content type not allowed")
            raise vol.Invalid("Only images and video are allowed")

        try:
            raise_if_invalid_filename(uploaded_file.filename)
        except ValueError as err:
            LOGGER.error("Invalid filename")
            raise web.HTTPBadRequest() from err

        try:
            await self.hass.async_add_executor_job(
                self._move_file,
                self.source.async_full_path(source_dir_id, location),
                uploaded_file,
            )
        except ValueError as err:
            LOGGER.error("Moving upload failed: %s", err)
            raise web.HTTPBadRequest() from err

        return self.json({
            "media_content_id":
            f"{data['media_content_id']}/{uploaded_file.filename}"
        })
Beispiel #25
0
async def delete_project(request: web.Request):
    project_uuid, uid = request.match_info.get("project_id"), request.get(
        RQT_USERID_KEY, ANONYMOUS_UID)

    try:
        await ProjectDB.delete_user_project(
            uid, project_uuid, db_engine=request.app[APP_DB_ENGINE_KEY])
    except ProjectNotFoundError:
        raise web.HTTPNotFound

    raise web.HTTPNoContent(content_type='application/json')
Beispiel #26
0
async def set_user_in_rooms(sid: str, app: web.Application,
                            request: web.Request) -> None:
    user_id = request.get(RQT_USERID_KEY, ANONYMOUS_USER_ID)
    primary_group, user_groups, all_group = await list_user_groups(
        app, user_id)
    groups = [primary_group
              ] + user_groups + ([all_group] if bool(all_group) else [])
    sio = get_socket_server(app)
    # TODO: check if it is necessary to leave_room when socket disconnects
    for group in groups:
        sio.enter_room(sid, f"{group['gid']}")
Beispiel #27
0
async def manage_lidar(request: Request):
    response = request.json()
    if "action" in response:
        action = response["action"]
        if action == "start":
            pass
        elif action == "stop":
            pass

    data = {'success': True}
    return web.json_response(data)
Beispiel #28
0
    def get_preflight_request_config(self, preflight_request: web.Request,
                                     origin: str, requested_method: str):
        assert self.is_preflight_request(preflight_request)

        request = preflight_request.clone(method=requested_method)
        for route, config in self._route_config.items():
            match_info, allowed_methods = yield from route.resource.resolve(
                request)
            if match_info is not None:
                return collections.ChainMap(config, self._default_config)
        else:
            raise KeyError
Beispiel #29
0
def websocket_rate_limit(r : web.Request, ws : web.WebSocketResponse):
    if LIMIT == 0:
        return False
    burst_max = LIMIT * 100
    pps = LIMIT
    ip = UTIL.get_request_ip(r)
    now = int(time.time())
    if ip not in r.app['limit']:
        r.app['limit'][ip] = {'count':burst_max, 'ts':now}
    else:
        if r.app['limit'][ip]['ts'] < now:
            r.app['limit'][ip]['count'] += (now - r.app['limit'][ip]['ts']) * pps
            r.app['limit'][ip]['ts'] = now
            if r.app['limit'][ip]['count'] > burst_max:
                r.app['limit'][ip]['count'] = burst_max
    if r.app['limit'][ip]['count'] <= 0:
        log.server_logger.error('client messaging too quickly: %s; %s; User-Agent: %s', ip, ws.id, str(
            r.headers.get('User-Agent')))
        return True
    r.app['limit'][ip]['count'] -= 1
    return False
Beispiel #30
0
        async def wrapper(req: web.Request) -> web.StreamResponse:
            content_type_matches = False
            for content_type in content_types:
                if content_type.value == req.content_type:
                    content_type_matches = True
                    break

            if not content_type_matches:
                return web.json_response(
                    {
                        "message":
                        f"Bad content type. Expected: {[c.value for c in content_types]}"
                    },
                    status=400,
                )

            if content_type == ContentType.JSON:
                try:
                    query = await req.json()
                except json.JSONDecodeError as e:
                    return web.json_response(
                        {"message": f"Error parsing json from body: {e}"},
                        status=400,
                    )
            elif content_type in (
                    ContentType.URLENCODED,
                    ContentType.FORM_DATA,
            ):
                query = await req.post()
            else:
                server_log.debug(
                    f"body_params: unknown content type: {content_type}")

            if unique:
                repeating = get_repeating(query.keys())

                if repeating is not None:
                    if json_response:
                        return web.json_response(
                            {repeating: "Repeats in body"}, status=400)

                    raise web.HTTPBadRequest(
                        reason=f"{repeating}: Repeats in body")

            req["body"] = req.get("body", {})

            try:
                req["body"].update(
                    **await converters.convert_map(params, query, req.app))
            except converters.ConvertError as e:
                return e.to_bad_request(json_response)

            return await endpoint(req)
 def make_request(self, method, path, headers=CIMultiDict(), *,
                  version=HttpVersion(1, 1), closing=False):
     self.app = mock.Mock()
     message = RawRequestMessage(method, path, version, headers, closing,
                                 False)
     self.payload = mock.Mock()
     self.transport = mock.Mock()
     self.writer = mock.Mock()
     self.reader = mock.Mock()
     req = Request(self.app, message, self.payload,
                   self.transport, self.reader, self.writer)
     return req
Beispiel #32
0
 async def middleware_handler(request: web.Request) -> web.Response:
     session: Session = SessionMaker()
     request.session = session
     response = await handler(request)
     try:
         session.commit()
     except Exception:
         logger.exception('Failed to commit session, rolling back...')
         session.rollback()
     finally:
         session.close()
     return response
Beispiel #33
0
def transparent(request: web.Request):
    response = yield from aiohttp.request(
        request.method,
        "%s://%s%s" % (request.scheme, request.session.endpoint.address, request.path),
        headers=request.headers,
        data=(yield from request.read())
    )
    return web.Response(
        status=response.status,
        headers=response.headers,
        body=(yield from response.read_and_close())
    )
Beispiel #34
0
async def python_eval(
        req: web.Request) -> Union[Dict[str, Any], web.StreamResponse]:
    if not req.config_dict["args"].with_eval:
        raise web.HTTPForbidden(reason="Python eval page not ebabled")

    if req.app.get("eval-session", None) is not None:
        raise web.HTTPConflict(reason="Eval session already launched")

    ws_current = web.WebSocketResponse()
    ws_ready = ws_current.can_prepare(req)
    if not ws_ready.ok:
        return {}

    await ws_current.prepare(req)

    req.app["eval-session"] = ws_current

    async for msg in ws_current:
        if msg.type == aiohttp.WSMsgType.text:
            server_log.warn(
                f"Evaluating code from python eval page: {msg.data}")
            try:
                stdout, tb, returned = await eval_code(msg.data, req)
            except CompilationError as e:
                await ws_current.send_json({
                    "action": "eval_compilation_error",
                    "text": str(e)
                })
                continue

            await ws_current.send_json({
                "action": "eval_result",
                "stdout": stdout,
                "traceback": tb,
                "returned": str(returned),
            })

    req.app["eval-session"] = None

    return ws_current
Beispiel #35
0
async def index(request: web.Request):
    """
    The API index

    A standard HTTP request will return a sample page with a simple example of api use.
    A WebSocket request will initiate a websocket connection making it possible to retrieve measurement and simulation data.

    Available endpoints are
    - /client for information about the clients websocket connections
    - /datasources/ for measurement data sources
    - /processors/ for running processors on the data
    - /blueprints/ for the blueprints used to create processors
    - /fmus/ for available FMUs (for the fmu blueprint)
    - /models/ for available models (for the fedem blueprint)
    - /topics/ for all available data sources (datasources and processors)
    """
    print("before session")
    session = await get_session(request)
    ws = web.WebSocketResponse()  # TODO: fix heartbeat clientside?
    session['id'] = client_id = request.remote  # TODO: better id
    print("after session")
    if ws.can_prepare(request):
        await ws.prepare(request)
        if client_id not in request.app['clients']:
            print("HELLOOOo")
            print("HELLOOOo")
            print("HELLOOOo")
            logger.info('New connection from %s', request.remote)
            request.app['clients'][client_id] = Client()
        else:
            logger.info('Reconnection from %s', request.remote)
        client = request.app['clients'][client_id]
        await client.add_websocket_connection(ws)
        try:
            async for message in ws:  # type: WSMessage
                try:
                    if message.data == '__ping__':
                        await ws.send_bytes(b'')
                    # else:
                    #     print(message.json())
                except AttributeError as e:
                    logger.exception('Error receiving message from %s',
                                     client_id)
            return ws
        finally:
            logger.info('Closing %s', request.remote)
            await client.remove_websocket_connection(ws)
            await ws.close()
    else:
        with open('html/index.html', 'r') as file:
            body = file.read()
        return web.Response(body=body, content_type='text/html')
Beispiel #36
0
    async def get_quill(self, request: web.Request):
        if 'filename2' in request.match_info:
            request.match_info['filename'] = request.match_info['filename'] + "/" + request.match_info['filename2']
        try:
            with open('public/' + request.match_info['filename'], 'rb') as qf:
                data = qf.read()
        except FileNotFoundError:
            raise web.HTTPNotFound()

        resp = web.Response(body=data)
        resp.headers['content-type'] = "text/" + request.match_info['filename'].strip("/").split(".")[-1]
        # print(resp.headers)
        return resp
Beispiel #37
0
async def get_project(request: web.Request):
    """Returns all projects accessible to a user (not necesarly owned)"""
    # TODO: temporary hidden until get_handlers_from_namespace refactor to seek marked functions instead!
    user_id, product_name = request[RQT_USERID_KEY], request[RQ_PRODUCT_KEY]
    try:
        project_uuid = request.match_info["project_id"]
    except KeyError as err:
        raise web.HTTPBadRequest(
            reason=f"Invalid request parameter {err}") from err

    user_available_services: List[
        Dict] = await catalog.get_services_for_user_in_product(
            request.app, user_id, product_name, only_key_versions=True)

    try:
        project = await projects_api.get_project_for_user(
            request.app,
            project_uuid=project_uuid,
            user_id=user_id,
            include_templates=True,
            include_state=True,
        )
        if not await project_uses_available_services(project,
                                                     user_available_services):
            unavilable_services = get_project_unavailable_services(
                project, user_available_services)
            formatted_services = ", ".join(
                f"{service}:{version}"
                for service, version in unavilable_services)
            # TODO: lack of permissions should be notified with https://httpstatuses.com/403 web.HTTPForbidden
            raise web.HTTPNotFound(reason=(
                f"Project '{project_uuid}' uses unavailable services. Please ask "
                f"for permission for the following services {formatted_services}"
            ))

        if new_uuid := request.get(RQ_REQUESTED_REPO_PROJECT_UUID_KEY):
            project["uuid"] = new_uuid

        return {"data": project}
Beispiel #38
0
def _init_header(request: web.Request) -> Dict[str, str]:
    """Create initial header."""
    headers = {
        X_HASSIO: os.environ.get('HASSIO_TOKEN', ""),
        CONTENT_TYPE: request.content_type,
    }

    # Add user data
    user = request.get('hass_user')
    if user is not None:
        headers[X_HASS_USER_ID] = request['hass_user'].id
        headers[X_HASS_IS_ADMIN] = str(int(request['hass_user'].is_admin))

    return headers
    def get_preflight_request_config(
            self,
            preflight_request: web.Request,
            origin: str,
            requested_method: str):
        assert self.is_preflight_request(preflight_request)

        request = preflight_request.clone(method=requested_method)
        for route, config in self._route_config.items():
            match_info, allowed_methods = yield from route.resource.resolve(
                request)
            if match_info is not None:
                return collections.ChainMap(config, self._default_config)
        else:
            raise KeyError
Beispiel #40
0
def start_session(request: web.Request):
    session = request.session
    session.endpoint = AndroidEndpoint()
    try:
        yield from session.endpoint.start(session.desired_capabilities)
        headers = {k: v for k, v in request.headers.items() if k != hdrs.HOST}
        response = yield from aiohttp.request(
            request.method,
            "%s://%s%s" % (request.scheme, session.endpoint.address, request.path),
            headers=headers,
            data=(yield from request.read())
        )
        if response.status == 200:
            body = yield from response.json()
            session.session_id = session.remote_session_id = body.get('sessionId')
        else:
            session.close()
    except:
        session.close()
        raise
    return response
Beispiel #41
0
 def create(self, request: Request):
     data = yield from request.json()
     return Response(status=200, body=(json.dumps(data)).encode())
Beispiel #42
0
    def validate(self, request: web.Request):
        """ Returns parameters extract from request and multidict errors

        :param request: Request
        :return: tuple of parameters and errors
        """
        parameters = {}
        files = {}
        errors = defaultdict(set)

        if request.method not in request.POST_METHODS:
            body = None
        elif request.content_type in (
                'application/x-www-form-urlencoded',
                'multipart/form-data'):
            try:
                body = yield from request.post()
            except Exception:
                body = Exception('Bad form')
        elif request.content_type == 'application/json':
            try:
                body = yield from request.json()
            except Exception:
                body = Exception('Bad json')
        else:
            body = None

        for name, param in self._parameters.items():
            where = param['in']
            vtype = param['type']
            is_array = vtype == 'array'

            if where == 'query':
                source = request.GET
            elif where == 'header':
                source = request.headers
            elif where == 'path':
                source = request.match_info
            elif body is None:
                source = ()
            elif where == 'formData':
                source = body
            elif where == 'body':
                if isinstance(body, BaseException):
                    errors[name].add(str(body))
                else:
                    parameters[name] = body
                continue
            else:
                raise ValueError(where)

            if is_array and hasattr(source, 'getall'):
                collection_format = param.get('collectionFormat')
                value = get_collection(source, name, collection_format)
            elif isinstance(source, Mapping) and name in source \
                    and (vtype not in ('number', 'integer') or
                         source[name] != ''):
                value = source[name]
            elif 'default' in param:
                parameters[name] = param['default']
                continue
            elif name in self._required:
                errors[name].add('Required')
                if isinstance(source, BaseException):
                    errors[name].add(str(body))
                continue
            else:
                continue

            if is_array:
                vtype = param['items']['type']
                vformat = param['items'].get('format')
            else:
                vformat = param.get('format')

            if source is body and isinstance(body, dict):
                pass
            elif vtype not in ('string', 'file'):
                value = convert(name, value, vtype, vformat, errors)

            if vtype == 'file':
                files[name] = value
            else:
                parameters[name] = value

        parameters = self._validate(parameters, errors)
        parameters.update(files)
        return parameters, errors
Beispiel #43
0
 def update_entity(self, request: Request) -> Response:
     values = yield from request.json()
     yield from GenericValidation.update_entity(_entity, values)
     yield from manager.update_entity(_entity, values)
     return json_response(update_success_message, status=HTTPStatusCodes.SUCCESS.value)
Beispiel #44
0
 def create_entity(self, request: Request) -> Response:
     values = yield from request.json()
     yield from GenericValidation.create_entity(_entity, values)
     result = yield from manager.create_entity(_entity, values)
     return json_response(result, status=HTTPStatusCodes.CREATED.value)