-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathChatScript.js
488 lines (384 loc) · 12.3 KB
/
ChatScript.js
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
var inputElem = document.querySelector('.chatMessage');
var contacts = document.querySelector('#contacts').children[0];
var messages = document.querySelector('.messages').children[0];
var userDisplayName = document.querySelector('#userDisplayName');
var chatroomDisplayName = document.querySelector('#chatroomDisplayName');
var userId;
var teamId;
var adminId = null;
var currentTeam = null;
var chatRef;
var othersRef;
// Variables to keep track of what kind of chat user is viewing
var inDM = false;
var inAnnounce = false;
// Keeps track if current user is an admin of the current team
var isAdmin = false;
// Used to set who sent a message
var nameOfSender = "Your Friend";
// Current time used for timestamps
var currTime;
// Sets userId and teamId when user is logged in
firebase.auth().onAuthStateChanged(async function (user) {
// User is signed in: set userId and teamId
if (user) {
userId = user.uid;
let ref = firebase.database().ref("Users/" + userId);
await loadTeamId(ref);
}
// No user is signed in.
else {
}
});
// Sets teamId
async function loadTeamId(ref) {
return ref.once('value').then(function (snapshot) {
teamId = snapshot.val().currTeam;
});
}
// Signs user out of website
function signOut() {
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log("Signing out");
firebase.auth().signOut();
}
});
}
// Determines if current user is an admin
function checkAdmin(ref) {
ref.once('value').then(function (snapshot) {
// Check if the current user is the same as the admin listed on team
isAdmin = (userId == snapshot.val().admin);
});
}
// Sets name of person sending message
function getName(ref) {
ref.once('value').then(function (snapshot) {
// Check if the current user is the same as the admin listed on team
nameOfSender = snapshot.val().Name;
});
}
// Gets the current time for timestamp
async function getCurrTime(ref) {
return ref.once('value').then(function (snapshot) {
let offset = snapshot.val();
let serverTime = new Date().getTime() + offset;
let myDate = new Date(serverTime);
currTime = myDate.toString().split(' ')[4];
});
}
// Sets up chat window for announcements, chatrooms, and directMessages according to parameters
function setUpChat(chatType, name, optionalId) {
// Sets up displays, variables, and refs based on chat type
if (chatType == "announcements") {
// Display name
chatroomDisplayName.innerHTML = "Announcements";
// Set type of chatroom
inDM = false;
inAnnounce = true;
// Call checkAdmin to set isAdmin
let adminRef = firebase.database().ref("Team/" + teamId);
checkAdmin(adminRef);
// Set reference to Announcements page on firebase
chatRef = firebase.database().ref("/Team/" + teamId + "/Chatroom/Announcements/AnnouncementsExt");
}
else if (chatType == "chatrooms") {
// Display name
chatroomDisplayName.innerHTML = name;
// Set type of chatroom
inDM = false;
inAnnounce = false;
// Set reference to chatrooms page on firebase
chatRef = firebase.database().ref("/Team/" + teamId + "/Chatroom/Chatrooms/" + name);
}
else { // directMessages
// Display name
chatroomDisplayName.innerHTML = name;
// Set type of chatroom
inDM = true;
inAnnounce = false;
// Set references for saving messages in both user's messages
chatRef = firebase.database().ref("/Team/" + teamId + "/Chatroom/directMessages/" + userId + "/" + optionalId);
othersRef = firebase.database().ref("/Team/" + teamId + "/Chatroom/directMessages/" + optionalId + "/" + userId);
}
// Removes all messages in the message window
while (messages.firstChild) {
messages.removeChild(messages.firstChild);
}
// Fill in chat window with each message from database branch
chatRef.child("msgArray").off();
chatRef.child("msgArray").on("child_added", snapshot => {
//snapshot.forEach(function(data) {
// Get value of message and time
let inputMsg = snapshot.val().message;
let inputSender = snapshot.val().sender;
let timestamp = snapshot.val().time;
// Determine who is sending the message
let source;
if (inputSender == userId) {
source = "client";
}
else {
source = "server";
}
// Set name of sender
friendRef = firebase.database().ref("/Users/" + inputSender);
getName(friendRef);
// Add chat bubble to window
if (chatType == "announcements") {
createHTMLMessage(inputMsg, "server", timestamp, "Admin");
}
else {
createHTMLMessage(inputMsg, source, timestamp, nameOfSender);
}
//});
});
}
// Wait for log in to work so we don't get a null uid
setTimeout(function () {
console.log("Ready to fill contacts!");
console.log("userID: " + userId);
console.log("teamId: " + teamId);
/** Set Name **/
let userRef = firebase.database().ref('/Users/' + userId);
userRef.on("value", snapshot => {
userDisplayName.innerHTML = snapshot.val().Name;
})
changeView();
/** Announcements **/
let announcementsRef = firebase.database().ref('/Team/' + teamId + '/Chatroom/Announcements');
announcementsRef.off();
announcementsRef.on("child_added", snapshot => {
// Fetch latest message on announcements
let latestMsg = snapshot.val().mostRecent;
// Truncates lates message if too long
if (latestMsg.length > 25) {
latestMsg = latestMsg.substring(0, 25) + "...";
}
// Generate HTML element on sidebar
createHTMLContact("announcements", "Announcements", latestMsg);
});
/** Announcements **/
/** Chatrooms **/
let chatroomsRef = firebase.database().ref('/Team/' + teamId + '/Chatroom/Chatrooms');
chatroomsRef.off();
chatroomsRef.once("value", snapshot => {
snapshot.forEach(function (data) {
// Fetch from database
let chatroomName = data.val().chatroomName;
let latestMsg = data.val().mostRecent;
// Truncates lates message if too long
if (latestMsg.length > 25) {
latestMsg = latestMsg.substring(0, 25) + "...";
}
// Generate HTML element on sidebar
createHTMLContact("chatrooms", chatroomName, latestMsg);
});
});
/** Chatrooms **/
/** Direct Messages **/
let friendsRef = firebase.database().ref('/Team/' + teamId + '/Chatroom/directMessages/' + userId);
friendsRef.off();
friendsRef.on("child_added", snapshot => {
// Fetch from database
let friendName = snapshot.val().name;
let friendId = snapshot.val().userId;
let latestMsg = snapshot.val().mostRecent;
// Truncates lates message if too long
if (latestMsg.length > 25) {
latestMsg = latestMsg.substring(0, 25) + "...";
}
// Generate HTML element on sidebar
createHTMLContact("directMessages", friendName, latestMsg, friendId);
});
/** Direct Messages **/
// Start at the announcements page
setUpChat("announcements", "Announcements");
}, 1500);
/**
* Updates message database
*/
async function updateMessageDatabase(msg) {
// Only let admins post to announcements
if ((inAnnounce && isAdmin) || (!inAnnounce)) {
// Get the currTime
await getCurrTime(firebase.database().ref("/.info/serverTimeOffset"));
// Write to database
// Create a new post reference with an auto-generated id
let newPostRef = chatRef.child("msgArray").push();
newPostRef.set({
sender: userId,
message: msg,
time: currTime
});
// Update the most recent message
chatRef.update({
mostRecent: msg
});
// If calling from directMessages then update other's too except if talking to self
if (inDM && (othersRef.toString() != chatRef.toString())) {
// Update other member's database info
newPostRef = othersRef.child("msgArray").push();
newPostRef.set({
sender: userId,
message: msg,
time: currTime
});
// Update the most recent message
othersRef.update({
mostRecent: msg
});
}
}
}
// Generates HTML element on sidebar for a specific contact
function createHTMLContact(chatType, name, latestMsg, optionalId) {
// Create elements of contact
let li = document.createElement("li");
let div1 = document.createElement("div");
let img = document.createElement("img");
let div2 = document.createElement("div");
let p1 = document.createElement("p");
let p2 = document.createElement("p");
// Edit attributes
li.className += "contact";
div1.className += "wrap";
div2.className += "meta";
p1.className += "name";
// Add img and ability to switch between chats
if (chatType == "announcements") {
img.src = "img/announcement.png";
div1.onclick = function () { setUpChat("announcements", "Announcements") };
}
else if (chatType == "chatrooms") {
img.src = "img/admin_1.png";
div1.onclick = function () { setUpChat("chatrooms", name) };
}
else {
img.src = "img/user.png";
div1.onclick = function () { setUpChat("directMessages", name, optionalId) };
}
// FIXME: Add online status !!!
// Add text
p1.innerHTML += name;
p2.innerHTML += latestMsg;
// Nest elements
div2.appendChild(p1);
div2.appendChild(p2);
div1.appendChild(img);
div1.appendChild(div2);
li.appendChild(div1);
// Add to HTML
contacts.appendChild(li);
}
// Generates HTML element on message window for a specific message
function createHTMLMessage(msg, source, time, name) {
// Timestamp
let div = document.createElement("p");
div.innerHTML += name + ": " + time.toString();
// Create elements of message box
let li = document.createElement("li");
let p = document.createElement("p");
let img = document.createElement("img");
p.innerHTML += msg;
// Determine the class attribute and image to append
if (source == 'server') {
li.className += "sent";
img.src = "img/eggperson.jpeg";
div.style = "padding-left: 50px; font-size: 12px"
}
else {
li.className += "replies";
img.src = "img/chat.jpg";
div.style = "padding-left: 500px; font-size: 12px"
}
// Add img and message to li
li.appendChild(img);
li.appendChild(p);
// Put html element on page
messages.append(li);
messages.append(div);
// Selects the messages class to always scroll to bottom
const messagesCont = document.querySelector('.messages');
shouldScroll = messagesCont.scrollTop + messagesCont.clientHeight === messagesCont.scrollHeight;
if (!shouldScroll) {
messagesCont.scrollTop = messagesCont.scrollHeight;
}
}
// Adds message to message window whenever user presses enter
inputElem.addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
if (key === 13) {
// Checked if the user entered anything
if (inputElem.value != "") {
updateMessageDatabase(inputElem.value);
inputElem.value = "";
}
}
});
/*** Add Chatroom Functionality below ***/
var inputElem2 = document.querySelector('#inputEmail');
var addChatroomButton = document.getElementById('addChatroomButton');
var addChatroomDialog = document.getElementById('addChatroomDialog');
addChatroomButton.addEventListener('click', function () {
addChatroomDialog.showModal();
});
/**
* Updates chatroom database
*/
async function updateChatroomDatabase() {
let name = inputElem2.value;
// Get the currTime
await getCurrTime(firebase.database().ref("/.info/serverTimeOffset"));
// Write to database
// Create a new post reference with an auto-generated id
let addChatroomRef = firebase.database().ref("/Team/" + teamId + "/Chatroom/Chatrooms/").child(name);
addChatroomRef.set({
mostRecent: "Welcome",
chatroomName: name
});
let newPostRef = addChatroomRef.child("msgArray").push();
newPostRef.set({
sender: userId,
message: "Welcome",
time: currTime
});
let chatroomName = name;
let latestMsg = "Welcome";
// Truncates lates message if too long
if (latestMsg.length > 25) {
latestMsg = latestMsg.substring(0, 25) + "...";
}
// Generate HTML element on sidebar
createHTMLContact("chatrooms", chatroomName, latestMsg);
inputElem2.value = "";
document.getElementById('addChatroomDialog').close();
}
async function getCurrTeam(ref){
return ref.once('value').then(function(snapshot){
currentTeam = snapshot.val();
console.log(currentTeam);
});
}
async function getAdminID(ref){
return ref.once('value').then(function(snapshot){
adminId = snapshot.val();
console.log(adminId);
})
}
async function changeView(){
var item = document.getElementById("move");
var ref = firebase.database().ref("Users/" + userId + "/currTeam");
await getCurrTeam(ref);
var aRef = firebase.database().ref("Team/" + currentTeam + "/admin");
await getAdminID(aRef);
if(adminId == userId){
console.log("Should not be printed");
item.href = "HomePage.html";
}
else{
item.href = "HomePageMem.html";
console.log("Should be printed");
}
}