-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
338 lines (300 loc) · 15.5 KB
/
index.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
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Serverless, secure & persistent multichat</title>
<!-- To efficiently implement sockets -->
<script src="https://unpkg.com/[email protected]/dist/peerjs.min.js"></script>
<!-- To easily manage dynamic rendering -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- Integrate font styles -->
<link href="https://fonts.googleapis.com/css2?family=Red+Hat+Display&display=swap" rel="stylesheet">
<!-- Material Design stylesheets -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script async src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<style>
body {
font-family: "Red Hat Display";
background-color: #ecf0f1;
}
div {
text-align: center;
}
p {
margin: 0.18em;
}
#chatbox {
height: 25rem;
text-align: left;
width: 95%;
margin: 0 auto;
overflow-y: scroll;
}
.row {
width: 100%;
margin: 0;
padding: 0 2em;
}
</style>
</head>
<body>
<div id="app">
<div id="login" v-if="screen === 'login'">
<div class="container">
<h1>Enter your username</h1>
<div class="row">
<form v-on:submit="submitLogin">
<div class="input-field col s8">
<input :disabled="loading" id="username" type="text" v-model="usernameInput" />
<label for="username">My username</label>
</div>
<button v-bind:class="{ disabled: loading }" class="btn-large waves-effect waves-light red col s4" type="submit">
Login<i class="material-icons right">login</i>
</button>
</form>
</div>
<p v-if="loading">Loading...</p>
<p v-if="peerError" style="color: red">{{ peerError }}</p>
<p>Crafted with ❤ <em>by <a href="https://r.milon.pro" target="_blank" rel="noopener noreferrer">Rubilmax</a></em></p>
</div>
</div>
<div id="chat" v-if="screen === 'chat'">
<div class="container">
<h1>Multichat</h1>
<p>Crafted with ❤ <em>by <a href="https://r.milon.pro" target="_blank" rel="noopener noreferrer">Rubilmax</a></em></p>
<p>Your username: {{ usernameInput }}</p>
</div>
<div class="row">
<div id="users" class="col s12 m5">
<div class="row">
<!-- We don't show connection form if the client is disconnected -->
<div v-if="!peer.disconnected">
<form v-on:submit="submitConnection">
<div class="input-field col s8">
<input :disabled="loading" id="target_id" type="text" v-model="targetIdInput" />
<label for="target_id">Target username</label>
</div>
<button v-bind:class="{ disabled: loading }" class="btn-large waves-effect waves-light col s4" type="submit">
Connect<i class="material-icons right">login</i>
</button>
</form>
<button class="btn-large waves-effect waves-light red col s12" v-on:click="disconnectPeer">
Disconnect from server<i class="material-icons right">logout</i>
</button>
<div class="col s12">
<em v-if="peerError" style="color: red">{{ peerError }}</em>
</div>
</div>
<div v-else class="container">
<h5>You are disconnected!</h5>
<em>You can still talk to connected users, but won't be able to reach or be reached by any new user!</em>
</div>
<div class="col s12">
<h4>Connected users</h4>
<p><i class="material-icons">portrait</i>{{ usernameInput }}</p>
<p v-for="peerId in peerIds">
<i class="material-icons">portrait</i>{{ getUsername(peerId) }}
</p>
</div>
</div>
</div>
<div class="col s12 m7">
<h4>Chatbox</h4>
<div id="chatbox">
<p v-for="chat in chats">{{ chat.sender }}: {{ chat.message }}</p>
</div>
<div class="row">
<form v-on:submit="submitChat">
<div class="input-field col s10">
<input id="chat_message" type="text" v-model="chatMessageInput" />
<label for="chat_message">Your message</label>
</div>
<button class="btn-floating btn-large waves-effect waves-light red" type="submit">
<i class="material-icons">send</i>
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
const appPrefix = "secure-p2p-multichat-"; // the prefix we will preprend to usernames
const oldChats = localStorage.getItem("chats");
const chats = oldChats ? JSON.parse(oldChats) : []; // oldChats may be undefined, which throws error if passed into JSON.parse
const app = new Vue({
el: "#app",
data: {
screen: "login", // initialize at login screen
usernameInput: localStorage.getItem("username"), // to load saved username
peerError: "",
loading: false,
peer: {}, // initialize as empty object instead of undefined
targetIdInput: "",
peerIds: [], // connected to nobody at first
connections: {}, // maps peerIds to their correspondig PeerJS's DataConnection objects
chats,
chatMessageInput: ""
},
// in case you want to enable automatic login
/*mounted: function () {
if (this.usernameInput && this.usernameInput.length > 0) {
this.submitLogin();
}
},*/
watch: {
chats: function () {
const chatbox = document.getElementById("chatbox");
if (chatbox) chatbox.scrollTop = 99999999; // to automatically scroll the chatbox to the most recent chat message
}
},
methods: {
// util functions to convert username to peer ids and vice-versa
getPeerId: username => appPrefix + username,
getUsername: peerId => peerId ? peerId.slice(appPrefix.length) : "",
// we keep track of connections ourselves as suggested in peerjs's documentation
addConnection: function (conn) {
this.connections[conn.peer] = conn;
this.updatePeerIds();
console.log(`Connected to ${conn.peer}!`);
},
removeConnection: function (conn) {
delete this.connections[conn.peer];
this.updatePeerIds();
},
updatePeerIds: function () {
this.peerIds = Object.keys(this.connections);
},
disconnectPeer: function () {
this.peer.disconnect();
},
// called to properly configure connection's client listeners
configureConnection: function (conn) {
conn.on("data", data => {
// if data is about connections (the list of peers sent when connected)
if (data.type === "connections") {
data.peerIds.forEach(peerId => {
if (!this.connections[peerId]) {
this.initiateConnection(peerId);
}
});
} else if (data.type === "chat") {
this.receiveChat(data.chat);
}
// please note here that if data.type is undefined, this endpoint won't do anything!
});
conn.on("close", () => this.removeConnection(conn));
conn.on("error", () => this.removeConnection(conn));
// if the caller joins have a call, we merge calls
conn.metadata.peerIds.forEach(peerId => {
if (!this.connections[peerId]) {
this.initiateConnection(peerId);
}
});
},
// called to initiate a connection (by the caller)
initiateConnection: function (peerId) {
if (!this.peerIds.includes(peerId) && peerId !== this.peer.id) {
this.loading = true;
this.peerError = "";
console.log(`Connecting to ${peerId}...`);
const options = {
metadata: {
// if the caller has peers, we send them to merge calls
peerIds: this.peerIds
},
serialization: "json"
};
const conn = this.peer.connect(peerId, options);
this.configureConnection(conn);
conn.on("open", () => {
this.addConnection(conn);
if (this.getUsername(conn.peer) === this.targetIdInput) {
this.targetIdInput = "";
this.loading = false;
}
});
}
},
createPeer: function () {
// options are useful in development to connect to local peerjs server
this.peer = new Peer(this.getPeerId(this.usernameInput)/*, {
host: 'localhost',
port: 8080,
path: 'app'
}*/);
// when peer is connected to signaling server
this.peer.on("open", () => {
this.screen = "chat"; // changing screen
this.loading = false;
this.peerError = "";
});
// error listener
this.peer.on("error", error => {
if (error.type === "peer-unavailable") { // if connection with new peer can't be established
this.loading = false;
this.peerError = `${this.targetIdInput} is unreachable!`; // custom error message
this.targetIdInput = "";
} else if (error.type === "unavailable-id") { // if requested id (thus username) is already taken
this.loading = false;
this.peerError = `${this.usernameInput} is already taken!`; // custom error message
} else this.peerError = error; // default error message
});
// when peer receives a connection
this.peer.on('connection', conn => {
if (!this.peerIds.includes(conn.peer)) {
this.configureConnection(conn);
conn.on("open", () => {
this.addConnection(conn);
// send every connection previously established to connect everyone (merge chat rooms)
conn.send({
type: "connections",
peerIds: this.peerIds
});
});
}
});
},
submitLogin: function (event) {
if (event) event.preventDefault(); // to prevent default behavior which is to POST to the same page
if (this.usernameInput.length > 0 && !this.loading) {
this.loading = true; // update status
this.peerError = ""; // reset error status
localStorage.setItem("username", this.usernameInput); // set username cookie to instanciate it at the next session
this.createPeer();
}
},
submitConnection: function (event) {
event.preventDefault(); // to prevent default behavior which is to POST to the same page
const peerId = this.getPeerId(this.targetIdInput); // the peer's id we want to connect to
this.initiateConnection(peerId);
},
receiveChat: function (chat) {
this.chats.push(chat);
localStorage.setItem("chats", JSON.stringify(this.chats));
},
submitChat: function (event) {
event.preventDefault(); // to prevent default behavior which is to POST to the same page
if (this.chatMessageInput.length > 0) {
// the chat object's data
const chat = {
sender: this.usernameInput,
message: this.chatMessageInput,
timestamp: new Date().getTime()
};
this.receiveChat(chat); // simulate receiving a chat
// send chat object to connected users
Object.values(this.connections).forEach(conn => {
conn.send({
type: "chat",
chat
});
});
this.chatMessageInput = ""; // reset chat message input
}
}
}
});
</script>
</html>