Пример #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)
Пример #2
0
def ranch_socket(ws: WebSocket):
    client_token = ws.environ["HTTP_AUTHORIZATION"].split()[1]
    client_id = check_token(client_token)

    # client_id = ":".join((ws.environ["REMOTE_ADDR"], ws.environ["REMOTE_PORT"]))
    app.logger.info(f"Client came: {client_id}")

    if current_user.is_authenticated:
        if current_user.role == "0":
            response = f"Client {client_id} does not have read permissions!"
            app.logger.info(response)
            return jsonify(response), 403
        else:
            while not ws.closed:
                message = producer()
                app.logger.info(f"Sending {message} to {client_id}")
                if message is None:
                    app.logger.info("Message from backend was None!")
                    continue

                clients = ws.handler.server.clients.values()
                try:
                    for client in clients:
                        client.ws.send(message)
                except geventwebsocket.exceptions.WebSocketError:
                    app.logger.info(f"Client {client_id} disappeared")
                    ws.close()

                for i in frange(0, SLEEP_TIMEOUT, SLEEP_STEP):
                    time.sleep(SLEEP_STEP)
    else:
        response = f"Client {client_id} is not authenticated!"
        app.logger.info(response)
        # return redirect(url_for("login"))
        return jsonify(response), 401
Пример #3
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)
Пример #4
0
        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()
Пример #5
0
def subscribe(ws: WebSocket):
    """
    Connect to the broadcast server and subscribe to telemetry data, which is
    sent down the WebSocket whenever it is received.
    """
    sock = socket.socket(socket.AF_UNIX)
    server_address = app.config['BROADCAST_PATH']

    try:
        sock.connect(server_address)
    except socket.error as e:
        logging.error('Could not connect to broadcast server.', exc_info=e)
        ws.close()
        return

    sock_file = sock.makefile(mode='r')
    while True:
        data = sock_file.readline()
        if not ws.closed:
            logging.debug(data.strip())
            for datum in separate(json.loads(data)):
                ws.send(json.dumps(datum))