Web exchange seems to work now

This commit is contained in:
Martin Asprusten
2025-04-20 14:13:29 +02:00
parent 14cdefea69
commit 564e449e33
11 changed files with 155 additions and 69 deletions
+7 -6
View File
@@ -1,10 +1,11 @@
from typing import Optional, Callable
from Crypto.PublicKey.ECC import EccKey
from src.SantaExchange.Message import Message
from src.SantaExchange.MessageHandler import MessageHandler
from src.SantaExchange.SantasBrain import Brain
from src.SantaExchange.UserInterface import UserInterface
from SantaExchange.Message import Message
from SantaExchange.MessageHandler import MessageHandler
from SantaExchange.SantasBrain import Brain
from SantaExchange.UserInterface import UserInterface
class ExchangeClient(MessageHandler, UserInterface):
def __init__(self, send_message_function, receive_user_function, announce_recipient_function):
@@ -25,4 +26,4 @@ class ExchangeClient(MessageHandler, UserInterface):
self.receive_user_function(name)
def announce_recipient(self, name: str, other_info: str):
self.announce_recipient_function(name, other_info)
self.announce_recipient_function(name, other_info)
+47 -14
View File
@@ -1,23 +1,56 @@
import "./pyodide.js";
async function prepare() {
self.postMessage({type: 'status', stage: 'initialize', text: 'Initializing...'});
let pyodide = await loadPyodide();
await pyodide.loadPackage("pycryptodome");
await pyodide.loadPackage("./santaexchange-0.1-py3-none-any.whl")
pyodide.runPython(`
class Test:
def calculate(self):
return 15
await pyodide.loadPackage("./santaexchange-0.1-py3-none-any.whl");
let response = await fetch('./exchange_client.py');
pyodide.runPython(await response.text())
a = Test()
function sendMessage(messageString) {
self.postMessage({type: 'message', message: messageString})
}
function receiveUser(username) {
self.postMessage({type: 'new_user', username: username})
}
function announceRecipient(recipient_name, recipient_info) {
self.postMessage({type: 'status', stage: 'finished', text: `Your secret santa receiver is \n${recipient_name}\n${recipient_info}`})
}
function printLogs(record) {
console.log(record);
}
pyodide.globals.set('send_message', sendMessage);
pyodide.globals.set('receive_user', receiveUser);
pyodide.globals.set('announce_recipient', announceRecipient);
pyodide.globals.set('print_logs_function', printLogs);
pyodide.runPython(`
exchange_worker = ExchangeClient(send_message, receive_user, announce_recipient)
`);
console.log('Running python function');
console.log(pyodide.globals.get('a').calculate());
}
prepare();
addEventListener('message', e => {
if (e.data.type == 'message') {
pyodide.globals.get('exchange_worker').decode_received_message(e.data.message);
} else if (e.data.type == 'set_user') {
let username = e.data.username;
let userinfo = e.data.userinfo;
pyodide.globals.get('exchange_worker').set_user_info(username, userinfo);
postMessage({type: 'status', stage: 'wait_for_start', text: 'Waiting for other participants'});
} else if (e.data.type == 'start') {
postMessage({
type: 'status',
stage: 'exchanging',
text: 'Performing exchange when all users have pressed start. This may take a minute or so.'
});
pyodide.globals.get('exchange_worker').start_exchange(e.data.users);
}
});
addEventListener('message', e => {
self.postMessage('Loading pyodide');
self.postMessage('Loaded pyodide');
});
self.postMessage({type: 'status', stage: 'wait_for_user', text: 'Initialized'})
}
prepare();
+1
View File
@@ -35,4 +35,5 @@ input {
textarea {
width: 30vw;
height: 20vh;
font-size: 20px;
}
+53 -21
View File
@@ -12,38 +12,70 @@
<br />
<label for="info_for_santa">Info for your santa (e.g. shipping address or similar):</label><br />
<textarea id="info_for_santa"></textarea><br />
<button id="submit_info_button">Submit your info</button>
<button id="submit_info_button" onclick="submitInfo();">Submit your info</button>
<br /><br /><br />
<p id="statusParagraph"></p>
<button>Start with current participants</button>
<pre id="statusParagraph"></pre>
<button id="start_exchange_button" onclick="submitStart();">Start with current participants</button>
<p>Current participants:</p>
<div id='participantList'></div>
<!--<script type="text/javascript">
<ul id='participantList'>
</ul>
<script type="text/javascript">
const socket = io();
const client_id = Math.floor(Math.random() * 2**64)
socket.emit('join', {room: window.location.pathname, 'client_id': client_id})
socket.on('message', data => {
// All messages are broadcast to everyone, so discard messages that were actually sent from ourselves
data = JSON.parse(data);
if (data['client_id'] != client_id) {
console.log(data);
console.log(data['message']);
window.pass_message_to_python(JSON.stringify(data['message']));
}
});
</script>-->
const other_users = []
let submitButton = document.getElementById('submit_info_button');
let startButton = document.getElementById('start_exchange_button');
submitButton.disabled = true;
startButton.disabled = true;
<script type="text/javascript">
const exchangeWorker = new Worker("{{ url_for('static', filename='exchange_worker.js') }}", { type: 'module' });
exchangeWorker.onmessage = (e) => {
console.log('Received message:');
console.log(e);
document.getElementById('statusParagraph').innerHTML = e.data;
if (e.data.type == 'status') {
document.getElementById('statusParagraph').innerHTML = e.data.text;
if (e.data.stage == 'wait_for_user') {
submitButton.disabled = false;
startButton.disabled = true;
} else if (e.data.stage == 'wait_for_start') {
submitButton.disabled = true;
startButton.disabled = false;
} else {
submitButton.disabled = true;
startButton.disabled = true;
}
} else if (e.data.type == 'message') {
socket.emit('message', {client_id: client_id, room: window.location.pathname, message: e.data.message});
} else if (e.data.type == 'new_user') {
let list = document.getElementById('participantList');
const childNode = document.createElement("li");
childNode.innerHTML = e.data.username;
other_users.push(e.data.username);
list.appendChild(childNode);
}
};
exchangeWorker.postMessage('Nothing');
socket.on('message', data => {
// All messages are broadcast to everyone, so discard messages that were actually sent from ourselves
if (data['client_id'] != client_id) {
exchangeWorker.postMessage({type: 'message', message: data['message']})
}
});
function submitInfo() {
let name = document.getElementById('own_name').value;
let info = document.getElementById('info_for_santa').value;
exchangeWorker.postMessage({type: 'set_user', username: name, userinfo: info});
}
function submitStart() {
exchangeWorker.postMessage({type: 'start', users: other_users});
}
socket.emit('join', {room: window.location.pathname, client_id: client_id})
</script>
</body>
</html>