def function350(function271): var4234 = function271('GET', '/') var3290 = WebSocketResponse() yield from var3290.prepare(var4234) with pytest.raises(RuntimeError) as var847: var3290.can_prepare(var4234) assert ('Already started' in str(var847.value))
def test_can_prepare_started(make_request): req = make_request("GET", "/") ws = WebSocketResponse() yield from ws.prepare(req) with pytest.raises(RuntimeError) as ctx: ws.can_prepare(req) assert "Already started" in str(ctx.value)
async def test_can_prepare_started(make_request): req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) with pytest.raises(RuntimeError) as ctx: ws.can_prepare(req) assert 'Already started' in str(ctx.value)
async def test_can_prepare_started(make_request) -> None: req = make_request("GET", "/") ws = WebSocketResponse() await ws.prepare(req) with pytest.raises(RuntimeError) as ctx: ws.can_prepare(req) assert "Already started" in str(ctx.value)
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: print('Someone joined.') for ws in request.app['sockets']: await ws.send_str('Someone joined') request.app['sockets'].append(resp) async for msg in resp: if msg.type == WSMsgType.TEXT: for ws in request.app['sockets']: if ws is not resp: await ws.send_str(msg.data) else: return resp return resp finally: request.app['sockets'].remove(resp) print('Someone disconnected.') for ws in request.app['sockets']: await ws.send_str('Someone disconnected.')
async def get(self): ws = WebSocketResponse() if ws.can_prepare(self.request): await self.websocket(ws) return if self.entry.etag == self.etag: return Response(status=304) return self.entry.to_response(Response)
async def websocket_chat(self, request): username = await authorized_userid(request) if username is None: return self.render_template( template_name='page/index.html', request=request, context={}, ) user_counter = await self.storage.get_all_users() resp = WebSocketResponse() available = resp.can_prepare(request) if not available: return self.render_template( template_name='page/chat.html', request=request, context={ 'user_name': username, 'user_count': len(user_counter), }, ) await resp.prepare(request) try: print('Someone joined.') for ws in request.app['sockets']: await ws.send_str('Someone joined.') request.app['sockets'].append(resp) async for msg in resp: if msg.type == WSMsgType.TEXT: data = { 'time': str(dt.now().time()), 'name': username, 'message': msg.data, } await self.save(data) for ws in request.app['sockets']: # if ws is not resp: await ws.send_json(data) else: return resp return resp finally: request.app['sockets'].remove(resp) print('Someone disconnected.') for ws in request.app['sockets']: await ws.send_str('Someone disconnected.')
async def process( self, request: Request, bot: Bot, ws_response: WebSocketResponse = None) -> Optional[Response]: if not request: raise TypeError("request can't be None") # if ws_response is None: # raise TypeError("ws_response can't be None") if not bot: raise TypeError("bot can't be None") try: # Only GET requests for web socket connects are allowed if (request.method == "GET" and ws_response and ws_response.can_prepare(request)): # All socket communication will be handled by the internal streaming-specific BotAdapter await self._connect(bot, request, ws_response) elif request.method == "POST": # Deserialize the incoming Activity if "application/json" in request.headers["Content-Type"]: body = await request.json() else: raise HTTPUnsupportedMediaType() activity: Activity = Activity().deserialize(body) # A POST request must contain an Activity if not activity.type: raise HTTPBadRequest # Grab the auth header from the inbound http request auth_header = (request.headers["Authorization"] if "Authorization" in request.headers else "") # Process the inbound activity with the bot invoke_response = await self.process_activity( auth_header, activity, bot.on_turn) # Write the response, serializing the InvokeResponse if invoke_response: return json_response(data=invoke_response.body, status=invoke_response.status) return Response(status=201) else: raise HTTPMethodNotAllowed except (HTTPUnauthorized, PermissionError) as _: raise HTTPUnauthorized
async def wshandler(request): vechicle = request.app['server'] ws_client = WebSocketResponse() ok, protocol = ws_client.can_prepare(request) if not ok: return Response(body=b"invalid connection", content_type='text/html') await ws_client.prepare(request) try: logger.info('Someone joined.') request.app['ws_clients'].append(ws_client) async for raw_msg in ws_client: if raw_msg.type == WSMsgType.TEXT: try: msg = json.loads(raw_msg.data) logger.debug('incomming msg: %s', msg) cmd = msg['cmd'] if cmd in vechicle.commands: for action in vechicle.commands[cmd]: action(msg['arg1']) else: logger.info('unknow command %s', cmd) await stream_state(vechicle) except Exception as e: logger.exception('invalid message %s', raw_msg.data) await ws_client.send_str( json.dumps({ 'result': 'error', 'message': str(e) }) ) else: return ws_client return ws_client finally: request.app['ws_clients'].remove(ws_client) logger.info('Someone disconnected.')
def wshandler(request): resp = WebSocketResponse() ok, protocol = resp.can_prepare(request) if not ok: return HTTPFound('/index.html') yield from resp.prepare(request) print('Client connected.') request.app['sockets'].append(resp) box.command({"command": "state"}) while True: msg = yield from resp.receive() if msg.tp == MsgType.text: box.command(json.loads(msg.data)) else: break request.app['sockets'].remove(resp) print('Someone disconnected.') return resp
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)
async def _connect_web_socket(self, bot: Bot, request: Request, ws_response: WebSocketResponse): if not request: raise TypeError("request can't be None") if ws_response is None: raise TypeError("ws_response can't be None") if not bot: raise TypeError( f"'bot: {bot.__class__.__name__}' argument can't be None") if not ws_response.can_prepare(request): raise HTTPBadRequest(text="Upgrade to WebSocket is required.") if not await self._http_authenticate_request(request): raise HTTPUnauthorized(text="Request authentication failed.") try: await ws_response.prepare(request) bf_web_socket = AiohttpWebSocket(ws_response) request_handler = StreamingRequestHandler(bot, self, bf_web_socket) if self.request_handlers is None: self.request_handlers = [] self.request_handlers.append(request_handler) await request_handler.listen() except Exception as error: import traceback # pylint: disable=import-outside-toplevel traceback.print_exc() raise Exception( f"Unable to create transport server. Error: {str(error)}")
async def stream(request): """ Web socket stream for """ ws_current = WebSocketResponse() ws_ready = ws_current.can_prepare(request) if not ws_ready.ok: return ws_current await ws_current.prepare(request) if 'websockets' not in request.app: request.app['websockets'] = WeakSet() request.app['websockets'].add(ws_current) while True: msg = await ws_current.receive() if msg.type == WSMsgType.text: for ws in request.app['websockets']: if ws is ws_current: continue await ws.send_str(msg.data) elif msg.type == WSMsgType.BINARY: for ws in request.app['websockets']: if ws is ws_current: continue await ws.send_bytes(msg.data) else: break request.app['websockets'].discard(ws_current) return ws_current
def test_can_prepare_without_upgrade(make_request): req = make_request('GET', '/', headers=CIMultiDict({})) ws = WebSocketResponse() assert (False, None) == ws.can_prepare(req)
def test_can_prepare_without_upgrade(make_request) -> None: req = make_request("GET", "/", headers=CIMultiDict({})) ws = WebSocketResponse() assert WebSocketReady(False, None) == ws.can_prepare(req)
def test_can_prepare_unknown_protocol(make_request): req = make_request('GET', '/') ws = WebSocketResponse() assert WebSocketReady(True, None) == ws.can_prepare(req)
def test_can_prepare_ok(make_request): req = make_request("GET", "/", protocols=True) ws = WebSocketResponse(protocols=("chat",)) assert (True, "chat") == ws.can_prepare(req)
def test_can_prepare_without_upgrade(self): req = self.make_request("GET", "/", headers=CIMultiDict({})) ws = WebSocketResponse() self.assertEqual((False, None), ws.can_prepare(req))
def test_can_prepare_ok(self): req = self.make_request('GET', '/') ws = WebSocketResponse(protocols=('chat',)) self.assertEqual((True, 'chat'), ws.can_prepare(req))
def test_can_prepare_invalid_method(make_request): req = make_request("POST", "/") ws = WebSocketResponse() assert (False, None) == ws.can_prepare(req)
def function2006(function271): var32 = function271('GET', '/', headers=CIMultiDict({})) var133 = WebSocketResponse() assert ((False, None) == var133.can_prepare(var32))
def function1547(function271): var3899 = function271('POST', '/') var3504 = WebSocketResponse() assert ((False, None) == var3504.can_prepare(var3899))
def function801(function271): var2751 = function271('GET', '/') var281 = WebSocketResponse() assert ((True, None) == var281.can_prepare(var2751))
def function1233(function271): var373 = function271('GET', '/', protocols=True) var725 = WebSocketResponse(protocols=('chat',)) assert ((True, 'chat') == var725.can_prepare(var373))
async def lobby_socket_handler(request): users = request.app["users"] sockets = request.app["lobbysockets"] seeks = request.app["seeks"] ws = WebSocketResponse() ws_ready = ws.can_prepare(request) if not ws_ready.ok: raise web.HTTPFound("/") await ws.prepare(request) session = await aiohttp_session.get_session(request) session_user = session.get("user_name") user = users[ session_user] if session_user is not None and session_user in users else None lobby_ping_task = None ping_counter = [0] async def lobby_pinger(ping_counter): """ Prevent Heroku to close inactive ws """ while not ws.closed: if ping_counter[0] > 2: await ws.close(code=1009) if ws in user.lobby_sockets: user.lobby_sockets.remove(ws) # online user counter will be updated in quit_lobby also! if len(user.lobby_sockets) == 0: # log.info("%s went offline (PINGER)" % user.username) await user.clear_seeks(sockets, seeks) await user.quit_lobby(sockets, disconnect=True) break if user.bot: await user.event_queue.put("\n") # heroku needs something at least in 50 sec not to close BOT connections (stream events) on server side else: await ws.send_json({ "type": "ping", "timestamp": "%s" % time() }) await asyncio.sleep(3) ping_counter[0] += 1 log.debug("-------------------------- NEW lobby WEBSOCKET by %s" % user) async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: if type(msg.data) == str: if msg.data == "close": log.debug("Got 'close' msg.") break else: data = json.loads(msg.data) if not data["type"] == "pong": log.debug("Websocket (%s) message: %s" % (id(ws), msg)) if data["type"] == "pong": ping_counter[0] -= 1 elif data["type"] == "get_seeks": response = get_seeks(seeks) await ws.send_json(response) elif data["type"] == "create_ai_challenge": no = await is_playing(request, user, ws) if no: continue variant = data["variant"] engine = users.get("Fairy-Stockfish") if engine is None or not engine.online(): # TODO: message that engine is offline, but capture BOT will play instead engine = users.get("Random-Mover") seek = Seek(user, variant, fen=data["fen"], color=data["color"], base=data["minutes"], inc=data["increment"], byoyomi_period=data["byoyomi_period"], level=data["level"], rated=data["rated"], chess960=data["chess960"], handicap=data["handicap"]) # print("SEEK", user, variant, data["fen"], data["color"], data["minutes"], data["increment"], data["level"], False, data["chess960"]) seeks[seek.id] = seek response = await new_game(request.app, engine, seek.id) await ws.send_json(response) if response["type"] != "error": gameId = response["gameId"] engine.game_queues[gameId] = asyncio.Queue() await engine.event_queue.put( challenge(seek, response)) elif data["type"] == "create_seek": no = await is_playing(request, user, ws) if no: continue print("create_seek", data) create_seek(seeks, user, data, ws) await lobby_broadcast(sockets, get_seeks(seeks)) if data.get("target"): queue = users[data["target"]].notify_queue if queue is not None: await queue.put( json.dumps({"notify": "new_challenge"})) elif data["type"] == "delete_seek": del seeks[data["seekID"]] del user.seeks[data["seekID"]] await lobby_broadcast(sockets, get_seeks(seeks)) elif data["type"] == "accept_seek": no = await is_playing(request, user, ws) if no: continue if data["seekID"] not in seeks: continue seek = seeks[data["seekID"]] # print("accept_seek", seek.as_json) response = await new_game(request.app, user, data["seekID"]) await ws.send_json(response) if seek.user.bot: gameId = response["gameId"] seek.user.game_queues[gameId] = asyncio.Queue() await seek.user.event_queue.put( challenge(seek, response)) else: await seek.ws.send_json(response) # Inform others, new_game() deleted accepted seek allready. await lobby_broadcast(sockets, get_seeks(seeks)) elif data["type"] == "lobby_user_connected": if session_user is not None: if data["username"] and data[ "username"] != session_user: log.info( "+++ Existing lobby_user %s socket connected as %s." % (session_user, data["username"])) session_user = data["username"] if session_user in users: user = users[session_user] else: user = User( request.app, username=data["username"], anon=data["username"].startswith( "Anon-")) users[user.username] = user response = { "type": "lobbychat", "user": "", "message": "%s joined the lobby" % session_user } else: if session_user in users: user = users[session_user] else: user = User( request.app, username=data["username"], anon=data["username"].startswith( "Anon-")) users[user.username] = user response = { "type": "lobbychat", "user": "", "message": "%s joined the lobby" % session_user } else: log.info( "+++ Existing lobby_user %s socket reconnected." % data["username"]) session_user = data["username"] if session_user in users: user = users[session_user] else: user = User( request.app, username=data["username"], anon=data["username"].startswith("Anon-")) users[user.username] = user response = { "type": "lobbychat", "user": "", "message": "%s rejoined the lobby" % session_user } ping_counter[0] = 0 await lobby_broadcast(sockets, response) # update websocket user.lobby_sockets.add(ws) sockets[user.username] = user.lobby_sockets response = { "type": "lobby_user_connected", "username": user.username } await ws.send_json(response) response = { "type": "fullchat", "lines": list(request.app["chat"]) } await ws.send_json(response) loop = asyncio.get_event_loop() lobby_ping_task = loop.create_task( lobby_pinger(ping_counter)) # send game count response = { "type": "g_cnt", "cnt": request.app["g_cnt"] } await ws.send_json(response) # send user count if len(user.game_sockets) == 0: # not connected to any game socket but connected to lobby socket if len(user.lobby_sockets) == 1: request.app["u_cnt"] += 1 response = { "type": "u_cnt", "cnt": request.app["u_cnt"] } await lobby_broadcast(sockets, response) else: response = { "type": "u_cnt", "cnt": request.app["u_cnt"] } await ws.send_json(response) elif data["type"] == "lobbychat": response = { "type": "lobbychat", "user": user.username, "message": data["message"] } await lobby_broadcast(sockets, response) request.app["chat"].append(response) elif data["type"] == "logout": await ws.close() elif data["type"] == "disconnect": # Used only to test socket disconnection... await ws.close(code=1009) else: log.debug("type(msg.data) != str %s" % msg) elif msg.type == aiohttp.WSMsgType.ERROR: log.debug("!!! Lobby ws connection closed with exception %s" % ws.exception()) else: log.debug("other msg.type %s %s" % (msg.type, msg)) log.info("--- Lobby Websocket %s closed" % id(ws)) if user is not None: if ws in user.lobby_sockets: user.lobby_sockets.remove(ws) # online user counter will be updated in quit_lobby also! if len(user.lobby_sockets) == 0: await user.clear_seeks(sockets, seeks) await user.quit_lobby(sockets, disconnect=False) if lobby_ping_task is not None: lobby_ping_task.cancel() return ws
def test_can_prepare_ok(make_request) -> None: req = make_request("GET", "/", protocols=True) ws = WebSocketResponse(protocols=("chat", )) assert WebSocketReady(True, "chat") == ws.can_prepare(req)
def test_can_prepare_invalid_method(self): req = self.make_request("POST", "/") ws = WebSocketResponse() self.assertEqual((False, None), ws.can_prepare(req))
def test_can_prepare_ok(self): req = self.make_request('GET', '/', protocols=True) ws = WebSocketResponse(protocols=('chat', )) self.assertEqual((True, 'chat'), ws.can_prepare(req))
def test_can_prepare_started(self): req = self.make_request("GET", "/") ws = WebSocketResponse() self.loop.run_until_complete(ws.prepare(req)) with self.assertRaisesRegex(RuntimeError, "Already started"): ws.can_prepare(req)
def test_can_prepare_unknown_protocol(self): req = self.make_request('GET', '/') ws = WebSocketResponse() self.assertEqual((True, None), ws.can_prepare(req))
def test_can_prepare_invalid_method(self): req = self.make_request('POST', '/') ws = WebSocketResponse() self.assertEqual((False, None), ws.can_prepare(req))
def test_can_prepare_without_upgrade(make_request): req = make_request('GET', '/', headers=CIMultiDict({})) ws = WebSocketResponse() assert WebSocketReady(False, None) == ws.can_prepare(req)
async def round_socket_handler(request): users = request.app["users"] sockets = request.app["lobbysockets"] seeks = request.app["seeks"] games = request.app["games"] db = request.app["db"] ws = WebSocketResponse(heartbeat=3.0, receive_timeout=10.0) ws_ready = ws.can_prepare(request) if not ws_ready.ok: return web.HTTPFound("/") await ws.prepare(request) session = await aiohttp_session.get_session(request) session_user = session.get("user_name") user = users[ session_user] if session_user is not None and session_user in users else None game = None opp_ws = None log.debug("-------------------------- NEW round WEBSOCKET by %s", user) try: async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: if msg.data == "close": log.debug("Got 'close' msg.") break else: data = json.loads(msg.data) # log.debug("Websocket (%s) message: %s" % (id(ws), msg)) if data["type"] == "move": # log.info("Got USER move %s %s %s" % (user.username, data["gameId"], data["move"])) game = await load_game(request.app, data["gameId"]) move = data["move"] await play_move(request.app, user, game, move, data["clocks"], data["ply"]) elif data["type"] == "analysis_move": game = await load_game(request.app, data["gameId"]) await analysis_move(request.app, user, game, data["move"], data["fen"], data["ply"]) elif data["type"] == "ready": game = await load_game(request.app, data["gameId"]) opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] if opp_player.bot: # Janggi game start have to wait for human player setup! if game.variant != "janggi" or not (game.bsetup or game.wsetup): await opp_player.event_queue.put( game.game_start) response = { "type": "gameStart", "gameId": data["gameId"] } await ws.send_json(response) else: response = { "type": "gameStart", "gameId": data["gameId"] } await ws.send_json(response) response = { "type": "user_present", "username": user.username } await round_broadcast(game, users, game.spectator_list, full=True) elif data["type"] == "board": game = await load_game(request.app, data["gameId"]) if game.variant == "janggi": if (game.bsetup or game.wsetup) and game.status <= STARTED: if game.bsetup: await ws.send_json({ "type": "setup", "color": "black", "fen": game.board.initial_fen }) elif game.wsetup: await ws.send_json({ "type": "setup", "color": "white", "fen": game.board.initial_fen }) else: board_response = game.get_board(full=True) await ws.send_json(board_response) else: board_response = game.get_board(full=True) await ws.send_json(board_response) elif data["type"] == "setup": # Janggi game starts with a prelude phase to set up horses and elephants # First the second player (Red) choses his setup! Then the first player (Blue) game = await load_game(request.app, data["gameId"]) game.board.initial_fen = data["fen"] game.initial_fen = game.board.initial_fen game.board.fen = game.board.initial_fen # print("--- Got FEN from %s %s" % (data["color"], data["fen"])) opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] game.steps[0]["fen"] = data["fen"] game.set_dests() if data["color"] == "black": game.bsetup = False response = { "type": "setup", "color": "white", "fen": data["fen"] } await ws.send_json(response) if opp_player.bot: game.board.janggi_setup("w") game.steps[0]["fen"] = game.board.initial_fen game.set_dests() else: opp_ws = users[opp_name].game_sockets[ data["gameId"]] await opp_ws.send_json(response) else: game.wsetup = False response = game.get_board(full=True) # log.info("User %s asked board. Server sent: %s" % (user.username, board_response["fen"])) await ws.send_json(response) if not opp_player.bot: opp_ws = users[opp_name].game_sockets[ data["gameId"]] await opp_ws.send_json(response) if opp_player.bot: await opp_player.event_queue.put(game.game_start) elif data["type"] == "analysis": game = await load_game(request.app, data["gameId"]) # If there is any fishnet client, use it. if len(request.app["workers"]) > 0: work_id = "".join( random.choice(string.ascii_letters + string.digits) for x in range(6)) work = { "work": { "type": "analysis", "id": work_id, }, # or: # "work": { # "type": "move", # "id": "work_id", # "level": 5 // 1 to 8 # }, "username": data["username"], "game_id": data["gameId"], # optional "position": game.board. initial_fen, # start position (X-FEN) "variant": game.variant, "chess960": game.chess960, "moves": " ".join(game.board.move_stack ), # moves of the game (UCI) "nodes": 500000, # optional limit # "skipPositions": [1, 4, 5] # 0 is the first position } request.app["works"][work_id] = work request.app["fishnet"].put_nowait( (ANALYSIS, work_id)) else: engine = users.get("Fairy-Stockfish") if (engine is not None) and engine.online: engine.game_queues[ data["gameId"]] = asyncio.Queue() await engine.event_queue.put( game.analysis_start(data["username"])) response = { "type": "roundchat", "user": "", "room": "spectator", "message": "Analysis request sent..." } await ws.send_json(response) elif data["type"] == "rematch": game = await load_game(request.app, data["gameId"]) if game is None: log.debug("Requested game %s not found!") response = { "type": "game_not_found", "username": user.username, "gameId": data["gameId"] } await ws.send_json(response) continue opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] handicap = data["handicap"] fen = "" if game.variant == "janggi" else game.initial_fen if opp_player.bot: if opp_player.username == "Random-Mover": engine = users.get("Random-Mover") else: engine = users.get("Fairy-Stockfish") if engine is None or not engine.online: # TODO: message that engine is offline, but capture BOT will play instead engine = users.get("Random-Mover") color = "w" if game.wplayer.username == opp_name else "b" if handicap: color = "w" if color == "b" else "b" seek = Seek(user, game.variant, fen=fen, color=color, base=game.base, inc=game.inc, byoyomi_period=game.byoyomi_period, level=game.level, rated=game.rated, chess960=game.chess960) seeks[seek.id] = seek response = await new_game(request.app, engine, seek.id) await ws.send_json(response) await engine.event_queue.put( challenge(seek, response)) gameId = response["gameId"] engine.game_queues[gameId] = asyncio.Queue() else: try: opp_ws = users[opp_name].game_sockets[ data["gameId"]] except KeyError: # opp disconnected pass if opp_name in game.rematch_offers: color = "w" if game.wplayer.username == opp_name else "b" if handicap: color = "w" if color == "b" else "b" seek = Seek(user, game.variant, fen=fen, color=color, base=game.base, inc=game.inc, byoyomi_period=game.byoyomi_period, level=game.level, rated=game.rated, chess960=game.chess960) seeks[seek.id] = seek response = await new_game( request.app, opp_player, seek.id) await ws.send_json(response) await opp_ws.send_json(response) else: game.rematch_offers.add(user.username) response = { "type": "offer", "message": "Rematch offer sent", "room": "player", "user": "" } game.messages.append(response) await ws.send_json(response) await opp_ws.send_json(response) elif data["type"] == "draw": game = await load_game(request.app, data["gameId"]) opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] response = await draw(games, data, agreement=opp_name in game.draw_offers) await ws.send_json(response) if opp_player.bot: if game.status > STARTED: await opp_player.game_queues[ data["gameId"]].put(game.game_end) else: try: opp_ws = users[opp_name].game_sockets[ data["gameId"]] await opp_ws.send_json(response) except KeyError: # opp disconnected pass if opp_name not in game.draw_offers: game.draw_offers.add(user.username) await round_broadcast(game, users, response) elif data["type"] == "logout": await ws.close() elif data["type"] == "byoyomi": game = await load_game(request.app, data["gameId"]) game.byo_correction += game.inc * 1000 game.byoyomi_periods[0 if data["color"] == "white" else 1] = data["period"] # print("BYOYOMI:", data) elif data["type"] in ("abort", "resign", "abandone", "flag"): game = await load_game(request.app, data["gameId"]) if data["type"] == "abort" and ( game is not None) and game.board.ply > 2: continue response = await game.game_ended(user, data["type"]) await ws.send_json(response) opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] if opp_player.bot: await opp_player.game_queues[data["gameId"] ].put(game.game_end) else: if data["gameId"] in users[opp_name].game_sockets: opp_ws = users[opp_name].game_sockets[ data["gameId"]] await opp_ws.send_json(response) await round_broadcast(game, users, response) elif data["type"] == "embed_user_connected": game = await load_game(request.app, data["gameId"]) if game is None: log.debug("Requested game %s not found!") response = { "type": "game_not_found", "gameId": data["gameId"] } await ws.send_json(response) continue else: response = {"type": "embed_user_connected"} await ws.send_json(response) elif data["type"] == "game_user_connected": game = await load_game(request.app, data["gameId"]) if session_user is not None: if data["username"] and data[ "username"] != session_user: log.info( "+++ Existing game_user %s socket connected as %s.", session_user, data["username"]) session_user = data["username"] if session_user in users: user = users[session_user] else: user = User( request.app, username=data["username"], anon=data["username"].startswith( "Anon-")) users[user.username] = user # Update logged in users as spactators if user.username != game.wplayer.username and user.username != game.bplayer.username and game is not None: game.spectators.add(user) else: if session_user in users: user = users[session_user] else: user = User( request.app, username=data["username"], anon=data["username"].startswith( "Anon-")) users[user.username] = user else: log.info( "+++ Existing game_user %s socket reconnected.", data["username"]) session_user = data["username"] if session_user in users: user = users[session_user] else: user = User( request.app, username=data["username"], anon=data["username"].startswith("Anon-")) users[user.username] = user # update websocket if data["gameId"] in user.game_sockets: await user.game_sockets[data["gameId"]].close() user.game_sockets[data["gameId"]] = ws user.update_online() # remove user seeks if len(user.lobby_sockets) == 0 or ( game.status <= STARTED and (user.username == game.wplayer.username or user.username == game.bplayer.username)): await user.clear_seeks(sockets, seeks) if game is None: log.debug("Requested game %s not found!") response = { "type": "game_not_found", "username": user.username, "gameId": data["gameId"] } await ws.send_json(response) continue else: if user.username != game.wplayer.username and user.username != game.bplayer.username: game.spectators.add(user) await round_broadcast(game, users, game.spectator_list, full=True) response = { "type": "game_user_connected", "username": user.username, "gameId": data["gameId"], "ply": game.board.ply } await ws.send_json(response) response = { "type": "crosstable", "ct": game.crosstable } await ws.send_json(response) response = { "type": "fullchat", "lines": list(game.messages) } await ws.send_json(response) response = { "type": "user_present", "username": user.username } await round_broadcast(game, users, response, full=True) # not connected to lobby socket but connected to game socket if len(user.game_sockets ) == 1 and user.username not in sockets: response = { "type": "u_cnt", "cnt": online_count(users) } await lobby_broadcast(sockets, response) elif data["type"] == "is_user_present": player_name = data["username"] player = users.get(player_name) await asyncio.sleep(1) if player is not None and data["gameId"] in ( player.game_queues if player.bot else player.game_sockets): response = { "type": "user_present", "username": player_name } else: response = { "type": "user_disconnected", "username": player_name } await ws.send_json(response) elif data["type"] == "moretime": # TODO: stop and update game stopwatch time with updated secs game = await load_game(request.app, data["gameId"]) opp_color = WHITE if user.username == game.bplayer.username else BLACK if opp_color == game.stopwatch.color: opp_time = game.stopwatch.stop() game.stopwatch.restart(opp_time + MORE_TIME) opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] if not opp_player.bot: opp_ws = users[opp_name].game_sockets[ data["gameId"]] response = { "type": "moretime", "username": opp_name } await opp_ws.send_json(response) await round_broadcast(game, users, response) elif data["type"] == "roundchat": gameId = data["gameId"] game = await load_game(request.app, gameId) # Users running a fishnet worker can ask server side analysis with chat message: !analysis if data["message"] == "!analysis" and user.username in request.app[ "fishnet_versions"]: for step in game.steps: if "analysis" in step: del step["analysis"] await ws.send_json({"type": "request_analysis"}) continue response = { "type": "roundchat", "user": user.username, "message": data["message"], "room": data["room"] } game.messages.append(response) for name in (game.wplayer.username, game.bplayer.username): player = users[name] if player.bot: if gameId in player.game_queues: await player.game_queues[gameId].put( '{"type": "chatLine", "username": "******", "room": "spectator", "text": "%s"}\n' % (user.username, data["message"])) else: if gameId in player.game_sockets: player_ws = player.game_sockets[gameId] await player_ws.send_json(response) await round_broadcast(game, users, response) elif data["type"] == "leave": response = { "type": "roundchat", "user": "", "message": "%s left the game" % user.username, "room": "player" } gameId = data["gameId"] game = await load_game(request.app, gameId) game.messages.append(response) opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] if not opp_player.bot and gameId in opp_player.game_sockets: opp_player_ws = opp_player.game_sockets[gameId] await opp_player_ws.send_json(response) response = { "type": "user_disconnected", "username": user.username } await opp_player_ws.send_json(response) await round_broadcast(game, users, response) elif data["type"] == "updateTV": if "profileId" in data and data["profileId"] != "": gameId = await tv_game_user( db, users, data["profileId"]) else: gameId = await tv_game(db, request.app) if gameId != data["gameId"] and gameId is not None: response = {"type": "updateTV", "gameId": gameId} await ws.send_json(response) elif data["type"] == "count": game = await load_game(request.app, data["gameId"]) cur_player = game.bplayer if game.board.color == BLACK else game.wplayer opp_name = game.wplayer.username if user.username == game.bplayer.username else game.bplayer.username opp_player = users[opp_name] opp_ws = users[opp_name].game_sockets[data["gameId"]] if user.username == cur_player.username: if data["mode"] == "start": game.start_manual_count() response = { "type": "count", "message": "Board's honor counting started", "room": "player", "user": "" } await ws.send_json(response) await opp_ws.send_json(response) await round_broadcast(game, users, response) elif data["mode"] == "stop": game.stop_manual_count() response = { "type": "count", "message": "Board's honor counting stopped", "room": "player", "user": "" } await ws.send_json(response) await opp_ws.send_json(response) await round_broadcast(game, users, response) else: response = { "type": "count", "message": "You can only start/stop board's honor counting on your own turn!", "room": "player", "user": "" } await ws.send_json(response) elif msg.type == aiohttp.WSMsgType.CLOSED: log.debug( "--- Round websocket %s msg.type == aiohttp.WSMsgType.CLOSED", id(ws)) break elif msg.type == aiohttp.WSMsgType.ERROR: log.error( "--- Round ws %s msg.type == aiohttp.WSMsgType.ERROR", id(ws)) break else: log.debug("--- Round ws other msg.type %s %s", msg.type, msg) except OSError: # disconnected pass except Exception: log.exception( "ERROR: Exception in round_socket_handler() owned by %s ", session_user) finally: log.debug("---fianlly: await ws.close()") await ws.close() if game is not None and not user.bot: if game.id in user.game_sockets: del user.game_sockets[game.id] user.update_online() if user.username != game.wplayer.username and user.username != game.bplayer.username: game.spectators.discard(user) await round_broadcast(game, users, game.spectator_list, full=True) # not connected to lobby socket and not connected to game socket if len(user.game_sockets) == 0 and user.username not in sockets: response = {"type": "u_cnt", "cnt": online_count(users)} await lobby_broadcast(sockets, response) if game is not None: response = {"type": "user_disconnected", "username": user.username} await round_broadcast(game, users, response, full=True) return ws
async def lobby_socket_handler(request): users = request.app["users"] sockets = request.app["lobbysockets"] seeks = request.app["seeks"] ws = WebSocketResponse(heartbeat=3.0, receive_timeout=10.0) ws_ready = ws.can_prepare(request) if not ws_ready.ok: raise web.HTTPFound("/") await ws.prepare(request) session = await aiohttp_session.get_session(request) session_user = session.get("user_name") user = users[ session_user] if session_user is not None and session_user in users else None if (user is not None) and (not user.enabled): await ws.close() session.invalidate() raise web.HTTPFound("/") log.debug("-------------------------- NEW lobby WEBSOCKET by %s" % user) try: async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: if msg.data == "close": log.debug("Got 'close' msg.") break else: data = json.loads(msg.data) if not data["type"] == "pong": log.debug("Websocket (%s) message: %s" % (id(ws), msg)) if data["type"] == "get_seeks": response = get_seeks(seeks) await ws.send_json(response) elif data["type"] == "create_ai_challenge": no = await is_playing(request, user, ws) if no: continue variant = data["variant"] engine = users.get("Fairy-Stockfish") if engine is None or not engine.online(): # TODO: message that engine is offline, but capture BOT will play instead engine = users.get("Random-Mover") seek = Seek(user, variant, fen=data["fen"], color=data["color"], base=data["minutes"], inc=data["increment"], byoyomi_period=data["byoyomiPeriod"], level=data["level"], rated=data["rated"], chess960=data["chess960"], alternate_start=data["alternateStart"]) # print("SEEK", user, variant, data["fen"], data["color"], data["minutes"], data["increment"], data["level"], False, data["chess960"]) seeks[seek.id] = seek response = await new_game(request.app, engine, seek.id) await ws.send_json(response) if response["type"] != "error": gameId = response["gameId"] engine.game_queues[gameId] = asyncio.Queue() await engine.event_queue.put( challenge(seek, response)) elif data["type"] == "create_seek": no = await is_playing(request, user, ws) if no: continue print("create_seek", data) create_seek(seeks, user, data, ws) await lobby_broadcast(sockets, get_seeks(seeks)) if data.get("target"): queue = users[data["target"]].notify_queue if queue is not None: await queue.put( json.dumps({"notify": "new_challenge"})) elif data["type"] == "delete_seek": del seeks[data["seekID"]] del user.seeks[data["seekID"]] await lobby_broadcast(sockets, get_seeks(seeks)) elif data["type"] == "accept_seek": no = await is_playing(request, user, ws) if no: continue if data["seekID"] not in seeks: continue seek = seeks[data["seekID"]] # print("accept_seek", seek.as_json) response = await new_game(request.app, user, data["seekID"]) await ws.send_json(response) if seek.user.bot: gameId = response["gameId"] seek.user.game_queues[gameId] = asyncio.Queue() await seek.user.event_queue.put( challenge(seek, response)) else: await seek.ws.send_json(response) # Inform others, new_game() deleted accepted seek allready. await lobby_broadcast(sockets, get_seeks(seeks)) elif data["type"] == "lobby_user_connected": if session_user is not None: if data["username"] and data[ "username"] != session_user: log.info( "+++ Existing lobby_user %s socket connected as %s." % (session_user, data["username"])) session_user = data["username"] if session_user in users: user = users[session_user] else: user = User( request.app, username=data["username"], anon=data["username"].startswith( "Anon-")) users[user.username] = user response = { "type": "lobbychat", "user": "", "message": "%s joined the lobby" % session_user } else: if session_user in users: user = users[session_user] else: user = User( request.app, username=data["username"], anon=data["username"].startswith( "Anon-")) users[user.username] = user response = { "type": "lobbychat", "user": "", "message": "%s joined the lobby" % session_user } else: log.info( "+++ Existing lobby_user %s socket reconnected." % data["username"]) session_user = data["username"] if session_user in users: user = users[session_user] else: user = User( request.app, username=data["username"], anon=data["username"].startswith("Anon-")) users[user.username] = user response = { "type": "lobbychat", "user": "", "message": "%s rejoined the lobby" % session_user } await lobby_broadcast(sockets, response) # update websocket user.lobby_sockets.add(ws) sockets[user.username] = user.lobby_sockets response = { "type": "lobby_user_connected", "username": user.username } await ws.send_json(response) response = { "type": "fullchat", "lines": list(request.app["chat"]) } await ws.send_json(response) # send game count response = { "type": "g_cnt", "cnt": request.app["g_cnt"] } await ws.send_json(response) # send user count response = { "type": "u_cnt", "cnt": online_count(users) } if len(user.game_sockets) == 0: await lobby_broadcast(sockets, response) else: await ws.send_json(response) elif data["type"] == "lobbychat": response = { "type": "lobbychat", "user": user.username, "message": data["message"] } await lobby_broadcast(sockets, response) request.app["chat"].append(response) elif data["type"] == "logout": await ws.close() elif data["type"] == "disconnect": # Used only to test socket disconnection... await ws.close(code=1009) elif msg.type == aiohttp.WSMsgType.CLOSED: log.debug( "--- Lobby websocket %s msg.type == aiohttp.WSMsgType.CLOSED" % id(ws)) break elif msg.type == aiohttp.WSMsgType.ERROR: log.error( "--- Lobby ws %s msg.type == aiohttp.WSMsgType.ERROR" % id(ws)) break else: log.debug("--- Lobby ws other msg.type %s %s" % (msg.type, msg)) except concurrent.futures._base.CancelledError: # client disconnected pass except Exception as e: log.error("!!! Lobby ws exception occured: %s" % type(e)) finally: log.debug("---fianlly: await ws.close()") await ws.close() if user is not None: if ws in user.lobby_sockets: user.lobby_sockets.remove(ws) # online user counter will be updated in quit_lobby also! if len(user.lobby_sockets) == 0: if user.username in sockets: del sockets[user.username] # not connected to lobby socket and not connected to game socket if len(user.game_sockets) == 0: response = {"type": "u_cnt", "cnt": online_count(users)} await lobby_broadcast(sockets, response) response = { "type": "lobbychat", "user": "", "message": "%s left the lobby" % user.username } await lobby_broadcast(sockets, response) await user.clear_seeks(sockets, seeks) return ws
def test_can_prepare_ok(make_request): req = make_request('GET', '/', protocols=True) ws = WebSocketResponse(protocols=('chat',)) assert WebSocketReady(True, 'chat') == ws.can_prepare(req)
def test_can_prepare_unknown_protocol(make_request): req = make_request('GET', '/') ws = WebSocketResponse() assert (True, None) == ws.can_prepare(req)
def test_can_prepare_invalid_method(make_request): req = make_request('POST', '/') ws = WebSocketResponse() assert WebSocketReady(False, None) == ws.can_prepare(req)
def test_can_prepare_unknown_protocol(make_request) -> None: req = make_request("GET", "/") ws = WebSocketResponse() assert WebSocketReady(True, None) == ws.can_prepare(req)
async def the_handler(request): response = WebSocketResponse() handler = ws_handler if response.can_prepare(request) else proxy_handler return await handler(request)
def test_can_prepare_started(self): req = self.make_request('GET', '/') ws = WebSocketResponse() self.loop.run_until_complete(ws.prepare(req)) with self.assertRaisesRegex(RuntimeError, 'Already started'): ws.can_prepare(req)
def test_can_prepare_ok(make_request): req = make_request('GET', '/', protocols=True) ws = WebSocketResponse(protocols=('chat', )) assert (True, 'chat') == ws.can_prepare(req)
def test_can_prepare_unknown_protocol(make_request): req = make_request("GET", "/") ws = WebSocketResponse() assert (True, None) == ws.can_prepare(req)
def test_can_prepare_invalid_method(make_request): req = make_request('POST', '/') ws = WebSocketResponse() assert (False, None) == ws.can_prepare(req)
def test_can_prepare_ok(self): req = self.make_request("GET", "/", protocols=True) ws = WebSocketResponse(protocols=("chat",)) self.assertEqual((True, "chat"), ws.can_prepare(req))
def test_can_prepare_without_upgrade(self): req = self.make_request('GET', '/', headers=CIMultiDict({})) ws = WebSocketResponse() self.assertEqual((False, None), ws.can_prepare(req))
def test_can_prepare_unknown_protocol(self): req = self.make_request("GET", "/") ws = WebSocketResponse() self.assertEqual((True, None), ws.can_prepare(req))