Files
FACULTATE-LICENTA/CEO/render/js/main_menu.js
T
2024-10-29 15:07:26 +02:00

256 lines
9.5 KiB
JavaScript

document.addEventListener('DOMContentLoaded', async function () {
setInterval(loadReceivedFiles, 3000); // Call loadReceivedFiles every 3000 ms (3 seconds)
const backupButton = document.getElementById('backup-dir');
const shareButton = document.getElementById('share-dir');
const changeInfoButton = document.getElementById('change-info');
const shareFileButton = document.getElementById('share-file');
const logoutButton = document.getElementById('logout');
const restoreBackupButton = document.getElementById('restore-backup');
const buttonOverviewDepartments = document.getElementById('overview-departments');
const buttonOverviewUsers = document.getElementById('overview-users');
const buttonResetDatabase = document.getElementById('reset-database');
const buttonSendAnnouncement = document.getElementById('send-announcement');
backupButton.addEventListener('click', async function () {
await setPath('backupDirectory');
});
shareButton.addEventListener('click', async function () {
await setPath('shareDirectory');
});
buttonResetDatabase.addEventListener('click', async function () {
// Show a confirmation dialog
const userConfirmed = await showConfirmationDialog("Are you sure you want to reset the database? This action cannot be undone.");
// If the user confirms, perform the database reset
if (userConfirmed) {
await resetDatabase();
} else {
window.electronAPI.showAlert("Database reset canceled.");
}
});
buttonSendAnnouncement.addEventListener('click', async function () {
fadeOut('announcement');
});
buttonOverviewDepartments.addEventListener('click', async function () {
fadeOut('overview_departments');
});
buttonOverviewUsers.addEventListener('click', async function () {
fadeOut('overview_users');
});
changeInfoButton.addEventListener('click', function () {
fadeOut('profile');
});
shareFileButton.addEventListener('click', function () {
fadeOut('share_file');
});
logoutButton.addEventListener('click', async function () {
fadeOut('login');
});
// Add event listener for the restore backup button
restoreBackupButton.addEventListener('click', async function () {
await restoreBackup();
});
});
async function initialSetup(){
await checkAndSetAllDirectories();
await loadReceivedFiles();
await fetchUserInfo();
}
async function restoreBackup() {
const backupDirectory = await window.electronAPI.readApplicationInfo('backupDirectory');
if (backupDirectory && backupDirectory.path) {
// If backup directory is already set, display an alert
await window.electronAPI.showAlert('You have already set a backup directory. You cannot restore again.');
return;
}
// Prompt the user to choose the destination for the restored backup
const destinationPath = await window.electronAPI.selectDirectory();
if (!destinationPath) {
return; // User canceled the directory selection
}
// Call the IPC method to initiate the backup retrieval process
window.electronAPI.startBackupRetrieval(destinationPath);
// Switch the content to the 'backup_retrieve' page
fadeOut('backup_retrieve');
}
async function checkAndSetAllDirectories() {
await attachNotificationButton('backupDirectory', 'Set your backup directory!', 'backup_alert', 'alert');
await attachNotificationButton('shareDirectory', 'Set your share directory!', 'share_alert', 'alert');
await attachNotificationButton('departmentDirectory', 'Set your department directory!', 'department_alert', 'alert');
}
async function checkPathExistence(pathKey) {
return await window.electronAPI.readApplicationInfo(pathKey);
}
async function setPath(pathKey) {
const path = await window.electronAPI.selectDirectory();
if (path === undefined) return;
const id = await window.electronAPI.createMemoryEntry()
console.log({id, path})
await window.electronAPI.writeApplicationInfo(pathKey, {id, path});
}
async function attachNotificationButton(pathKey, buttonText, buttonId, buttonName) {
const path = await checkPathExistence(pathKey);
if (!path) {
const notificationsDiv = document.getElementById('notifications');
const button = document.createElement('button');
button.className='alert';
button.id = buttonId;
button.name = buttonName;
button.textContent = buttonText;
button.addEventListener('click', async function () {
await setPath(pathKey);
button.remove(); // Remove button after setting the path
});
notificationsDiv.appendChild(button);
}
}
async function fetchUserInfo() {
const usernameField = document.getElementById('username-field');
// Read the user credentials from the userConfig
let userInfo = await window.electronAPI.readUserConfig('user_info');
if (userInfo && userInfo.name) {
usernameField.textContent = userInfo.name;
return;
}
// Update the greeting with the fetched user's name
if (usernameField) {
usernameField.textContent = userInfo.name; // Update the h1 with the user's name
} else {
console.error("Username field is not available in the DOM.");
}
}
async function loadReceivedFiles() {
// Read the shareDirectory from applicationInfo
const shareDirectoryData = await window.electronAPI.readApplicationInfo('shareDirectory');
if (!shareDirectoryData || !shareDirectoryData.id) {
console.log('No received files or directory ID found.');
return;
}
const directoryId = shareDirectoryData.id;
// Fetch the directory structure (JSON objects with user names and file paths)
const directoryStructure = await window.electronAPI.readMemoryEntry(directoryId);
if (!directoryStructure || !directoryStructure.structure) {
console.log('No received files found in the directory structure.');
return;
}
const notificationsDiv = document.getElementById('notifications');
const existingButtons = Array.from(notificationsDiv.children).map(button => button.getAttribute('data-filepath'));
// Iterate over each user and their files in the structure
Object.keys(directoryStructure.structure).forEach(userName => {
const userFiles = directoryStructure.structure[userName];
// Iterate over each file of the user
Object.keys(userFiles).forEach(fileName => {
const filePath = userFiles[fileName];
// Check if a button for this file path already exists
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));
notificationsDiv.appendChild(button);
}
});
});
}
async function removeReceivedFile(filePath) {
// Read the shareDirectory from applicationInfo
const shareDirectoryData = await window.electronAPI.readApplicationInfo('shareDirectory');
if (!shareDirectoryData || !shareDirectoryData.id) {
console.log('No directory ID found to update.');
return;
}
const directoryId = shareDirectoryData.id;
// Fetch the directory structure
let directoryStructure = await window.electronAPI.readMemoryEntry(directoryId);
if (directoryStructure && directoryStructure.structure) {
// Iterate over each user and their files
for (let userName in directoryStructure.structure) {
let userFiles = directoryStructure.structure[userName];
// Check if the file exists and remove it
if (userFiles[filePath]) {
delete userFiles[filePath];
// Remove the user if no more files are left
if (Object.keys(userFiles).length === 0) {
delete directoryStructure.structure[userName];
}
// Update the directory structure in memory
await window.electronAPI.updateMemoryEntry(directoryId, directoryStructure);
console.log(`File ${filePath} removed from memory.`);
return;
}
}
} else {
console.log('No directory structure found in memory to update.');
}
}
async function handleFileReceivedButtonPressed(filePath, button) {
console.log('Notification button clicked!');
// Open the file in the file explorer
await window.electronAPI.showFileInExplorer(filePath)
.then(() => console.log('File explorer opened for: ' + filePath))
.catch(error => console.error('Error opening file explorer:', error));
// Remove the button after opening the file
button.remove();
// Remove the file from memory
await removeReceivedFile(filePath);
}
async function showConfirmationDialog(message) {
return new Promise((resolve) => {
const userResponse = window.confirm(message); // Show native confirmation dialog
resolve(userResponse); // Resolve with true (OK) or false (Cancel)
});
}
async function resetDatabase(){
fadeOut('reset_database');
}