program finalizat

This commit is contained in:
andrei-mihnea-cerbu
2024-10-29 15:07:26 +02:00
parent ab1eaec413
commit 979539d3db
138 changed files with 14602 additions and 5068 deletions
+35
View File
@@ -0,0 +1,35 @@
// Load announcement content from the application info when the page loads
async function loadAnnouncement() {
try {
const announcementText = await window.electronAPI.readApplicationInfo('announcement');
const announcementContent = document.getElementById('announcement-content');
if (announcementContent && announcementText) {
console.log('Announcement:', announcementText);
announcementContent.innerHTML = formatTextForHtml(announcementText);
}
} catch (error) {
console.error('Failed to load announcement:', error);
document.getElementById('announcement-content').textContent = 'Failed to load announcement.';
}
}
function formatTextForHtml(text) {
// Replace newlines with <br> tags
let formattedText = text.replace(/\n/g, '<br>');
// Replace tabs with a few non-breaking spaces for indentation
formattedText = formattedText.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
// Replace other special characters as needed
// Example: Handle double spaces by converting to &nbsp;
formattedText = formattedText.replace(/ /g, ' &nbsp;');
return formattedText;
}
// Close the window when the close button is clicked
function closeWindow() {
window.electronAPI.writeApplicationInfo('announcement', '');
window.electronAPI.closeAnnouncementWindow();
}
+15 -4
View File
@@ -24,13 +24,24 @@ function fadeOut(destination) {
async function waitForResponse() {
return new Promise((resolve) => {
const idResponseCheck = setInterval(async () => {
const status = await window.electronAPI.hasResponseArrived();
if (status) {
if (await window.electronAPI.hasResponseArrived()) {
clearInterval(idResponseCheck);
const response = await window.electronAPI.getLastUcResult();
resolve(response || null); // Resolve the response or null if not available
resolve(await window.electronAPI.getLastUcResult()); // Resolve the response or null if not available
}
}, 100); // Check every 100 milliseconds if the response has arrived
});
}
function toggleScroll(idComponent, scrollHeight = 180) {
const element = document.getElementById(idComponent); // Using getElementById
if (!element) {
console.error(`Element with ID '${idComponent}' not found.`);
return;
}
if (element.scrollHeight > scrollHeight) {
element.style.overflowY = 'auto'; // Enable scroll if content overflows
} else {
element.style.overflowY = 'hidden'; // Disable scroll if content fits
}
}
+99 -85
View File
@@ -1,7 +1,12 @@
let codeLogin = '';
let codeFindByEmail = '';
let codeFindKeyByUser = '';
let codeOk = '';
document.addEventListener('DOMContentLoaded', async function () {
const submitButton = document.getElementById('submit');
const signUpButton = document.getElementById('signup');
const resetPasswordButton = document.getElementById('resetPassword');
const signUpButton = document.getElementById('signup');
// Retrieve the operation codes via IPC
const operationCodes = await window.electronAPI.getOperationsCodes();
@@ -10,21 +15,21 @@ document.addEventListener('DOMContentLoaded', async function () {
return;
}
const codeLogin = operationCodes.LOGIN;
const codeFindByEmail = operationCodes.FIND_BY_EMAIL;
const codeFindKeyByUser = operationCodes.FIND_KEY_BY_USER_ID;
const codeOk = operationCodes.OK;
signUpButton.addEventListener('click', function (e) {
e.preventDefault();
window.electronAPI.changeContent('sign_up');
});
codeLogin = operationCodes.LOGIN;
codeFindByEmail = operationCodes.FIND_BY_EMAIL;
codeFindKeyByUser = operationCodes.FIND_KEY_BY_USER_ID;
codeOk = operationCodes.OK;
resetPasswordButton.addEventListener('click', function (e) {
e.preventDefault();
window.electronAPI.changeContent('reset_password');
});
signUpButton.addEventListener('click', function (e) {
e.preventDefault();
window.electronAPI.changeContent('sign_up');
});
// Submit button logic (handle login)
submitButton.addEventListener('click', async function (e) {
e.preventDefault();
@@ -72,79 +77,88 @@ document.addEventListener('DOMContentLoaded', async function () {
await window.electronAPI.closeUcSocket();
await window.electronAPI.changeContent('main_menu');
});
async function attemptLogin(email, password) {
const app_type = await window.electronAPI.readUserConfig('app_type');
const messageData = { email, password, app_type };
// Send the login message to the server
if (!await window.electronAPI.sendUcMessage(codeLogin, messageData)) {
await window.electronAPI.showAlert('Failed to send login request.');
return false;
}
// Wait for the response using waitForResponse
const response = await waitForResponse();
if (response && response.operationCode === codeOk) {
await window.electronAPI.resetApplicationInfo();
await window.electronAPI.resetUserConfig();
await window.electronAPI.writeUserConfig('app_type', app_type);
await window.electronAPI.writeUserConfig('user_info', { email, password });
return true;
}else if(response && respone.operationCode !== codeOk){
await window.electronAPI.showAlert(response.metaInfo.message);
return false;
}
await window.electronAPI.showAlert('Invalid login response received.');
return false;
}
async function fetchAndStoreUserInfo(userEmail) {
if (!await window.electronAPI.sendUcMessage(codeFindByEmail, { email: userEmail })) {
await window.electronAPI.showAlert('Failed to send request to fetch user info.');
return false;
}
// Wait for the response using waitForResponse
const response = await waitForResponse();
if (response && response.operationCode === codeOk) {
let userInfo = await window.electronAPI.readUserConfig('user_info');
if (!userInfo) {
userInfo = {};
}
userInfo.id = response.metaInfo.id;
userInfo.departmentId = response.metaInfo.departmentId;
userInfo.name = response.metaInfo.name || 'User';
await window.electronAPI.writeUserConfig('user_info', userInfo);
return true;
}
await window.electronAPI.showAlert('Failed to fetch user info from server.');
return false;
}
async function fetchAndStoreEncryptionKey(userId) {
if (!await window.electronAPI.sendUcMessage(codeFindKeyByUser, { userId })) {
await window.electronAPI.showAlert('Failed to send request to fetch encryption key.');
return false;
}
// Wait for the response using waitForResponse
const response = await waitForResponse();
if (response && response.operationCode === codeOk) {
const encryptionKey = {
key: response.metaInfo.key.key,
iv: response.metaInfo.key.iv,
};
await window.electronAPI.writeUserConfig('encryption_key', encryptionKey);
return true;
}
await window.electronAPI.showAlert('Failed to fetch encryption key from server.');
return false;
}
});
async function attemptLogin(email, password) {
const app_type = await window.electronAPI.readUserConfig('app_type');
const messageData = {email, password, app_type};
// Send the login message to the server
if (!await window.electronAPI.sendUcMessage(codeLogin, messageData)) {
await window.electronAPI.showAlert('Failed to send login request.');
return false;
}
// Wait for the response using waitForResponse
const response = await waitForResponse();
if (!response) {
await window.electronAPI.showAlert('No response from server.');
return false;
}
if (response.operationCode !== codeOk) {
await window.electronAPI.showAlert(response.metaInfo.message);
return false;
}
const user_info = await window.electronAPI.readUserConfig('user_info');
if (!user_info || (user_info && user_info.email !== email)) {
await window.electronAPI.resetApplicationInfo();
await window.electronAPI.resetMemory();
await window.electronAPI.resetUserConfig();
await window.electronAPI.writeUserConfig('app_type', app_type);
await window.electronAPI.writeUserConfig('user_info', {email, password});
return true;
}
return true;
}
async function fetchAndStoreUserInfo(userEmail) {
if (!await window.electronAPI.sendUcMessage(codeFindByEmail, {email: userEmail})) {
await window.electronAPI.showAlert('Failed to send request to fetch user info.');
return false;
}
// Wait for the response using waitForResponse
const response = await waitForResponse();
if (response && response.operationCode === codeOk) {
let userInfo = await window.electronAPI.readUserConfig('user_info');
if (!userInfo) {
userInfo = {};
}
userInfo.id = response.metaInfo.id;
userInfo.departmentId = response.metaInfo.departmentId;
userInfo.name = response.metaInfo.name || 'User';
await window.electronAPI.writeUserConfig('user_info', userInfo);
return true;
}
await window.electronAPI.showAlert('Failed to fetch user info from server.');
return false;
}
async function fetchAndStoreEncryptionKey(userId) {
if (!await window.electronAPI.sendUcMessage(codeFindKeyByUser, {userId})) {
await window.electronAPI.showAlert('Failed to send request to fetch encryption key.');
return false;
}
// Wait for the response using waitForResponse
const response = await waitForResponse();
if (response && response.operationCode === codeOk) {
const encryptionKey = {
key: response.metaInfo.key.key,
iv: response.metaInfo.key.iv,
};
await window.electronAPI.writeUserConfig('encryption_key', encryptionKey);
return true;
}
await window.electronAPI.showAlert('Failed to fetch encryption key from server.');
return false;
}
+9 -4
View File
@@ -9,9 +9,6 @@ document.addEventListener('DOMContentLoaded', async function () {
const shareFileButton = document.getElementById('share-file');
const logoutButton = document.getElementById('logout');
const restoreBackupButton = document.getElementById('restore-backup');
await fetchUserInfo();
await checkAndSetAllDirectories();
backupButton.addEventListener('click', async function () {
await setPath('backupDirectory');
@@ -43,6 +40,12 @@ document.addEventListener('DOMContentLoaded', async function () {
});
});
async function initialSetup(){
await checkAndSetAllDirectories();
await loadReceivedFiles();
await fetchUserInfo();
}
async function restoreBackup() {
const backupDirectory = await window.electronAPI.readApplicationInfo('backupDirectory');
@@ -59,7 +62,7 @@ async function restoreBackup() {
}
// Call the IPC method to initiate the backup retrieval process
await window.electronAPI.startBackupRetrieval(destinationPath);
window.electronAPI.startBackupRetrieval(destinationPath);
// Switch the content to the 'backup_retrieve' page
fadeOut('backup_retrieve');
@@ -89,6 +92,7 @@ async function attachNotificationButton(pathKey, buttonText, buttonId, buttonNam
if (!path) {
const notificationsDiv = document.getElementById('notifications');
const button = document.createElement('button');
button.className='alert';
button.id = buttonId;
button.name = buttonName;
button.textContent = buttonText;
@@ -152,6 +156,7 @@ async function loadReceivedFiles() {
if (!existingButtons.includes(filePath)) {
const button = document.createElement('button');
button.setAttribute('data-filepath', filePath); // Set a custom attribute to track the file path
button.className = 'notification';
button.name = 'notification';
button.textContent = `You received a file "${fileName}" from ${userName}`; // Display the userName and file name
button.addEventListener('click', () => handleFileReceivedButtonPressed(filePath, button));
+4 -3
View File
@@ -10,8 +10,8 @@ document.addEventListener('DOMContentLoaded', async function () {
usernameInput.value = name;
passwordInput.value = password;
const backButton = document.querySelector('button[name="login"]');
const submitButton = document.querySelector('button[name="submit"]');
const backButton = document.getElementById('back');
const submitButton = document.getElementById('submit');
// Get operation codes from the backend
const operationCodes = await window.electronAPI.getOperationsCodes();
@@ -39,7 +39,8 @@ document.addEventListener('DOMContentLoaded', async function () {
const name = usernameInput.value;
const password = passwordInput.value;
const { id, departmentId, app_type } = await window.electronAPI.readUserConfig('user_info'); // Fetch login data
const { id, departmentId } = await window.electronAPI.readUserConfig('user_info'); // Fetch login data
const app_type = await window.electronAPI.readUserConfig('app_type'); // Fetch app type
// Prepare the data to be sent via the UC socket
const messageData = {
+4
View File
@@ -0,0 +1,4 @@
document.addEventListener('DOMContentLoaded', async function () {
await new Promise(resolve => setTimeout(resolve, 7000));
window.electronAPI.changeContent('login');
});
+20 -17
View File
@@ -1,3 +1,6 @@
let codeResetPassword = '';
let codeOk = '';
document.addEventListener('DOMContentLoaded', async function () {
const backToLoginButton = document.getElementById('backToLogin');
const resetPasswordButton = document.getElementById('resetPassword');
@@ -9,8 +12,8 @@ document.addEventListener('DOMContentLoaded', async function () {
return;
}
const codeResetPassword = operationCodes.RESET_PASSWORD;
const codeOk = operationCodes.OK;
codeResetPassword = operationCodes.RESET_PASSWORD;
codeOk = operationCodes.OK;
// Back to login
backToLoginButton.addEventListener('click', function (e) {
@@ -45,19 +48,19 @@ document.addEventListener('DOMContentLoaded', async function () {
await window.electronAPI.showAlert('Password reset successfully.');
window.electronAPI.changeContent('login');
});
async function attemptResetPassword(email, newPassword) {
const app_type = await window.electronAPI.readUserConfig('app_type');
const messageData = { email, newPassword, app_type };
if (!await window.electronAPI.sendUcMessage(codeResetPassword, messageData)) return false;
const response = await waitForResponse();
if (response && response.operationCode === codeOk) {
return true;
} else {
await window.electronAPI.showAlert(response?.metaInfo?.message || 'Error resetting password.');
return false;
}
}
});
async function attemptResetPassword(email, newPassword) {
const app_type = await window.electronAPI.readUserConfig('app_type');
const messageData = { email, newPassword, app_type };
if (!await window.electronAPI.sendUcMessage(codeResetPassword, messageData)) return false;
const response = await waitForResponse();
if (response && response.operationCode === codeOk) {
return true;
} else {
await window.electronAPI.showAlert(response?.metaInfo?.message || 'Error resetting password.');
return false;
}
}
+80 -72
View File
@@ -1,62 +1,13 @@
let pathToFile = '';
let fetchUsersInterval = null;
document.addEventListener('DOMContentLoaded', async function () {
let user_info = {};
let pathToFile = '';
const selectFileButton = document.getElementById('selectFile');
const submitButton = document.getElementById('submitButton');
const backButton = document.getElementById('backButton');
user_info = await window.electronAPI.readUserConfig('user_info');
if (!user_info) {
await window.electronAPI.showAlert('No user_info entry found.');
return;
}
// Function to update the file name display
function updateFileName() {
const fileNameElement = document.getElementById('fileName');
if (!fileNameElement) {
return;
}
if (pathToFile.trim() === '') {
fileNameElement.textContent = 'No file chosen';
} else {
fileNameElement.textContent = pathToFile.split('\\').pop().split('/').pop();
}
}
updateFileName();
// Fetch user information from applicationInfo and create checkboxes for selecting users
async function fetchUsersAndCreateCheckboxes() {
const usersInfoId = await window.electronAPI.readApplicationInfo('active_users_info');
if (!usersInfoId) {
await window.electronAPI.showAlert('Internal error.');
return;
}
const usersInfo = await window.electronAPI.readMemoryEntry(usersInfoId);
if (!usersInfo || usersInfo.length === 0) {
await window.electronAPI.showAlert('No active users found.');
await window.electronAPI.changeContent('main_menu');
return;
}
const usersDiv = document.querySelector('.choose_user_form_content');
usersDiv.innerHTML = '';
usersInfo.forEach(user => {
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = 'users';
checkbox.value = user.ip; // Store user's IP in the value
const label = document.createElement('label');
label.innerHTML = `${user.user_info.name}`; // Display user's name
label.insertBefore(checkbox, label.firstChild);
usersDiv.appendChild(label);
});
}
// Event listener for selecting the file
document.getElementById('selectFile').addEventListener('click', async function () {
selectFileButton.addEventListener('click', async function (event) {
event.preventDefault();
try {
pathToFile = await window.electronAPI.selectFile();
updateFileName();
@@ -64,14 +15,7 @@ document.addEventListener('DOMContentLoaded', async function () {
console.error('Error opening file dialog:', error);
}
});
// Event listener for back button to navigate to main menu
document.getElementById('backButton').addEventListener('click', function () {
fadeOut('main_menu');
});
// Submit button logic to queue file send tasks and then navigate to main_menu.html
document.getElementById('submitButton').addEventListener('click', async function (event) {
submitButton.addEventListener('click', async function (event) {
event.preventDefault();
// Check if a file was chosen
@@ -80,6 +24,11 @@ document.addEventListener('DOMContentLoaded', async function () {
return;
}
const user_info = await window.electronAPI.readUserConfig('user_info');
if (!user_info) {
return;
}
const form = document.getElementById('userDestForm');
const checkboxes = form.querySelectorAll('input[name="users"]');
const selectedUserIps = Array.from(checkboxes)
@@ -100,19 +49,78 @@ document.addEventListener('DOMContentLoaded', async function () {
userName: user_info.name // Sender's username from userConfig
};
await window.electronAPI.addTaskToSendFileQueue(task);
await window.electronAPI.showAlert('File sent to the queue.');
console.log(`Task added to send file to IP ${selectedUserIp}`);
} catch (error) {
console.error(`Error processing IP ${selectedUserIp}:`, error);
}
}
// Navigate back to the main menu after all tasks are queued
fadeOut('main_menu'); // Navigate to the main menu
});
backButton.addEventListener('click', function (event) {
event.preventDefault();
fadeOut('main_menu');
});
// Fetch users and create checkboxes every 5 seconds (in case of updates)
setInterval(fetchUsersAndCreateCheckboxes, 5000);
fetchUsersAndCreateCheckboxes().then(() => console.log('User checkboxes rendered'));
});
// Function to update the file name display
function updateFileName() {
const fileNameElement = document.getElementById('selectFile');
if (!fileNameElement) {
return;
}
if (pathToFile.trim() === '') {
fileNameElement.textContent = 'No file chosen';
} else {
fileNameElement.textContent = pathToFile.split('\\').pop().split('/').pop();
}
}
async function fetchUsersAndCreateCheckboxes() {
// Step 1: Get the currently checked users before refreshing the list
const selectedUserIps = new Set(
Array.from(document.querySelectorAll('input[name="users"]:checked'))
.map(checkbox => checkbox.value)
);
const usersInfoId = await window.electronAPI.readApplicationInfo('active_users_info');
if (!usersInfoId) {
await window.electronAPI.showAlert('Internal error.');
return;
}
const usersInfo = await window.electronAPI.readMemoryEntry(usersInfoId);
if (!usersInfo || usersInfo.length === 0) {
await window.electronAPI.showAlert('No active users found.');
clearInterval(fetchUsersInterval);
fetchUsersInterval = null;
await window.electronAPI.changeContent('main_menu');
return;
}
const usersDiv = document.getElementById('choose_user_form_content');
usersDiv.innerHTML = ''; // Clear the list before updating
usersInfo.forEach(user => {
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = 'users';
checkbox.value = user.ip; // Store user's IP in the value
// Step 2: Check if this user was previously selected
if (selectedUserIps.has(user.ip)) {
checkbox.checked = true; // Restore checked state
}
const label = document.createElement('label');
label.innerHTML = `${user.user_info.name}`; // Display user's name
label.insertBefore(checkbox, label.firstChild);
usersDiv.appendChild(label);
});
toggleScroll('choose_user_form_content');
}
+48 -46
View File
@@ -1,3 +1,14 @@
let codeOk = '';
let codeGetDepartments = '';
let codeSignUp = '';
let userData = {
email: null,
name: null,
password: null,
app_type: null,
departmentId: null
};
document.addEventListener('DOMContentLoaded', async function () {
const nextToStep2Button = document.getElementById('nextToStep2');
const backToStep1Button = document.getElementById('backToStep1');
@@ -7,15 +18,6 @@ document.addEventListener('DOMContentLoaded', async function () {
const step1 = document.getElementById('step1');
const step2 = document.getElementById('step2');
// This object will hold the user data
let userData = {
email: null,
name: null,
password: null,
app_type: null,
departmentId: null
};
if (!await window.electronAPI.openUcSocket()) {
alert('Internal error of the application.');
return;
@@ -27,16 +29,15 @@ document.addEventListener('DOMContentLoaded', async function () {
return;
}
const codeGetDepartments = operationCodes.GET_DEPARTMENTS;
const codeSignUp = operationCodes.SIGN_UP;
const codeOk = operationCodes.OK;
codeGetDepartments = operationCodes.GET_DEPARTMENTS;
codeSignUp = operationCodes.SIGN_UP;
codeOk = operationCodes.OK;
let departments = await getDepartments();
if (departments === null) {
await window.electronAPI.showAlert('Failed to fetch departments.');
return;
}
console.log(departments);
// Handle form submission for Step 1 (Profile Information)
nextToStep2Button.addEventListener('click', async function (e) {
@@ -98,37 +99,38 @@ document.addEventListener('DOMContentLoaded', async function () {
await window.electronAPI.closeUcSocket();
await window.electronAPI.changeContent('login');
});
async function getDepartments() {
if (!await window.electronAPI.sendUcMessage(codeGetDepartments)) return null;
const response = await waitForResponse();
if (response && response.operationCode === codeOk) {
return response.metaInfo.departments;
}
return null;
}
async function attemptSignUp() {
if (!await window.electronAPI.sendUcMessage(codeSignUp, userData)) return false;
const response = await waitForResponse();
if (response && response.operationCode === codeOk) {
return true;
}
await window.electronAPI.showAlert(`Signup failed: ${response?.metaInfo?.message || 'Unknown error'}`);
return false;
}
// Function to switch between steps
function switchStep(fromStep, toStep) {
fromStep.classList.remove('active'); // Fade out the current step
setTimeout(() => {
fromStep.style.display = 'none'; // Hide the current step after transition
toStep.style.display = 'flex'; // Ensure display is flex for the next step
setTimeout(() => {
toStep.classList.add('active'); // Fade in the next step
}, 20); // Small delay to allow display change before applying opacity
}, 500); // Transition duration (0.5s)
}
});
async function getDepartments() {
if (!await window.electronAPI.sendUcMessage('GET_DEPARTMENTS')) return null;
const response = await waitForResponse();
console.log(response);
if (response && response.operationCode === codeOk) {
return response.metaInfo.departments;
}
return null;
}
async function attemptSignUp() {
if (!await window.electronAPI.sendUcMessage(codeSignUp, userData)) return false;
const response = await waitForResponse();
if (response && response.operationCode === codeOk) {
return true;
}
await window.electronAPI.showAlert(`Signup failed: ${response?.metaInfo?.message || 'Unknown error'}`);
return false;
}
// Function to switch between steps
function switchStep(fromStep, toStep) {
fromStep.classList.remove('active'); // Fade out the current step
setTimeout(() => {
fromStep.style.display = 'none'; // Hide the current step after transition
toStep.style.display = 'flex'; // Ensure display is flex for the next step
setTimeout(() => {
toStep.classList.add('active'); // Fade in the next step
}, 20); // Small delay to allow display change before applying opacity
}, 500); // Transition duration (0.5s)
}