diff --git a/CEO/backupSchemes.json b/CEO/backupSchemes.json
index 9e26dfe..c84ae04 100644
--- a/CEO/backupSchemes.json
+++ b/CEO/backupSchemes.json
@@ -1 +1,7 @@
-{}
\ No newline at end of file
+{
+ "7c0ef9d5-23ed-47a6-bfb4-fdcfce436904": {
+ "ip": "192.168.0.195",
+ "directoryStructure": "{\"backup_dir\":{\"files\":[],\"fisiere\":{\"files\":[\"New Microsoft Excel Worksheet.xlsx\",\"New Microsoft Word Document.docx\"]}}}",
+ "totalSize": 19363
+ }
+}
\ No newline at end of file
diff --git a/CEO/jobs/backup.js b/CEO/jobs/backup.js
index 3a0c8ae..4b85119 100644
--- a/CEO/jobs/backup.js
+++ b/CEO/jobs/backup.js
@@ -4,6 +4,7 @@ const path = require('path');
const { decryptFileInPlace, encryptFileInPlace, encryptFileWithKey, decryptFileWithKey} = require("../src/main/aes_encrypt");
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
+
async function decryptAndGetServerIP(filePath) {
try {
await lockFile(filePath);
diff --git a/CEO/src/main/main.js b/CEO/src/main/main.js
index 8cc5fcf..388cb49 100644
--- a/CEO/src/main/main.js
+++ b/CEO/src/main/main.js
@@ -6,7 +6,6 @@ const {fork} = require('child_process');
const {encryptFileInPlace, decryptFileInPlace} = require('./aes_encrypt');
const {lockFile, unlockFile} = require("../../helpers/lock_mechanism");
-//const {decryptUserFilesToDirectory} = require("../../jobs/backup");
const isMac = process.platform === 'darwin';
let html_page = undefined;
@@ -18,7 +17,7 @@ let backupProcess = null;
let externalEndpointsProcess = null;
let sendFileProcess = null;
-const create_initial_keys = () => {
+const createInitialKeys = () => {
const SECRET_KEY = crypto.randomBytes(32);
const IV = crypto.randomBytes(16);
@@ -32,7 +31,7 @@ const create_initial_keys = () => {
console.log(`IV saved to ${ivPath}`);
}
-const delete_external_files = () => {
+const deleteMainComponentsAtErrorStart = () => {
const ipConfigPath = path.join(__dirname, '..', '..', 'ipConfig.json');
const loginDataPath = path.join(__dirname, '..', '..', 'loginData.json');
@@ -54,6 +53,28 @@ const delete_external_files = () => {
}
+const checkForServerConnection = async () => {
+ const pathToIpConfig = path.join(__dirname, '..', '..', 'ipConfig.json');
+
+ try {
+ await fs.promises.access(pathToIpConfig);
+
+ await lockFile(pathToIpConfig);
+ await decryptFileInPlace(pathToIpConfig);
+ const ipConfig = await fs.promises.readFile(pathToIpConfig, 'utf-8');
+ const { ip } = JSON.parse(ipConfig);
+
+ const response = await fetch(`http://${ip}/heartbeat`);
+
+ await encryptFileInPlace(pathToIpConfig)
+ await unlockFile(pathToIpConfig);
+ return response.ok;
+ } catch (error) {
+ console.error("Error:", error);
+ return false;
+ }
+};
+
const createMainWindow = (async (title, width, height) => {
mainWindow = new BrowserWindow({
title: title,
@@ -70,18 +91,11 @@ const createMainWindow = (async (title, width, height) => {
await fs.promises.access(path.join(__dirname, '..', '..', 'secret.key'), fs.constants.F_OK);
await fs.promises.access(path.join(__dirname, '..', '..', 'iv.key'), fs.constants.F_OK);
} catch (err) {
- create_initial_keys();
- delete_external_files();
+ createInitialKeys();
+ deleteMainComponentsAtErrorStart();
}
- html_page = 'ip_config.html';
-
- try {
- await fs.promises.access(path.join(__dirname, '..', '..', 'ipConfig.json'));
- html_page = 'login.html';
- } catch (err) {
- html_page = 'ip_submit.html';
- }
+ html_page = await checkForServerConnection() ? 'login.html' : 'ip_submit.html';
//mainWindow.setMenu(null);
mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', html_page))
diff --git a/CEO/src/renderer/html/sending_file_confirmation.html b/CEO/src/renderer/html/sending_file_confirmation.html
index 7774872..ca50d3a 100644
--- a/CEO/src/renderer/html/sending_file_confirmation.html
+++ b/CEO/src/renderer/html/sending_file_confirmation.html
@@ -9,47 +9,7 @@
-
+ ;
-
-
-
-
+
+
+
+
+
diff --git a/User/src/renderer/html/sending_file_confirmation.html b/User/src/renderer/html/sending_file_confirmation.html
index 7774872..ca50d3a 100644
--- a/User/src/renderer/html/sending_file_confirmation.html
+++ b/User/src/renderer/html/sending_file_confirmation.html
@@ -9,47 +9,7 @@
-
+ ;
Sending file
diff --git a/User/src/renderer/js/main_menu.js b/User/src/renderer/js/main_menu.js
index bc81839..bc84454 100644
--- a/User/src/renderer/js/main_menu.js
+++ b/User/src/renderer/js/main_menu.js
@@ -1,8 +1,10 @@
document.addEventListener('DOMContentLoaded', async function () {
await insertUsername();
- const backupButton = document.getElementById('backup');
+ const backupButton = document.getElementById('backup_dir');
const shareButton = document.getElementById('share_dir');
+ const departmentButton = document.getElementById('department_dir');
+
const changeDepartmentButton = document.getElementById('change_department');
const changeInfoButton = document.getElementById('change_info');
const shareFileButton = document.getElementById('share_file');
@@ -85,7 +87,17 @@ document.addEventListener('DOMContentLoaded', async function () {
console.log('Set backup directory button clicked!');
window.electronAPI.openJsonDirConfigDialog('dirShare.json')
- .then(() => console.log('Back-up directory set'))
+ .then(() => console.log('Share directory set'))
+ .catch(async error => await window.electronAPI.showAlert(error.message)
+ .then(() => console.log('Alert window opened'))
+ .catch(error => console.error('Error showing alert:', error)));
+ });
+
+ departmentButton.addEventListener('click', function () {
+ console.log('Set backup directory button clicked!');
+
+ window.electronAPI.openJsonDirConfigDialog('dirDepartment.json')
+ .then(() => console.log('Department directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)));
@@ -142,7 +154,7 @@ document.addEventListener('DOMContentLoaded', async function () {
if (!fileExists) {
const notificationsDiv = document.getElementById('notifications');
const button = document.createElement('button');
- button.id = 'share_file_alert';
+ button.id = 'share_dir_alert';
button.name = 'alert';
button.textContent = 'Set your share directory!';
button.addEventListener('click', handleShareButtonPressed);
@@ -193,7 +205,7 @@ document.addEventListener('DOMContentLoaded', async function () {
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)));
- const button = document.getElementById('backup_alert');
+ const button = document.getElementById('share_dir_alert');
button.remove();
}
@@ -206,7 +218,7 @@ document.addEventListener('DOMContentLoaded', async function () {
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)));
- const button = document.getElementById('backup_alert');
+ const button = document.getElementById('department_alert');
button.remove();
}
diff --git a/User/src/renderer/js/sending_file_confirmation.js b/User/src/renderer/js/sending_file_confirmation.js
new file mode 100644
index 0000000..f1b46f6
--- /dev/null
+++ b/User/src/renderer/js/sending_file_confirmation.js
@@ -0,0 +1,54 @@
+document.addEventListener("DOMContentLoaded", async function () {
+ async function performUploads() {
+ try {
+ const uploadFile = await window.electronAPI.readFile('usersDestTemp.json');
+ const uploadData = JSON.parse(uploadFile.content);
+
+ const uploadPromises = uploadData.users.map(async (user) => {
+ try {
+ const formData = new FormData();
+ const file = await fetch(uploadData.filePath).then(response => response.blob());
+ formData.append('file', file);
+ formData.append('idUser', user.userId);
+ formData.append('nameOfFile', user.fileName);
+
+ await timeout(5000); // Timeout to simulate delay or wait
+ const url = `http://${user.destIp}:${user.destPort}/upload`;
+ const uploadResponse = await fetch(url, {
+ method: 'POST',
+ body: formData
+ });
+
+ if (!uploadResponse.ok) {
+ throw new Error(`HTTP error during file upload to ${user.userId}: status ${uploadResponse.status}`);
+ }
+
+ return {userId: user.userId, success: true, message: `Upload successful for user ${user.userId}`};
+ } catch (error) {
+ console.error(`Failed to upload for user ${user.userId}:`, error);
+ return {userId: user.userId, success: false, message: `Upload failed for user ${user.userId}`};
+ }
+ });
+
+ const results = await Promise.all(uploadPromises);
+ results.forEach(result => {
+ if (result.success) {
+ console.log(result.message);
+ }
+ });
+ console.log('All files processed. Check the console for detailed results.');
+ } catch (error) {
+ console.error('An error occurred during uploads:', error);
+ } finally {
+ await window.electronAPI.deleteFile('usersDestTemp.json');
+ }
+ }
+
+ function timeout(ms) {
+ return new Promise(resolve => setTimeout(resolve, ms));
+ }
+
+ await performUploads();
+ await timeout(10000);
+ fadeOut('main_menu.html');
+});
\ No newline at end of file
diff --git a/User/src/renderer/js/share_file.js b/User/src/renderer/js/share_file.js
index 462fbc9..bf2717f 100644
--- a/User/src/renderer/js/share_file.js
+++ b/User/src/renderer/js/share_file.js
@@ -72,8 +72,8 @@ document.addEventListener("DOMContentLoaded", async function () {
event.preventDefault();
console.log('Submit button clicked');
- const fileInput = document.getElementById('fileInput');
- if (!fileInput.files.length) {
+ // Check if pathToFile has content
+ if (!pathToFile.trim()) {
await window.electronAPI.showAlert('File not chosen!')
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
@@ -94,13 +94,19 @@ document.addEventListener("DOMContentLoaded", async function () {
}
const uploadData = {
- filePath: fileInput.files[0].path,
+ filePath: pathToFile, // Use the pathToFile variable
users: []
};
for (const userId of selectedUserIds) {
try {
- const ipResponse = await fetch(`http://${serverIp}/backup_schemes/${userId}`);
+ const ipResponse = await fetch(`http://${serverIp}/backup_schemes/${userId}`,{
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'x-api-key': 'uc_api',
+ }
+ });
if (!ipResponse.ok) {
throw new Error(`Failed to fetch IP address for user ${userId}: status ${ipResponse.status}`);
}
@@ -109,21 +115,25 @@ document.addEventListener("DOMContentLoaded", async function () {
userId,
destIp,
destPort: 3000, // Static destination port
- fileName: fileInput.files[0].name
+ fileName: pathToFile.split('\\').pop().split('/').pop()
});
} catch (error) {
console.error('Error fetching user data:', error);
}
}
- window.electronAPI.writeFile('usersDestTemp.json', JSON.stringify(uploadData))
- .then(() => {
+ window.electronAPI.writeFile('usersDestTemp.json', JSON.stringify(uploadData, null, 2))
+ .then(async () => {
console.log('File saved successfully');
fadeOut('sending_file_confirmation.html');
})
.catch(error => console.error('Failed to save file:', error));
});
+ function timeout(ms) {
+ return new Promise(resolve => setTimeout(resolve, ms));
+ }
+
fetchUsersAndCreateCheckboxes().then(() => console.log('Page rendered'))
});
diff --git a/User/usersInSystem.json b/User/usersInSystem.json
index e59098a..0ca3084 100644
Binary files a/User/usersInSystem.json and b/User/usersInSystem.json differ