Removed obsolete js files

This commit is contained in:
Rohan Sircar 2020-05-27 17:18:54 +05:30
parent 8b3774de8e
commit 7c6d4a5c05
10 changed files with 2 additions and 2431 deletions

1
chatto/.gitignore vendored
View File

@ -38,3 +38,4 @@ bundle.min.js
src/main/javascript/node/ src/main/javascript/node/
dist dist
out out
yarn-error.log

View File

@ -1,3 +0,0 @@
@import url("node_modules/alertifyjs/build/css/alertify.css");
@import url("node_modules/alertifyjs/build/css/themes/bootstrap.min.css");
@import url("node_modules/alertifyjs/build/css/themes/default.min.css");

View File

@ -1,560 +0,0 @@
// import { sprintf } from 'sprintf-js';
// import { vsprintf } from 'sprintf-js';
/*var off_payment_method = document.getElementsByName('offline_payment_method');
var ischecked_method = false;
for ( var i = 0; i < off_payment_method.length; i++) {
if(off_payment_method[i].checked) {
ischecked_method = true;
break;
}
}
if(!ischecked_method) { //payment method button is not checked
alert("Please choose Offline Payment Method");
}*/
// var css = require('./app.css');
// console.log(css);
// var alertify = require('alertifyjs');
var log = require('loglevel');
var sjcl = require('sjcl');
var markdownit = require('markdown-it');
var md = new markdownit();
var Handlebars = require('handlebars');
var DOMPurify = require('dompurify');
var Fuse = require('fuse.js');
require('./test.js');
var toUserRadios = document.getElementsByName('toUser');
var isCheckedUser = false;
var chatTextArea = document.getElementById('chatTextArea');
var postNewMessageUrl = `http://${hostAddress}/api/chat/post/message`; //hostAddress variable is set in the thymeleaf head fragment
var getAllMessagesUrl = `http://${hostAddress}/api/chat/get/messages/`;
var getNewMessagesUrl = `http://${hostAddress}/api/chat/get/messages/`;
var getActiveUsersUrl = `http://${hostAddress}/api/chat/get/active-users/`;
// var postNewMessageUrl = "http://localhost:8080/api/chat/post/message";
// var getAllMessagesUrl = "http://localhost:8080/api/chat/get/messages/";
// var getNewMessagesUrl = "http://localhost:8080/api/chat/get/messages/";
// var messageLog = [];
var username = localStorage.getItem('username');
var authToken = localStorage.getItem('authToken');
var passphraseInput = document.getElementById('passphrase');
var iterations = 100000;
var source = document.getElementById("msg_container_template").innerHTML;
var msgContainerTemplate = Handlebars.compile(source);
var source = document.getElementById("msg_container_send_template").innerHTML;
var msgContainerSendTemplate = Handlebars.compile(source);
var source = document.getElementById("user-contact-online-template").innerHTML;
var userContactOnlineTemplate = Handlebars.compile(source);
var source = document.getElementById("user-contact-offline-template").innerHTML;
var userContactOfflineTemplate = Handlebars.compile(source);
var chatAreaNew = document.getElementById('chat_area_new');
var userBoxes = document.getElementsByName('user-box');
var activeUsers = {};
var fuseOptions = {
shouldSort: true,
threshold: 0.01,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
"userName",
]
};
log.setLevel('TRACE');
alertify.set('notifier', 'position', 'top-center');
// Loop through the buttons and add the active class to the current/clicked button
// for (var i = 0; i < btns.length; i++) {
// btns[i].addEventListener("click", function() {
// var current = document.getElementsByClassName("active");
// // If there's no active class
// if (current.length > 0) {
// current[0].className = current[0].className.replace(" active", "");
// }
// // Add the active class to the current/clicked button
// this.className += " active";
// });
// }
getActiveUsers(authToken)
.then(data => {
// activeUsers = data;
sessionStorage.setItem('activeUsers', JSON.stringify(data));
log.log(sessionStorage.getItem('activeUsers'));
})
for (let i = 0; i < userBoxes.length; i++) {
userBoxes[i].addEventListener('click', userCallBack)
}
function addUserCallBacks() {
for (let i = 0; i < userBoxes.length; i++) {
userBoxes[i].addEventListener('click', userCallBack)
}
}
function userCallBack() {
let current = document.getElementsByClassName('user-box active');
let passphrase = passphraseInput.value;
if (current.length > 0) {
if (passphrase == '') {
// alert('Please input passphrase')
alertify.error('Please enter a passphrase');
return;
}
current[0].className = current[0].className.replace(" active", "");
}
// Add the active class to the current/clicked button
else if (current.length == 0) {
let elem = document.getElementById('passphrase-initial');
passphrase = elem.value;
if (passphrase == '') {
// alert('Please input passphrase')
alertify.error('Please enter a passphrase');
return;
}
document.getElementById('no-user-selected').hidden = true;
document.getElementById('chat-card').hidden = false;
elem.hidden = true;
}
// console.log(this.getElementsByClassName('to-user-span'));
let userName = this.getElementsByClassName('to-user-span')[0].innerText;
document.getElementById('user-name-span').innerText = userName;
populateMessages(userName, passphrase);
sessionStorage.setItem('selectedUser', userName);
this.className += " active";
}
function populateMessages(userName, passphrase) {
console.log('Selected user = ' + userName);
if (passphrase == '') {
alert('Please input passphrase')
return;
}
// console.log(userName);
if (sessionStorage.getItem(userName) == null) {
chatTextArea.textContent = '';
chatAreaNew.innerHTML = '';
getAllMessages(userName)
.then(json => {
if (json == null) return;
console.log(json);
let i = 0;
let messageLog = [];
let messageLogNew = [];
let lastMessageTimeStamp;
if (json.length > 0) {
json.forEach(function(obj) {
// console.log(obj.toUser);
messageCipher = JSON.stringify(obj.messageCipher);
console.log(messageCipher);
// let message = sjcl.decrypt("password", messageCipher);
let message = md.render(sjcl.decrypt(passphrase, messageCipher));
let utcDate = obj.messageTime;
lastMessageTimeStamp = utcDate;
let localDate = new Date(utcDate);
let messageLine = sprintf('%s %s: %s ', localDate, obj.fromUser, message);
// localDate.``
// console.log('localDate = ' + localDate);
console.log(messageLine);
// chatTextArea.append(obj.fromUser + ": " + message + "\n");
chatTextArea.append(messageLine + '\n');
messageLog[i++] = messageLine;
chatTextArea.scrollTop = chatTextArea.scrollHeight;
// console.log('Message log = ' + messageLog);
let context = { fromUser: obj.fromUser, message: message, time: localDate.toLocaleString() };
let msgContainer;
if (obj.fromUser == username) {
msgContainer = msgContainerSendTemplate(context);
} else {
msgContainer = msgContainerTemplate(context);
}
messageLogNew.push(JSON.stringify(context));
$(chatAreaNew).append(DOMPurify.sanitize(msgContainer));
});
sessionStorage.setItem(userName, JSON.stringify(messageLog));
sessionStorage.setItem(userName + username + 'new', JSON.stringify(messageLogNew));
// console.log()
// sessionStorage.clear();
console.log('Last message time = ' + lastMessageTimeStamp);
sessionStorage.setItem(userName + '-time', lastMessageTimeStamp);
}
});
} else {
console.log("Stored messages = " + sessionStorage.getItem(userName));
let storedMessages = JSON.parse(sessionStorage.getItem(userName));
let storedMessagesNew = JSON.parse(sessionStorage.getItem(userName + username + 'new'));
let lastMessageTime = sessionStorage.getItem(userName + '-time');
console.log("last message time stamp = " + lastMessageTime);
if (lastMessageTime != null) {
getNewMessages(userName, lastMessageTime)
.then(json => {
if (json == null) return;
console.log(json)
if (json.length > 0) {
json.forEach(function(obj) {
let messageCipher = JSON.stringify(obj.messageCipher);
let message = md.render(sjcl.decrypt(passphrase, messageCipher));
// console.log(message);
// chatTextArea.append(message + "\n");
let utcDate = obj.messageTime;
lastMessageTimeStamp = utcDate;
let localDate = new Date(utcDate);
let messageLine = sprintf('%s %s: %s', localDate, obj.fromUser, message);
// localDate.``
// console.log('localDate = ' + localDate);
console.log(messageLine);
// chatTextArea.append(obj.fromUser + ": " + message + "\n");
chatTextArea.append(messageLine + '\n');
chatTextArea.scrollTop = chatTextArea.scrollHeight;
storedMessages.push(messageLine);
let context = { fromUser: obj.fromUser, message: message, time: localDate.toLocaleString() };
let msgContainer;
if (obj.fromUser == username) {
msgContainer = msgContainerSendTemplate(context);
} else {
msgContainer = msgContainerTemplate(context);
}
storedMessagesNew.push(JSON.stringify(context));
$(chatAreaNew).append(DOMPurify.sanitize(msgContainer));
})
sessionStorage.setItem(userName + '-time', lastMessageTimeStamp);
sessionStorage.setItem(userName, JSON.stringify(storedMessages));
sessionStorage.setItem(userName + username + 'new', JSON.stringify(storedMessagesNew));
console.log("this value stored" + sessionStorage.getItem(userName))
console.log("last message time stamp = " + lastMessageTimeStamp);
console.log(sessionStorage.getItem(userName + '-time'));
}
chatTextArea.textContent = '';
chatAreaNew.innerHTML = '';
console.log("Stored messages 2 = " + storedMessages);
storedMessages.forEach(function(messageLine) {
chatTextArea.append(messageLine + '\n');
chatTextArea.scrollTop = chatTextArea.scrollHeight;
// let context = {message: messageLine};
// let msgContainer;
// if(obj.fromUser == username)
// {
// msgContainer = msgContainerSendTemplate(context);
// }
// else{
// msgContainer = msgContainerTemplate(context);
// }
// $(chatAreaNew).append(msgContainer);
})
storedMessagesNew.forEach(function(contextString) {
let context = JSON.parse(contextString);
let msgContainer;
if (context.fromUser == username) {
msgContainer = msgContainerSendTemplate(context);
} else {
msgContainer = msgContainerTemplate(context);
}
$(chatAreaNew).append(DOMPurify.sanitize(msgContainer));
scrollChatAreaAnimated(2400);
})
});
}
// chatTextArea.append(JSON.stringify(storedMessages));
}
// sessionStorage.setItem('status', 'ready');
// sessionStorage.setItem('userName', messageLog);
// console.log('Message log = ' + messageLog);
// }
// let passphraseKey = userName + '-passphrase';
// sessionStorage.setItem(passphraseKey, passphrase);
// console.log(sessionStorage.getItem(passphraseKey));
}
// var lastMessageTimeStamp;
// console.log(authToken);
// 'Basic ' + btoa("hmm" + ":" + "hmm")
Handlebars.registerHelper('avatar', function() {
return '<div class="img_cont_msg"> <img src="https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg" class="rounded-circle user_img_msg"> </div>';
});
// var user;
function getSelectedUser() {
for (var i = 0; i < toUserRadios.length; i++) {
if (toUserRadios[i].checked) {
let user = toUserRadios[i].value;
console.log('sending to user = ' + user);
isCheckedUser = true;
return user;
}
}
}
function getSelectedUserNew() {
return sessionStorage.getItem('selectedUser');
}
document.getElementById('chatMessageForm').addEventListener('submit', function(e) {
let chatInput = document.getElementById('chatInput');
e.preventDefault();
let user = getSelectedUserNew();
if (!this.checkValidity()) {
console.log("error");
this.classList.add('was-validated');
return;
}
this.classList.add('was-validated');
if (user == null) {
// window.alert('please select a user');
alertify.error('Please select a user');
return;
}
let messageContent = chatInput.value;
let context = { fromUser: username, message: md.render(messageContent), time: new Date().toLocaleString() };
let msgContainer = msgContainerSendTemplate(context);
$(chatAreaNew).append(DOMPurify.sanitize(msgContainer));
scrollChatAreaAnimated(2400);
let messageCipher = sjcl.encrypt(passphraseInput.value, messageContent, { mode: "gcm", ts: 128, adata: "", iter: iterations });
let messageCipherJson = JSON.parse(messageCipher);
let chatMessageDTO = {
"toUser": user,
"messageCipher": messageCipherJson
}
messageSend(JSON.stringify(chatMessageDTO));
})
document.getElementById('user-search').addEventListener('submit', function(e) {
e.preventDefault();
let contactsBox = document.getElementById('contacts-box');
let temp = contactsBox.innerHTML;
// log.trace(temp);
let searchTerm = document.getElementById('user-search-term').value;
log.debug("search term value = " + searchTerm);
let list = JSON.parse(sessionStorage.getItem('activeUsers'));
log.debug("active users");
log.debug(list);
let fuse = new Fuse(list, fuseOptions);
let searchResult = fuse.search(searchTerm);
populateContactsBox(contactsBox, searchResult);
addUserCallBacks();
log.debug(searchResult);
})
document.getElementById('user-search-term').addEventListener('input', function(e) {
e.preventDefault();
if (this.value.length < 2) {
log.debug("inputted")
let cancelButton = document.getElementById('user-search-cancel');
cancelButton.hidden = false;
}
})
document.getElementById('user-search-cancel').addEventListener('click', function(e) {
e.preventDefault();
let list = JSON.parse(sessionStorage.getItem('activeUsers'));
let contactsBox = document.getElementById('contacts-box');
populateContactsBox(contactsBox,list);
addUserCallBacks();
document.getElementById('user-search-term').value = "";
this.hidden = true;
})
function populateContactsBox(contactsBox, list)
{
let userContactBoxList = "";
list.forEach(function(activeUser) {
log.debug(activeUser);
if (activeUser.online) {
userContactBoxList += userContactOnlineTemplate(activeUser);
} else {
userContactBoxList += userContactOfflineTemplate(activeUser);
}
})
contactsBox.innerHTML = userContactBoxList;
}
// console.log('Credentials = ' + JSON.parse(sessionStorage.getItem('credentials')));
function messageSend(chatMessageDTO) {
let headers = new Headers();
// console.log("Token = " + btoa("hmm" + ":" + "hmm"))
// headers.append('Accept','application/json')
headers.append('Content-Type', 'application/json');
// headers.append('Authorization', basicAuthToken);
headers.append('X-AUTH-TOKEN', authToken);
fetch(postNewMessageUrl, {
method: 'POST',
headers: headers,
body: chatMessageDTO
})
.then(response => {
console.log(response);
return response.clone();
})
.then(response => fetchHandler(response));
}
async function getAllMessages(toUser) {
let headers = new Headers();
// headers.append('Accept','application/json')
// headers.append('Content-Type', 'application/json');
// headers.append('Authorization', basicAuthToken);
headers.append('X-AUTH-TOKEN', authToken);
let response = await fetch(getAllMessagesUrl + toUser, {
method: 'GET',
headers: headers
});
console.log(response);
if (fetchErrorHandler(response.clone())) {
return null;
}
// if (response.status == 440) {
// window.alert('Token has expired. Please login again');
// return null;
// }
let data = await response.json();
return data;
}
async function getNewMessages(toUser, lastMessageTimeStamp) {
let headers = new Headers();
// headers.append('Authorization', basicAuthToken);
headers.append('X-AUTH-TOKEN', authToken);
let response = await fetch(`${getNewMessagesUrl}${toUser}/${lastMessageTimeStamp}`, {
method: 'GET',
headers: headers
});
console.log(response.clone());
if (fetchErrorHandler(response.clone())) {
return null;
}
let data = await response.json();
return data;
}
async function getActiveUsers(authToken2) {
let headers = new Headers();
// headers.append('Authorization', basicAuthToken);
headers.append('X-AUTH-TOKEN', authToken2);
let response = await fetch(getActiveUsersUrl, {
method: 'GET',
headers: headers
});
console.log(response.clone());
if (fetchErrorHandler(response.clone())) {
return null;
}
let data = await response.json();
return data;
}
$(document).ready(function() {
$('#action_menu_btn').click(function() {
$('.action_menu').toggle();
});
});
function fetchHandler(response) {
if (response.ok) {
return response.json().then(json => {
// the status was ok and there is a json body
// return Promise.resolve({ json: json, response: response });
alertify.success('Message sent succesfully' + sprintf(" (http code %d)", response.status));
}).catch(err => {
// the status was ok but there is no json body
// return Promise.resolve({ response: response });
alertify.success('Message sent succesfully' + sprintf(" (http code %d)", response.status));
});
} else {
return response.json().catch(err => {
// the status was not ok and there is no json body
// throw new Error(response.statusText);
alertify.error('Some error occured. Please try again.');
}).then(json => {
// the status was not ok but there is a json body
// throw new Error(json.error.message); // example error message returned by a REST
let delay = alertify.get('notifier', 'delay');
alertify.set('notifier', 'delay', 30);
let errorMessage = "";
json.errors.forEach(function(data) {
errorMessage += sprintf("Field Name: %s \n Rejected value: %s \n Reason: %s \n", data.field_name, data.rejected_value, data.error_message);
});
alertify.error(sprintf('There were errors in your message - %s', errorMessage));
alertify.set('notifier', 'delay', delay);
});
}
}
function fetchErrorHandler(response) {
// alertify.success('Current position : ' + alertify.get('notifier', 'position'));
if (!response.ok) {
return response.text().catch(err => {
// the status was not ok and there is no json body
// throw new Error(response.statusText);
// window.alert(sprintf('Some error occured. Http code is %s', response.status));
alertify.error(sprintf('Some error occured. Http code is %s', response.status));
return true;
}).then(json => {
// the status was not ok but there is a json body
// throw new Error(json.error.message); // example error message returned by a REST API
// window.alert(sprintf('Error: %s (Http code %s)', json, response.status));
alertify.error(sprintf('Some error occured. Http code is %s', response.status));
console.log(json);
return true;
});
}
}
function scrollChatAreaAnimated(delay) {
$(chatAreaNew).stop().animate({
scrollTop: $(chatAreaNew)[0].scrollHeight
}, delay);
}

View File

@ -1 +0,0 @@
log.info("test success");

File diff suppressed because one or more lines are too long

View File

@ -1,311 +0,0 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" th:if="false"></script>
<script src="http://blackpeppersoftware.github.io/thymeleaf-fragment.js/thymeleaf-fragment.js" defer="defer" th:if="false"></script>
<div th:replace="fragments/head :: headFragment">
<meta charset="UTF-8">
<title id="pageTitle">Chat</title>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sjcl/1.0.8/sjcl.min.js" integrity="sha256-nIoG9XIePM1QNttI6KAGLYGNxc4DNinxxmOZW0/Z7uA=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.4.2/handlebars.min.js" integrity="sha256-oh7N5nthuhldTk8/34Za7FXv3BkeVN9vAnYk/pLfC78=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.0.3/purify.min.js" integrity="sha256-58eGKW6SunbeAY1RP9WEbg3nViB9o1qDnxV4yCITqx4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/10.0.0/markdown-it.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.12.0/alertify.min.js" integrity="sha256-yscIZgtlDR9q6eoYCRmcaiNE6W80UFSnq+6Llwu4NLI=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.12.0/css/alertify.min.css" integrity="sha256-nhstgDCuZGQRk+wvwXZIPt278arHtuZKJ1YQ0rrXiL4=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.12.0/css/themes/default.css" integrity="sha256-dawRQVhnqw8jRXaGnK0aj/NpOsPaQm+Em1sWN+fvegI=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.12.0/css/themes/bootstrap.css" integrity="sha256-1fgYpB3cyITZIur7E+Mj3R54NtlN9HwHykgKTJf0pmU=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.4.5/fuse.min.js" integrity="sha256-Yrh3VGzE4d9b4KANknPJAhfcKt9SgHTL0v/FrJFoPzw=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/loglevel/1.6.4/loglevel.min.js" integrity="sha256-ACTlnmNCkOooSKkPCKYbiex8WLE82aeiN+Z9ElZag5Q=" crossorigin="anonymous"></script>
<script src="./bundle.js"></script>
<link rel="stylesheet" th:href="@{/css/chat.css}" href="../../resources/static/css/chat.css">
<!-- <script th:src="@{js/my_Crypto.js}" type="text/javascript"></script> -->
</head>
<body>
<div th:include="fragments/navbar :: navbarFragment"></div>
<header id="chat-section">
<div class="dark-overlay">
<div class="chat-inner container bg-primary">
<div class="row">
<div class="col-sm d-lg-block">
<h1 class="display-4">Chat with your friends</h1>
<div class="d-flex">
<div class="p-4 align-self-start">
</div>
<div class="p-4 align-self-end">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Laboriosam dolorem nostrum consequatur eos voluptates. Ipsam ullam quos illo qui. Quaerat corrupti nisi numquam rerum quasi nesciunt deserunt fugit commodi consequatur!
</div>
</div>
</div>
</div>
</div>
</div>
</header>
<div class="container-fluid h-100">
<div class="row justify-content-center h-100 mt-3">
<div class="col-md-4 col-xl-3 chat">
<div class="card mb-sm-3 mb-md-0 contacts_card">
<div class="card-header">
<form action="#" id="user-search">
<div class="input-group">
<input type="text" placeholder="Search..." id="user-search-term" class="form-control search">
<button class="search-cancel" id="user-search-cancel" hidden><i class="fas fa-times"></i></button>
<div class="input-group-prepend">
<button class="input-group-text search_btn"><i class="fas fa-search"></i></button>
</div>
</div>
</form>
</div>
<div class="card-body contacts_body">
<ui class="contacts">
<li class="active">
<div class="d-flex bd-highlight">
<div class="img_cont">
<img src="https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg" class="rounded-circle user_img">
<span class="online_icon"></span>
</div>
<div class="user_info">
<span>Khalid</span>
<p>Kalid is online</p>
</div>
</div>
</li>
</ui>
<ui class="contacts" id="contacts-box">
<th:block th:each="au: ${activeUsers}">
<li name="user-box" class="user-box">
<div class="d-flex bd-highlight">
<div class="img_cont">
<img src="https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg" class="rounded-circle user_img">
<span th:if="${au.online == true}" class="online_icon"></span>
</div>
<div class="user_info">
<span class="to-user-span" th:text="${au.userName}">Khalid</span>
<div th:switch="${au.online}">
<p th:case="true" th:text="${au.userName} + ' is online'">Khalid is online</p>
<th:block th:case="false">
<th:block th:if="${au.lastActive == null}">
<p th:text="'User has not logged in yet'"></p>
</th:block>
<th:block th:if="${au.lastActive != null}">
<p th:text="'Last active ' + ${au.lastActive}">Last active 3 hours ago</p>
</th:block>
<!-- <p th:case="${au.online == true}" th:text="${au.userName} + ' is online'">Khalid is online</p>
<p th:if="${au.online == false}" th:text="${au.userName} + ' is offline' + ' Last active = ' + ${au.lastActive}">Khalid is offline. -->
<!-- <span th:text="'Last active = ' + ${au.lastActive}"></span> -->
</th:block>
</div>
</div>
<div class="d-flex flex-column ml-auto">
<div class="text-right">Dec 25</div>
<div style="color: rgba(255,255,255,0.7);">Hello how are you</div>
</div>
</div>
</li>
</th:block>
</ui>
</div>
<div class="card-footer"></div>
</div>
</div>
<div class="col-md-8 col-xl-6 chat">
<div class="card" id="no-user-selected">
<div class="m-auto">
<div class="d-flex justify-content-center">
<div class="align-self-center">
<h2 class="display-4 no-user-selected-h2">Please select a user</h2>
<input class="form-control type_msg" size="10" type="password" id="passphrase-initial" placeholder="Passphrase " required>
</div>
</div>
</div>
</div>
<div class="card" id="chat-card" hidden>
<div class="card-header msg_head">
<div class="d-flex bd-highlight">
<div class="img_cont">
<img src="https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg" class="rounded-circle user_img">
<span class="online_icon"></span>
</div>
<div class="user_info">
<span id="user-name-span">Chat with Khalid</span>
<p id="num-messages-p">1767 Messages</p>
</div>
<div class="video_cam">
<span><i class="fas fa-video"></i></span>
<span><i class="fas fa-phone"></i></span>
</div>
</div>
<span id="action_menu_btn"><i class="fas fa-ellipsis-v"></i></span>
<div class="action_menu">
<ul>
<li><i class="fas fa-user-circle"></i> View profile</li>
<li><i class="fas fa-users"></i> Add to close friends</li>
<li><i class="fas fa-plus"></i> Add to group</li>
<li><i class="fas fa-ban"></i> Block</li>
</ul>
</div>
</div>
<div class="card-body msg_card_body" id="chat_area_new">
</div>
<div class="card-footer">
<form action="#" th:object="${chatMessageDTO}" method="post" id="chatMessageForm" class="needs-validation" novalidate>
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text attach_btn"><i class="fas fa-paperclip"></i></span>
</div>
<input class="form-control type_msg" size="10" type="password" id="passphrase" placeholder="Passphrase " required>
<textarea name="" id="chatInput" class="form-control type_msg" placeholder="Type your message..." required></textarea>
<div class="input-group-append">
<button class="input-group-text send_btn"><i class="fas fa-location-arrow"></i></button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<section hidden>
<div class="container">
<div class="row">
<div class="col-sm">
<h4 class="display-4 text-center py-2">Chat</h4>
<div class="card text-white bg-primary mb-3 card-form rounded mx-auto">
<div class="card-body rounded">
<!-- <h4 class="card-title">Chat</h4> -->
<div class="form-group">
<textarea id="chatTextArea" class="form-control-lg py-2" disabled></textarea>
</div>
<!-- <form action="#" th:action="@{/seedstartermng}" th:object="${seedStarter}" method="post"> -->
<!-- th:action="@{/api/chat}" -->
<div class="card-text">
</div>
<form action="#" th:object="${chatMessageDTO}" method="post" class="needs-validation" novalidate>
<div class="row">
<div class="col-3">
<div class="form-group">
<label class="lead" for="toUser">User to send to: </label>
<th:block th:each="userName: ${userNames}">
<input class="form-control" type="radio" th:field="*{toUser}" th:value="${userName}">
<label class="btn btn-secondary" th:for="${#ids.prev('toUser')}" th:text="${userName}">
Demo User
</label>
</th:block>
</div>
</div>
<div class="col">
<div class="my-form-inputs container">
<div class="form-group">
<label for="chatInput">Your message: </label>
<textarea class="form-control" type="text" required></textarea>
<div class="invalid-feedback">
Cannot be empty
</div>
</div>
<div class="form-group">
<label for="passphrase">Passphrase: </label>
<input class="form-control" type="password" required>
</div>
<div class="form-group text-center">
<button class="btn btn-secondary mx-auto">Submit</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<template id="msg_container_template">
<div class="d-flex justify-content-start mb-4">
<div class="img_cont_msg">
<img src="https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg" class="rounded-circle user_img_msg">
</div>
<div class="msg_container">
{{{message}}}
<span class="msg_time">{{time}}</span>
</div>
</div>
</template>
<template id="msg_container_send_template">
<div class="d-flex justify-content-end mb-4">
<div class="msg_container_send">
{{{message}}}
<span class="msg_time_send">{{time}}</span>
</div>
<!-- <div class="img_cont_msg">
<img src="https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg"
class="rounded-circle user_img_msg">
</div> -->
{{{avatar}}}
</div>
</template>
<template id="user-contact-online-template">
<li name="user-box" class="user-box">
<div class="d-flex bd-highlight">
<div class="img_cont">
<img src="https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg" class="rounded-circle user_img">
<span class="online_icon"></span>
</div>
<div class="user_info">
<span class="to-user-span">{{userName}}</span>
<p>{{userName}} is online</p>
</div>
<div class="d-flex flex-column ml-auto">
<div class="text-right">Dec 25</div>
<div style="color: rgba(255,255,255,0.7);">Hello how are you</div>
</div>
</div>
</li>
</template>
<template id="user-contact-offline-template">
<li name="user-box" class="user-box">
<div class="d-flex bd-highlight">
<div class="img_cont">
<img src="https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg" class="rounded-circle user_img">
</div>
<div class="user_info">
<span class="to-user-span">{{userName}}</span>
<p>Last active {{lastActive}}</p>
</div>
<div class="d-flex flex-column ml-auto">
<div class="text-right">Dec 25</div>
<div style="color: rgba(255,255,255,0.7);">Hello how are you</div>
</div>
</div>
</li>
</template>
</body>
<!-- <script th:src="@{js/chat.js}" type="text/javascript"></script> -->
<script src="../static/js/bundle.js" th:src="@{/js/bundle.js}"></script>
<script src="../static/js/chatStatic.js" th:if="false"></script>
</html>
<!-- <div th:include="::frag (${value1},${value2})">...</div>
<div th:include="::frag (onevar=${value1},twovar=${value2})">...</div> -->

View File

@ -1,157 +0,0 @@
Arguments:
/home/rohan/.nvm/versions/node/v12.10.0/bin/node /home/rohan/.nvm/versions/node/v12.10.0/bin/yarn add handlebars.js
PATH:
/home/rohan/.sdkman/candidates/maven/current/bin:/home/rohan/.sdkman/candidates/java/current/bin:/home/rohan/.nvm/versions/node/v12.10.0/bin:/home/rohan/miniconda3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/rohan/.cargo/bin:/home/rohan/.platformio/penv/bin
Yarn version:
1.19.2
Node version:
12.10.0
Platform:
linux x64
Trace:
Error: https://registry.yarnpkg.com/handlebars.js: Not found
at Request.params.callback [as _callback] (/home/rohan/.nvm/versions/node/v12.10.0/lib/node_modules/yarn/lib/cli.js:66927:18)
at Request.self.callback (/home/rohan/.nvm/versions/node/v12.10.0/lib/node_modules/yarn/lib/cli.js:140586:22)
at Request.emit (events.js:209:13)
at Request.<anonymous> (/home/rohan/.nvm/versions/node/v12.10.0/lib/node_modules/yarn/lib/cli.js:141558:10)
at Request.emit (events.js:209:13)
at IncomingMessage.<anonymous> (/home/rohan/.nvm/versions/node/v12.10.0/lib/node_modules/yarn/lib/cli.js:141480:12)
at Object.onceWrapper (events.js:298:28)
at IncomingMessage.emit (events.js:214:15)
at endReadableNT (_stream_readable.js:1178:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
npm manifest:
{
"dependencies": {
"alertifyjs": "^1.12.0",
"chart.js": "^2.9.3",
"dompurify": "^2.0.7",
"fuse.js": "^3.4.6",
"loglevel": "^1.6.6",
"markdown-it": "^10.0.0"
}
}
yarn manifest:
No manifest
Lockfile:
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
alertifyjs@^1.12.0:
version "1.12.0"
resolved "https://registry.yarnpkg.com/alertifyjs/-/alertifyjs-1.12.0.tgz#75be1eac23e059d3b990ab076979d36a45aa21ac"
integrity sha512-BWEFsLhPM1MBEAQ6jFATNO8ESCh1LDZzUslJ2g/E6NnI3QfyfIvpCuw07SiUQy59E6HSsdb8c5RgqiOwTcRQ2Q==
argparse@^1.0.7:
version "1.0.10"
resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911"
integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==
dependencies:
sprintf-js "~1.0.2"
chart.js@^2.9.3:
version "2.9.3"
resolved "https://registry.yarnpkg.com/chart.js/-/chart.js-2.9.3.tgz#ae3884114dafd381bc600f5b35a189138aac1ef7"
integrity sha512-+2jlOobSk52c1VU6fzkh3UwqHMdSlgH1xFv9FKMqHiNCpXsGPQa/+81AFa+i3jZ253Mq9aAycPwDjnn1XbRNNw==
dependencies:
chartjs-color "^2.1.0"
moment "^2.10.2"
chartjs-color-string@^0.6.0:
version "0.6.0"
resolved "https://registry.yarnpkg.com/chartjs-color-string/-/chartjs-color-string-0.6.0.tgz#1df096621c0e70720a64f4135ea171d051402f71"
integrity sha512-TIB5OKn1hPJvO7JcteW4WY/63v6KwEdt6udfnDE9iCAZgy+V4SrbSxoIbTw/xkUIapjEI4ExGtD0+6D3KyFd7A==
dependencies:
color-name "^1.0.0"
chartjs-color@^2.1.0:
version "2.4.1"
resolved "https://registry.yarnpkg.com/chartjs-color/-/chartjs-color-2.4.1.tgz#6118bba202fe1ea79dd7f7c0f9da93467296c3b0"
integrity sha512-haqOg1+Yebys/Ts/9bLo/BqUcONQOdr/hoEr2LLTRl6C5LXctUdHxsCYfvQVg5JIxITrfCNUDr4ntqmQk9+/0w==
dependencies:
chartjs-color-string "^0.6.0"
color-convert "^1.9.3"
color-convert@^1.9.3:
version "1.9.3"
resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8"
integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==
dependencies:
color-name "1.1.3"
color-name@1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25"
integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=
color-name@^1.0.0:
version "1.1.4"
resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"
integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==
dompurify@^2.0.7:
version "2.0.7"
resolved "https://registry.yarnpkg.com/dompurify/-/dompurify-2.0.7.tgz#f8266ad38fe1602fb5b3222f31eedbf5c16c4fd5"
integrity sha512-S3O0lk6rFJtO01ZTzMollCOGg+WAtCwS3U5E2WSDY/x/sy7q70RjEC4Dmrih5/UqzLLB9XoKJ8KqwBxaNvBu4A==
entities@~2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/entities/-/entities-2.0.0.tgz#68d6084cab1b079767540d80e56a39b423e4abf4"
integrity sha512-D9f7V0JSRwIxlRI2mjMqufDrRDnx8p+eEOz7aUM9SuvF8gsBzra0/6tbjl1m8eQHrZlYj6PxqE00hZ1SAIKPLw==
fuse.js@^3.4.6:
version "3.4.6"
resolved "https://registry.yarnpkg.com/fuse.js/-/fuse.js-3.4.6.tgz#545c3411fed88bf2e27c457cab6e73e7af697a45"
integrity sha512-H6aJY4UpLFwxj1+5nAvufom5b2BT2v45P1MkPvdGIK8fWjQx/7o6tTT1+ALV0yawQvbmvCF0ufl2et8eJ7v7Cg==
linkify-it@^2.0.0:
version "2.2.0"
resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-2.2.0.tgz#e3b54697e78bf915c70a38acd78fd09e0058b1cf"
integrity sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw==
dependencies:
uc.micro "^1.0.1"
loglevel@^1.6.6:
version "1.6.6"
resolved "https://registry.yarnpkg.com/loglevel/-/loglevel-1.6.6.tgz#0ee6300cc058db6b3551fa1c4bf73b83bb771312"
integrity sha512-Sgr5lbboAUBo3eXCSPL4/KoVz3ROKquOjcctxmHIt+vol2DrqTQe3SwkKKuYhEiWB5kYa13YyopJ69deJ1irzQ==
markdown-it@^10.0.0:
version "10.0.0"
resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-10.0.0.tgz#abfc64f141b1722d663402044e43927f1f50a8dc"
integrity sha512-YWOP1j7UbDNz+TumYP1kpwnP0aEa711cJjrAQrzd0UXlbJfc5aAq0F/PZHjiioqDC1NKgvIMX+o+9Bk7yuM2dg==
dependencies:
argparse "^1.0.7"
entities "~2.0.0"
linkify-it "^2.0.0"
mdurl "^1.0.1"
uc.micro "^1.0.5"
mdurl@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e"
integrity sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4=
moment@^2.10.2:
version "2.24.0"
resolved "https://registry.yarnpkg.com/moment/-/moment-2.24.0.tgz#0d055d53f5052aa653c9f6eb68bb5d12bf5c2b5b"
integrity sha512-bV7f+6l2QigeBBZSM/6yTNq4P2fNpSWj/0e7jQcy87A8e7o2nAfP/34/2ky5Vw4B9S446EtIhodAzkFCcR4dQg==
sprintf-js@~1.0.2:
version "1.0.3"
resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c"
integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=
uc.micro@^1.0.1, uc.micro@^1.0.5:
version "1.0.6"
resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac"
integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==

View File

@ -1,547 +0,0 @@
// import { sprintf } from 'sprintf-js';
// import { vsprintf } from 'sprintf-js';
/*var off_payment_method = document.getElementsByName('offline_payment_method');
var ischecked_method = false;
for ( var i = 0; i < off_payment_method.length; i++) {
if(off_payment_method[i].checked) {
ischecked_method = true;
break;
}
}
if(!ischecked_method) { //payment method button is not checked
alert("Please choose Offline Payment Method");
}*/
var toUserRadios = document.getElementsByName('toUser');
var isCheckedUser = false;
var chatTextArea = document.getElementById('chatTextArea');
var postNewMessageUrl = `http://${hostAddress}/api/chat/post/message`; //hostAddress variable is set in the thymeleaf head fragment
var getAllMessagesUrl = `http://${hostAddress}/api/chat/get/messages/`;
var getNewMessagesUrl = `http://${hostAddress}/api/chat/get/messages/`;
var getActiveUsersUrl = `http://${hostAddress}/api/chat/get/active-users/`;
// var postNewMessageUrl = "http://localhost:8080/api/chat/post/message";
// var getAllMessagesUrl = "http://localhost:8080/api/chat/get/messages/";
// var getNewMessagesUrl = "http://localhost:8080/api/chat/get/messages/";
// var messageLog = [];
var username = localStorage.getItem('username');
var authToken = localStorage.getItem('authToken');
var passphraseInput = document.getElementById('passphrase');
var iterations = 100000;
var source = document.getElementById("msg_container_template").innerHTML;
var msgContainerTemplate = Handlebars.compile(source);
var source = document.getElementById("msg_container_send_template").innerHTML;
var msgContainerSendTemplate = Handlebars.compile(source);
var source = document.getElementById("user-contact-online-template").innerHTML;
var userContactOnlineTemplate = Handlebars.compile(source);
var source = document.getElementById("user-contact-offline-template").innerHTML;
var userContactOfflineTemplate = Handlebars.compile(source);
var chatAreaNew = document.getElementById('chat_area_new');
var userBoxes = document.getElementsByName('user-box');
var md = window.markdownit();
var activeUsers = {};
var fuseOptions = {
shouldSort: true,
threshold: 0.01,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
"userName",
]
};
log.setLevel('TRACE');
alertify.set('notifier', 'position', 'top-center');
// Loop through the buttons and add the active class to the current/clicked button
// for (var i = 0; i < btns.length; i++) {
// btns[i].addEventListener("click", function() {
// var current = document.getElementsByClassName("active");
// // If there's no active class
// if (current.length > 0) {
// current[0].className = current[0].className.replace(" active", "");
// }
// // Add the active class to the current/clicked button
// this.className += " active";
// });
// }
getActiveUsers(authToken)
.then(data => {
// activeUsers = data;
sessionStorage.setItem('activeUsers', JSON.stringify(data));
log.log(sessionStorage.getItem('activeUsers'));
})
for (let i = 0; i < userBoxes.length; i++) {
userBoxes[i].addEventListener('click', userCallBack)
}
function addUserCallBacks() {
for (let i = 0; i < userBoxes.length; i++) {
userBoxes[i].addEventListener('click', userCallBack)
}
}
function userCallBack() {
let current = document.getElementsByClassName('user-box active');
let passphrase = passphraseInput.value;
if (current.length > 0) {
if (passphrase == '') {
// alert('Please input passphrase')
alertify.error('Please enter a passphrase');
return;
}
current[0].className = current[0].className.replace(" active", "");
}
// Add the active class to the current/clicked button
else if (current.length == 0) {
let elem = document.getElementById('passphrase-initial');
passphrase = elem.value;
if (passphrase == '') {
// alert('Please input passphrase')
alertify.error('Please enter a passphrase');
return;
}
document.getElementById('no-user-selected').hidden = true;
document.getElementById('chat-card').hidden = false;
elem.hidden = true;
}
// console.log(this.getElementsByClassName('to-user-span'));
let userName = this.getElementsByClassName('to-user-span')[0].innerText;
document.getElementById('user-name-span').innerText = userName;
populateMessages(userName, passphrase);
sessionStorage.setItem('selectedUser', userName);
this.className += " active";
}
function populateMessages(userName, passphrase) {
console.log('Selected user = ' + userName);
if (passphrase == '') {
alert('Please input passphrase')
return;
}
// console.log(userName);
if (sessionStorage.getItem(userName) == null) {
chatTextArea.textContent = '';
chatAreaNew.innerHTML = '';
getAllMessages(userName)
.then(json => {
if (json == null) return;
console.log(json);
let i = 0;
let messageLog = [];
let messageLogNew = [];
let lastMessageTimeStamp;
if (json.length > 0) {
json.forEach(function(obj) {
// console.log(obj.toUser);
messageCipher = JSON.stringify(obj.messageCipher);
console.log(messageCipher);
// let message = sjcl.decrypt("password", messageCipher);
let message = md.render(sjcl.decrypt(passphrase, messageCipher));
let utcDate = obj.messageTime;
lastMessageTimeStamp = utcDate;
let localDate = new Date(utcDate);
let messageLine = sprintf('%s %s: %s ', localDate, obj.fromUser, message);
// localDate.``
// console.log('localDate = ' + localDate);
console.log(messageLine);
// chatTextArea.append(obj.fromUser + ": " + message + "\n");
chatTextArea.append(messageLine + '\n');
messageLog[i++] = messageLine;
chatTextArea.scrollTop = chatTextArea.scrollHeight;
// console.log('Message log = ' + messageLog);
let context = { fromUser: obj.fromUser, message: message, time: localDate.toLocaleString() };
let msgContainer;
if (obj.fromUser == username) {
msgContainer = msgContainerSendTemplate(context);
} else {
msgContainer = msgContainerTemplate(context);
}
messageLogNew.push(JSON.stringify(context));
$(chatAreaNew).append(DOMPurify.sanitize(msgContainer));
});
sessionStorage.setItem(userName, JSON.stringify(messageLog));
sessionStorage.setItem(userName + username + 'new', JSON.stringify(messageLogNew));
// console.log()
// sessionStorage.clear();
console.log('Last message time = ' + lastMessageTimeStamp);
sessionStorage.setItem(userName + '-time', lastMessageTimeStamp);
}
});
} else {
console.log("Stored messages = " + sessionStorage.getItem(userName));
let storedMessages = JSON.parse(sessionStorage.getItem(userName));
let storedMessagesNew = JSON.parse(sessionStorage.getItem(userName + username + 'new'));
let lastMessageTime = sessionStorage.getItem(userName + '-time');
console.log("last message time stamp = " + lastMessageTime);
if (lastMessageTime != null) {
getNewMessages(userName, lastMessageTime)
.then(json => {
if (json == null) return;
console.log(json)
if (json.length > 0) {
json.forEach(function(obj) {
let messageCipher = JSON.stringify(obj.messageCipher);
let message = md.render(sjcl.decrypt(passphrase, messageCipher));
// console.log(message);
// chatTextArea.append(message + "\n");
let utcDate = obj.messageTime;
lastMessageTimeStamp = utcDate;
let localDate = new Date(utcDate);
let messageLine = sprintf('%s %s: %s', localDate, obj.fromUser, message);
// localDate.``
// console.log('localDate = ' + localDate);
console.log(messageLine);
// chatTextArea.append(obj.fromUser + ": " + message + "\n");
chatTextArea.append(messageLine + '\n');
chatTextArea.scrollTop = chatTextArea.scrollHeight;
storedMessages.push(messageLine);
let context = { fromUser: obj.fromUser, message: message, time: localDate.toLocaleString() };
let msgContainer;
if (obj.fromUser == username) {
msgContainer = msgContainerSendTemplate(context);
} else {
msgContainer = msgContainerTemplate(context);
}
storedMessagesNew.push(JSON.stringify(context));
$(chatAreaNew).append(DOMPurify.sanitize(msgContainer));
})
sessionStorage.setItem(userName + '-time', lastMessageTimeStamp);
sessionStorage.setItem(userName, JSON.stringify(storedMessages));
sessionStorage.setItem(userName + username + 'new', JSON.stringify(storedMessagesNew));
console.log("this value stored" + sessionStorage.getItem(userName))
console.log("last message time stamp = " + lastMessageTimeStamp);
console.log(sessionStorage.getItem(userName + '-time'));
}
chatTextArea.textContent = '';
chatAreaNew.innerHTML = '';
console.log("Stored messages 2 = " + storedMessages);
storedMessages.forEach(function(messageLine) {
chatTextArea.append(messageLine + '\n');
chatTextArea.scrollTop = chatTextArea.scrollHeight;
// let context = {message: messageLine};
// let msgContainer;
// if(obj.fromUser == username)
// {
// msgContainer = msgContainerSendTemplate(context);
// }
// else{
// msgContainer = msgContainerTemplate(context);
// }
// $(chatAreaNew).append(msgContainer);
})
storedMessagesNew.forEach(function(contextString) {
let context = JSON.parse(contextString);
let msgContainer;
if (context.fromUser == username) {
msgContainer = msgContainerSendTemplate(context);
} else {
msgContainer = msgContainerTemplate(context);
}
$(chatAreaNew).append(DOMPurify.sanitize(msgContainer));
scrollChatAreaAnimated(2400);
})
});
}
// chatTextArea.append(JSON.stringify(storedMessages));
}
// sessionStorage.setItem('status', 'ready');
// sessionStorage.setItem('userName', messageLog);
// console.log('Message log = ' + messageLog);
// }
// let passphraseKey = userName + '-passphrase';
// sessionStorage.setItem(passphraseKey, passphrase);
// console.log(sessionStorage.getItem(passphraseKey));
}
// var lastMessageTimeStamp;
// console.log(authToken);
// 'Basic ' + btoa("hmm" + ":" + "hmm")
Handlebars.registerHelper('avatar', function() {
return '<div class="img_cont_msg"> <img src="https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg" class="rounded-circle user_img_msg"> </div>';
});
// var user;
function getSelectedUser() {
for (var i = 0; i < toUserRadios.length; i++) {
if (toUserRadios[i].checked) {
let user = toUserRadios[i].value;
console.log('sending to user = ' + user);
isCheckedUser = true;
return user;
}
}
}
function getSelectedUserNew() {
return sessionStorage.getItem('selectedUser');
}
document.getElementById('chatMessageForm').addEventListener('submit', function(e) {
let chatInput = document.getElementById('chatInput');
e.preventDefault();
let user = getSelectedUserNew();
if (!this.checkValidity()) {
console.log("error");
this.classList.add('was-validated');
return;
}
this.classList.add('was-validated');
if (user == null) {
// window.alert('please select a user');
alertify.error('Please select a user');
return;
}
let messageContent = chatInput.value;
let context = { fromUser: username, message: md.render(messageContent), time: new Date().toLocaleString() };
let msgContainer = msgContainerSendTemplate(context);
$(chatAreaNew).append(DOMPurify.sanitize(msgContainer));
scrollChatAreaAnimated(2400);
let messageCipher = sjcl.encrypt(passphraseInput.value, messageContent, { mode: "gcm", ts: 128, adata: "", iter: iterations });
let messageCipherJson = JSON.parse(messageCipher);
let chatMessageDTO = {
"toUser": user,
"messageCipher": messageCipherJson
}
messageSend(JSON.stringify(chatMessageDTO));
})
document.getElementById('user-search').addEventListener('submit', function(e) {
e.preventDefault();
let contactsBox = document.getElementById('contacts-box');
let temp = contactsBox.innerHTML;
// log.trace(temp);
let searchTerm = document.getElementById('user-search-term').value;
log.debug("search term value = " + searchTerm);
let list = JSON.parse(sessionStorage.getItem('activeUsers'));
log.debug("active users");
log.debug(list);
let fuse = new Fuse(list, fuseOptions);
let searchResult = fuse.search(searchTerm);
populateContactsBox(contactsBox, searchResult);
addUserCallBacks();
log.debug(searchResult);
})
document.getElementById('user-search-term').addEventListener('input', function(e) {
e.preventDefault();
if (this.value.length < 2) {
log.debug("inputted")
let cancelButton = document.getElementById('user-search-cancel');
cancelButton.hidden = false;
}
})
document.getElementById('user-search-cancel').addEventListener('click', function(e) {
e.preventDefault();
let list = JSON.parse(sessionStorage.getItem('activeUsers'));
let contactsBox = document.getElementById('contacts-box');
populateContactsBox(contactsBox,list);
addUserCallBacks();
document.getElementById('user-search-term').value = "";
this.hidden = true;
})
function populateContactsBox(contactsBox, list)
{
let userContactBoxList = "";
list.forEach(function(activeUser) {
log.debug(activeUser);
if (activeUser.online) {
userContactBoxList += userContactOnlineTemplate(activeUser);
} else {
userContactBoxList += userContactOfflineTemplate(activeUser);
}
})
contactsBox.innerHTML = userContactBoxList;
}
// console.log('Credentials = ' + JSON.parse(sessionStorage.getItem('credentials')));
function messageSend(chatMessageDTO) {
let headers = new Headers();
// console.log("Token = " + btoa("hmm" + ":" + "hmm"))
// headers.append('Accept','application/json')
headers.append('Content-Type', 'application/json');
// headers.append('Authorization', basicAuthToken);
headers.append('X-AUTH-TOKEN', authToken);
fetch(postNewMessageUrl, {
method: 'POST',
headers: headers,
body: chatMessageDTO
})
.then(response => {
console.log(response);
return response.clone();
})
.then(response => fetchHandler(response));
}
async function getAllMessages(toUser) {
let headers = new Headers();
// headers.append('Accept','application/json')
// headers.append('Content-Type', 'application/json');
// headers.append('Authorization', basicAuthToken);
headers.append('X-AUTH-TOKEN', authToken);
let response = await fetch(getAllMessagesUrl + toUser, {
method: 'GET',
headers: headers
});
console.log(response);
if (fetchErrorHandler(response.clone())) {
return null;
}
// if (response.status == 440) {
// window.alert('Token has expired. Please login again');
// return null;
// }
let data = await response.json();
return data;
}
async function getNewMessages(toUser, lastMessageTimeStamp) {
let headers = new Headers();
// headers.append('Authorization', basicAuthToken);
headers.append('X-AUTH-TOKEN', authToken);
let response = await fetch(`${getNewMessagesUrl}${toUser}/${lastMessageTimeStamp}`, {
method: 'GET',
headers: headers
});
console.log(response.clone());
if (fetchErrorHandler(response.clone())) {
return null;
}
let data = await response.json();
return data;
}
async function getActiveUsers(authToken2) {
let headers = new Headers();
// headers.append('Authorization', basicAuthToken);
headers.append('X-AUTH-TOKEN', authToken2);
let response = await fetch(getActiveUsersUrl, {
method: 'GET',
headers: headers
});
console.log(response.clone());
if (fetchErrorHandler(response.clone())) {
return null;
}
let data = await response.json();
return data;
}
$(document).ready(function() {
$('#action_menu_btn').click(function() {
$('.action_menu').toggle();
});
});
function fetchHandler(response) {
if (response.ok) {
return response.json().then(json => {
// the status was ok and there is a json body
// return Promise.resolve({ json: json, response: response });
alertify.success('Message sent succesfully' + sprintf(" (http code %d)", response.status));
}).catch(err => {
// the status was ok but there is no json body
// return Promise.resolve({ response: response });
alertify.success('Message sent succesfully' + sprintf(" (http code %d)", response.status));
});
} else {
return response.json().catch(err => {
// the status was not ok and there is no json body
// throw new Error(response.statusText);
alertify.error('Some error occured. Please try again.');
}).then(json => {
// the status was not ok but there is a json body
// throw new Error(json.error.message); // example error message returned by a REST
let delay = alertify.get('notifier', 'delay');
alertify.set('notifier', 'delay', 30);
let errorMessage = "";
json.errors.forEach(function(data) {
errorMessage += sprintf("Field Name: %s \n Rejected value: %s \n Reason: %s \n", data.field_name, data.rejected_value, data.error_message);
});
alertify.error(sprintf('There were errors in your message - %s', errorMessage));
alertify.set('notifier', 'delay', delay);
});
}
}
function fetchErrorHandler(response) {
// alertify.success('Current position : ' + alertify.get('notifier', 'position'));
if (!response.ok) {
return response.text().catch(err => {
// the status was not ok and there is no json body
// throw new Error(response.statusText);
// window.alert(sprintf('Some error occured. Http code is %s', response.status));
alertify.error(sprintf('Some error occured. Http code is %s', response.status));
return true;
}).then(json => {
// the status was not ok but there is a json body
// throw new Error(json.error.message); // example error message returned by a REST API
// window.alert(sprintf('Error: %s (Http code %s)', json, response.status));
alertify.error(sprintf('Some error occured. Http code is %s', response.status));
console.log(json);
return true;
});
}
}
function scrollChatAreaAnimated(delay) {
$(chatAreaNew).stop().animate({
scrollTop: $(chatAreaNew)[0].scrollHeight
}, delay);
}

View File

@ -1,57 +0,0 @@
var cipherText = sjcl.encrypt("password", "data");
console.log(cipherText);
var plainText = sjcl.decrypt("password", cipherText);
console.log(plainText);
var field = document.getElementById('crypt');
// field.innerText = plainText;
var jsonString = "{\"iv\":\"2rtnuXaJXFuQGO9ncaVkmA==\",\"v\":1,\"iter\":10000,\"ks\":128,\"ts\":64,\"mode\":\"ccm\",\"adata\":\"\",\"cipher\":\"aes\",\"salt\":\"H1z7o3f6qlQ=\",\"ct\":\"lF9Uno7ihjVv01M8\"}";
var myJSON = JSON.parse(jsonString);
console.log(myJSON);
// let base64 = require('base-64');
let headers = new Headers();
console.log("Token = " + btoa("hmm" + ":" + "hmm"))
// headers.append('Accept','application/json')
// headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Basic ' + btoa("hmm" + ":" + "hmm"));
// headers.append('Authorization', 'Basic aG1tOmhtbQ==');
// aG1tOmhtbQ==
var messageCipher;
fetch('http://localhost:8080/api/messages', {
method: 'GET',
headers: headers
// credentials: 'include'
}).then(response => response.json())
.then(json => {
// console.log('parsed json', JSON.stringify(json)) // access json.body here
// console.log('parsed json', json[0].messageCipher);
messageCipher = JSON.stringify(json[0].messageCipher);
console.log(messageCipher);
console.log(sjcl.decrypt("password", messageCipher));
});
// console.log("New message = " + messageCipher);
// [{"messageID":5,"fromUser":{"userID":3,"userName":"user2","joinDate":1569224699000},"toUser":{"userID":6,"userName":"novo","joinDate":1569224706000},"messageCipher":{"iv":"2rtnuXaJXFuQGO9ncaVkmA==","v":1,"mode":"ccm","adata":"","cipher":"aes","salt":"H1z7o3f6qlQ=","iter":10000,"ks":128,"ts":64,"ct":"lF9Uno7ihjVv01M8"},"messageTime":1569685335000}]
var url = 'http://localhost:8080/api/users'
xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == XMLHttpRequest.DONE) {
// alert(xhr.responseText);
console.log(xml.responseText);
// console.log(xml.getResponseHeader('X-CSRF-TOKEN'));
}
}
xml.open('GET', url)
xml.setRequestHeader('Authorization', 'Basic aG1tOmhtbQ==');
xml.setRequestHeader("X-CSRF-TOKEN", "fetch");
xml.send(null);