예제 #1
0
async def ws():
    global users
    g_user = ""
    try:
        while True:
            data = await websocket.receive()

            try:
                message_json = json.loads(data)
            except Exception as e:
                print(e)

            database = db.Database()

            # switch
            if message_json.get("type") == None:
                await websocket.send("Invalid")
            else:
                if message_json["type"] == "init":
                    g_user = message_json["username"]
                    users[g_user] = websocket._get_current_object()

                if message_json["type"] == "chat":
                    if users.get(message_json['receiver']) != None:
                        receiver_websocket = users[message_json['receiver']]
                        await receiver_websocket.send(data)

                    database.add_message(message_json['sender'],
                                         message_json['receiver'],
                                         message_json['content'])
            database.update_websocket_id(data,
                                         id(websocket._get_current_object()))

    except asyncio.CancelledError:
        del users[g_user]
예제 #2
0
 async def wrapper(*args, **kwargs):
     global connected
     connected.add(websocket._get_current_object())
     try:
         return await func(*args, **kwargs)
     finally:
         connected.remove(websocket._get_current_object())
예제 #3
0
 async def wrapper(*args, **kwargs):
     ws_clients.add(websocket._get_current_object())
     print(f"adding {websocket._get_current_object()}")
     try:
         return await func(*args, **kwargs)
     finally:
         ws_clients.remove(websocket._get_current_object())
예제 #4
0
 async def wrapper(*args, **kwargs):
     u = User.current()
     if u is None:
         return
     if u.queue is None:
         u.queue = asyncio.Queue()
     u.websockets.add(websocket._get_current_object())
     u.connected = True
     await u.init_timer()
     await broadcast({'type': 'join', 'data': u.name})
     await broadcast({
         'type':
         'list',
         'data': [
             u.to_dict()
             for u in [u for u in authorized_users if u.connected]
         ]
     })
     try:
         return await func(u, *args, **kwargs)
     finally:
         u.websockets.remove(websocket._get_current_object())
         if len(u.websockets) == 0:
             u.connected = False
             await broadcast({'type': 'part', 'data': u.name})
             await broadcast({
                 'type':
                 'list',
                 'data': [
                     u.to_dict()
                     for u in [u for u in authorized_users if u.connected]
                 ]
             })
예제 #5
0
 async def wrapper(*args, **kwargs):
     print("wrapping: adding connection")
     app.connected.add(websocket._get_current_object())
     try:
         return await func(*args, **kwargs)
     finally:
         print("wrapper: removing connection")
         app.connected.remove(websocket._get_current_object())
예제 #6
0
 async def wrapper(*args, **kwargs):
     # if args.verbosity > 1: print(f'{OV}entered wrapper(){OM}')
     global connected
     connected.add(websocket._get_current_object())
     try:
         return await func(*args, **kwargs)
     finally:
         connected.remove(websocket._get_current_object())
예제 #7
0
 async def _func(*args, **kwargs):
     # pylint: disable=protected-access
     CONNECTED_WEBSOCKET.add(websocket._get_current_object())
     try:
         return await func(*args, **kwargs)
     finally:
         LOGGER.debug('A client disconected')
         CONNECTED_WEBSOCKET.remove(websocket._get_current_object())
예제 #8
0
 async def wrapper(
     *args, **kwargs
 ):  #This could be done in the function below but atm as a proof of concept it works
     global clients
     clients.add(websocket._get_current_object())
     try:
         return await func(*args, **kwargs)
     finally:
         print("Client left")
         clients.remove(websocket._get_current_object())
예제 #9
0
async def chat():
    try:
        connections.add(websocket._get_current_object())
        async with trio.open_nursery() as nursery:
            nursery.start_soon(heartbeat)
            while True:
                message = await websocket.receive()
                await broadcast(message)
    finally:
        connections.remove(websocket._get_current_object())
예제 #10
0
async def ws():
    connections.add(websocket._get_current_object())
    try:
        while True:
            message = await websocket.receive()
            await chat_db.save_message(json.loads(message))
            send_coroutines = [
                connection.send(message) for connection in connections
            ]
            await asyncio.gather(*send_coroutines)
    finally:
        connections.remove(websocket._get_current_object())
예제 #11
0
async def ws():
  # When a new user connects, store the connection
  connections.add(websocket._get_current_object())
  try:
    while True:
      # Await new message comming from the user
      message = await websocket.receive()
      # Once a message is received, send the message to all the other connected users
      for connection in connections:
        await connection.send(f'{message}')
  # When the user disconnects (i.e. close their browser tab) remove the connection from the connection store to prevent memory leaks
  except asyncio.CancelledError:
    connections.remove(websocket._get_current_object())
예제 #12
0
 async def emit(self, data):
     """."""
     for x in self.clients:
         try:
             await x.send(data)
         except:
             self.clients.remove(websocket._get_current_object())
예제 #13
0
async def ws(session_id) -> Response:
    while True:
        player_id = id(websocket._get_current_object())
        logger.info(f"Player {player_id} connected to session {session_id}")
        players = current_app.games[session_id]
        try:
            data = await websocket.receive()
            action = PlayerAction.from_str(data)

            current_game = StatusGetter(
                session_id, SessionRepo(players)
            ).perform()
            updated_player = Updater(
                current_game.current_player,
                action,
                data,
                current_game.get_status(),
            ).perform()
            update_player_in_list(
                players, current_game.current_player, updated_player
            )
        except asyncio.CancelledError:
            logger.info(
                f"Player {player_id} disconnected from session {session_id}"
            )
            raise
        else:
            response = Responder(
                action, current_game, WebsocketResponder(),
            ).perform()
            await response
예제 #14
0
 async def add_conn(self):
     if not self.anyone_listening():
         print("starting a socket")
         app.nursery.start_soon(self._heartbeat_task)
         # todo: start a socket
     print("con-man: adding connection")
     self.active_clients.add(websocket._get_current_object())
     await self._update_clients()
예제 #15
0
파일: server.py 프로젝트: smurfix/deframed
        async def ws_sub(sid):
            """SubWorker websocket"""
            try:
                w = self.sub_worker[sid]
            except KeyError:
                raise NotFound

            else:
                await w.run(websocket._get_current_object())
예제 #16
0
 async def ws():
     try:
         sock = websocket._get_current_object()
         socks.add(sock)
         while True:
             data = await sock.receive()
             print("IN", data)
     finally:
         socks.discard(sock)
예제 #17
0
async def ws():
    if app.data_updates is None:
        app.data_updates = Queue()

    ws = websocket._get_current_object()
    app.ws_handler.add_connection(ws)
    # producer = create_task(ws_send())
    consumer = create_task(ws_receive(ws))
    await gather(consumer)
예제 #18
0
async def ws(room_id: str):
    room = None
    for existing in rooms:
        if existing.id == room_id:
            room = existing
            break
    else:
        room = await Room.from_id(room_id)
        if room is None:
            return {"status": 404, "error": "Invalid room ID."}, 404
        rooms.append(room)

    local_socket = websocket._get_current_object()

    cookie_string = local_socket.headers.get("Cookie", "")
    cookie = SimpleCookie()
    cookie.load(cookie_string)

    cookies = {}
    for key, morsel in cookie.items():
        cookies[key] = morsel.value

    user_info = None
    try:
        decoded = decode_token(cookies["access_token_cookie"])
    except Exception:
        user_info = {
            "identity": str(uuid.uuid4()),
            "name": "Guest"
        }
    else:
        name = decoded["user_claims"]["name"]
        identity = decoded["identity"]
        user_info = {
            "identity": identity,
            "name": name
        }

    local_socket.user_info = user_info
    await room.add_socket(local_socket)

    await local_socket.send(json.dumps({
        "components": await room.get_components(),
        "info": await room.get_info(),
        "user_info": user_info
    }))

    try:
        while True:
            data = await local_socket.receive()
            resp = await generate_response(local_socket, room, data)
            if resp and resp.get("result"):
                await local_socket.send(json.dumps(resp))
    except asyncio.CancelledError:
        # Client disconnected
        await room.remove_socket(local_socket)
        raise
예제 #19
0
async def ws():
    while True:
        data = await websocket.receive()
        data = json.loads(data)
        username = data.get("username", None)
        print(connected_ws.keys())
        print(str(connected_ws))
        if not username in connected_ws:
            print("NEW LOG IN")
            connected_ws.setdefault(username, websocket._get_current_object())
            for key, value in connected_ws.items():
                if key == username:
                    continue
                send_data = {"from": username, "to": key, "text":"Hello I'm {}".format(username), "type":"join", "time":int(time.time()*1000)}
                echo_data = {"from" : key, "to" : username, "text" : "Hello back, I'm {}".format(key), "type":"join", "time": int(time.time()*1000)}
                await connected_ws[username].send(json.dumps(echo_data))
                await value.send(json.dumps(send_data))
        elif data["type"] == "join":
            print("DUPLICATE SESSION FOR ", username)
            await connected_ws[username].send("Your session is terminated because you account is logged in elsewhere")
            current_time = data.get("time", 0)
            connected_ws[username] = websocket._get_current_object()
            for key, value in connected_ws.items():
                if key == username:
                    continue
                echo_data = {"from" : key, "to" : username, "text" : "Hello back, I'm {}".format(key), "type":"join", "time" : current_time}
                await connected_ws[username].send(json.dumps(echo_data))
        elif data["type"] == "chat":
            print("{} is chatting ".format(username))
            with_person = data["with_person"]
            if with_person in connected_ws:
                send_data = {"from": username, "to": with_person, "text":data["text"], "type":"chat", "time":data["time"]}
                await connected_ws[with_person].send(json.dumps(send_data))
                conversation_id, first_name = database.generate_conversation_id(username, with_person)
                save_data = {"conversation_id":conversation_id, "text":data["text"], "firstname" : first_name, "from": username, "to":with_person, "time":data["time"]}
                database.save_single_message(**save_data)

            for key, value in connected_ws.items():
                await value.send("Hello {}, i'm {}, {}".format(key, username, data["text"]))

            

        print(str(data))
        await websocket.send('hello'+ username)
예제 #20
0
async def on_charge_point_connect(charger_id):
    cp = ChargePoint(charger_id, WebSocketProxy(charger_id,
        websocket._get_current_object(), get_queue()))

    charge_points[charger_id] = cp

    await cp.start()

    del charge_points[charger_id]
    l.msg('Charge point disconnected', charger_id=charger_id)
예제 #21
0
    async def client_update_ws():
        while True:
            ws = websocket._get_current_object()
            ws_id = next(key for key, value in ws_clients.items()
                         if value == ws)
            if ws_id == -1:
                logging.warning("Invalid client request")
                return

            data = await websocket.receive()
            await process_message_request(ws, ws_id, data)
예제 #22
0
파일: app.py 프로젝트: 7185/lemuria
async def wsocket():
    """Websocket"""
    user = User.current()
    if user is None:
        return
    user.websockets.add(websocket._get_current_object())
    user.connected = True
    await user.set_timer()
    producer = asyncio.create_task(sending(user))
    consumer = asyncio.create_task(receiving(user))
    await asyncio.gather(producer, consumer)
예제 #23
0
async def channel_feed_websocket():
    obj = websocket._get_current_object()

    feeds.add(obj)

    consumer = asyncio.ensure_future(
        copy_current_websocket_context(receiving)(), )
    try:
        await asyncio.gather(consumer)
    finally:
        consumer.cancel()
        feeds.remove(obj)
예제 #24
0
async def receiving():
    while True:
        # Receives data from each websocket and does nothing with it (for now)
        data = await websocket.receive()
        try:
            data = decode_message(data)
        except:
            continue

        obj = websocket._get_current_object()
        if obj in connections:
            room = rooms[connections[obj]]
            room.push_new_state(data, obj)
예제 #25
0
 async def wrapper(*args, **kwargs):
     global connected
     global connected_ws
     connected.add(websocket._get_current_object())
     try:
         return await func(*args, **kwargs)
     finally:
         connected.remove(websocket._get_current_object())
         key = None
         try:
             for key, value in connected_ws.items():
                 if value == websocket._get_current_object():
                     print("DELETE CONNECTION TO : ",key)
                     del connected_ws[key]
                     break
             for remaining_key, value in connected_ws.items():
                 if remaining_key == key:
                     continue
                 send_data = {"from": key, "to": remaining_key, "text":"Goodbye I'm {}".format(key), "type":"quit", "time": int(time.time()*1000)}
                 flag = database.insert_new_user(key, int(time.time()*1000))
                 await value.send(json.dumps(send_data))
         except RuntimeError:
             pass
예제 #26
0
파일: api.py 프로젝트: zihen/quart-restplus
    async def error_router(self, original_handler, e):
        """
        This function decides whether the error occured in a quart-restplus
        endpoint or not. If it happened in a quart-restplus endpoint, our
        handler will be dispatched. If it happened in an unrelated view, the
        app's original error handler will be dispatched.
        In the event that the error occurred in a quart-restplus endpoint but
        the local handler can't resolve the situation, the router will fall
        back onto the original_handler as last resort.

        :param function original_handler: the original Quart error handler for the app
        :param Exception e: the exception raised while handling the request
        """
        try:
            # Ignore websocket request
            websocket._get_current_object()
        except:
            if self._has_qr_route():
                try:
                    return await self.handle_error(e)
                except Exception as err:
                    log.exception(err)
        return await original_handler(e)
예제 #27
0
 async def open_socket():
     # Get out of the global context, and get the actual websocket connection, such that we can understand
     # what is going
     ws = websocket._get_current_object()
     # For now, just use the binderadapter
     async with BinderAdapter(app) as adapter:
         connection = Connection(adapter, app, ws)
         notify_future = app.notify_connect(connection)
         try:
             await asyncio.gather(connection.run(), notify_future)
         finally:
             app.logger.debug("Closed socket, deregister!: {}".format(
                 connection.ID))
             app.hub.deregister(connection)
             await app.notify_disconnect(connection)
예제 #28
0
            async def wrapper(*args, **kwargs):
                id = wrapper.id_counter
                ws_clients[id] = websocket._get_current_object()
                logging.debug(f"adding ws client {id:3d}")
                on_connect(id)
                wrapper.id_counter += 1

                try:
                    return await func(*args, **kwargs)
                except asyncio.CancelledError as error:
                    logging.debug(f"ws client disconnected {id:03d}")
                    raise error
                finally:
                    logging.debug(f"removing ws client {id:03d}")
                    del ws_clients[id]
                    await on_disconnect(id)
예제 #29
0
파일: ws.py 프로젝트: 7185/lemuria
async def sending(user: User):
    await broadcast({'type': 'join', 'data': await user.name})
    await broadcast_userlist()
    try:
        while True:
            data = await user.queue.get()
            for socket in user.websockets:
                await socket.send_json(data)
    finally:
        user.websockets.remove(websocket._get_current_object())
        if not user.websockets:
            user.connected = False
            # Force Timer cancel
            await user.set_timer()
            await broadcast({'type': 'part', 'data': await user.name})
            await broadcast_userlist()
예제 #30
0
    async def wrapper(session_id, *args, **kwargs):
        if session_id not in current_app.games:
            current_app.games[session_id] = []

        cur_game = current_app.games[session_id]

        if len(cur_game) > 2:
            abort(403)

        ws = websocket._get_current_object()
        player = Player(id(ws), session_id, ws)
        cur_game.append(player)

        try:
            return await func(session_id, *args, **kwargs)
        finally:
            cur_game.remove(player)