-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimal_chat_global_replication_ack.html
518 lines (420 loc) · 19.6 KB
/
minimal_chat_global_replication_ack.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Minimal Multichat</title>
<script src="https://unpkg.com/[email protected]/dist/peerjs.min.js"></script>
</head>
<body>
<h1>Multichat</h1>
<!-- Login Section -->
<div id="login">
<label for="username">Enter your username:</label>
<input id="username" type="text">
<button onclick="submitLogin(event)">Login</button>
<p id="loginError" style="color: red;"></p>
</div>
<!-- Chat Section -->
<div id="chat" style="display: none;">
<h2>Welcome, <span id="currentUser"></span></h2>
<!-- Connection Section -->
<div>
<label for="targetUsername">Connect to user:</label>
<input id="targetUsername" type="text">
<button onclick="submitConnection(event)">Connect</button>
</div>
<h3>Connected Users:</h3>
<ul id="userList"></ul>
<!-- Chat Box -->
<h3>Chat:</h3>
<div id="chatbox" style="border: 1px solid black; height: 200px; overflow-y: scroll; padding: 5px;"></div>
<!-- Message Input -->
<div>
<input id="message" type="text" placeholder="Type a message">
<button onclick="submitChat(event)">Send</button>
</div>
</div>
<script>
const appPrefix = "p2p-multichat-test-";
//let peer;
//let connections = {};
//let chats = [];
let screen = "login"; // initialize at login screen
let usernameInput = localStorage.getItem("username"); // to load saved username
let peerError = "";
let loading = false;
let peer = {}; // initialize as empty object instead of undefined
let targetIdInput = "";
let peerIds = []; // connected to nobody at first
let connections = {}; // maps peerIds to their correspondig PeerJS's DataConnection objects
//let chats = [];
let chats = {};
let chatMessageInput = "";
// util functions to convert username to peer ids and vice-versa
function getPeerId(username) {
return appPrefix + username;
}
function getUsername(peerId) {
return peerId ? peerId.slice(appPrefix.length) : "";
}
// we keep track of connections ourselves as suggested in peerjs's documentation
function addConnection(conn) {
connections[conn.peer] = conn;
updatePeerIds();
console.log(`Connected to ${conn.peer}!`);
}
function removeConnection(conn) {
console.log(`!!DELETE ${conn.peer}...`);
delete connections[conn.peer];
updatePeerIds();
}
function updatePeerIds() {
const userList = document.getElementById('userList');
userList.innerHTML = Object.keys(connections).map(user => `<li>${getUsername(user)}</li>`).join('');
peerIds = Object.keys(connections);
}
function disconnectPeer() {
peer.disconnect();
}
// At the top of the script, define constants for the acknowledgment timeout
const ACK_TIMEOUT = 5000; // Timeout in milliseconds (5 seconds)
// Updated `configureConnection` function for acknowledgment
function configureConnection(conn) {
conn.on("data", async data => {
if (data.type === "connections") {
data.peerIds.forEach(peerId => {
if (!connections[peerId]) {
initiateConnection(peerId);
}
});
} else if (data.type === "chat") {
receiveChat(data.chat);
// Send acknowledgment (chat hash) back to sender
console.log(`Sending ACK to: ${conn.peer}`);
conn.send({
type: "ack",
hash: data.chat.hash,
});
} else if (data.type === "ack") {
// Handle acknowledgment received for a specific message hash
console.log(`Acknowledgment received for hash: ${data.hash}`);
if (pendingAcks[data.hash]) {
clearTimeout(pendingAcks[data.hash].timeout);
delete pendingAcks[data.hash];
}
}
});
conn.on("close", () => removeConnection(conn));
conn.on("error", () => removeConnection(conn));
conn.metadata.peerIds.forEach(peerId => {
if (!connections[peerId]) {
initiateConnection(peerId);
}
});
}
// called to properly configure connection's client listeners
/*function configureConnection(conn) {
conn.on("data", data => {
// if data is about connections (the list of peers sent when connected)
console.log(`!!received ${data.type}...`);
if (data.type === "connections") {
//console.log(`!!Connecting here [configconn data] to ${peerId}...`);
data.peerIds.forEach(peerId => {
//console.log(`!!Connecting here [configconn data] to ${peerId}...`);
if (!connections[peerId]) {
initiateConnection(peerId);
}
});
} else if (data.type === "chat") {
receiveChat(data.chat);
//send ACK as HASH
}
// please note here that if data.type is undefined, this endpoint won't do anything!
});
conn.on("close", () => removeConnection(conn));
conn.on("error", () => removeConnection(conn));
// if the caller joins have a call, we merge calls
conn.metadata.peerIds.forEach(peerId => {
console.log(`!!Connecting here [configconn gen] to ${peerId}...`);
if (!connections[peerId]) {
initiateConnection(peerId);
}
});
}*/
// called to initiate a connection (by the caller)
function initiateConnection(peerId) {
if (!peerIds.includes(peerId) && peerId !== peer.id) {
loading = true;
peerError = "";
console.log(`Connecting to ${peerId}...`);
const options = {
metadata: {
// if the caller has peers, we send them to merge calls
peerIds: peerIds
},
serialization: "json"
};
const conn = peer.connect(peerId, options);
configureConnection(conn);
conn.on("open", () => {
addConnection(conn);
//console.log(`!!Connecting here [initconn open] to ${peerId}...`);
if (getUsername(conn.peer) === targetIdInput) {
targetIdInput = "";
loading = false;
}
});
}
}
function createPeer() {
// options are useful in development to connect to local peerjs server
peer = new Peer(getPeerId(usernameInput)/*, {
host: 'localhost',
port: 8080,
path: 'app'
}*/);
// peer = new Peer(getPeerId(usernameInput), {
// host: '127.0.0.1',
// port: 9000,
// key: 'peerjs',
// path: '/myapp'
// });
// when peer is connected to signaling server
peer.on("open", () => {
screen = "chat"; // changing screen
loading = false;
peerError = "";
});
// error listener
peer.on("error", error => {
if (error.type === "peer-unavailable") { // if connection with new peer can't be established
loading = false;
peerError = `${targetIdInput} is unreachable!`; // custom error message
targetIdInput = "";
} else if (error.type === "unavailable-id") { // if requested id (thus username) is already taken
loading = false;
peerError = `${usernameInput} is already taken!`; // custom error message
} else peerError = error; // default error message
});
// when peer receives a connection
peer.on('connection', conn => {
if (!peerIds.includes(conn.peer)) {
configureConnection(conn);
conn.on("open", () => {
console.log(`!!Connecting here [createpeer open] to ...${conn.peer}`);
addConnection(conn);
// send every connection previously established to connect everyone (merge chat rooms)
conn.send({
type: "connections",
peerIds: peerIds
});
});
}
});
}
function submitLogin(event) {
if (event) event.preventDefault(); // to prevent default behavior which is to POST to the same page
usernameInput = document.getElementById('username').value
if (usernameInput.length > 0 && !loading) {
loading = true; // update status
peerError = ""; // reset error status
localStorage.setItem("username", usernameInput); // set username cookie to instanciate it at the next session
document.getElementById('loginError').textContent = '';
document.getElementById('currentUser').textContent = usernameInput;
document.getElementById('login').style.display = 'none';
document.getElementById('chat').style.display = 'block';
createPeer();
}
}
function submitConnection(event) {
event.preventDefault(); // to prevent default behavior which is to POST to the same page
targetIdInput = document.getElementById('targetUsername').value;
const peerId = getPeerId(targetIdInput); // the peer's id we want to connect to
initiateConnection(peerId);
}
async function sha256(message) {
//function sha256(message) {
// encode as UTF-8
const msgBuffer = new TextEncoder().encode(message);
// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
//const hashBuffer = crypto.subtle.digest('SHA-256', msgBuffer);
// convert ArrayBuffer to Array
const hashArray = Array.from(new Uint8Array(hashBuffer));
// convert bytes to hex string
const hashHex = await hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
//const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
function receiveChat(chat) {
//chats.push(chat);
//console.log(`received chat with hash... ${chat.hash}`);
chats[chat.hash] = chat;
// if(!chats[chat.hash]){
// chats[chat.hash] = chat;
// }
const chatbox = document.getElementById('chatbox');
//chatbox.innerHTML = chats.map(chat => `<p>${ chat.sender } : ${ chat.message } # ${ chat.hash }</p>`).join('');
//Object.keys( d ).map( function(key){ return key+"="+d[key] }).join("&") //outputs "foo=0&bar=1"
chatbox.innerHTML = Object.keys(chats).map(function(key){
chat = chats[key];
return `<p>${ chat.sender } : ${ chat.message } # ${ chat.hash }</p>`;
}).join('');
chatbox.scrollTop = chatbox.scrollHeight;
//localStorage.setItem("chats", JSON.stringify(chats));
}
// Object to keep track of pending acknowledgments
let pendingAcks = {};
// Updated `submitChat` function with acknowledgment handling
async function submitChat(event) {
event.preventDefault();
chatMessageInput = document.getElementById('message').value;
if (chatMessageInput.length > 0) {
const MAX_RETRIES = 10; // Number of retries before giving up
let chatTime = new Date().getTime();
let fullMessage = usernameInput + ':' + chatMessageInput + ':' + chatTime;
const messageHash = await sha256(fullMessage);
const chat = {
sender: usernameInput,
message: chatMessageInput,
timestamp: chatTime,
hash: messageHash
};
receiveChat(chat); // Simulate receiving a chat locally
// Function to handle retry logic
const sendWithRetry = (conn, retriesLeft) => {
console.log(`Sending chat to ${conn.peer} with ${retriesLeft} retries left...`);
conn.send({
type: "chat",
chat
});
pendingAcks[messageHash] = {
chat,
conn,
retriesLeft,
timeout: setTimeout(() => {
if (retriesLeft > 0) {
console.log(`Retrying for hash: ${messageHash}. Retries left: ${retriesLeft - 1}`);
// Close the existing connection and reinitiate
const peerId = conn.peer;
removeConnection(conn);
initiateConnection(peerId);
// Retry sending the chat
sendWithRetry(peer.connections[peerId][0], retriesLeft - 1);
} else {
console.log(`Failed to send message after ${MAX_RETRIES} attempts: ${messageHash}`);
delete pendingAcks[messageHash]; // Clean up if retries are exhausted
}
}, ACK_TIMEOUT)
};
};
// Send chat to all connected users with retry logic
Object.values(connections).forEach(conn => {
sendWithRetry(conn, MAX_RETRIES);
});
chatMessageInput = ""; // Reset input field
document.getElementById('message').value = '';
console.log(`Message SENT TO ALL `);
}
}
/*async function submitChat(event) {
event.preventDefault();
chatMessageInput = document.getElementById('message').value;
if (chatMessageInput.length > 0) {
let chatTime = new Date().getTime();
let fullMessage = usernameInput + ':' + chatMessageInput + ':' + chatTime;
const messageHash = await sha256(fullMessage);
const chat = {
sender: usernameInput,
message: chatMessageInput,
timestamp: chatTime,
hash: messageHash
};
receiveChat(chat); // Simulate receiving a chat locally
// Send chat to all connected users
Object.values(connections).forEach(conn => {
console.log(`Sending chat to... ${conn.peer}`);
conn.send({
type: "chat",
chat
});
// Set up acknowledgment handling
pendingAcks[messageHash] = {
chat,
conn,
timeout: setTimeout(() => {
console.log(`Acknowledgment not received for hash: ${messageHash}. Retrying...`);
// Reinitiate connection and resend chat
const peerId = conn.peer;
removeConnection(conn); // Close existing connection
initiateConnection(peerId); // Reconnect
conn.send({
type: "chat",
chat
});
}, ACK_TIMEOUT),
};
});
chatMessageInput = ""; // Reset input field
document.getElementById('message').value = '';
}
}*/
/*async function submitChat(event) {
event.preventDefault(); // to prevent default behavior which is to POST to the same page
chatMessageInput = document.getElementById('message').value;
if (chatMessageInput.length > 0) {
// the chat object's data
//let chat;
let chatTime = new Date().getTime();
let fullMessage = usernameInput + ':' + chatMessageInput + ':' + chatTime;
// sha256(fullMessage).then((messageHash) => {
// chat = {
// sender: usernameInput,
// message: chatMessageInput,
// timestamp: chatTime,
// hash: messageHash
// };}).then(() => {
// receiveChat(chat); // simulate receiving a chat
// }).then(() => {
// // send chat object to connected users
// Object.values(connections).forEach(conn => {
// console.log(`sending chat to... ${conn.peer}`);
// conn.send({
// type: "chat",
// chat
// });
// });
// }).then(() => {
// chatMessageInput = ""; // reset chat message input
// document.getElementById('message').value = '';
// });
const messageHash = await sha256(fullMessage);
const chat = {
sender: usernameInput,
message: chatMessageInput,
timestamp: chatTime,
hash: messageHash
};
receiveChat(chat); // simulate receiving a chat
//send chat object to connected users
Object.values(connections).forEach(conn => {
console.log(`sending chat to... ${conn.peer}`);
conn.send({
type: "chat",
chat
});
//receive ACK
//if no ACK in n seconds
//close peer connection
//initiate new connection
//send chat again
//else move on to next
});
chatMessageInput = ""; // reset chat message input
document.getElementById('message').value = '';
}
}*/
</script>
</body>
</html>