Pepguy commited on
Commit
2d34f28
·
verified ·
1 Parent(s): 566e794

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +71 -53
app.js CHANGED
@@ -1,66 +1,84 @@
1
- // host.js (Bun)
2
 
3
- const DELIVERY_SERVER_URL = "wss://pepguy-activity-delivery.hf.space";
4
- const HOST_SECRET = "a-very-secret-host-key"; // Must match the delivery server
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- let deliverySocket;
 
 
 
 
 
 
 
 
7
 
8
- function connectToDeliveryServer() {
9
- console.log(`Attempting to connect to delivery server at ${DELIVERY_SERVER_URL}...`);
 
 
 
 
10
 
11
- try {
12
- deliverySocket = new WebSocket(DELIVERY_SERVER_URL, {
13
- headers: { "X-Host-Secret": HOST_SECRET },
14
- });
15
 
16
- deliverySocket.onopen = () => {
17
- console.log("✅ Successfully connected to delivery server.");
18
- };
19
 
20
- deliverySocket.onmessage = (event) => {
21
- let msg;
22
  try {
23
- msg = JSON.parse(event.data);
24
- console.log("msg")
25
- } catch {
26
- return;
27
- }
28
 
29
- if (msg.action === "post" && msg.roomId && msg.message) {
30
- const finalPayload = JSON.stringify({
31
- roomId: msg.roomId,
32
- message: msg.message,
33
- timestamp: Date.now(),
34
- });
35
-
36
- // The instruction for the delivery server is to 'broadcast' this payload
37
- const broadcastInstruction = JSON.stringify({
38
- roomId: msg.roomId,
39
- payload: finalPayload,
40
- });
41
-
42
- if (deliverySocket.readyState === 1) {
43
- deliverySocket.send(broadcastInstruction);
44
  }
45
- console.log("broadcasted")
46
- }
47
- };
48
 
49
- deliverySocket.onclose = (event) => {
50
- console.error(`❌ Disconnected from delivery server. Code: ${event.code}. Reconnecting in 5s...`);
51
- setTimeout(connectToDeliveryServer, 5000);
52
- };
53
-
54
- deliverySocket.onerror = (error) => {
55
- console.error("WebSocket error:", error.message);
56
- };
57
 
58
- } catch (error) {
59
- console.error("Failed to initiate connection:", error.message);
60
- setTimeout(connectToDeliveryServer, 5000);
61
  }
62
- }
63
 
64
- connectToDeliveryServer();
65
-
66
- console.log("✅ Host server logic is running.");
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const events = [];
2
 
3
+ const html = `
4
+ <!DOCTYPE html>
5
+ <html>
6
+ <head>
7
+ <title>Timed Event Scheduler</title>
8
+ </head>
9
+ <body>
10
+ <h1>Schedule Timed Event</h1>
11
+ <form onsubmit="submitEvent(event)">
12
+ <label>ID: <input type="text" id="id" required /></label><br />
13
+ <label>Delay (sec): <input type="number" id="delay" required /></label><br />
14
+ <label>Message: <input type="text" id="message" /></label><br />
15
+ <button type="submit">Submit</button>
16
+ </form>
17
+ <script>
18
+ async function submitEvent(e) {
19
+ e.preventDefault();
20
+ const id = document.getElementById('id').value;
21
+ const delay = parseInt(document.getElementById('delay').value) * 1000;
22
+ const message = document.getElementById('message').value;
23
 
24
+ const res = await fetch('/events', {
25
+ method: 'POST',
26
+ headers: { 'Content-Type': 'application/json' },
27
+ body: JSON.stringify({
28
+ id,
29
+ timestamp: Date.now() + delay,
30
+ data: { message }
31
+ })
32
+ });
33
 
34
+ alert(await res.text());
35
+ }
36
+ </script>
37
+ </body>
38
+ </html>
39
+ `;
40
 
41
+ Bun.serve({
42
+ port: 7860,
43
+ fetch: async (req) => {
44
+ const url = new URL(req.url);
45
 
46
+ if (req.method === "GET" && url.pathname === "/") {
47
+ return new Response(html, { headers: { "Content-Type": "text/html" } });
48
+ }
49
 
50
+ if (req.method === "POST" && url.pathname === "/events") {
 
51
  try {
52
+ const body = await req.json();
53
+ const { id, timestamp, data } = body;
 
 
 
54
 
55
+ if (!id || !timestamp) {
56
+ return new Response("Missing 'id' or 'timestamp'", { status: 400 });
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  }
 
 
 
58
 
59
+ events.push({ id, timestamp: Number(timestamp), data });
60
+ return new Response("Event scheduled", { status: 200 });
61
+ } catch {
62
+ return new Response("Invalid JSON", { status: 400 });
63
+ }
64
+ }
 
 
65
 
66
+ return new Response("Not Found", { status: 404 });
 
 
67
  }
68
+ });
69
 
70
+ // Non-blocking timer loop
71
+ setInterval(() => {
72
+ const now = Date.now();
73
+ const due = events.filter(e => e.timestamp <= now);
74
+ if (due.length > 0) {
75
+ due.forEach(e => {
76
+ console.log(`⏰ Event due: [${e.id}]`, e.data);
77
+ });
78
+ // Remove fired events
79
+ for (const e of due) {
80
+ const index = events.findIndex(ev => ev.id === e.id);
81
+ if (index !== -1) events.splice(index, 1);
82
+ }
83
+ }
84
+ }, 1000);