Example #1
0
 def __init__(self, shared_secret: str,
              loop: asyncio.AbstractEventLoop) -> None:
     self.app = web.Application()
     self.ready_wait = loop.create_future()
     self.secret_key = "".join(
         random.choices(string.ascii_lowercase + string.digits, k=64))
     self.shared_secret = shared_secret
     for path in ("whoami", "login", "login/prepare", "login/2fa",
                  "login/check_approved", "login/approved", "logout",
                  "disconnect", "reconnect", "refresh"):
         self.app.router.add_options(f"/api/{path}", self.login_options)
     self.app.router.add_get("/api/whoami", self.status)
     self.app.router.add_post("/api/login/prepare", self.login_prepare)
     self.app.router.add_post("/api/login", self.login)
     self.app.router.add_post("/api/login/2fa", self.login_2fa)
     self.app.router.add_get("/api/login/check_approved",
                             self.login_check_approved)
     self.app.router.add_post("/api/login/approved", self.login_approved)
     self.app.router.add_post("/api/logout", self.logout)
     self.app.router.add_post("/api/disconnect", self.disconnect)
     self.app.router.add_post("/api/reconnect", self.reconnect)
     self.app.router.add_post("/api/refresh", self.refresh)
     self.app.router.add_static(
         "/",
         pkg_resources.resource_filename("mautrix_facebook.web", "static/"))
Example #2
0
def _exec_listener_thread_safe(loop: AbstractEventLoop,
                               listener: ListenerCb[K], context: Context,
                               event_instance: K) -> "Future[None]":
    # Create an internal future to better control the listener result
    result_future: "Future[None]" = loop.create_future()
    listener_loop = retrieve_loop_from_listener(listener) or loop
    if loop is listener_loop:
        context.run(
            _exec_listener,
            loop,
            result_future.cancel,
            result_future.set_exception,
            result_future.set_result,
            listener,
            event_instance,
        )
    else:
        listener_loop.call_soon_threadsafe(
            context.run,
            _exec_listener,
            listener_loop,
            partial(loop.call_soon_threadsafe, result_future.cancel),
            partial(loop.call_soon_threadsafe, result_future.set_exception),
            partial(loop.call_soon_threadsafe, result_future.set_result),
            listener,
            event_instance,
        )

    return result_future
Example #3
0
 def __init__(self, dt: datetime.datetime, *,
              loop: asyncio.AbstractEventLoop) -> None:
     self.loop: asyncio.AbstractEventLoop = loop
     self.future: asyncio.Future[None] = loop.create_future()
     relative_delta = discord.utils.compute_timedelta(dt)
     self.handle = loop.call_later(relative_delta, self.future.set_result,
                                   True)
Example #4
0
 def __init__(self, loop: AbstractEventLoop, response: bytes) -> None:
     """Initialize the state response message."""
     super().__init__(loop, response, ResponseMessageType.STATE)
     self._power_consumption = 0
     self._electric_current = 0.0
     self._init_future = loop.create_future()
     ensure_future(self.initialize(response), loop=loop)
Example #5
0
def waitForEvent(emitter: EventEmitter, eventName: str,  # noqa: C901
                 predicate: Callable[[Any], bool], timeout: float,
                 loop: asyncio.AbstractEventLoop) -> Awaitable:
    """Wait for an event emitted from the emitter."""
    promise = loop.create_future()

    def resolveCallback(target: Any) -> None:
        promise.set_result(target)

    def rejectCallback(exception: Exception) -> None:
        promise.set_exception(exception)

    async def timeoutTimer() -> None:
        await asyncio.sleep(timeout / 1000)
        rejectCallback(
            TimeoutError('Timeout exceeded while waiting for event'))

    def _listener(target: Any) -> None:
        if not predicate(target):
            return
        cleanup()
        resolveCallback(target)

    listener = addEventListener(emitter, eventName, _listener)
    if timeout:
        eventTimeout = loop.create_task(timeoutTimer())

    def cleanup() -> None:
        removeEventListeners([listener])
        if timeout:
            eventTimeout.cancel()

    return promise
Example #6
0
def waitForEvent(emitter: EventEmitter, eventName: str,  # noqa: C901
                 predicate: Callable[[Any], bool], timeout: float,
                 loop: asyncio.AbstractEventLoop) -> Awaitable:
    """Wait for an event emitted from the emitter."""
    promise = loop.create_future()

    def resolveCallback(target: Any) -> None:
        promise.set_result(target)

    def rejectCallback(exception: Exception) -> None:
        promise.set_exception(exception)

    async def timeoutTimer() -> None:
        await asyncio.sleep(timeout / 1000)
        rejectCallback(
            TimeoutError('Timeout exceeded while waiting for event'))

    def _listener(target: Any) -> None:
        if not predicate(target):
            return
        cleanup()
        resolveCallback(target)

    listener = addEventListener(emitter, eventName, _listener)
    if timeout:
        eventTimeout = loop.create_task(timeoutTimer())

    def cleanup() -> None:
        removeEventListeners([listener])
        if timeout:
            eventTimeout.cancel()

    return promise
 def __init__(
     self,
     dispatcher_fiber: Any,
     object_factory: Callable[[ChannelOwner, str, str, Dict], ChannelOwner],
     transport: Transport,
     loop: asyncio.AbstractEventLoop,
 ) -> None:
     super().__init__()
     self._dispatcher_fiber = dispatcher_fiber
     self._transport = transport
     self._transport.on_message = lambda msg: self.dispatch(msg)
     self._waiting_for_object: Dict[str, Callable[[ChannelOwner],
                                                  None]] = {}
     self._last_id = 0
     self._objects: Dict[str, ChannelOwner] = {}
     self._callbacks: Dict[int, ProtocolCallback] = {}
     self._object_factory = object_factory
     self._is_sync = False
     self._child_ws_connections: List["Connection"] = []
     self._loop = loop
     self.playwright_future: asyncio.Future[
         "Playwright"] = loop.create_future()
     self._error: Optional[BaseException] = None
     self.is_remote = False
     self._init_task: Optional[asyncio.Task] = None
Example #8
0
    def __init__(self, loop: asyncio.AbstractEventLoop):
        self._std: Dict[int, asyncio.StreamReader] = {
            self._stdout: asyncio.StreamReader(loop=loop),
            self._stderr: asyncio.StreamReader(loop=loop),
        }

        self.process_end_waiter: asyncio.Future[None] = loop.create_future()
Example #9
0
 def __init__(self, correlation_id: bytes, loop: asyncio.AbstractEventLoop) -> None:
     self.correlation_id = correlation_id
     self.headers = None
     # Create a future for sending the result
     self._future = loop.create_future()
     self._loop   = loop
     self._chunks = None
     self._has_more = False
     self.data = None
 async def test_event_client_once_cb(self, mr_clean: Cleaner,
                                     event_loop: AbstractEventLoop):
     future = event_loop.create_future()
     client = await connect(url=self.wsurl)
     mr_clean.add_disposable(client)
     client.once("Network.requestWillBeSent",
                 lambda x: future.set_result(x))
     await client.Network.enable()
     await client.Page.navigate("https://google.com")
     assert await future is not None
Example #11
0
def _add_signal_handlers(loop: AbstractEventLoop) -> "Future[Any]":
    """Add signal handlers so shutdown can be handled normally, returning the stop future."""
    log.info("Adding signal handlers...")
    stop = loop.create_future()
    for sig in SHUTDOWN_SIGNALS:
        if sys.platform == "win32":
            signal.signal(sig, lambda s, f: stop.set_result(None))
        else:
            loop.add_signal_handler(sig, stop.set_result, None)
    return stop
Example #12
0
 async def threadsafe_partitions_assigned(
         self, receiver_loop: asyncio.AbstractEventLoop,
         assigned: Set[TP]) -> None:
     promise = await self._method_queue.call(
         receiver_loop.create_future(),
         self.on_partitions_assigned,
         assigned,
     )
     # wait for main-thread to finish processing request
     await promise
Example #13
0
File: utils.py Project: decaz/aiopg
 def __init__(
     self,
     queue: asyncio.Queue,  # type: ignore
     loop: asyncio.AbstractEventLoop,
 ):
     self._loop = loop
     self._queue = queue
     self._close_event = loop.create_future()
     # suppress Future exception was never retrieved
     self._close_event.add_done_callback(lambda f: f.exception())
def create_future(loop: asyncio.AbstractEventLoop) -> asyncio.Future:
    """
    Return a Future, using the loop if possible.

    loop.create_future() is better, but was only added in Python 3.5.2, see:

    https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.create_future
    """
    if hasattr(loop, 'create_future'):
        return loop.create_future()
    return asyncio.Future(loop=loop)
Example #15
0
 async def threadsafe_partitions_revoked(
         self, receiver_loop: asyncio.AbstractEventLoop,
         revoked: Set[TP]) -> None:
     """Call rebalancing callback in a thread-safe manner."""
     promise = await self._method_queue.call(
         receiver_loop.create_future(),
         self.on_partitions_revoked,
         revoked,
     )
     # wait for main-thread to finish processing request
     await promise
Example #16
0
    def __init__(
        self, loop: asyncio.AbstractEventLoop, logger: logging.Logger, probe_routine: Callable[[], Awaitable[bool]]
    ):
        """
        Base class for Java subprocess communication.
        It's used to automatically relay logs to python's logging framework and to automatically check the process'
        status.

        :param loop: The asyncio event loop to use for communicating with this component.
                     If `None` then the running loop within the active thread will be used or a new one will be created
                     if there is no running loop.
        :param logger: The logger used to relay the subprocess logs and to log other events.
        :param probe_routine: The coroutine that's used to asynchronously check if the subprocess is ready.
        """
        super().__init__()
        self.loop = loop
        self.startup_complete = loop.create_future()
        self.disconnected = loop.create_future()
        self.exited = loop.create_future()
        self._logger = logger
        self._probe = probe_routine
Example #17
0
    def wrap_to_future(loop: asyncio.AbstractEventLoop, func: Callable[..., T],
                       *args: Any, **kwargs: Any) -> asyncio.Future:
        future = loop.create_future()

        def _inner():  # type: ignore
            try:
                return future.set_result(func(*args, **kwargs))
            except Exception as e:
                return future.set_exception(e)

        loop.call_soon(_inner)
        return future
Example #18
0
    def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
        # Store a reference to loop to avoid relying on self.server._loop.
        self.loop = loop

        # Keep track of active connections.
        self.websockets: Set[WebSocketServerProtocol] = set()

        # Task responsible for closing the server and terminating connections.
        self.close_task: Optional[asyncio.Task[None]] = None

        # Completed when the server is closed and connections are terminated.
        self.closed_waiter: asyncio.Future[None] = loop.create_future()
async def test_async_set_color_lights(event_loop: asyncio.AbstractEventLoop,
                                      MockConnectedGateway):
    mode = 7
    result = event_loop.create_future()
    result.set_result(b"")
    with patch(
            "screenlogicpy.requests.lights.ScreenLogicProtocol.await_send_message",
            return_value=result,
    ) as mockRequest:
        gateway = MockConnectedGateway
        assert await gateway.async_set_color_lights(mode)
        await gateway.async_disconnect()
        assert mockRequest.call_args.args[0] == 12556
        assert mockRequest.call_args.args[1] == struct.pack("<II", 0, mode)
Example #20
0
 def __init__(self, loop: AbstractEventLoop, idx: int,
              schedule_details: List[bytes]) -> None:
     """Initialize the schedule."""
     self._loop = loop
     self._enabled = False
     self._recurring = False
     self._schedule_id = str(int(schedule_details[idx][0:2], 16))
     self._days = []  # type: List[str]
     self._schedule_data = b""
     self._start_time = WAITING_TEXT
     self._end_time = WAITING_TEXT
     self._duration = WAITING_TEXT
     self._init_future = loop.create_future()
     ensure_future(self.initialize(idx, schedule_details), loop=loop)
    async def test_event_client_on_cb(self, mr_clean: Cleaner,
                                      event_loop: AbstractEventLoop):
        future = event_loop.create_future()
        client = await connect(url=self.wsurl, remote=True)
        mr_clean.add_disposable(client)

        def listener(x):
            if not future.done():
                future.set_result(x)

        client.on("Network.requestWillBeSent", listener)

        await client.Network.enable()
        await client.Page.navigate("https://google.com")
        assert await future is not None
async def test_async_set_scg_config(event_loop: asyncio.AbstractEventLoop,
                                    MockConnectedGateway):
    pool_output = 50
    spa_output = 0
    result = event_loop.create_future()
    result.set_result(b"")
    with patch(
            "screenlogicpy.requests.heat.ScreenLogicProtocol.await_send_message",
            return_value=result,
    ) as mockRequest:
        gateway = MockConnectedGateway
        assert await gateway.async_set_scg_config(pool_output, spa_output)
        await gateway.async_disconnect()
        assert mockRequest.call_args.args[0] == 12576
        assert mockRequest.call_args.args[1] == struct.pack(
            "<IIIII", 0, pool_output, spa_output, 0, 0)
async def test_async_set_circuit(event_loop: asyncio.AbstractEventLoop,
                                 MockConnectedGateway):
    circuit_id = 505
    circuit_state = 1
    result = event_loop.create_future()
    result.set_result(b"")
    with patch(
            "screenlogicpy.requests.button.ScreenLogicProtocol.await_send_message",
            return_value=result,
    ) as mockRequest:
        gateway = MockConnectedGateway
        assert await gateway.async_set_circuit(circuit_id, circuit_state)
        await gateway.async_disconnect()
        assert mockRequest.call_args.args[0] == 12530
        assert mockRequest.call_args.args[1] == struct.pack(
            "<III", 0, circuit_id, circuit_state)
async def test_async_set_heat_temp(event_loop: asyncio.AbstractEventLoop,
                                   MockConnectedGateway):
    body = 0
    temp = 88
    result = event_loop.create_future()
    result.set_result(b"")
    with patch(
            "screenlogicpy.requests.heat.ScreenLogicProtocol.await_send_message",
            return_value=result,
    ) as mockRequest:
        gateway = MockConnectedGateway
        assert await gateway.async_set_heat_temp(body, temp)
        await gateway.async_disconnect()
        assert mockRequest.call_args.args[0] == 12528
        assert mockRequest.call_args.args[1] == struct.pack(
            "<III", 0, body, temp)
    async def test_connects_and_emits_closed_after_dispose_supplied_url(
        self, event_loop: AbstractEventLoop
    ):
        future = event_loop.create_future()
        client = await connect(url="http://localhost:9222")

        def cb():
            if not future.done():
                future.set_result(True)

        client.set_close_callback(cb)

        async with timeout(10, loop=event_loop):
            await client.dispose()

        async with timeout(10, loop=event_loop):
            assert await future
Example #26
0
async def start_tls(
    loop: asyncio.AbstractEventLoop,
    transport: asyncio.Transport,
    protocol: asyncio.Protocol,
    sslcontext: ssl.SSLContext,
    server_side: bool = False,
    server_hostname: Optional[str] = None,
    ssl_handshake_timeout: Optional[Union[float, int]] = None,
) -> asyncio.Transport:
    # We use hasattr here, as uvloop also supports start_tls.
    if hasattr(loop, "start_tls"):
        return await loop.start_tls(  # type: ignore
            transport,
            protocol,
            sslcontext,
            server_side=server_side,
            server_hostname=server_hostname,
            ssl_handshake_timeout=ssl_handshake_timeout,
        )

    waiter = loop.create_future()
    ssl_protocol = SSLProtocol(loop, protocol, sslcontext, waiter, server_side,
                               server_hostname)

    # Pause early so that "ssl_protocol.data_received()" doesn't
    # have a chance to get called before "ssl_protocol.connection_made()".
    transport.pause_reading()

    # Use set_protocol if we can
    if hasattr(transport, "set_protocol"):
        transport.set_protocol(ssl_protocol)  # type: ignore
    else:
        transport._protocol = ssl_protocol  # type: ignore

    conmade_cb = loop.call_soon(ssl_protocol.connection_made, transport)
    resume_cb = loop.call_soon(transport.resume_reading)

    try:
        await asyncio.wait_for(waiter, timeout=ssl_handshake_timeout)
    except Exception:
        transport.close()
        conmade_cb.cancel()
        resume_cb.cancel()
        raise

    return ssl_protocol._app_transport
Example #27
0
 def __init__(self, loop: AbstractEventLoop, message: Union[bytes,
                                                            str]) -> None:
     """Initialize the broadcast message."""
     self._loop = loop
     self._verified = self._validated = False
     self._power_consumption = 0
     self._electric_current = 0.0
     self._ip_address = WAITING_TEXT
     self._mac_address = WAITING_TEXT
     self._name = WAITING_TEXT
     self._device_id = WAITING_TEXT
     self._auto_off_set = WAITING_TEXT
     self._remaining_time_to_off = WAITING_TEXT
     self._init_future = loop.create_future()
     fixed_msg = (message if isinstance(message, bytes) else
                  message.encode(ENCODING_CODEC))
     ensure_future(self.initialize(fixed_msg), loop=loop)
    def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
        self.stack_trace: traceback.StackSummary = traceback.StackSummary()
        self.future = loop.create_future()
        # The outer task can get cancelled by the user, this forwards the cancellation to the inner task.
        current_task = asyncio.current_task()

        def cb(task: asyncio.Task) -> None:
            if current_task:
                current_task.remove_done_callback(cb)
            if task.cancelled():
                self.future.cancel()

        if current_task:
            current_task.add_done_callback(cb)
            self.future.add_done_callback(
                lambda _: current_task.remove_done_callback(cb)
                if current_task else None)
Example #29
0
async def _shutdown_default_executor(loop: asyncio.AbstractEventLoop) -> None:
    """Backport of cpython 3.9 schedule the shutdown of the default executor."""
    future = loop.create_future()

    def _do_shutdown() -> None:
        try:
            loop._default_executor.shutdown(wait=True)  # type: ignore  # pylint: disable=protected-access
            loop.call_soon_threadsafe(future.set_result, None)
        except Exception as ex:  # pylint: disable=broad-except
            loop.call_soon_threadsafe(future.set_exception, ex)

    thread = threading.Thread(target=_do_shutdown)
    thread.start()
    try:
        await future
    finally:
        thread.join()
    async def test_event_on_cb_removable(self, mr_clean: Cleaner,
                                         event_loop: AbstractEventLoop):
        future = event_loop.create_future()
        client: Client = await connect(url=self.wsurl)
        mr_clean.add_disposable(client)

        def listener(x):
            if not future.done():
                future.set_result(x)

        remove = client.Network.requestWillBeSent(listener)
        assert remove is not None and callable(remove)
        await client.Network.enable()
        await client.Page.navigate("https://google.com")
        assert await future is not None
        remove()
        assert len(client.listeners("Network.requestWillBeSent")) == 0
    async def test_connects_and_emits_closed_after_dispose_default_url(
        self, mr_clean: Cleaner, event_loop: AbstractEventLoop
    ):
        future = event_loop.create_future()
        client = await connect()

        def listener():
            if not future.done():
                future.set_result(True)

        mr_clean.addEventListener(client, ConnectionEvents.Disconnected, listener)

        async with timeout(10, loop=event_loop):
            await client.dispose()

        async with timeout(10, loop=event_loop):
            assert await future