示例#1
0
def obs_ws_connect(buffer_queue, host, port, password):
	ws = WebSocket()
	try:
		ws.connect(f'ws://{host}:{port}')

		ws.send(json.dumps({
			"request-type": "GetAuthRequired",
			"message-id": "1"
		}))
		res = json.loads(ws.recv())

		if res['status'] != 'ok':
			buffer_queue.put(('ERR', res['error']))
			return None

		if res.get('authRequired'):
			sec = base64.b64encode(hashlib.sha256((password + res['salt']).encode('utf-8')).digest())
			auth = base64.b64encode(hashlib.sha256(sec + res['challenge'].encode('utf-8')).digest()).decode('utf-8')
			ws.send(json.dumps({"request-type": "Authenticate", "message-id": '2', "auth": auth}))

			res = json.loads(ws.recv())
			if res['status'] != 'ok':
				self.buffer_queue.put(('ERR', res['error']))
				return None

		return ws

	except socket.error as error:
		buffer_queue.put(('ERR', error))
		return None
示例#2
0
class TestAuthentication(TestCase):
    def setUp(self):
        self.ws = WebSocket(sslopt={'check_hostname': False})
        self.ws.connect(url='wss://sim.smogon.com/showdown/websocket')
        msg = ''
        while not msg.startswith('|challstr|'):
            msg = self.ws.recv()
        self.challstr = msg[msg.find('|challstr|') + len('|challstr|'):]
        self.ws.settimeout(.5)

    def test_auth_temp_user(self):
        username = generate_username()
        assertion = auth_temp_user(self.challstr, username)
        login_cmd = f'|/trn {username},0,{assertion}'
        self.ws.send(login_cmd)
        self._username_in_msg(username)

    def test_login(self):
        with open('ts_auth.txt', 'r') as file:
            username, password = file.read().splitlines()
        assertion = login(self.challstr, username, password)
        login_cmd = f'|/trn {username},0,{assertion}'
        self.ws.send(login_cmd)
        self._username_in_msg(username)

    def _username_in_msg(self, username):
        msg = ''
        while not msg.startswith('|updateuser|'):
            msg = self.ws.recv()
        self.assertIn(username, msg)

    def tearDown(self):
        self.ws.close()
示例#3
0
def send_message(msg_type, data):
    panel_config = load_config()
    ws = WebSocket()
    ws.connect("ws://" + panel_config['uri'][0] + "/core")
    message = '{"type": "' + msg_type + '", "data":' + data + '}'
    ws.send(message)
    ws.recv()
    ws.close()
示例#4
0
def test_echo(server):
    ws = WebSocket()
    ws.connect(f'ws://127.0.0.1:{server}')
    ws.send('Hello World!')
    data = json.loads(ws.recv())
    assert {'msg': 'Hello World!', 'id': 1} == data
    data = json.loads(ws.recv())
    assert {'msg': 'Hello World!', 'id': 1} == data
示例#5
0
def TESTSocketandRequest(token):
    ws_url = "ws://{}:{}/connectToServer".format(base_url, port)
    ws = WebSocket()
    print('*Connecting Socket*')
    ws.connect(ws_url)
    print('*Sending Login Token To Authenticate Socket Gateway*')
    ws.send(dumps({"tok": token}))
    print('*Socket Connection Status*', ws.recv())
    print('Simulating A Demo Requests')
    TESTRequest()
    print('Request Submitted')
    return loads(ws.recv())
示例#6
0
async def get_data_from_local_cache(ws: websocket.WebSocket, data: str):
    nonce = secrets.token_urlsafe(20).replace("-", "_")
    # reconstruct the localStorage object that discord has hidden from me to extract games
    # code borrowed from https://stackoverflow.com/a/53773662/6508769 TYSM for the answer it saved me :P
    # modified to not modify the client and not to break any TOS
    msg = runtime_evaluate_json(f"""
            (function () {{
              function g_{nonce}() {{
                  const iframe = document.createElement('iframe');
                  document.body.append(iframe);
                  const pd = Object.getOwnPropertyDescriptor(iframe.contentWindow, 'localStorage');
                  iframe.remove();
                  return pd;
                }};
            return g_{nonce}().get.apply().{data}      
        }})()""")
    log.debug("DISCORD_LOCAL_STORAGE_REQUEST: " + str(msg))
    ws.send(msg)
    while True:
        resp = ws.recv()
        if 'result' in json.loads(resp):
            resp_dict = json.loads(resp)
            break
    if LOG_SENSITIVE_DATA:
        log.debug(f"DISCORD_RESPONSE_FOR_{data}: {str(resp_dict)}")
    return resp_dict['result']['result']['value']
示例#7
0
    def test(self, port=None, prefix="", scheme="http"):
        """
        kosmos `j.tools.packages.webinterface.test()'
        :return:
        """
        base_url = "0.0.0.0"
        if port:
            base_url = base_url + f":{port}"

        if prefix:
            base_url = base_url + f"/{prefix}"

        url = f"{scheme}://{base_url}"

        j.servers.threebot.start(background=True)
        gedis_client = j.clients.gedis.get(
            name="default", host="127.0.0.1", port=8901, package_name="zerobot.packagemanager"
        )

        gedis_client.actors.package_manager.package_add(
            j.core.tools.text_replace(
                "{DIR_BASE}/code/github/threefoldtech/jumpscaleX_core/JumpscaleCore/servers/gedis/pytests/test_package"
            )
        )
        gedis_client.reload()
        print("testing gedis http")
        assert (
            j.clients.http.post(
                f"{url}/zerobot/test_package/actors/actor/echo",
                data=b'{"args":{"_input":"hello world"}}',
                headers={"Content-Type": "application/json"},
            )
            .read()
            .decode()
            == "hello world"
        )
        print("gedis http OK")

        print("testing gedis websocker")
        from websocket import WebSocket
        import ssl

        ws = WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE})
        ws.connect(f"wss://{base_url}/gedis/websocket")
        assert ws.connected

        payload = """{
        "namespace": "default",
        "actor": "echo",
        "command": "actor.echo",
        "args": {"_input": "hello world"},
        "headers": {"response_type":"json"}
        }"""
        ws.send(payload)
        assert ws.recv() == "hello world"
        print("gedis websocket OK")

        print("tearDown")
        gedis_client.actors.package_manager.package_delete("zerobot.test_package")
        j.servers.threebot.default.stop()
示例#8
0
def get_gluware_version(addr):
    message = None
    ssl_cert_off = {"cert_reqs": CERT_NONE}

    # Turn off SSL certificate checking
    ws = WebSocket(sslopt=ssl_cert_off)

    try:
        ws.connect(
            'wss://{address}/ControlApi/socket.io/?EIO=3&transport=websocket'.
            format(address=addr))
    except ws_exception.WebSocketBadStatusException as con_error:
        print('Connection error: {info}'.format(info=con_error))
        return

    ws.send(
        '421["request",{"service":"DocsService","method":"getVersion","payload":{}}]'
    )

    while True:
        message = ws.recv()
        #print(message)
        if not message:
            print('Empty message')
            return
        if 'gluware_version' in message:
            break

    json_string = message[4:-1]
    json_payload = loads(json_string)['payload']
    payload = loads(json_payload)
    return payload['gluware_version']['semver']
示例#9
0
class RPANChat:
    def __init__(self, user_agent: str):
        self._header = {'User-Agent': user_agent}
        self._websocket = WebSocket()

    def __iter__(self):
        while True:
            try:
                comment_data = self._websocket.recv()
            except WebSocketConnectionClosedException:
                return

            comment_json = json.loads(comment_data)
            if comment_json['type'] != 'new_comment':
                continue
            payload = comment_json['payload']
            author = payload['author']
            body = payload['body']
            created_utc = payload['created_utc']
            id = payload['_id36']
            yield RPANComment(author, body, created_utc, id)

    def connect(self, stream_id: str) -> None:
        strapi_request = requests.get(
            f'https://strapi.reddit.com/videos/t3_{stream_id}',
            headers=self._header)
        if strapi_request.status_code != 200:
            raise ConnectionError
        stream_json = strapi_request.json()
        live_comments_websocket = stream_json['data']['post'][
            'liveCommentsWebsocket']
        self._websocket.connect(live_comments_websocket, header=self._header)

    def disconnect(self) -> None:
        self._websocket.close()
示例#10
0
    def send_transaction(self, message: ExonumMessage) -> str:
        """
        Sends a transaction into an Exonum node via WebSocket.
        Example:
        >>> response = client.send_websocket_transaction(message)
        >>> print(response)
        {"result":"success","response":{"tx_hash":"48b7d71d388f3c2dfa665bcf837e1fa0417ca559fb0163533ea72de6319e61ca"}}
        Parameters
        ----------
        message: ExonumMessage
            Prepared and signed an Exonum message.
        Returns
        -------
        result: str
            Result of the WebSocket request.
            If a transaction is correct and it is accepted, it will contain a JSON with a hash of the transaction.
        """
        body_raw = message.signed_raw()
        if body_raw is None:
            logger.critical("Attempt to send an unsigned message through websocket.")
            raise RuntimeError("Attempt to send an unsigned message.")
        data = json.dumps({"type": "transaction", "payload": {"tx_body": body_raw.hex()}})

        ws_client = WebSocket()
        ws_client.connect(self._address)
        ws_client.send(data)
        response = ws_client.recv()
        ws_client.close()

        return response
示例#11
0
class _App(WebSocketApp):
    def __init__(self, *args, **kwargs):
        super(_App, self).__init__(*args, **kwargs)
        self.keep_running = True
    
    def run_forever(self):
        """
        run event loop for WebSocket framework.
        This loop is infinite loop and is alive during websocket is available.
        """
        if self.sock:
            raise WebSocketException('Socket already exists')
        try:
            self.sock = WebSocket()
            self.sock.connect(self.url)
            sleep(2)
            self._run_with_no_err(self.on_open)
            while self.keep_running:
                data = self.sock.recv()
                if data is None:
                    break
                self._run_with_no_err(self.on_message, data)
        except Exception, e:
            self._run_with_no_err(self.on_error, e)
        finally:
示例#12
0
def pooling_loop(ws: websocket.WebSocket) -> None:
    try:
        while True:
            msg = ws.recv()
            typer.echo(msg)
    except websocket.WebSocketConnectionClosedException:
        #        typer.echo('[Error]: Name already taken, please reconnect with different name')
        return
class Websocket(Transport):
    name = 'websocket'

    def __init__(self, *args, **kwargs):
        super(Websocket, self).__init__(*args, **kwargs)
        self.scheme = 'ws'
        self.connection = WebSocket()
        self.reading = False
        self.writing = False
        self.read_loop = None

    def get_uri(self):
        query = {'EIO': '3', 'transport': self.name}

        if self.client and self.client.sid:
            query['sid'] = self.client.sid

        querystring = urllib.parse.urlencode(query)

        return '%s://%s:%d%s/?%s' % (self.scheme, self.hostname, self.port,
                                     self.path, querystring)

    def loop_read(self):
        while self.state in ['opening', 'open']:
            if self.state == 'opening':
                self.handle_open()
            packet = self.read()
            packet = self.parser.decode_packet(packet)
            self.handle_packet(packet)

    def do_open(self):
        self.connection.connect(self.get_uri())
        self.read_loop = self.client.start_loop(self.loop_read)

    def do_close(self):
        def close():
            self.send([Packet(Packet.CLOSE)])
            self.client.stop_loop(self.read_loop)

        if self.state == 'open':
            close()
        else:
            self.once('open', close)

    def do_send(self, packets):
        for packet in packets:
            enc_packet = self.parser.encode_packet(packet)
            self.write(enc_packet)

    def read(self):
        self.reading = True
        packet = self.connection.recv()
        return packet

    def write(self, packet):
        self.writing = True
        logger.debug('Sending payload: %s' % repr(packet))
        self.connection.send(packet)
示例#14
0
class WebSocketApp(object):
    """
    Higher level of APIs are provided. 
    The interface is like JavaScript WebSocket object.
    """
    def __init__(self, url,
                 on_open = None, on_message = None, on_error = None, 
                 on_close = None, symbol='btc_cny'):
        """
        url: websocket url.
        on_open: callable object which is called at opening websocket.
          this function has one argument. The arugment is this class object.
        on_message: callbale object which is called when recieved data.
         on_message has 2 arguments. 
         The 1st arugment is this class object.
         The passing 2nd arugment is utf-8 string which we get from the server.
       on_error: callable object which is called when we get error.
         on_error has 2 arguments.
         The 1st arugment is this class object.
         The passing 2nd arugment is exception object.
       on_close: callable object which is called when closed the connection.
         this function has one argument. The arugment is this class object.
        """
        self.url = url
        self.sock = WebSocket()
        self.sock.connect(self.url)
        self.symbol = ''.join(symbol.split('_'))
        self.send("{'event':'addChannel','channel':'ok_%s_depth'}" % self.symbol)

    def send(self, data):
        """
        send message. data must be utf-8 string or unicode.
        """
        self.sock.send(data)

    def close(self):
        """
        close websocket connection.
        """
        self.sock.close()

    def depth(self, symbol='btc_cny'):
        try:
            data = self.sock.recv()
            resp = json.loads(data)
            return resp[0]['data']
        except Exception as e:
            logging.info("except[%s]" % e)

    def _run_with_no_err(self, callback, *args):
        if callback:
            try:
                callback(self, *args)
            except Exception as e:
                if logger.isEnabledFor(logging.DEBUG):
                    logger.error(e)
示例#15
0
文件: ws.py 项目: kosuke316/pybybit
 def _onmessage(self, ws: websocket.WebSocket) -> None:
     Thread(target=self._heartbeat, args=[ws], daemon=True).start()
     while True:
         try:
             msg: str = ws.recv()
         except Exception:
             break
         else:
             for cb in self._callbacks:
                 cb(msg, ws)
示例#16
0
def listen_ws_and_forward_to_socket(client: socket, ws: websocket.WebSocket):
    message = ' '
    while message:
        message = ws.recv()
        if message:
            # log.info(message)
            client.sendall(message)
        else:
            #log.info("Dong cmn socket roi")
            shutdown_socket(client)
示例#17
0
def init_instrument_subscription(instrument_id: str, ws: WebSocket):
    instrument_data = {"type": "instrument", "id": instrument_id}
    ws.send(f'sub 1 {json.dumps(instrument_data)}')
    response = ws.recv()
    print(response)
    index = response.split(" ", 1)[0].strip()
    assert 1 == int(index)
    code = response.split(" ", 2)[1].strip()
    assert 'A' == code
    body = json.loads(response.split(" ", 2)[2])
    validator = Draft6Validator(instrument.INSTRUMENT_TOPIC_SCHEMA)
    validator.validate(body)
示例#18
0
def receive_json_response(
        websocket_connector: websocket.WebSocket) -> Union[Dict, None]:
    """Receives data from the web server
    Args:
        websocket_connector (websocket.WebSocket): Allows data to be received
    Returns:
        Dict: Dictionary containing the data received
    """
    response = websocket_connector.recv()
    if response:
        return json.loads(response)
    return None
示例#19
0
def follow(filename):
    url = 'ws://localhost:9292/follow/{}'.format(filename)
    ws = WebSocket()

    try:
        ws.connect(url)
        while True:
            msg = ws.recv()
            print('{} :: {}'.format(filename, msg), end='')

    finally:
        # ws.close() takes forever
        ws.shutdown()
示例#20
0
class Client():
    _instance = None

    @staticmethod
    def Get():
        if Client._instance is None:
            Client._instance = Client()

        return Client._instance

    def __init__(self):
        self.socket = WebSocket()
        self.userId = random.randint(0, 65536)

    def Start(self):
        import configReader
        serverIp = configReader.ConfigReader.GetVariable('SERVER_IP')
        serverPort = configReader.ConfigReader.GetVariable('PORT')

        self.socket.connect('ws://' + serverIp + ':' + serverPort + '/')

        messageData = {'user_id' : self.userId}
        message = '[playerJoined, ' + json.dumps(messageData) + ']'
        self.socket.send(message)

        engine.Engine.Get().Start()

        self.Close()

    def GetMessage(self):
        messageData = self.socket.recv()
        return json.loads(messageData)

    def SendPlayerMovedMessage(self, factor):
        messageData = {'user_id' : self.userId, 'factor' : factor}
        message = '[playerMoved, ' + json.dumps(messageData) + ']'
        self.socket.send(message)

    def SendPlayerTurnedMessage(self, factor):
        messageData = {'user_id' : self.userId, 'factor' : factor}
        message = '[playerTurned, ' + json.dumps(messageData) + ']'
        self.socket.send(message)

    def SendPlayerFiredMessage(self):
        messageData = {'user_id' : self.userId}
        message = '[playerFired, ' + json.dumps(messageData) + ']'
        self.socket.send(message)

    def Close(self):
        self.socket.close()
示例#21
0
 def _do_start_listening(
     self,
     callback: Optional[Callable[[str, Any], None]],
     connection: websocket.WebSocket,
 ) -> None:
     """Do start listening."""
     while True:
         data = connection.recv()
         if not data:
             return
         response = helper.process_api_response(data)
         event = response.get("event", "*")
         self._websocket_event(event, response)
         if callback:
             callback(event, response)
示例#22
0
class client(object):
    stopping = False
    greenlets = None

    def __init__(self, args, url):
        self.args = args

        self.tuntap = tuntap.tuntap(args.tuntap)

        self.ws = WebSocket()
        self.ws.connect(url)

        self.greenlets = [
            gevent.spawn(self.read_ws),
            gevent.spawn(self.read_fd)
        ]

    def read_fd(self):
        while not self.stopping:
            try:
                msg = os.tp_read(self.tuntap.fd, 1500)
                if not self.ws.connected:
                    break
                if not msg:
                    self.stopping = True
                    self.ws.close()
                    break
            except IOError:
                break
            self.ws.send_binary(msg)

    def read_ws(self):
        while not self.stopping:
            try:
                msg = self.ws.recv()
                if not msg:
                    break
            except websocket.WebSocketConnectionClosedException:
                self.stopping = True
                self.greenlets[1].kill()
                break
            except:
                continue
            os.tp_write(self.tuntap.fd, bytes(msg))

    def join(self):
        gevent.joinall(self.greenlets)
示例#23
0
class WSTunnel:
	def __init__(self, *args, **kwargs):
		self.ws = WebSocket(*args, **kwargs)

	def send(self, data):
		return self.ws.send_binary(data)

	def recv(self):
		return self.ws.recv()

	def connect(self, *args, **kwargs):
		self.ws.connect(*args, **kwargs)

	def up(self):
		pass

	def down(self):
		self.ws.close()
示例#24
0
def update():
    db = MongoClient('213.183.48.116').golos
    ws = WebSocket()
    ws.connect('wss://api.golos.cf')
    print('Starting update')
    for post in db.posts.find():
        ws.send(
            dumps({
                "id": 1,
                "method": "get_content",
                "params": [post['author'], post['permlink']]
            }))
        ids = post['id']
        response = eval(ws.recv())['result']
        db.posts.update({'id': ids}, {
            '$set': {
                'reward': response['pending_payout_value'],
                'votes': response['net_votes'],
                'comments': response['children']
            }
        })
        print('Updated post' + str(ids))
示例#25
0
def test_websocket(app: Flask, aio: AioHTTP):
    """Test for websocket"""
    @app.route('/echo')
    @websocket
    def echo():
        while True:
            msg = yield from aio.ws.receive_msg()

            if msg.tp == aiohttp.MsgType.text:
                aio.ws.send_str(msg.data)
            elif msg.tp == aiohttp.MsgType.close:
                break
            elif msg.tp == aiohttp.MsgType.error:
                break

    with Server(app, aio) as server:
        ws = WebSocket()
        ws.connect(server.ws_url('/echo'))
        try:
            ws.send('foo')
            assert 'foo' == ws.recv()
        finally:
            ws.close()
示例#26
0
async def open_friends_page(ws: websocket.WebSocket):
    # Simulate the user clicking on the "Home" button.
    msg = runtime_evaluate_json(
        r"document.querySelector('a[aria-label=\"Home\"][href]').click()")
    ws.send(msg)
    ws.recv()
    # Simulate the user clicking on the "Friends" button.
    msg = runtime_evaluate_json(
        r"document.querySelector(\"a[href='/channels/@me']\").click()")
    ws.send(msg)
    ws.recv()
    # Navigates to the PersonWaving icon, goes up two elements, and then selects the second button (All) to show all of
    # the user's friends.
    msg = runtime_evaluate_json(
        r"document.querySelectorAll(\"svg[name='PersonWaving']\")[1].parentElement."
        r"parentElement.querySelectorAll(\"div[role='button']\")[2].click()")
    ws.send(msg)
    ws.recv()
示例#27
0
def main(addr):
    """
    Get gluware version with websocket

    :param addr: ip address of host (str)
    :return: version (str)
    """

    # Turn off SSL certificate checking
    ssl_cert_off = {"cert_reqs": CERT_NONE}
    ws = WebSocket(sslopt=ssl_cert_off)

    try:
        ws.connect(
            'wss://{address}/ControlApi/socket.io/?EIO=3&transport=websocket'.
            format(address=addr))
    except ws_exception.WebSocketBadStatusException:
        return
    except Exception:
        return

    ws.send(
        '421["request",{"service":"DocsService","method":"getVersion","payload":{}}]'
    )

    while True:
        message = ws.recv()
        if not message:
            return
        if 'gluware_version' in message:
            break

    json_string = message[4:-1]
    json_payload = loads(json_string)['payload']
    payload = loads(json_payload)
    return payload['gluware_version']['semver']
    def socket_main(self):

        port = 7001
        try:
            self.server.bind(('', port))
            self.server.listen(100)
        except Exception as e:
            print(e)
            exit()
        self.socket_list.add(self.server)

        while True:
            r, w, e = select(self.socket_list, [], [])
            for sock in r:
                if sock == self.server:
                    conn, addr = sock.accept()
                    if WebSocket.handshake(conn):
                        self.socket_list.add(conn)
                else:
                    data = WebSocket.recv(sock)
                    if not data:
                        self.socket_list.remove(sock)
                    else:
                        WebSocket.send(conn, data)
def test_websocket_connection():


    ws_user = WebSocket()
    ws_agent = WebSocket()
    sender_id = str(np.random.randint(1234562523))+"_"+"john123"

    ws_user.connect(env_config['RASA_URL'])
    ws_agent.connect(env_config['RASA_URL'])
    ws_user.send(login(sender_id))
    received_data=ws_user.recv()


    ws_user.send(send_msg(sender_id,'Hi'))
    received_data=ws_user.recv()


    ws_user.send(send_msg(sender_id,'Yes'))
    received_data=ws_user.recv()


    ws_agent.send(login('HA_agent5+'+sender_id))
    received_data=ws_agent.recv()


    ws_user.send(send_msg(sender_id,'Yes'))
    received_data=ws_user.recv()

    ws_user.send(send_msg(sender_id,'ok'))
    received_data = requests.get(env_config['conv_listen_address'] + "?sender_id=" + sender_id)

    ws_agent.send(send_msg('HA_agent5+'+sender_id, "Hi john, Your payoff amount is $1461"))
    received_data=ws_user.recv()
    ws_user.send(send_msg(sender_id,"ok"))

    return 'success'
示例#30
0
ws = WebSocket()
ws.connect('wss://api.golos.cf')

print('Sending for 100')

#Sending query to fetch last 100 posts
ws.send(
    json.dumps({
        "id": 6,
        "method": "get_discussions_by_created",
        "params": [{
            "tag": "",
            "limit": "100"
        }]
    }))
post = eval(ws.recv())['result']

#get needed params and dump in db
for i in post:
    ids = i['id']
    try:
        tags = eval(i['json_metadata'])['tags']
    except:
        tags = []
    write = dump = {
        'id': ids,
        'author': i['author'],
        'permlink': i['permlink'],
        'timestamp': i['created'].split('T')[0],
        'title': i['title'],
        'votes': i['net_votes'],
示例#31
0
class CloudClient:
    """Spokestack client for cloud based speech to text

    Args:
        key_id (str): identity from spokestack api credentials
        key_secret (str): secret key from spokestack api credentials
        socket_url (str): url for socket connection
        audio_format (str): format of input audio
        sample_rate (int): audio sample rate (kHz)
        language (str): language for recognition
        limit (int): Limit of messages per api response
        idle_timeout (Any): Time before client timeout. Defaults to None
    """
    def __init__(
        self,
        key_id: str,
        key_secret: str,
        socket_url: str = "wss://api.spokestack.io",
        audio_format: str = "PCM16LE",
        sample_rate: int = 16000,
        language: str = "en",
        limit: int = 10,
        idle_timeout: Union[float, None] = None,
    ) -> None:

        self._body: str = json.dumps({
            "format": audio_format,
            "rate": sample_rate,
            "language": language,
            "limit": limit,
        })
        self._socket_url: str = socket_url
        self._key_id: str = key_id
        self._key: bytes = key_secret.encode("utf-8")
        signature = hmac.new(self._key, self._body.encode("utf-8"),
                             hashlib.sha256).digest()
        self._signature = base64.b64encode(signature).decode("utf-8")
        self._socket: Any = None

        self._response: Dict[str, Any] = {
            "error": None,
            "final": True,
            "hypotheses": [],
            "status": None,
        }
        self._sample_rate: int = sample_rate
        self._idle_timeout = idle_timeout
        self._idle_count: int = 0

    def __call__(self,
                 audio: Union[bytes, np.ndarray],
                 limit: int = 1) -> List[str]:
        """Audio to text interface for the cloud client

        Args:
            audio (bytes|np.ndarray): input audio can be in the form of
                                      bytes or np.float, np.int16 array with
                                      conversions handled. other types with produce
                                      a TypeError
            limit (int): number of predictions to return

        Returns: list of transcripts, and their confidence values of size limit

        """
        if isinstance(audio, bytes):
            audio = np.frombuffer(audio, np.int16)
        elif np.issubdtype(audio.dtype, np.floating):
            # convert and rescale to PCM-16
            audio = (audio * (2**15 - 1)).astype(np.int16)
        elif not np.issubdtype(audio.dtype, np.int16):
            raise TypeError("invalid_audio")

        chunk_size = self._sample_rate
        self.connect()
        self.initialize()

        for i in range(0, len(audio), chunk_size):
            frame = audio[i:][:chunk_size]
            self.send(frame)
            self.receive()

        self.end()
        while not self._response["final"]:
            self.receive()
        self.disconnect()

        hypotheses = self._response.get("hypotheses", [])
        return hypotheses[:limit]

    @property
    def is_connected(self) -> bool:
        """ status of the socket connection """
        if self._socket:
            return True
        return False

    def connect(self) -> None:
        """ connects to websocket """
        if self._socket is None:
            self._socket = WebSocket()
            self._socket.connect(f"{self._socket_url}/v1/asr/websocket")

    def initialize(self) -> None:
        """ sends/receives the initial api request """
        if not self._socket:
            raise ConnectionError("Not Connected")

        message = {
            "keyId": self._key_id,
            "signature": self._signature,
            "body": self._body,
        }
        self._socket.send(json.dumps(message))
        self._response = json.loads(self._socket.recv())
        if not self._response["status"] == "ok":
            raise APIError(self._response)

    def disconnect(self) -> None:
        """ disconnects client socket connection """
        if self._socket:
            self._socket.close()
            self._socket = None

    def send(self, frame: np.ndarray) -> None:
        """sends a single frame of audio

        Args:
            frame (np.ndarray): segment of PCM-16 encoded audio

        """
        if self._socket:
            self._socket.send_binary(frame.tobytes())
        else:
            raise ConnectionError("Not Connected")

    def end(self) -> None:
        """ sends empty string in binary to indicate last frame """
        if self._socket:
            self._socket.send_binary(b"")
        else:
            raise ConnectionError("Not Connected")

    def receive(self) -> None:
        """ receives the api response """
        if self._socket:
            timeout = self._socket.timeout
            try:
                self._socket.timeout = 0
                response = self._socket.recv()
                self._response = json.loads(response)
            except Exception:
                pass
            self._socket.timeout = timeout
        else:
            raise ConnectionError("Not Connected")

    @property
    def response(self) -> dict:
        """ current response message"""
        return self._response

    @property
    def is_final(self) -> bool:
        """ status of most recent sever response """
        return self._response["final"]

    @property
    def idle_timeout(self) -> Any:
        """ property for maximum idle time """
        return self._idle_timeout

    @property
    def idle_count(self) -> int:
        """ current counter of idle time """
        return self._idle_count

    @idle_count.setter
    def idle_count(self, value: int) -> None:
        """ sets the idle counter"""
        self._idle_count = value
示例#32
0
#!/usr/bin/env python3

from websocket import WebSocket
from json import loads
from sys import argv
from guess import *

L = "e"

ws = WebSocket()
ws.connect("ws://lab.algonics.net/anticaptcha/ws")

# Super
print(ws.recv())

while True:
    msg = " ".join(argv[1:])
    m = "{{\"message\": \"{}\"}}".format(msg)
    ws.send(m)

    r = ws.recv()
    r = loads(r)
    challenge = r["challenge"]
    response = int(challenge, 13)
    # print("Challenge: {}, reponse: {}".format(challenge, response))

    m = "{{\"reponse\": \"{}\"}}".format(response)
    ws.send(m)

    r = ws.recv()
    r = loads(r)
示例#33
0
class WebSocketApp(object):
    """
    Higher level of APIs are provided. 
    The interface is like JavaScript WebSocket object.
    """
    def __init__(self,
                 url,
                 on_open=None,
                 on_message=None,
                 on_error=None,
                 on_close=None):
        """
        url: websocket url.
        on_open: callable object which is called at opening websocket.
          this function has one argument. The arugment is this class object.
        on_message: callbale object which is called when recieved data.
         on_message has 2 arguments. 
         The 1st arugment is this class object.
         The passing 2nd arugment is utf-8 string which we get from the server.
       on_error: callable object which is called when we get error.
         on_error has 2 arguments.
         The 1st arugment is this class object.
         The passing 2nd arugment is exception object.
       on_close: callable object which is called when closed the connection.
         this function has one argument. The arugment is this class object.
        """
        self.url = url
        self.on_open = on_open
        self.on_message = on_message
        self.on_error = on_error
        self.on_close = on_close
        self.sock = None

    def send(self, data):
        """
        send message. data must be utf-8 string or unicode.
        """
        self.sock.send(data)

    def close(self):
        """
        close websocket connection.
        """
        self.sock.close()

    def run_forever(self):
        """
        run event loop for WebSocket framework.
        This loop is infinite loop and is alive during websocket is available.
        """
        if self.sock:
            raise WebSocketException("socket is already opened")
        try:
            self.sock = WebSocket()
            self.sock.connect(self.url)
            self._run_with_no_err(self.on_open)
            while True:
                data = self.sock.recv()
                if data is None:
                    break
                self._run_with_no_err(self.on_message, data)
        except Exception, e:
            self._run_with_no_err(self.on_error, e)
        finally:
示例#34
0
class CarlaHostQtWeb(CarlaHostQtNull):
    def __init__(self):
        CarlaHostQtNull.__init__(self)

        self.host = "localhost"
        self.port = 2228

        self.baseurl = "http://{}:{}".format(self.host, self.port)

        self.socket = WebSocket()
        self.socket.connect("ws://{}:{}/ws".format(self.host, self.port), timeout=1)

        self.isRemote = True
        self.isRunning = True
        self.peaks = []

        for i in range(99):
            self.peaks.append((0.0, 0.0, 0.0, 0.0))

    def get_engine_driver_count(self):
        return int(requests.get("{}/get_engine_driver_count".format(self.baseurl)).text)

    def get_engine_driver_name(self, index):
        return requests.get("{}/get_engine_driver_name".format(self.baseurl), params={
            'index': index,
        }).text

    def get_engine_driver_device_names(self, index):
        return requests.get("{}/get_engine_driver_device_names".format(self.baseurl), params={
            'index': index,
        }).text.split("\n")

    def get_engine_driver_device_info(self, index, name):
        return requests.get("{}/get_engine_driver_device_info".format(self.baseurl), params={
            'index': index,
            'name': name,
        }).json()

    def engine_init(self, driverName, clientName):
        return bool(int(requests.get("{}/engine_init".format(self.baseurl), params={
            'driverName': driverName,
            'clientName': clientName,
        }).text))

    def engine_close(self):
        return bool(int(requests.get("{}/engine_close".format(self.baseurl)).text))

    def engine_idle(self):
        if not self.isRunning:
            return

        while True:
            try:
                line = self.socket.recv().strip()
            except WebSocketConnectionClosedException:
                self.isRunning = False
                if self.fEngineCallback is None:
                    self.fEngineCallback(None, ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0, "")
                return

            if line == "Keep-Alive":
                return

            elif line.startswith("Carla: "):
                if self.fEngineCallback is None:
                    continue

                # split values from line
                action, pluginId, value1, value2, value3, valueStr = line[7:].split(" ",5)

                # convert to proper types
                action   = int(action)
                pluginId = int(pluginId)
                value1   = int(value1)
                value2   = int(value2)
                value3   = float(value3)

                # pass to callback
                self.fEngineCallback(None, action, pluginId, value1, value2, value3, valueStr)

            elif line.startswith("Peaks: "):
                # split values from line
                pluginId, value1, value2, value3, value4 = line[7:].split(" ",5)

                # convert to proper types
                pluginId = int(pluginId)
                value1   = float(value1)
                value2   = float(value2)
                value3   = float(value3)
                value4   = float(value4)

                # store peaks
                self.peaks[pluginId] = (value1, value2, value3, value4)

    def is_engine_running(self):
        if not self.isRunning:
            return False

        try:
            return bool(int(requests.get("{}/is_engine_running".format(self.baseurl)).text))
        except requests.exceptions.ConnectionError:
            if self.fEngineCallback is None:
                self.fEngineCallback(None, ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0, "")

    def set_engine_about_to_close(self):
        return bool(int(requests.get("{}/set_engine_about_to_close".format(self.baseurl)).text))

    def set_engine_option(self, option, value, valueStr):
        requests.get("{}/set_engine_option".format(self.baseurl), params={
            'option': option,
            'value': value,
            'valueStr': valueStr,
        })

    def load_file(self, filename):
        return bool(int(requests.get("{}/load_file".format(self.baseurl), params={
            'filename': filename,
        }).text))

    def load_project(self, filename):
        return bool(int(requests.get("{}/load_project".format(self.baseurl), params={
            'filename': filename,
        }).text))

    def save_project(self, filename):
        return bool(int(requests.get("{}/save_project".format(self.baseurl), params={
            'filename': filename,
        }).text))

    def patchbay_connect(self, groupIdA, portIdA, groupIdB, portIdB):
        return bool(int(requests.get("{}/patchbay_connect".format(self.baseurl), params={
            'groupIdA': groupIdA,
            'portIdA': portIdA,
            'groupIdB': groupIdB,
            'portIdB': portIdB,
        }).text))

    def patchbay_disconnect(self, connectionId):
        return bool(int(requests.get("{}/patchbay_disconnect".format(self.baseurl), params={
            'connectionId': connectionId,
        }).text))

    def patchbay_refresh(self, external):
        return bool(int(requests.get("{}/patchbay_refresh".format(self.baseurl), params={
            'external': int(external),
        }).text))

    def transport_play(self):
        requests.get("{}/transport_play".format(self.baseurl))

    def transport_pause(self):
        requests.get("{}/transport_pause".format(self.baseurl))

    def transport_bpm(self, bpm):
        requests.get("{}/transport_bpm".format(self.baseurl), params={
            'bpm': bpm,
        })

    def transport_relocate(self, frame):
        requests.get("{}/transport_relocate".format(self.baseurl), params={
            'frame': frame,
        })

    def get_current_transport_frame(self):
        return int(requests.get("{}/get_current_transport_frame".format(self.baseurl)).text)

    def get_transport_info(self):
        if self.isRunning:
            try:
                return requests.get("{}/get_transport_info".format(self.baseurl)).json()
            except requests.exceptions.ConnectionError:
                if self.fEngineCallback is None:
                    self.fEngineCallback(None, ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0, "")
        return PyCarlaTransportInfo()

    def get_current_plugin_count(self):
        return int(requests.get("{}/get_current_plugin_count".format(self.baseurl)).text)

    def get_max_plugin_number(self):
        return int(requests.get("{}/get_max_plugin_number".format(self.baseurl)).text)

    def add_plugin(self, btype, ptype, filename, name, label, uniqueId, extraPtr, options):
        return bool(int(requests.get("{}/add_plugin".format(self.baseurl), params={
            'btype': btype,
            'ptype': ptype,
            'filename': filename,
            'name': name,
            'label': label,
            'uniqueId': uniqueId,
            'options': options,
        }).text))

    def remove_plugin(self, pluginId):
        return bool(int(requests.get("{}/remove_plugin".format(self.baseurl), params={
            'filename': pluginId,
        }).text))

    def remove_all_plugins(self):
        return bool(int(requests.get("{}/remove_all_plugins".format(self.baseurl)).text))

    def rename_plugin(self, pluginId, newName):
        return requests.get("{}/rename_plugin".format(self.baseurl), params={
            'pluginId': pluginId,
            'newName': newName,
        }).text

    def clone_plugin(self, pluginId):
        return bool(int(requests.get("{}/clone_plugin".format(self.baseurl), params={
            'pluginId': pluginId,
        }).text))

    def replace_plugin(self, pluginId):
        return bool(int(requests.get("{}/replace_plugin".format(self.baseurl), params={
            'pluginId': pluginId,
        }).text))

    def switch_plugins(self, pluginIdA, pluginIdB):
        return bool(int(requests.get("{}/switch_plugins".format(self.baseurl), params={
            'pluginIdA': pluginIdA,
            'pluginIdB': pluginIdB,
        }).text))

    def load_plugin_state(self, pluginId, filename):
        return bool(int(requests.get("{}/load_plugin_state".format(self.baseurl), params={
            'pluginId': pluginId,
            'filename': filename,
        }).text))

    def save_plugin_state(self, pluginId, filename):
        return bool(int(requests.get("{}/save_plugin_state".format(self.baseurl), params={
            'pluginId': pluginId,
            'filename': filename,
        }).text))

    def export_plugin_lv2(self, pluginId, lv2path):
        return bool(int(requests.get("{}/export_plugin_lv2".format(self.baseurl), params={
            'pluginId': pluginId,
            'lv2path': lv2path,
        }).text))

    def get_plugin_info(self, pluginId):
        return requests.get("{}/get_plugin_info".format(self.baseurl), params={
            'pluginId': pluginId,
        }).json()

    def get_audio_port_count_info(self, pluginId):
        return requests.get("{}/get_audio_port_count_info".format(self.baseurl), params={
            'pluginId': pluginId,
        }).json()

    def get_midi_port_count_info(self, pluginId):
        return requests.get("{}/get_midi_port_count_info".format(self.baseurl), params={
            'pluginId': pluginId,
        }).json()

    def get_parameter_count_info(self, pluginId):
        return requests.get("{}/get_parameter_count_info".format(self.baseurl), params={
            'pluginId': pluginId,
        }).json()

    def get_parameter_info(self, pluginId, parameterId):
        return requests.get("{}/get_parameter_info".format(self.baseurl), params={
            'pluginId': pluginId,
            'parameterId': parameterId,
        }).json()

    def get_parameter_scalepoint_info(self, pluginId, parameterId, scalePointId):
        return requests.get("{}/get_parameter_scalepoint_info".format(self.baseurl), params={
            'pluginId': pluginId,
            'parameterId': parameterId,
            'scalePointId': scalePointId,
        }).json()

    def get_parameter_data(self, pluginId, parameterId):
        return requests.get("{}/get_parameter_data".format(self.baseurl), params={
            'pluginId': pluginId,
            'parameterId': parameterId,
        }).json()

    def get_parameter_ranges(self, pluginId, parameterId):
        return requests.get("{}/get_parameter_ranges".format(self.baseurl), params={
            'pluginId': pluginId,
            'parameterId': parameterId,
        }).json()

    def get_midi_program_data(self, pluginId, midiProgramId):
        return requests.get("{}/get_midi_program_data".format(self.baseurl), params={
            'pluginId': pluginId,
            'midiProgramId': midiProgramId,
        }).json()

    def get_custom_data(self, pluginId, customDataId):
        return requests.get("{}/get_custom_data".format(self.baseurl), params={
            'pluginId': pluginId,
            'customDataId': customDataId,
        }).json()

    def get_custom_data_value(self, pluginId, type_, key):
        return requests.get("{}/get_custom_data_value".format(self.baseurl), params={
            'pluginId': pluginId,
            'type_': type_,
            'key': key,
        }).text

    def get_chunk_data(self, pluginId):
        return requests.get("{}/get_chunk_data".format(self.baseurl), params={
            'pluginId': pluginId,
        }).text

    def get_parameter_count(self, pluginId):
        return int(requests.get("{}/get_parameter_count".format(self.baseurl), params={
            'pluginId': pluginId,
        }).text)

    def get_program_count(self, pluginId):
        return int(requests.get("{}/get_program_count".format(self.baseurl), params={
            'pluginId': pluginId,
        }).text)

    def get_midi_program_count(self, pluginId):
        return int(requests.get("{}/get_midi_program_count".format(self.baseurl), params={
            'pluginId': pluginId,
        }).text)

    def get_custom_data_count(self, pluginId):
        return int(requests.get("{}/get_custom_data_count".format(self.baseurl), params={
            'pluginId': pluginId,
        }).text)

    def get_parameter_text(self, pluginId, parameterId):
        return requests.get("{}/get_parameter_text".format(self.baseurl), params={
            'pluginId': pluginId,
            'parameterId': parameterId,
        }).text

    def get_program_name(self, pluginId, programId):
        return requests.get("{}/get_program_name".format(self.baseurl), params={
            'pluginId': pluginId,
            'programId': programId,
        }).text

    def get_midi_program_name(self, pluginId, midiProgramId):
        return requests.get("{}/get_midi_program_name".format(self.baseurl), params={
            'pluginId': pluginId,
            'midiProgramId': midiProgramId,
        }).text

    def get_real_plugin_name(self, pluginId):
        return requests.get("{}/get_real_plugin_name".format(self.baseurl), params={
            'pluginId': pluginId,
        }).text

    def get_current_program_index(self, pluginId):
        return int(requests.get("{}/get_custom_data_count".format(self.baseurl), params={
            'pluginId': pluginId,
        }).text)

    def get_current_midi_program_index(self, pluginId):
        return int(requests.get("{}/get_custom_data_count".format(self.baseurl), params={
            'pluginId': pluginId,
        }).text)

    def get_default_parameter_value(self, pluginId, parameterId):
        return float(requests.get("{}/get_default_parameter_value".format(self.baseurl), params={
            'pluginId': pluginId,
            'parameterId': parameterId,
        }).text)

    def get_current_parameter_value(self, pluginId, parameterId):
        if self.isRunning:
            try:
                return float(requests.get("{}/get_current_parameter_value".format(self.baseurl), params={
                    'pluginId': pluginId,
                    'parameterId': parameterId,
                }).text)
            except requests.exceptions.ConnectionError:
                if self.fEngineCallback is None:
                    self.fEngineCallback(None, ENGINE_CALLBACK_QUIT, 0, 0, 0, 0.0, "")
        return 0.0

    def get_internal_parameter_value(self, pluginId, parameterId):
        return float(requests.get("{}/get_internal_parameter_value".format(self.baseurl), params={
            'pluginId': pluginId,
            'parameterId': parameterId,
        }).text)

    def get_input_peak_value(self, pluginId, isLeft):
        return self.peaks[pluginId][0 if isLeft else 1]

    def get_output_peak_value(self, pluginId, isLeft):
        return self.peaks[pluginId][2 if isLeft else 3]

    def set_option(self, pluginId, option, yesNo):
        requests.get("{}/set_option".format(self.baseurl), params={
            'pluginId': pluginId,
            'option': option,
            'yesNo': int(yesNo),
        })

    def set_active(self, pluginId, onOff):
        requests.get("{}/set_active".format(self.baseurl), params={
            'pluginId': pluginId,
            'onOff': int(onOff),
        })

    def set_drywet(self, pluginId, value):
        requests.get("{}/set_drywet".format(self.baseurl), params={
            'pluginId': pluginId,
            'value': value,
        })

    def set_volume(self, pluginId, value):
        requests.get("{}/set_volume".format(self.baseurl), params={
            'pluginId': pluginId,
            'value': value,
        })

    def set_balance_left(self, pluginId, value):
        requests.get("{}/set_balance_left".format(self.baseurl), params={
            'pluginId': pluginId,
            'value': value,
        })

    def set_balance_right(self, pluginId, value):
        requests.get("{}/set_balance_right".format(self.baseurl), params={
            'pluginId': pluginId,
            'value': value,
        })

    def set_panning(self, pluginId, value):
        requests.get("{}/set_panning".format(self.baseurl), params={
            'pluginId': pluginId,
            'value': value,
        })

    def set_ctrl_channel(self, pluginId, channel):
        requests.get("{}/set_ctrl_channel".format(self.baseurl), params={
            'pluginId': pluginId,
            'channel': channel,
        })

    def set_parameter_value(self, pluginId, parameterId, value):
        requests.get("{}/set_parameter_value".format(self.baseurl), params={
            'pluginId': pluginId,
            'parameterId': parameterId,
            'value': value,
        })

    def set_parameter_midi_channel(self, pluginId, parameterId, channel):
        requests.get("{}/set_parameter_midi_channel".format(self.baseurl), params={
            'pluginId': pluginId,
            'parameterId': parameterId,
            'channel': channel,
        })

    def set_parameter_midi_cc(self, pluginId, parameterId, cc):
        requests.get("{}/set_parameter_midi_cc".format(self.baseurl), params={
            'pluginId': pluginId,
            'parameterId': parameterId,
            'cc': cc,
        })

    def set_program(self, pluginId, programId):
        requests.get("{}/set_program".format(self.baseurl), params={
            'pluginId': pluginId,
        })

    def set_midi_program(self, pluginId, midiProgramId):
        requests.get("{}/set_midi_program".format(self.baseurl), params={
            'pluginId': pluginId,
            'midiProgramId': midiProgramId,
        })

    def set_custom_data(self, pluginId, type_, key, value):
        requests.get("{}/set_custom_data".format(self.baseurl), params={
            'pluginId': pluginId,
            'type': type_,
            'key': key,
            'value': value,
        })

    def set_chunk_data(self, pluginId, chunkData):
        requests.get("{}/set_chunk_data".format(self.baseurl), params={
            'pluginId': pluginId,
            'chunkData': chunkData,
        })

    def prepare_for_save(self, pluginId):
        requests.get("{}/prepare_for_save".format(self.baseurl), params={
            'pluginId': pluginId,
        })

    def reset_parameters(self, pluginId):
        requests.get("{}/reset_parameters".format(self.baseurl), params={
            'pluginId': pluginId,
        })

    def randomize_parameters(self, pluginId):
        requests.get("{}/randomize_parameters".format(self.baseurl), params={
            'pluginId': pluginId,
        })

    def send_midi_note(self, pluginId, channel, note, velocity):
        requests.get("{}/send_midi_note".format(self.baseurl), params={
            'pluginId': pluginId,
            'channel': channel,
            'note': note,
            'velocity': velocity,
        })

    def get_buffer_size(self):
        return int(requests.get("{}/get_buffer_size".format(self.baseurl)).text)

    def get_sample_rate(self):
        return float(requests.get("{}/get_sample_rate".format(self.baseurl)).text)

    def get_last_error(self):
        return requests.get("{}/get_last_error".format(self.baseurl)).text

    def get_host_osc_url_tcp(self):
        return requests.get("{}/get_host_osc_url_tcp".format(self.baseurl)).text

    def get_host_osc_url_udp(self):
        return requests.get("{}/get_host_osc_url_udp".format(self.baseurl)).text
示例#35
0
class WebSocketApp(object):
    """
    Higher level of APIs are provided. 
    The interface is like JavaScript WebSocket object.
    """
    def __init__(self, url,
                 on_open = None, on_message = None, on_error = None, 
                 on_close = None):
        """
        url: websocket url.
        on_open: callable object which is called at opening websocket.
          this function has one argument. The arugment is this class object.
        on_message: callbale object which is called when recieved data.
         on_message has 2 arguments. 
         The 1st arugment is this class object.
         The passing 2nd arugment is utf-8 string which we get from the server.
       on_error: callable object which is called when we get error.
         on_error has 2 arguments.
         The 1st arugment is this class object.
         The passing 2nd arugment is exception object.
       on_close: callable object which is called when closed the connection.
         this function has one argument. The arugment is this class object.
        """
        self.url = url
        self.on_open = on_open
        self.on_message = on_message
        self.on_error = on_error
        self.on_close = on_close
        self.sock = None

    def send(self, data):
        """
        send message. data must be utf-8 string or unicode.
        """
        self.sock.send(data)

    def close(self):
        """
        close websocket connection.
        """
        self.sock.close()

    def run_forever(self):
        """
        run event loop for WebSocket framework.
        This loop is infinite loop and is alive during websocket is available.
        """
        if self.sock:
            raise WebSocketException("socket is already opened")
        try:
            self.sock = WebSocket()
            self.sock.connect(self.url)
            self._run_with_no_err(self.on_open)
            while True:
                data = self.sock.recv()
                if data is None:
                    break
                self._run_with_no_err(self.on_message, data)
        except Exception, e:
            self._run_with_no_err(self.on_error, e)
        finally: