This commit is contained in:
andrei-mihnea-cerbu
2024-04-22 16:30:40 +03:00
parent 7cf1729d08
commit 9ac718bea3
24 changed files with 275 additions and 163 deletions
+27 -13
View File
@@ -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))
+5 -4
View File
@@ -36,14 +36,15 @@
<img alt="" src="../assets/user_1144760.png">
</div>
<div class="left_block_content">
<div class="left_block_buttons">
<button id="backup" name="menu_button">Set backup directory</button>
<button id="share_dir" name="menu_button">Set share directory</button>
</div>
<div class="left_block_buttons">
<button id="change_info" name="menu_button">Change your info</button>
<button id="change_department" name="menu_button">Change work department</button>
</div>
<div class="left_block_buttons">
<button id="backup_dir" name="menu_button">Set backup directory</button>
<button id="department_dir" name="menu_button">Set department directory</button>
<button id="share_dir" name="menu_button">Set share directory</button>
</div>
<div class="left_block_buttons">
<button id="share_file" name="menu_button">Share a file</button>
<button id="decrypt" name="menu_button">Decrypt files</button>
@@ -9,47 +9,7 @@
<link href="../css/transition.css" rel="stylesheet">
<script src="../js/transition.js"></script>
<script>
import * as fs from "fs";
document.addEventListener("DOMContentLoaded", async function () {
async function performUploads() {
try {
const uploadData = JSON.parse(await window.electronAPI.readFile('usersDestTemp.json'));
const uploadPromises = uploadData.users.map(async (user) => {
const formData = new FormData();
formData.append('file', fs.readFileSync(uploadData.filePath));
formData.append('idUser', user.userId);
formData.append('nameOfFile', user.fileName);
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}` };
});
const results = await Promise.all(uploadPromises);
results.forEach(result => {
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);
}
}
await performUploads();
fadeOut('main_menu.html');
});
</script>
<script src="../js/sending_file_confirmation.js"></script>;
<title>Sending file</title>
</head>
+17 -5
View File
@@ -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();
}
@@ -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');
});
+17 -7
View File
@@ -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'))
});