Exemplo n.º 1
0
def your_print_is_ready(ws: WebSocket):
    global printer_jsons, printer_jsons_last
    clients.add(ws)
    logging.info(f'Client {ws} joined')
    try:
        keep_alive(ws)
        while not ws.closed:
            gevent.sleep(0.1)
            msg = ws.receive()
            if msg:
                message_json = json.loads(msg)
                if 'key' in message_json and secrets.compare_digest(
                        message_json['key'], x_api_key):
                    if ws in clients:
                        clients.remove(ws)
                    if 'printers' not in message_json:
                        logging.info(
                            f'Poller {ws} sent a message but it had no printers'
                        )
                        continue
                    new_printer_jsons = message_json['printers']
                    if new_printer_jsons != printer_jsons:
                        logging.info(f'Poller {ws} updated values')
                        printer_jsons = new_printer_jsons
                        printer_jsons_last = datetime.utcnow()
                        for client in clients:
                            update(client)
                    logging.info(f'Processed values from poller {ws}')
                else:
                    logging.info(f'Client {ws} key did not match expected key')
    finally:
        if ws and not ws.closed:
            ws.close()
        logging.info(f'Client {ws} left')
        clients.remove(ws)
Exemplo n.º 2
0
def listen(ws: WebSocket):
    listener = WebsocketListener(ws)
    listeners.append(listener)
    logger.info("websocket client from %s has been connected",
                listener.remote_addr)
    while not ws.closed:
        raw_msg = ws.receive()
        if not raw_msg:
            break
        message = Message.create(raw_msg)

        logger.debug("Message %s received from %s", message,
                     listener.remote_addr)

        if message.id not in socket_watcher:
            listener.send(Message(message.id, {}, 'unknown id'))
            continue

        try:
            socket_watcher.send(message)
        except SocketSendError as e:
            logger.exception("cannot send message: %s", e)
            listener.send(Message(message.id, {}, 'unknown id'))
            continue

    listeners.remove(listener)

    logger.info(
        "websocket client from %s has been disconnected. Remaining listeners: %s",
        listener.remote_addr, len(listeners))
Exemplo n.º 3
0
    def handle(self, socket: WebSocket):
        self.context.g_set(hard_code.GK_SOCKET, socket)

        self.on_connect()
        while self._loop:
            data_str = None
            try:
                data_str = socket.receive()
                if not data_str:
                    continue
                data = json.loads(data_str)  # type: dict
                if isinstance(data, dict):
                    event = 'on_%s' % data.pop('event')
                    if hasattr(
                            self,
                            event) and event not in dir(EventSocketController):
                        kwargs = data.pop('data', {})
                        getattr(self, event)(**kwargs)
                        continue
                self.on_message(data)
            except json.JSONDecodeError:
                self.on_message(data_str)
            except WebSocketError as e:
                if MSG_SOCKET_DEAD in e.args:
                    break
                self.on_error(e)
            except Exception as e:
                self.on_error(e)
        self.on_disconnect()
Exemplo n.º 4
0
def game_socket(ws: WebSocket) -> None:
    while not ws.closed:
        query = ws.receive()
        if query is None:
            continue

        print(f"Received:`{query}`")

        messages: List[Message]
        for command in commands:
            if command.command_matches(query):
                messages = command.apply_command(
                    matches, query[len(command.STARTS_WITH):])
                break
        else:
            messages = [Command.error_msg("Invalid command sent", query)]
            pass

        for message in messages:
            if message.add_sender_to_spectate_map:
                add_client_to_map(message.match_id, ws)

            msg_to_send_str = to_json_str(message.message)
            if message.reply_to_only_sender:
                ws.send(msg_to_send_str)
            else:
                removed_clients: List[WebSocket] = []
                for client in game_clients[message.match_id]:
                    try:
                        client.send(msg_to_send_str)
                    except WebSocketError:
                        removed_clients.append(client)
                for client in removed_clients:
                    game_clients[message.match_id].remove(client)
Exemplo n.º 5
0
Arquivo: Api.py Projeto: Wanket/RnD-py
        def message_socket(ws: WebSocket, connection: Connection) -> None:
            if Api.__COOKIE_SESSION_NAME not in session:
                ws.close()

                return

            db_session = connection.session()

            for post in db_session.query(Post).all():
                ws.send(
                    Message(datetime=floor(post.datetime.timestamp()),
                            author=post.author,
                            text=post.message).serialize())

            with MessageSubscribersQueue.subscribe(request, ws):
                ws.receive()
Exemplo n.º 6
0
 def cmd(ws: WebSocket):
     ws_id = self.wsCollector.add(ws)
     while not ws.closed:
         message = ws.receive()
         if message is not None:
             # noinspection PyBroadException
             msg = {'token': '', 'cmd': None}
             # noinspection PyBroadException
             try:
                 msg = json.loads(message)
             except:
                 msg['cmd'] = message
             if (msg.get('type', None) is not None) and (msg.get(
                     'msg', None) is not None):
                 BdsLogger.put_log(msg['type'], msg['msg'])
             if self.tokenManager.checkToken(msg.get(
                     'token', '')) or self.wsCollector.check(ws_id):
                 result = self.wsCollector.update(ws_id)
                 if result == 1:
                     ws.send(
                         json.dumps(self.tokenManager.pass_msg,
                                    ensure_ascii=False))
                 self.cmd_in_via_ws(msg.get('cmd', None))
             else:
                 ws.send(
                     json.dumps(self.tokenManager.error_msg,
                                ensure_ascii=False))
Exemplo n.º 7
0
 def register_client(self, ws: WebSocket):
     gevent.spawn(pinger, ws)
     L.info(f"Client {ws} connected")
     self.clients.add(ws)
     try:
         while ws.receive():
             pass
     finally:
         L.info(f"Client {ws} disconnected")
         self.clients.remove(ws)
Exemplo n.º 8
0
def ws(websocket: WebSocket):
    while not websocket.closed:
        split_message = websocket.receive().split()
        action = split_message[0].upper()
        if action == 'RUN':
            session_id = split_message[1]
            if session_id in _valid_session_ids:
                data = _generator.get_bytes(_BYTES_PER_TRIAL)
                hit = to_bool(data, _generator.bit_numbering)
                websocket.send('HIT %d' % (1 if hit else 0))
                _log_file.write(f'{utc_datetime_string()},{request.remote_addr},{session_id},{hit},{base64.b64encode(data).decode("utf-8")},{_generator.id},{_generator.bit_numbering.value}\n')
                _log_file.flush()
Exemplo n.º 9
0
def ws(websocket: WebSocket):
    while not websocket.closed:
        split_message = websocket.receive().split()
        action = split_message[0].upper()
        if action == 'PING':
            _generator.get_bytes(_BYTES_PER_TRIAL)
            websocket.send('PONG')
        elif action == 'RUN':
            run_id = split_message[1]
            trial_count = int(split_message[2])
            if run_id in _valid_run_ids:
                threading.Thread(target=run_trials,
                                 args=(websocket, run_id, trial_count,
                                       request.remote_addr)).start()
Exemplo n.º 10
0
def game_socket(ws: WebSocket) -> None:
    while not ws.closed:
        message = ws.receive()
        if message is None:
            continue

        print(f"Received:`{message}`")
        msg_to_send: Union[StateDict, CommandResponse]
        broadcast_id: Optional[str] = None
        broadcast_only_to_sender = False
        match_id: str

        if message == "create":
            msg_to_send = game_create()
        elif message == "cards":
            msg_to_send = list_cards()
        elif message.startswith("join "):
            msg_to_send = game_join(message[5:])
            if msg_to_send["messageType"] != "error":
                match_id = msg_to_send["matchId"]
                broadcast_id = match_id
        elif message.startswith("state "):
            msg_to_send = game_state(message[6:])
        elif message.startswith("move "):
            split = message.split(" ")
            # Command format: move [match_id] [token] [card] [move]
            # Example: move 5f9c394ee71e1740c218587b iq2V39W9WNm0EZpDqEcqzoLRhSkdD3lY boar a1a2
            msg_to_send = game_move(split[1], split[2], split[3], split[4])
            if msg_to_send["messageType"] != "error":
                match_id = msg_to_send["matchId"]
                broadcast_id = match_id
        elif message.startswith("spectate "):
            msg_to_send = game_spectate(message[9:])
            if msg_to_send["messageType"] != "error":
                match_id = msg_to_send["matchId"]
                add_client_to_map(match_id, ws)
                broadcast_id = match_id
                broadcast_only_to_sender = True
        else:
            msg_to_send = error_msg("Invalid command sent", message)

        msg_to_send_str = to_json_str(msg_to_send)
        ws.send(msg_to_send_str)
        if broadcast_id is not None:
            if broadcast_only_to_sender:
                game_state_str = to_json_str(game_state(broadcast_id))
                ws.send(game_state_str)
            else:
                broadcast_state(broadcast_id, ObjectId(broadcast_id))
Exemplo n.º 11
0
def ws_io(ws: WebSocket):
    while not ws.closed:
        content = ws.receive()
        if content is not None:
            note = json.loads(content)
            print(f"[WS] reach note <{note['name']}>")
            ws_c.add(ws, note['name'])
            with open('notes/%s' % note['name'], 'w') as f:
                f.write(
                    json.dumps({
                        'title': note['title'],
                        'body': note['body']
                    }))
                f.close()
            ws_c.sent_to_all(note['name'], note['title'], note['body'])
Exemplo n.º 12
0
def echo(ws: WebSocket):
    print("Connection accepted")
    count = 0
    sid = None
    caller_number = None
    dad = DetectAndDeter(TEST_NAME)
    in_queue, out_queue = dad.queues
    dad.start()
    dad.make_greeting(ONE_PARTY_RECORDING_CONSENT)

    while not ws.closed:
        message = ws.receive()
        if message is None:
            continue

        data = json.loads(message)
        if data['event'] == "connected":
            pass
        elif data['event'] == "start":
            sid = data['streamSid']
            logging.info(data)
            caller_number = data["start"]["customParameters"]["callerNumber"]

            # start_recording(data['start']['callSid'])
        elif data['event'] == "media":
            in_queue.put(base64.b64decode(data['media']['payload']))
            if not out_queue.empty():
                ws.send(json.dumps({
                    "event": "media",
                    "streamSid": sid,
                    "media": {
                        "payload": out_queue.get()
                    }}))
        elif data['event'] == 'stop':
            pass
        elif data['event'] == "closed":
            break
        else:
            raise RuntimeError(f"Unknown event: {data['event']} | data: {data}")
        count += 1

    dad.close()
    log = dad.fill_log_info(caller_number)
    logging.info(f"Connection closed | SID: {sid} | messages: {count}")
    print(f"Connection closed | SID: {sid} | messages: {count}")

    with open(LOG_PATH/f"call{clean_name(log['start'])}.json", 'w') as f:
        json.dump(log, f)
Exemplo n.º 13
0
def page_socket(socket: WebSocket, page_id):
    try:
        page = pages[page_id]
    except KeyError:
        socket.close(message="page {} does not exist".format(page_id))
        return
    socket.send(json.dumps({"type": "num_peers", "num_peers": len(page.sockets)}))
    page.add(socket)
    print("num sockets", len(page.sockets))
    while not socket.closed:
        message = socket.receive()
        if message is None:
            continue
        page.send(socket, message)

    page.remove(socket)
Exemplo n.º 14
0
        def handle(socket: WebSocket):
            """
            Wrap the current WS class, dispatching events to it as necessary. We're using gevent, so there's
            no need to worry about blocking here.
            """

            ws = cls(
                socket
            )  # Instantiate the current class, passing it the WS object

            ws.on_open()  # Call the "on_open" handler

            while not socket.closed:  # As long as the socket is open...
                message = socket.receive()  # Wait for a message

                if not socket.closed:  # If the socket didn't just close (there's always a None message on closing)
                    ws.on_message(message)  # Call the "on_message" handler

            ws.on_close(
            )  # The socket just closed, call the "on_close" handler
Exemplo n.º 15
0
    def recognize(self, web_socket: WebSocket):
        values = list()
        for i in range(AUDIO_RANGE):
            src = web_socket.receive()
            if src is None:
                logger.info("src is None. {}".format(i))
                break
            audio_data = np.frombuffer(src, dtype="float32")
            values.append(audio_data)
            # logger.debug("index:{}, data:{}".format(i, audio_data))
        v = np.array(values)
        v.flatten()
        # バイナリに16ビットの整数に変換して保存
        # -32768 <= int16 <= 32767
        arr = (v * 32767).astype(np.int16)
        file_name = self._create_file_name()
        with wave.open(file_name, 'wb') as wf:
            wf.setnchannels(AUDIO_CHANNEL_SIZE)
            wf.setsampwidth(SAMPLE_WIDTH)
            wf.setframerate(SAMPLE_RATE)
            wf.writeframes(arr.tobytes('C'))
        file_names = [file_name]
        messages = list()

        def _report(result: MatchResult):
            messages.append(result.match_file_names)

        self._matcher.execute(file_names, _report)
        self._delete_file(file_name)
        # flatten
        messages = list(chain.from_iterable(messages))
        # messages = [audfprint/sound/cicada_abra.mp3]
        object_name = self._get_object_name(messages)
        if object_name is None:
            send_message = "Not found"
        else:
            send_message = object_name
        logger.info(send_message)
        web_socket.send(send_message)
        self._delete_file(file_name)
Exemplo n.º 16
0
def play_game(websocket: WebSocket):
    print('Websocket connnected')
    args = json.loads(websocket.receive())

    print('Starting game with {}'.format(args))

    player = WebsocketPlayer(args['name'], websocket)
    ai = getattr(dominion_ai, args['ai'])(args['ai'])

    if args['game'] == 'random':
        reqs = set(
            map(lambda req: getattr(dominion.cards, req), args['requires']))
        reqs.update(ai.requires())
        game = make_random_game(player, ai, reqs)
    else:
        game = make_premade_game(player, ai, args['game'])

    game.start()
    while not game.is_over():
        game.run_next_phase()
    game.complete()

    print('Finished game.')
Exemplo n.º 17
0
def listen(socket: WebSocket):
    try:
        user_id = current_user.id_
        device_id = uuid.uuid4().hex

        while not socket.closed:
            message = socket.receive()
            json_msg = json_dict(message)
            if json_msg.get("transport_type"):
                # TODO: handle unknown transport types
                device_conn = DeviceConnection(socket,
                                               json_msg["transport_type"],
                                               tuple(json_msg["notify_apps"]))
                message_handler.new_client(user_id, device_id, device_conn)

    except WebSocketError as err:
        if err.args[0] == MSG_SOCKET_DEAD:
            current_app.logger.debug(
                f"client's WebSocket lost connection with server, {user_id} {device_id}"
            )
        else:
            raise err

    message_handler.remove_client(user_id, device_id)
Exemplo n.º 18
0
def play_chess(ws: WebSocket):
    while not ws.closed:
        try:
            # receive message.
            message: str = ws.receive()

            if message is None:
                continue

            # message format: `action data`
            message: list = message.split(' ')

            # 连接大厅
            if message[0] == 'connect':
                # 已经在大厅里
                if ws in hall.users:
                    ws.send(json.dumps({'alert': 'already online'}))
                    continue

                # 进入大厅
                hall.users.update({ws: User(ws, message[1])})
                hall.broadcast_rooms()

            # 进入房间
            elif message[0] == 'enter':
                user = hall.users[ws]
                room = hall.rooms[message[1]]
                if user.room is not None:
                    hall.rooms[user.room].users.remove(user)
                user.status = 'in room'
                user.room = room.uuid

                # 房间满了
                if len(room.users) == 2:
                    ws.send(json.dumps({'alert': 'full'}))
                    continue

                # 房间里有一个人
                elif len(room.users) == 1:
                    room.users.append(user)
                    room.broadcast()
                    hall.broadcast_rooms()

                # 房间里没人
                else:
                    room.users.append(user)
                    room.broadcast()
                    hall.broadcast_rooms()

            # 准备
            elif message[0] == 'ready':
                user = hall.users[ws]
                room = hall.rooms[user.room]
                user.status = 'ready'

                # 房间还有其他人
                if len(room.users) == 2:
                    another_index = 1 - room.users.index(user)
                    room.users[another_index].ws.send(
                        json.dumps({
                            'info':
                            room.users[another_index].name + ' ready'
                        }))
                    room.broadcast()

                    # 对方也准备了,开始游戏
                    if room.users[another_index].status == 'ready':
                        room.status = 'gaming'
                        room.first_player = random.randint(0, 1)
                        room.cur_player = room.first_player
                        hall.broadcast_rooms()
                        room.users[room.first_player].ws.send(
                            json.dumps({'alert': '你先手'}))
                        room.users[1 - room.first_player].ws.send(
                            json.dumps({'alert': '你后手'}))

            # 下棋
            elif message[0] == 'put':
                user = hall.users[ws]
                room = hall.rooms[user.room]

                if user == room.users[room.cur_player]:
                    room.count += 1
                    color = room.cur_chess_color()
                    room.board[int(message[2])][int(message[1])] = color
                    room.cur_player = 1 - room.cur_player
                    for user in room.users:
                        user.ws.send(json.dumps({'board':
                                                 room.board.tolist()}))
                    if room.win(int(message[1]), int(message[2])):
                        room.game_init()
                        winner = user.name
                        for user in room.users:
                            user.ws.send(
                                json.dumps({'result': winner + ' win'}))
                            user.ws.send(json.dumps({'room':
                                                     room.serialize()}))
                        room.users[0].status = 'in room'
                        room.users[1].status = 'in room'
                        hall.broadcast_rooms()
                        continue
                    elif room.count == 100:
                        room.game_init()
                        for user in room.users:
                            user.ws.send(json.dumps({'result': 'draw'}))
                            user.ws.send(json.dumps({'room':
                                                     room.serialize()}))
                        room.users[0].status = 'in room'
                        room.users[1].status = 'in room'
                        room.status = 'idle'
                        hall.broadcast_rooms()
                        continue
            elif message[0] == 'leave':
                user = hall.users[ws]
                room = hall.rooms[user.room]

                room.users.remove(user)
                user.status = 'online'
                user.room = None
                room.game_init()
                hall.broadcast_rooms()
                room.broadcast()
        except Exception as e:
            print(str(e))

    user = hall.users[ws]

    if user.room is not None:
        room = hall.rooms[user.room]
        room.users.remove(user)
        room.game_init()

        for user in room.users:
            user.ws.send(json.dumps({'room': room.serialize()}))

    del hall.users[ws]
    hall.broadcast_rooms()