-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.html
209 lines (181 loc) · 5.89 KB
/
chat.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Chat</title>
</head>
<body style="display: flex; gap: 12px;">
<nav id="allUsers" hidden style="width: 200px;">
<h1>All users</h1>
<ul id="usernamesList"></ul>
</nav>
<main style="flex: 1">
<p>
Status: <span id="state">Disconnected</span>
<button onclick="closeConnection();">Close</button>
<button onclick="deleteCookie('session_id');location.reload()">Logout</button>
</p>
<section id="signForm">
<form onsubmit="return signInOrUp(this)">
<h1>Login/Register</h1>
<input type="text" placeholder="Username" name="username" value="otto"> <br>
<input type="password" placeholder="Password" name="password" value="1234"> <br>
<button type="submit">Sign in or register</button>
</form>
</section>
<section id="welcomeHeader" hidden>
<h1>Hello <span id="username"></span>!</h1>
</section>
<section id="chatWindow" hidden>
<h3>Your chat with <span id="otherUser"></span>.</h3>
<div id="scrollDiv" style="height: 200px; overflow: auto;border:1px solid black;">
<pre id="currentMessages"></pre>
</div>
<form onsubmit="return sendMessageTo();">
<input id="myMessage" placeholder="Nachricht senden">
<button type="submit" >Senden</button>
</form>
</section>
</main>
<script>
var socket = null;
var messages = {};
var myUserName = null;
var openChatWithUser = null;
function updateMessages() {
if (socket == null) return;
if (openChatWithUser == null) return;
var displayMessages = messages[openChatWithUser];
if (displayMessages == null) return;
var newMessageString = "";
for (var message of displayMessages) {
var time = new Date(message.created_at).toString().slice(16, 24);
newMessageString += `[${time}] ${message.from}\n${message.message}\n\n`;
}
currentMessages.innerText += newMessageString.replace(currentMessages.innerText, "");
scrollDiv.scrollTo(0, scrollDiv.scrollTopMax)
}
function sendMessageTo() {
socket.send(JSON.stringify({
kind: "new-message",
message: {
from: myUserName,
to: openChatWithUser,
message: myMessage.value,
created_at: +new Date(),
}
}));
return false;
}
function openChatWith(username) {
otherUser.innerText = username;
chatWindow.hidden = false;
openChatWithUser = username;
currentMessages.innerText = "";
updateMessages();
}
function updateUserList(usernames) {
if (socket == null) return;
var list = "";
for (var username of usernames) {
username = escape(username);
if (username == myUserName) continue;
console.log(username, myUserName);
list += `<li onclick="openChatWith('${username}')">${username}</li>`;
}
usernamesList.innerHTML = list;
}
function signInOrUp(form) {
let data = new FormData(form);
socket.send(JSON.stringify({
kind: "login",
user: {
username: data.get("username"),
password: data.get("password")
}
}));
return false;
}
function activate_session(name) {
console.log("Hello", name);
username.innerText = name;
welcomeHeader.hidden = false;
allUsers.hidden = false;
signForm.hidden = true;
}
function check_old_session() {
if (socket === null) return;
const session_id = getCookie("session_id");
if (session_id === undefined) return;
socket.send(JSON.stringify({
kind: "check-session",
session_id: session_id
}));
}
function closeConnection() {
state.innerText = "Closed";
socket.close();
socket = null;
}
function connect () {
state.innerText = "Connecting... ";
socket = new WebSocket('ws://localhost:3000');
socket.onerror = e => console.log("[ERROR]", e);
socket.onmessage = m => {
console.log(m);
const data = JSON.parse(m.data);
switch (data["kind"]) {
case "error": alert(data['err']['message']); break;
case "update-online-users":
updateUserList(data["online_users"]["usernames"]);
console.log(data);
break;
case "invalid-session":
console.log("Invalid cookie");
deleteCookie("session_id");
break;
case "session":
document.cookie = "session_id=" + data["session_id"];
activate_session(data["user"]["username"]);
myUserName = data["user"]["username"];
break;
case "new-message":
var otherUser = data["message"]["from"];
if (otherUser == myUserName) {
otherUser = data["message"]["to"];
}
if (messages[otherUser] === undefined) {
messages[otherUser] = [];
}
messages[otherUser].push(data['message']);
updateMessages();
break;
default: alert("Unknown error :/");
}
};
socket.onclose = e => {
state.innerText = "Disconnected (" + e.code + ")";
socket = null;
};
socket.onopen = _ => {
state.innerText = "Connected ";
check_old_session();
};
}
connect();
// helper functions from stackoverflow xD
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
function deleteCookie( name ) {
if (getCookie(name)) {
document.cookie = name + "=" +
";expires=Thu, 01 Jan 1970 00:00:01 GMT";
}
}
</script>
</body>
</html>