0

I know how to broadcast but i can not target clients. Here is my script:

import json    
import trio
from quart import render_template, websocket, render_template_string
from quart_trio import QuartTrio    
from quart_auth import current_user,login_required    
from quart_auth import AuthUser, login_user, logout_user, AuthManager    
import random

connections = set()

app = QuartTrio(__name__)
AuthManager(app)    
app.secret_key = "secret key"    

@app.route("/")
async def index():        
    clean_guy = await current_user.is_authenticated        
    if not clean_guy:        
        fake_ID = random.randrange(0, 9999) #quick dirty to test
        login_user(AuthUser(fake_ID)) 
        return await render_template_string("{{ current_user.__dict__ }}")
    return await render_template_string("{{ current_user.__dict__ }}")      

@app.websocket("/ws")
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())


async def broadcast(message):
    for connection in connections:
        await connection.send(json.dumps({"type": "message", "value": message}))    

async def heartbeat():
    while True:
        await trio.sleep(1)
        await websocket.send(json.dumps({"type": "heartbeat"}))    

if __name__ == '__main__':    
    app.run(host='0.0.0.0', port=5000)

Here is my template:

<div>      
  <div>
    <ul>    
    </ul>
  </div>
  <form>
    <input type="text">
    <button type="submit">Send</button>
  </form>
</div>

<script type="text/javascript">
  document.addEventListener("DOMContentLoaded", function() {
    const ws = new WebSocket(`ws://${window.location.host}/ws`);
    ws.onmessage = function(event) {
      const data = JSON.parse(event.data);
      if (data.type === "message") {
        const ulDOM = document.querySelectorAll("ul")[0];
        const liDOM = document.createElement("li");
        liDOM.innerText = data.value;
        ulDOM.appendChild(liDOM);
      }
    }
    document.querySelectorAll("form")[0].onsubmit = function(event) {
      event.preventDefault();
      const inputDOM = document.querySelectorAll("input")[0];
      ws.send(inputDOM.value);
      inputDOM.value = "";
      return false;
    };
  });
</script>

Also one problem: if i use this in my script:

return await render_template("{{ current_user.__dict__ }}")

i am not able to display it with my jinja template even if i add {{ current_user.dict }} in my template.

I also noticed that:

  • with mozilla: i get something stable like {'_auth_id': 9635, 'action': <Action.PASS: 2>}
  • with chrome: it changes on each refresh, it looks like {'_auth_id': 529, 'action': <Action.WRITE: 3>}

I need to display the author, and the destination , and an input with a send button, how to fix the template ?

Is it also possible to send messages to targeted users with post via curl or websocat ? how to do that ?

laticoda
  • 100
  • 14

1 Answers1

1

Quart-Auth uses cookies to identify the user on each request/websocket-request so you can always get the identity of the user from the current_user if request is authenticated. Then for your need you will need to map websocket connections to each user (so you can target messages), hence the connections mapping should be a dictionary of connections, e.g.

import random
from collections import defaultdict

from quart import request, websocket
from quart_trio import QuartTrio      
from quart_auth import (
    AuthUser, current_user, login_required, login_user, logout_user, AuthManager 
)   

connections = defaultdict(set)

app = QuartTrio(__name__)
AuthManager(app)    
app.secret_key = "secret key"    

@app.route("/login", methods=["POST"])
async def login():
    # Figure out who the user is,
    user_id = random.randrange(0, 9999)
    login_user(AuthUser(fake_ID)) 
    return {}

@app.websocket("/ws")
@login_required
async def chat():
    user_id = await current_user.auth_id
    try:
        connections[user_id].add(websocket._get_current_object())
        while True:
            data = await websocket.receive_json()
            await broadcast(data["message"])
    finally:
        connections[user_id].remove(websocket._get_current_object())

@app.route('/broadcast', methods=['POST'])
@login_required
async def send_broadcast():   
    data = await request.get_json()
    await broadcast(data["message"], data.get("target_id"))
    return {}

async def broadcast(message, target = None):
    if target is None:
        for user_connections in connections.values():
            for connection in user_connections:
                await connection.send_json({"type": "message", "value": message})
    else:
        for connection in connections[target]:
            await connection.send_json({"type": "message", "value": message})

 
if __name__ == '__main__':    
    app.run(host='0.0.0.0', port=5000)

You can then send to the /broadcast either JSON that is just a message {"message": "something"} or a message with an id to target someone specifically {"message": "something for user 2", "target_id": 2}. Note as well the @login_required decorator ensures the route handler is only called for logged in users.

pgjones
  • 6,044
  • 1
  • 14
  • 12