예제 #1
0
    async def get(self):
        ws = WebSocketResponse()
        await ws.prepare(self.request)

        with self.resource:
            while not ws.closed:
                try:
                    item = await asyncio.wait_for(self.resource.queue.get(), 2)
                except asyncio.TimeoutError:
                    ws.ping()
                    continue
                except asyncio.CancelledError:
                    break

                if item['action'] == 'cleared':
                    data = {'action': 'cleared'}
                elif item['action'] == 'received':
                    data = {
                        'action': 'received',
                        'msg': serialize_message(item['msg']),
                    }
                else:
                    data = None

                if data:
                    ws.send_str(json.dumps(data))

        return ws
예제 #2
0
 def test_send_str_closing(self):
     req = self.make_request('GET', '/')
     ws = WebSocketResponse()
     ws.start(req)
     ws.close()
     with self.assertRaises(RuntimeError):
         ws.send_str('string')
예제 #3
0
def test_send_str_closed(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    yield from ws.close()
    with pytest.raises(RuntimeError):
        ws.send_str('string')
예제 #4
0
 def test_send_str_closed(self):
     req = self.make_request("GET", "/")
     ws = WebSocketResponse()
     self.loop.run_until_complete(ws.prepare(req))
     self.loop.run_until_complete(ws.close())
     with self.assertRaises(RuntimeError):
         ws.send_str("string")
예제 #5
0
 def test_send_str_closed(self):
     req = self.make_request('GET', '/')
     ws = WebSocketResponse()
     ws.start(req)
     self.loop.run_until_complete(ws.close())
     with self.assertRaises(RuntimeError):
         ws.send_str('string')
예제 #6
0
def test_send_str_closed(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    yield from ws.close()
    with pytest.raises(RuntimeError):
        ws.send_str('string')
예제 #7
0
def function2561(function271, arg922):
    var2863 = function271('GET', '/')
    var2278 = WebSocketResponse()
    yield from var2278.prepare(var2863)
    var2278._reader.feed_data(WS_CLOSED_MESSAGE, 0)
    yield from var2278.close()
    arg922.spy(ws_logger, 'warning')
    var2278.send_str('string')
    assert ws_logger.warning.called
예제 #8
0
def test_send_str_closed(make_request, mocker):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    yield from ws.close()

    mocker.spy(ws_logger, 'warning')
    ws.send_str('string')
    assert ws_logger.warning.called
예제 #9
0
async def test_send_str_closed(make_request, mocker):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    await ws.prepare(req)
    ws._reader.feed_data(WS_CLOSED_MESSAGE, 0)
    await ws.close()

    mocker.spy(ws_logger, 'warning')
    ws.send_str('string')
    assert ws_logger.warning.called
예제 #10
0
def test_send_str_closed(make_request, mocker):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    ws._reader.feed_data(WS_CLOSED_MESSAGE, 0)
    yield from ws.close()

    mocker.spy(ws_logger, 'warning')
    ws.send_str('string')
    assert ws_logger.warning.called
예제 #11
0
    async def rpc_reconnect(self, ws: web.WebSocketResponse, r: web.Response,
                            account: str):
        """When a websocket connection sends a subscribe request, do this reconnection step"""
        log.server_logger.info('reconnecting;' + self.util.get_request_ip(r) +
                               ';' + ws.id)

        rpc = {
            "action": "account_info",
            "account": account,
            "pending": True,
            "representative": True
        }
        log.server_logger.info('sending account_info %s', account)
        response = await self.json_post(rpc)

        if response is None:
            log.server_logger.error('reconnect error; %s ; %s',
                                    self.util.get_request_ip(r), ws.id)
            ws.send_str('{"error":"reconnect error"}')
        else:
            log.server_logger.debug('received response for account_info %s',
                                    json.dumps(response))
            if account in r.app['subscriptions']:
                r.app['subscriptions'][account].add(ws.id)
            else:
                r.app['subscriptions'][account] = set()
                r.app['subscriptions'][account].add(ws.id)
            r.app['cur_prefs'][ws.id] = await r.app['rdata'].hget(
                ws.id, "currency")
            await r.app['rdata'].hset(ws.id, "last-connect",
                                      float(time.time()))
            price_cur = await r.app['rdata'].hget(
                "prices",
                f"{self.price_prefix}-" + r.app['cur_prefs'][ws.id].lower())
            price_btc = await r.app['rdata'].hget("prices",
                                                  f"{self.price_prefix}-btc")
            response['currency'] = r.app['cur_prefs'][ws.id].lower()
            response['price'] = float(price_cur)
            response['btc'] = float(price_btc)
            if self.banano_mode:
                response['nano'] = float(await r.app['rdata'].hget(
                    "prices", f"{self.price_prefix}-nano"))
            response['pending_count'] = await self.get_pending_count(r,
                                                                     account,
                                                                     uid=ws.id)
            response = json.dumps(response)

            log.server_logger.info(
                'reconnect response sent ; %s bytes; %s; %s',
                str(len(response)), self.util.get_request_ip(r), ws.id)

            await ws.send_str(response)
예제 #12
0
    async def background(self, ws: web.WebSocketResponse):
        commander = car_connector.Commander(self.car)

        while not ws.closed:
            try:
                command = self.command_queue.get_nowait()
                commander.send_command(command)
                ws.send_str(command)
                # print('Response:', response, now())
                self.command_queue.task_done()
            except Empty:
                await asyncio.sleep(0.01)
        print('Close background for car ID', self.car_id)
예제 #13
0
async def ws_handler(request):
    ws = WebSocketResponse()
    await ws.prepare(request)
    user_id = request.GET.get('user_id', -1)

    async for msg in ws:
        if msg.tp == MsgType.text:
            if msg.data == 'close':
                await remove_socket(app=ws.app, socket=ws, user_id=user_id)
            else:
                add_socket(app=request.app, socket=ws, user_id=user_id)
                ws.send_str(msg.data * 2)
    return ws
예제 #14
0
async def ws_handler(request):
    ws = WebSocketResponse()
    await ws.prepare(request)
    user_id = request.GET.get('user_id', -1)

    async for msg in ws:
        if msg.tp == MsgType.text:
            if msg.data == 'close':
                await remove_socket(app=ws.app, socket=ws, user_id=user_id)
            else:
                add_socket(app=request.app, socket=ws, user_id=user_id)
                ws.send_str(msg.data * 2)
    return ws
예제 #15
0
async def websocket_handler(request):
    resp = WebSocketResponse()
    await resp.prepare(request)

    async with AsyncTail(filepath=request.app['filepath']) as atail:
        async for line in atail:
            resp.send_str(json.dumps({
                'action': 'sent',
                'text': line
            }))

    resp.send_str(json.dumps({
        'action': 'close',
    }))
    await resp.close()
    print('Web socket connection closed')
    return resp
예제 #16
0
    def notifications(request, response):
        notifications = NotificationManager.instance()
        ws = WebSocketResponse()
        yield from ws.prepare(request)

        asyncio.async(process_websocket(ws))

        with notifications.queue() as queue:
            while True:
                try:
                    notification = yield from queue.get_json(5)
                except asyncio.futures.CancelledError:
                    break
                if ws.closed:
                    break
                ws.send_str(notification)
        return ws
예제 #17
0
파일: server.py 프로젝트: RodericDay/teburu
def wshandler(request):

    resp = WebSocketResponse()
    ok, protocol = resp.can_start(request)
    if not ok:
        with open(WS_FILE, 'rb') as fp:
            return Response(body=fp.read(), content_type='text/html')

    sockets = request.app['sockets']
    if len(sockets) == 0: restart_game()
    sockets.append(resp)
    resp.start(request)

    # login
    msg = yield from resp.receive()
    keycode = msg.data
    existing = USERMAP.get(keycode)
    if not existing or not existing.closed:
        random.seed(random.SystemRandom())
        keycode = ''.join(random.sample(string.ascii_letters, 32))
    USERMAP[keycode] = resp

    # communicate
    update_id_info(sockets)
    resp.send_str(json.dumps(ACTIONS))

    while True:
        msg = yield from resp.receive()

        if msg.tp == MsgType.text:

            move = json.loads(msg.data)+[len(ACTIONS)]
            ACTIONS.append(move)
            for ws in sockets:
                ws.send_str(json.dumps([move]))

        else:
            break

    sockets.remove(resp)
    update_id_info(sockets)
    return resp
예제 #18
0
async def ws_handler(request):
    resp = WebSocketResponse()
    ok, protocol = resp.can_start(request)
    logger.debug('ok %s, protocol %s', ok, protocol)
    if not ok:
        raise Exception('Could not start!')

    await resp.prepare(request)
    logger.debug('Someone joined.')
    app = request.app
    app['sockets'].append(resp)

    async for msg in resp:
        if msg.tp == MsgType.text:
            try:
                m = json.loads(msg.data)
                logger.debug('Got msg %s', m)
                if m['type'] in MSG_TYPES:
                    if hasattr(request, 'session'):
                        await get_tweets(resp, app, request.session, m, request.conn)
                    else:
                        logger.info('Unknown client, closing')
                        break
            except Exception as e:
                logger.exception('Got error %s', e)
                resp.send_str(json.dumps({'type': 'error', 'desc': 'Server error'}))
                break

        elif msg.tp == MsgType.error:
            logger.exception('ws connection closed with exception %s', resp.exception())

    await resp.close()
    app['sockets'].remove(resp)
    logger.debug('Connection is closed %s', resp)
    logger.debug('Return Response')
    return resp
예제 #19
0
async def websocket_handler(request):
    '''
    use websocket to handle button clicks/LED changes
    '''
    resp = WebSocketResponse()
    ok, protocol = resp.can_prepare(request)
    if not ok:
        return Response(body='This is a WebSocket, not a WebSite',
                        content_type='text/html')
    await resp.prepare(request)
    try:
        # new connection - send current GPIO configuration
        led_states = gpio_led.get_values()
        resp.send_str(json.dumps({'states': led_states, 'lines': GPIO_LINES}))
        request.app['sockets'].append(resp)

        # async wait for new WebSocket messages
        async for msg in resp:
            if msg.type == WSMsgType.TEXT:
                led_states = gpio_led.get_values()
                data = json.loads(msg.data)

                # switch selected GPIO by its pin number
                if 'switch_gpio' in data:
                    led_nr = GPIO_LINES.index(data['switch_gpio'])
                    led_states[led_nr] = int(not led_states[led_nr])
                    gpio_led.set_values(tuple(led_states))

                # update LED states to all connected clients
                for ws in request.app['sockets']:
                    await ws.send_str(json.dumps({'states': led_states}))
        return resp
    finally:
        # remove disconnected connections.
        # we do not need to send them the state update anymore
        request.app['sockets'].remove(resp)
예제 #20
0
def test_send_str_nonstring(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    with pytest.raises(TypeError):
        ws.send_str(b'bytes')
예제 #21
0
def test_nonstarted_send_str():
    ws = WebSocketResponse()
    with pytest.raises(RuntimeError):
        ws.send_str('string')
예제 #22
0
def test_send_str_nonstring(make_request):
    req = make_request('GET', '/')
    ws = WebSocketResponse()
    yield from ws.prepare(req)
    with pytest.raises(TypeError):
        ws.send_str(b'bytes')
예제 #23
0
 def test_nonstarted_send_str(self):
     ws = WebSocketResponse()
     with self.assertRaises(RuntimeError):
         ws.send_str('string')
예제 #24
0
def function2625(function271):
    var4377 = function271('GET', '/')
    var1358 = WebSocketResponse()
    yield from var1358.prepare(var4377)
    with pytest.raises(TypeError):
        var1358.send_str(b'bytes')
예제 #25
0
 def test_send_str_nonstring(self):
     req = self.make_request('GET', '/')
     ws = WebSocketResponse()
     ws.start(req)
     with self.assertRaises(TypeError):
         ws.send_str(b'bytes')
예제 #26
0
def function742():
    var3256 = WebSocketResponse()
    with pytest.raises(RuntimeError):
        var3256.send_str('string')
예제 #27
0
 def test_send_str_nonstring(self):
     req = self.make_request('GET', '/')
     ws = WebSocketResponse()
     self.loop.run_until_complete(ws.prepare(req))
     with self.assertRaises(TypeError):
         ws.send_str(b'bytes')
예제 #28
0
 def test_send_str_nonstring(self):
     req = self.make_request("GET", "/")
     ws = WebSocketResponse()
     self.loop.run_until_complete(ws.prepare(req))
     with self.assertRaises(TypeError):
         ws.send_str(b"bytes")
async def wshandler(request):
    resp = WebSocketResponse()
    ok, protocol = resp.can_prepare(request)
    if not ok:
        with open(WS_FILE, 'rb') as fp:
            return Response(body=fp.read(), content_type='text/html')

    await resp.prepare(request)

    try:
        # перебираем всех уже подключенных пользователей и рассылаем им сообщение
        for ws in request.app['sockets']:
            ws.send_str('Someone joined')
        # добавляем новое соединение
        # if resp not in request.app['sockets']:
        request.app['sockets'].append(resp)

        # ws.send_str('{"actions": ["do_login"]}')
        # return resp

        # if getattr(resp, 'user_id') is not None:
        # перебираем свои сообщения
        async for msg in resp:
            if msg.type == WSMsgType.TEXT:
                try:
                    json_data = json.loads(msg.data)
                except Exception:
                    json_data = {}

                id_to = None
                message = None
                user_to = None
                message_obj = None

                try:
                    id_to = json_data.get('id_to', False)
                    message = json_data.get('message')
                except Exception:
                    pass

                if id_to:
                    user_to = User.where('id', '=', id_to).first()
                # @TODO: add check - is he in contact list?
                if user_to and getattr(resp, 'user_id', False) and message:
                    message_obj = Message()
                    message_obj.id_from = resp.user_id
                    message_obj.id_to = user_to.id
                    message_obj.message = message
                    message_obj.is_viewed = False
                    message_obj.save()
                # перебираем все соединения
                for i, ws in enumerate(request.app['sockets']):
                    # если это не я
                    if ws is not resp:
                        try:
                            # if id_to and getattr(resp, 'user_id', False) and message and str(id_to) == str(ws.user_id):
                            if user_to and message_obj:
                                # reciever is online
                                if getattr(ws, 'user_id', False) and str(id_to) == str(ws.user_id):
                                    send_object = {
                                        'id_to': user_to.id,
                                        'id_from': resp.user_id,
                                        'message': message
                                    }
                                    ws.send_str(str(send_object))
                                    message_obj.is_viewed = True
                                    message_obj.save()
                            else:
                                pass
                        except Exception:
                            pass
                            # ws.send_str(json_data.get('message'))
                    # если это я
                    else:
                        if not getattr(ws, 'user_id', False):
                            try:
                                api_token = json_data.get('api_token')
                                if api_token is not None and api_token:
                                    user = User.where('api_token', '=', api_token).first()
                                    if user is not None:
                                        request.app['sockets'][i].user_id = user.id
                                        resp.user_id = user.id
                                        resp.send_str('{"authorized": true}')
                                    else:
                                        resp.send_str(get_relogin())
                                else:
                                    resp.send_str(get_relogin())
                            except Exception:
                                resp.send_str(get_relogin())
                        else:
                            resp.send_str('{"ok": true}')
            else:
                return resp
        return resp
    finally:
        # разрываем соединение
        request.app['sockets'].remove(resp)
        for ws in request.app['sockets']:
            ws.send_str('Someone disconnected.')
예제 #30
0
def test_nonstarted_send_str():
    ws = WebSocketResponse()
    with pytest.raises(RuntimeError):
        ws.send_str('string')