Skip to content
Snippets Groups Projects
Commit e3c0f5de authored by Markus Klose's avatar Markus Klose
Browse files

Group message + comments

parent 1197e673
No related branches found
No related tags found
No related merge requests found
......@@ -104,16 +104,25 @@ io.on('connection', (socket) => {
io.on('connection', (socket) => {
socket.on('private message', (response) => {
var private_msg = response.private_msg;
var private_msg = response.msg;
var receiver = response.receiver;
var sender = response.name;
var array = Array.from(activeUsers);
var dateTime = new Date().toTimeString();
for(var i = 0; i<array.length; i++) {
if(array[i][1] == receiver){
io.emit(receiver, {
private_msg : private_msg,
sender : sender
msg : private_msg,
sender : sender,
receiver: receiver,
dateTime: dateTime
})
io.emit(sender, {
msg : private_msg,
sender : sender,
receiver: receiver,
dateTime: dateTime
})
return 0;
}
......@@ -122,8 +131,58 @@ io.on('connection', (socket) => {
status: 401
})
})
socket.on('groupMessage', (response) => {
let sender = response.name;
let receivers = response.receivers;
let groupMsg = response.groupMsg;
var dateTime = new Date().toTimeString();
console.log("receivers", receivers[0]);
console.log("groupmsg", groupMsg);
let a = activeUsers.values;
console.log("sender", sender);
/* for ()
if (activeUsers receivers[i].trim()) */
for (let i = 0; i<receivers.length; i++) {
io.emit(receivers[i].trim(), {
msg: groupMsg,
sender: sender,
receiver: receivers,
dateTime: dateTime
})
}
io.emit(sender, {
msg: groupMsg,
sender: sender,
receiver: receivers,
dateTime: dateTime
})
})
})
async function getKeyFromVal(receiver){
return new Promise( () => {
var array = Array.from(activeUsers);
console.log("usersArray: " + array);
var receiverSocketId;
for (var i = 0; i<array.length; i++){
console.log("array[i] ", array[i][0]);
if(array[i][1] == receiver) {
receiverSocketId = array[i][0];
console.log("Receiver ID in if: ", receiverSocketId);
resolve(receiverSocketId);
} else {
resolve("false");
}
}
})
}
//Logs message from Socket to Console
io.on('connection', (socket) => {
......
......@@ -13,7 +13,7 @@ router.get('/', async(req, res) => {
authHeader = req.headers.authorization;
try{
const verify = jwt.verify(authHeader, process.env.ACCESS_TOKEN_SECRET);
jwt.verify(authHeader, process.env.ACCESS_TOKEN_SECRET);
res.sendStatus(200);
} catch(err){
console.log(err);
......
......@@ -7,16 +7,37 @@ const router = express.Router()
const bodyParser = require('body-parser');
require('dotenv').config();
/**
* Summary:
* Function tto verify the Login of a client.
*
* Description:
* Username and password of client get checked, whether they exist in the database.
* Function will check, whether username and password from request are the same, as in the database.
* If successful, a JWT accessToke is created and statuscode 200 and the Accesstoke are sent to client.
* If not successful, statuscode 401 is sent to client.
*
*
* @fires fetch to "/login"
* @fires function getCookie()
* @listens submit event of "Submit" Button
*
* @param {Json} req Json Body from Client.
*
*
* @return {Json} res Response from server.
*/
router.post('/', async(req, res) => {
var name = req.body.name;
var password = req.body.password;
//res.status(200);
User.findOne({name: name})
.then(user => {
if(user){
bcrypt.compare(password, user.password, function (err, result) {
if(err){
//console.log("Login Route Error");
res.json(err);
}
if(result){
......
......@@ -36,7 +36,7 @@
<ul id="activeUsers">Active Users</ul>
<ul id="messages"></ul>
<ul id="messages">Messages</ul>
<ul id="messages_private"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" placeholder="Send to all"/><button>Send</button>
......@@ -69,27 +69,62 @@
var username = getCookie("username");
/**
* Summary:
* Sends username to server.
*
* Description:
* Immediately after entering the chatroom, the username gets written from the cookie and sent to the server, to update the list of active users.
*
* @fires socket.emit() to event 'userLogin'
*
*/
socket.emit('userLogin', {
name : username
});
/**
* Summary:
* Function for sending a private message.
*
* Description:
* This function is triggered when the "submit" button of the private message is pressed
* It takes the inputvalues from the private message form and the name of the designated receiver from the private receiver form
* if both values are not empty, a json, containing the message, the name of the receiver and the name of the sender, is sent to the server
* after sending the forms are emptied und the focus is set on the private message form.
*
*
* @fires socket.emit() to event 'private message'
* @fires
* @listens submit event of "Submit" Button
*/
form_private.addEventListener('submit', function(e){
e.preventDefault();
if(input_private.value && receiver.value){
socket.emit("private message",
{
private_msg : input_private.value,
msg : input_private.value,
receiver : receiver.value,
name : username
});
input_private.value = '';
receiver.value = '';
input_private.focus;
receiver.focus;
}
})
//Receive private Messages
/**
* Summary:
* Function listening for private chat messages.
*
* Description:
* This function listens to incoming private chat messages and group messages from the server, adressed to this specific client.
* The username of the client is read from the cookie that was created, when logging into chatroom.
* The message from the server is demultiplexed into message, name of the sender, name of the receiver/ names of the receivers, current time.
* The contents of the message will be dynamically displayed on the clients screen.
*
* @listens socket.on() 'username' event, where the username is the username of the current client.
*/
socket.on(username ,function(response){
if(response.status == 401){
......@@ -97,13 +132,16 @@
return 0;
}
var private_msg = response.private_msg;
var private_msg = response.msg;
var sender = response.sender;
//var private_msg = response.private_msg;
console.log("New private Message: ", response.private_msg," From: ", response.sender);
var receiver = response.receiver;
var date = response.dateTime;
var dateTime = date.split(" ")[0];
console.log("Private Message: ", private_msg," From: ", sender);
var item = document.createElement('li');
var nameMsg = "new private Message from: " + sender + ": " + private_msg;
var nameMsg = "Message from: " + sender + " to " + receiver + ": " + private_msg + " --" + dateTime;
item.textContent = nameMsg;
messages.appendChild(item);
......@@ -111,20 +149,59 @@
});
/**
* Summary:
* Function for sending a group message.
*
* Description:
* This function is triggered when the "submit" button of the group message is pressed
* It takes the inputvalues from the group message form and the name of the designated receivers from the group receiver form
* if the number of receivers is 1, the client gets alerted, that the private message is ideal for this task.
* Json with message, receivers and name of sender is sent to server.
*
*
* @fires socket.emit() to event 'groupMessage'
* @listens submit event of "Submit" Button
*/
form_multiple_receiver.addEventListener('submit', function(e){
e.preventDefault();
var group_msg = input_multiple.value;
var receivers = input_multiple_receiver.value;
var receiverArr = receivers.split(',').trim();
var receiverArr = receivers.split(',');
if (receiverArr.length == 1) {
alert("Sie haben nur einen Empfänger angegeben, hierfür können Sie die private Nachricht nutzen");
input_multiple.value = "";
input_multiple_receiver.value = "";
input_private.focus;
}
else {
console.log("Multiple Shit: ", receiverArr);
socket.emit('groupMessage', {
receivers: receiverArr,
groupMsg: group_msg,
name: username
});
}
})
//Event Listener to trigger emit function. Sends 'chat message' event and Message to Server
/**
* Summary:
* Function for sending a message and multimedia file to all active users.
*
* Description:
* This function is triggered when the "submit" button of the message is pressed
* It takes the inputvalues from the message form and the input of the fileinput
* if message form is filled, json with msg and name of sender is sent
* if multimediainput is filled, it will be sent.
*
* @fires socket.emit() to event 'chat message'
* @listens submit event of "Submit" Button
*/
form.addEventListener('submit', function(e) {
e.preventDefault();
if(fileUpload.files.length){
......@@ -140,6 +217,19 @@
}
});
/**
* Summary:
* Function listening for chat messages.
*
* Description:
* This function listens to incoming chat messages from the server.
* If a message is received, it will be demultiplexed into the message, the name of the sender and the current time.
* After demultiplexing, the message will be appended dynamically to the html dom and displayed.
*
*
* @listens socket.on() 'chat message' event
*/
socket.on('chat message', function(response) {
console.log(response);
var msg = response.msg;
......@@ -155,6 +245,17 @@
window.scrollTo(0, document.body.scrollHeight);
});
/**
* Summary:
* Function listening for updates from the server regarding active users.
*
* Description:
* This function listens to incoming update messages from the server regarding the users, who are currently online in the chatroom.
* The Array with users will bei demultiplexed from the message and dynamically displayed on the screen.
* As soon as the message is received, the list with active users is updated.
*
* @listens socket.on() 'updateUserList' event
*/
socket.on('updateUserlist', function(req) {
console.log("Update");
var userList = req.userList;
......@@ -170,6 +271,11 @@
}
});
// Alex schreib nen Kommentar
function upload(files) {
var fileObject = files[0];
var url = URL.createObjectURL(fileObject);
......@@ -214,14 +320,20 @@
messages.appendChild(audioHTML);
});
/* function getUsernameFromCookie() {
var decodedCookie = decodeURIComponent(document.cookie);
console.log("CookieArr", decodedCookie);
var cArr = decodedCookie.split(":");
console.log(cArr);
return cArr[1];
} */
/**
* Summary:
* Function for getting values from cookie.
*
* Description:
* This function gets the name of a key and returns it's value from a cookie.
*
*
* @
*
* @param {String} name name of the key, it's value is wished.
*
* @return {String} value of the key in cookie.
*/
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
......
......@@ -22,7 +22,20 @@
const form = document.getElementById('login-form');
form.addEventListener('submit', submitLoginData);
async function submitLoginData(event) {
/**
* Summary:
* Handles Login of Client.
*
* Description:
* Logindata of Client, username and password are sent to server.
* If Serverresponse 200 Clientlogin accepted, the Username is saved in a cookie, and the client is redirected into the chatroom
* If Serverresponse != 200 inputform for username/password are emptied.
*
* @fires fetch to "/login"
* @fires function getCookie()
* @listens submit event of "Submit" Button
*/
function submitLoginData(event) {
event.preventDefault();
......@@ -48,71 +61,62 @@
.then(response => response.json())
.then((result) => {
var token = result.accessToken;
var status = result.statusCode;
document.cookie = `token=${token}`;
if (status == 200){
authToken();
}
})
.catch(error => console.log('error', error));
}
console.log("Result ", result);
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
async function authToken(){
var token = getCookie("token").split(',');
var myHeaders = new Headers();
var status = result.statusCode;
console.log("Status ", status);
myHeaders.append("Authorization", token[0]);
var token = result.token;
console.log("Token ", token);
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
if (status === "200") {
fetch("http://localhost:3000/authenticate", requestOptions)
.then((response) => {
// Weiterleitung an Chatroom, bei erfolreicher Anmeldung (StatusCode == 200)
if (response.status === 200) {
// Rückmeldung an Client
var divErfolgreich = document.createElement('div');
divErfolgreich.textContent = "Erfolgreich eingeloggt! Sie werden in den Chatroom weitergeleitet";
document.body.appendChild(divErfolgreich);
// Speichern des Username in Cookie
setCookie(username.value.trim());
/* socket.emit('userLogin', {
name : username.value.trim()
}); */
// Kurzer Timeout, dass der Client die Nachricht lesen kann
setTimeout(function(){
window.location.href = "/chatroom";
}, 2000);
}
// Bei nicht erfolgreichem Login (StatusCode != 200) werden die Eingabefelder geleert und dem Client eine Rückmeldung gegeben
else {
username.value = "";
password.value = "";
var loginFailed = document.createElement('div');
loginFailed.setAttribute("id", "loginFailed");
loginFailed.textContent = "Login fehlgeschlagen, bitte versuche es erneut";
document.body.appendChild(loginFailed);
}
console.log(result)
})
.catch(error => console.log('error', error));
}
/**
* Summary:
* Hanldes Cookie for Login.
*
* Description:
* If UserLogin is successful, this function creates a cookie and stores the username of the logged in client.
* Format: "key" : "username:name" --> "" : "username:John"
*
* @ToDo write "username" in key field and the name in "value" field
* @listens function submitLoginData()
*
* @param {String} name Name is the input of the client, written in the loginform.
*
*/
function setCookie(name) {
document.cookie = "username=" + name;
console.log("Username setCookie");
document.cookie = "username:" + name;
}
</script>
</body>
......
......@@ -9,7 +9,8 @@
<div id = "register">
<h1>Registration</h1>
<form id="reg-form">
<!-- Anmeldeformular des Clients, Username, Passwort und ein Knopf zum Bestätigen -->
<!-- Anmeldeformular des Clients, Username, Passwort, ein Knopf zum Bestätigen -->
<input type="text" autocomplete="off" id="username" placeholder="Username" />
<input type="password" autocomplete="off" id="password" placeholder="Password" />
<input type="submit" value="Submit Form" />
......@@ -21,8 +22,20 @@
const form = document.getElementById('reg-form');
form.addEventListener('submit', submitRegistrationData);
// Funktion zum senden der Registraturdaten an den Server
// Wird ausgeführt, wenn der "Submit" Button gedrückt wird
/**
* Summary:
* Function for registrating a client.
*
* Description:
* This function checks, whether the two input fields are filled out.
* Input Values from Client, username and password are sent to server.
* 200 ok response from Server redirects client to the loginpage.
* 401 response from Server tells cleint to try again.
*
*
* @fires fetch to "/register"
* @listens submit event of "Submit" Button
*/
async function submitRegistrationData(event) {
event.preventDefault();
......@@ -30,15 +43,12 @@
var username = document.getElementById("username");
var password = document.getElementById("password");
// Prüfung ob Eingabe im Loginfeld bzw. Passwortfeld leer sind
if (username.value.trim().length && password.value.trim().length !== 0) {
console.log(username, password);
// HTML Header wird erstellt und hinzugefügt
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
// Json File mit den Eingabedaten des Clients wird erstellt
var raw = JSON.stringify({
"name": username.value.trim(),
"password": password.value.trim()
......@@ -53,7 +63,6 @@
fetch("http://localhost:3000/register", requestOptions)
.then((response) => {
// Wenn der HTML StatusCode zwischen 200-299 liegt
if(response.ok){
if (document.getElementById("divLeer")) {
......@@ -62,7 +71,6 @@
divLeer.parentNode.removeChild(divLeer);
}
// Rückmeldung an Client, kurzer Timeout, Weiterleitung an Loginseite
var divErfolgreich = document.createElement('div');
divErfolgreich.textContent = "Erfolgreich registriert! Weiterleitung zum Login.";
document.body.appendChild(divErfolgreich);
......@@ -84,7 +92,6 @@
})
.catch(error => console.log('error', error));
}
// Im Fall, dass eines der Eingabefelder leer ist, werden beide Felder geleert und der Client wird aufgefordert eine erneute Eingabe zu tätigen
else {
username.value = "";
......
......@@ -7,7 +7,7 @@
<title>Document</title>
</head>
<body>
<!-- Start Seite, mit Buttons, mit Links tur Loginseite/ Registrierungsseite -->
<!-- Start Seite, mit Buttons, die zur Loginseite/ Registrierungsseite weiterleiten-->
<h1>Guten Tag!</h1>
<a href="/login">Login</a>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment