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
+7 -1
View File
@@ -1 +1,7 @@
{} {
"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
}
}
+1
View File
@@ -4,6 +4,7 @@ const path = require('path');
const { decryptFileInPlace, encryptFileInPlace, encryptFileWithKey, decryptFileWithKey} = require("../src/main/aes_encrypt"); const { decryptFileInPlace, encryptFileInPlace, encryptFileWithKey, decryptFileWithKey} = require("../src/main/aes_encrypt");
const {lockFile, unlockFile} = require("../helpers/lock_mechanism"); const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
async function decryptAndGetServerIP(filePath) { async function decryptAndGetServerIP(filePath) {
try { try {
await lockFile(filePath); await lockFile(filePath);
+27 -13
View File
@@ -6,7 +6,6 @@ const {fork} = require('child_process');
const {encryptFileInPlace, decryptFileInPlace} = require('./aes_encrypt'); const {encryptFileInPlace, decryptFileInPlace} = require('./aes_encrypt');
const {lockFile, unlockFile} = require("../../helpers/lock_mechanism"); const {lockFile, unlockFile} = require("../../helpers/lock_mechanism");
//const {decryptUserFilesToDirectory} = require("../../jobs/backup");
const isMac = process.platform === 'darwin'; const isMac = process.platform === 'darwin';
let html_page = undefined; let html_page = undefined;
@@ -18,7 +17,7 @@ let backupProcess = null;
let externalEndpointsProcess = null; let externalEndpointsProcess = null;
let sendFileProcess = null; let sendFileProcess = null;
const create_initial_keys = () => { const createInitialKeys = () => {
const SECRET_KEY = crypto.randomBytes(32); const SECRET_KEY = crypto.randomBytes(32);
const IV = crypto.randomBytes(16); const IV = crypto.randomBytes(16);
@@ -32,7 +31,7 @@ const create_initial_keys = () => {
console.log(`IV saved to ${ivPath}`); console.log(`IV saved to ${ivPath}`);
} }
const delete_external_files = () => { const deleteMainComponentsAtErrorStart = () => {
const ipConfigPath = path.join(__dirname, '..', '..', 'ipConfig.json'); const ipConfigPath = path.join(__dirname, '..', '..', 'ipConfig.json');
const loginDataPath = path.join(__dirname, '..', '..', 'loginData.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) => { const createMainWindow = (async (title, width, height) => {
mainWindow = new BrowserWindow({ mainWindow = new BrowserWindow({
title: title, 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, '..', '..', 'secret.key'), fs.constants.F_OK);
await fs.promises.access(path.join(__dirname, '..', '..', 'iv.key'), fs.constants.F_OK); await fs.promises.access(path.join(__dirname, '..', '..', 'iv.key'), fs.constants.F_OK);
} catch (err) { } catch (err) {
create_initial_keys(); createInitialKeys();
delete_external_files(); deleteMainComponentsAtErrorStart();
} }
html_page = 'ip_config.html'; html_page = await checkForServerConnection() ? 'login.html' : 'ip_submit.html';
try {
await fs.promises.access(path.join(__dirname, '..', '..', 'ipConfig.json'));
html_page = 'login.html';
} catch (err) {
html_page = 'ip_submit.html';
}
//mainWindow.setMenu(null); //mainWindow.setMenu(null);
mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', html_page)) mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', html_page))
@@ -9,47 +9,7 @@
<link href="../css/transition.css" rel="stylesheet"> <link href="../css/transition.css" rel="stylesheet">
<script src="../js/transition.js"></script> <script src="../js/transition.js"></script>
<script> <script src="../js/sending_file_confirmation.js"></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>
<title>Sending file</title> <title>Sending file</title>
</head> </head>
@@ -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');
});
+18 -8
View File
@@ -4,7 +4,7 @@ document.addEventListener("DOMContentLoaded", async function () {
await window.electronAPI.readFile('ipConfig.json') await window.electronAPI.readFile('ipConfig.json')
.then(result => { .then(result => {
const jsonData = JSON.parse(result.content); const jsonData = JSON.parse(result.content);
ip = jsonData.ip; serverIp = jsonData.ip;
}) })
function updateFileName() { function updateFileName() {
@@ -72,8 +72,8 @@ document.addEventListener("DOMContentLoaded", async function () {
event.preventDefault(); event.preventDefault();
console.log('Submit button clicked'); console.log('Submit button clicked');
const fileInput = document.getElementById('fileInput'); // Check if pathToFile has content
if (!fileInput.files.length) { if (!pathToFile.trim()) {
await window.electronAPI.showAlert('File not chosen!') await window.electronAPI.showAlert('File not chosen!')
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)); .catch(error => console.error('Error showing alert:', error));
@@ -94,13 +94,19 @@ document.addEventListener("DOMContentLoaded", async function () {
} }
const uploadData = { const uploadData = {
filePath: fileInput.files[0].path, filePath: pathToFile, // Use the pathToFile variable
users: [] users: []
}; };
for (const userId of selectedUserIds) { for (const userId of selectedUserIds) {
try { 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) { if (!ipResponse.ok) {
throw new Error(`Failed to fetch IP address for user ${userId}: status ${ipResponse.status}`); throw new Error(`Failed to fetch IP address for user ${userId}: status ${ipResponse.status}`);
} }
@@ -109,21 +115,25 @@ document.addEventListener("DOMContentLoaded", async function () {
userId, userId,
destIp, destIp,
destPort: 3000, // Static destination port destPort: 3000, // Static destination port
fileName: fileInput.files[0].name fileName: pathToFile.split('\\').pop().split('/').pop()
}); });
} catch (error) { } catch (error) {
console.error('Error fetching user data:', error); console.error('Error fetching user data:', error);
} }
} }
window.electronAPI.writeFile('usersDestTemp.json', JSON.stringify(uploadData)) window.electronAPI.writeFile('usersDestTemp.json', JSON.stringify(uploadData, null, 2))
.then(() => { .then(async () => {
console.log('File saved successfully'); console.log('File saved successfully');
fadeOut('sending_file_confirmation.html'); fadeOut('sending_file_confirmation.html');
}) })
.catch(error => console.error('Failed to save file:', error)); .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')) fetchUsersAndCreateCheckboxes().then(() => console.log('Page rendered'))
}); });
+4
View File
@@ -52,6 +52,10 @@ app.use('/admin', adminRouter);
app.use('/ceo', ceoRouter); app.use('/ceo', ceoRouter);
app.use('/backup_schemes', backupSchemesRouter); app.use('/backup_schemes', backupSchemesRouter);
app.use('/heartbeat', (req, res) => {
return res.status(200).json({message: 'Server ap and running.'});
})
app.listen(port, () => { app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`); console.log(`Server running on http://localhost:${port}`);
}); });
+12 -1
View File
@@ -1 +1,12 @@
{} {
"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
},
"59c712d9-e6dd-438f-aec9-31ca2ae750e6": {
"ip": "192.168.0.195",
"directoryStructure": "{\"backup_dir\":{\"files\":[],\"fisiere\":{\"files\":[\"New Microsoft Excel Worksheet.xlsx\",\"New Microsoft Word Document.docx\"]}}}",
"totalSize": 19363
}
}
+20 -1
View File
@@ -1,4 +1,23 @@
const express = require('express'); const checkForServerConnection = async () => {
const pathToIpConfig = path.join(__dirname, '..', '..', 'ipConfig.json');
await lockFile.lock(pathToIpConfig);
try {
await decryptFileInPlace(pathToIpConfig);
const ipConfig = await fs.readFile(pathToIpConfig, 'utf-8');
const { ip } = JSON.parse(ipConfig);
const response = await fetch(`http://${ip}:5000/heartbeat`);
if (response.ok) {
return true;
} else {
return false;
}
} catch (error) {
console.error("Error:", error);
return false;
} finally {
await lockFile.unlock(pathToIpConfig);
}
};const express = require('express');
const crypto = require('crypto'); const crypto = require('crypto');
const { v4: uuidv4 } = require('uuid'); const { v4: uuidv4 } = require('uuid');
+8 -3
View File
@@ -1,7 +1,12 @@
{ {
"4659e71f-9bb4-4902-97d8-097efa138333": { "7c0ef9d5-23ed-47a6-bfb4-fdcfce436904": {
"ip": "192.168.0.195", "ip": "192.168.0.195",
"directoryStructure": "{\"to_backup\":{\"files\":[\"fisier_random.txt\"],\"alte fis\":{\"files\":[\"alt fisier.txt\",\"fisier now.txt\",\"New Microsoft Excel Worksheet.xlsx\"]}}}", "directoryStructure": "{\"backup_dir\":{\"files\":[],\"fisiere\":{\"files\":[\"New Microsoft Excel Worksheet.xlsx\",\"New Microsoft Word Document.docx\"]}}}",
"totalSize": 8482 "totalSize": 19363
},
"59c712d9-e6dd-438f-aec9-31ca2ae750e6": {
"ip": "192.168.0.195",
"directoryStructure": "{\"backup_dir\":{\"files\":[],\"fisiere\":{\"files\":[\"New Microsoft Excel Worksheet.xlsx\",\"New Microsoft Word Document.docx\"]}}}",
"totalSize": 19363
} }
} }
-18
View File
@@ -1,18 +0,0 @@
{
"path": "C:\\Users\\Andrei Cerbu\\Documents\\to_backup",
"structure": {
"to_backup": {
"files": [
"fisier_random.txt"
],
"alte fis": {
"files": [
"alt fisier.txt",
"fisier now.txt",
"New Microsoft Excel Worksheet.xlsx"
]
}
}
},
"size": 8482
}
-3
View File
@@ -1,3 +0,0 @@
{
"path": "C:\\Users\\Andrei Cerbu\\Documents\\department_shared_files"
}
-3
View File
@@ -1,3 +0,0 @@
{
"path": "C:\\Users\\Andrei Cerbu\\Documents\\share_directory"
}
+1
View File
@@ -232,3 +232,4 @@ process.on('SIGINT', async () => {
} }
}); });
encryptFileInPlace(path.join(__dirname, '..', 'usersDestTemp.json'))
+1 -1
View File
@@ -1 +1 @@
!ִ©׀.:¦ !r©}QXֿ¯@Ki*¨»עu[9Jצ/¥¨ׁdל-סC$n¥¼¦jW4"¡wו¾{ֱ^·\־טJֱײ פ˜ ־³RAךQTc4שE'I®עvעlַ7E־;ֱ9jה3ִ±אֻˆֲַ UU©1קל Ï5oÏíâʾ´ˆÐ8ð´úcAš=6ZÍö·š¯±ûøļÊhå£Ñ«E ëšýY¦ŒÛFY«áQ>tá݃xÔFFÙzEoašE ×CEŽƒèüzȽAé\$¬¨D¬ÿ*}>ŸŒ¬}Kâ¡/ev(¯¤Ý¸E`øg.GܽÙlçž`ÿÝ]SXwã¨ÛwˆðUûL
+27 -13
View File
@@ -6,7 +6,6 @@ const {fork} = require('child_process');
const {encryptFileInPlace, decryptFileInPlace} = require('./aes_encrypt'); const {encryptFileInPlace, decryptFileInPlace} = require('./aes_encrypt');
const {lockFile, unlockFile} = require("../../helpers/lock_mechanism"); const {lockFile, unlockFile} = require("../../helpers/lock_mechanism");
//const {decryptUserFilesToDirectory} = require("../../jobs/backup");
const isMac = process.platform === 'darwin'; const isMac = process.platform === 'darwin';
let html_page = undefined; let html_page = undefined;
@@ -18,7 +17,7 @@ let backupProcess = null;
let externalEndpointsProcess = null; let externalEndpointsProcess = null;
let sendFileProcess = null; let sendFileProcess = null;
const create_initial_keys = () => { const createInitialKeys = () => {
const SECRET_KEY = crypto.randomBytes(32); const SECRET_KEY = crypto.randomBytes(32);
const IV = crypto.randomBytes(16); const IV = crypto.randomBytes(16);
@@ -32,7 +31,7 @@ const create_initial_keys = () => {
console.log(`IV saved to ${ivPath}`); console.log(`IV saved to ${ivPath}`);
} }
const delete_external_files = () => { const deleteMainComponentsAtErrorStart = () => {
const ipConfigPath = path.join(__dirname, '..', '..', 'ipConfig.json'); const ipConfigPath = path.join(__dirname, '..', '..', 'ipConfig.json');
const loginDataPath = path.join(__dirname, '..', '..', 'loginData.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) => { const createMainWindow = (async (title, width, height) => {
mainWindow = new BrowserWindow({ mainWindow = new BrowserWindow({
title: title, 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, '..', '..', 'secret.key'), fs.constants.F_OK);
await fs.promises.access(path.join(__dirname, '..', '..', 'iv.key'), fs.constants.F_OK); await fs.promises.access(path.join(__dirname, '..', '..', 'iv.key'), fs.constants.F_OK);
} catch (err) { } catch (err) {
create_initial_keys(); createInitialKeys();
delete_external_files(); deleteMainComponentsAtErrorStart();
} }
html_page = 'ip_config.html'; html_page = await checkForServerConnection() ? 'login.html' : 'ip_submit.html';
try {
await fs.promises.access(path.join(__dirname, '..', '..', 'ipConfig.json'));
html_page = 'login.html';
} catch (err) {
html_page = 'ip_submit.html';
}
//mainWindow.setMenu(null); //mainWindow.setMenu(null);
mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', html_page)) mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', html_page))
+5 -4
View File
@@ -36,14 +36,15 @@
<img alt="" src="../assets/user_1144760.png"> <img alt="" src="../assets/user_1144760.png">
</div> </div>
<div class="left_block_content"> <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"> <div class="left_block_buttons">
<button id="change_info" name="menu_button">Change your info</button> <button id="change_info" name="menu_button">Change your info</button>
<button id="change_department" name="menu_button">Change work department</button> <button id="change_department" name="menu_button">Change work department</button>
</div> </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"> <div class="left_block_buttons">
<button id="share_file" name="menu_button">Share a file</button> <button id="share_file" name="menu_button">Share a file</button>
<button id="decrypt" name="menu_button">Decrypt files</button> <button id="decrypt" name="menu_button">Decrypt files</button>
@@ -9,47 +9,7 @@
<link href="../css/transition.css" rel="stylesheet"> <link href="../css/transition.css" rel="stylesheet">
<script src="../js/transition.js"></script> <script src="../js/transition.js"></script>
<script> <script src="../js/sending_file_confirmation.js"></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>
<title>Sending file</title> <title>Sending file</title>
</head> </head>
+17 -5
View File
@@ -1,8 +1,10 @@
document.addEventListener('DOMContentLoaded', async function () { document.addEventListener('DOMContentLoaded', async function () {
await insertUsername(); await insertUsername();
const backupButton = document.getElementById('backup'); const backupButton = document.getElementById('backup_dir');
const shareButton = document.getElementById('share_dir'); const shareButton = document.getElementById('share_dir');
const departmentButton = document.getElementById('department_dir');
const changeDepartmentButton = document.getElementById('change_department'); const changeDepartmentButton = document.getElementById('change_department');
const changeInfoButton = document.getElementById('change_info'); const changeInfoButton = document.getElementById('change_info');
const shareFileButton = document.getElementById('share_file'); const shareFileButton = document.getElementById('share_file');
@@ -85,7 +87,17 @@ document.addEventListener('DOMContentLoaded', async function () {
console.log('Set backup directory button clicked!'); console.log('Set backup directory button clicked!');
window.electronAPI.openJsonDirConfigDialog('dirShare.json') 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) .catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error))); .catch(error => console.error('Error showing alert:', error)));
@@ -142,7 +154,7 @@ document.addEventListener('DOMContentLoaded', async function () {
if (!fileExists) { if (!fileExists) {
const notificationsDiv = document.getElementById('notifications'); const notificationsDiv = document.getElementById('notifications');
const button = document.createElement('button'); const button = document.createElement('button');
button.id = 'share_file_alert'; button.id = 'share_dir_alert';
button.name = 'alert'; button.name = 'alert';
button.textContent = 'Set your share directory!'; button.textContent = 'Set your share directory!';
button.addEventListener('click', handleShareButtonPressed); button.addEventListener('click', handleShareButtonPressed);
@@ -193,7 +205,7 @@ document.addEventListener('DOMContentLoaded', async function () {
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error))); .catch(error => console.error('Error showing alert:', error)));
const button = document.getElementById('backup_alert'); const button = document.getElementById('share_dir_alert');
button.remove(); button.remove();
} }
@@ -206,7 +218,7 @@ document.addEventListener('DOMContentLoaded', async function () {
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error))); .catch(error => console.error('Error showing alert:', error)));
const button = document.getElementById('backup_alert'); const button = document.getElementById('department_alert');
button.remove(); 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(); event.preventDefault();
console.log('Submit button clicked'); console.log('Submit button clicked');
const fileInput = document.getElementById('fileInput'); // Check if pathToFile has content
if (!fileInput.files.length) { if (!pathToFile.trim()) {
await window.electronAPI.showAlert('File not chosen!') await window.electronAPI.showAlert('File not chosen!')
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)); .catch(error => console.error('Error showing alert:', error));
@@ -94,13 +94,19 @@ document.addEventListener("DOMContentLoaded", async function () {
} }
const uploadData = { const uploadData = {
filePath: fileInput.files[0].path, filePath: pathToFile, // Use the pathToFile variable
users: [] users: []
}; };
for (const userId of selectedUserIds) { for (const userId of selectedUserIds) {
try { 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) { if (!ipResponse.ok) {
throw new Error(`Failed to fetch IP address for user ${userId}: status ${ipResponse.status}`); throw new Error(`Failed to fetch IP address for user ${userId}: status ${ipResponse.status}`);
} }
@@ -109,21 +115,25 @@ document.addEventListener("DOMContentLoaded", async function () {
userId, userId,
destIp, destIp,
destPort: 3000, // Static destination port destPort: 3000, // Static destination port
fileName: fileInput.files[0].name fileName: pathToFile.split('\\').pop().split('/').pop()
}); });
} catch (error) { } catch (error) {
console.error('Error fetching user data:', error); console.error('Error fetching user data:', error);
} }
} }
window.electronAPI.writeFile('usersDestTemp.json', JSON.stringify(uploadData)) window.electronAPI.writeFile('usersDestTemp.json', JSON.stringify(uploadData, null, 2))
.then(() => { .then(async () => {
console.log('File saved successfully'); console.log('File saved successfully');
fadeOut('sending_file_confirmation.html'); fadeOut('sending_file_confirmation.html');
}) })
.catch(error => console.error('Failed to save file:', error)); .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')) fetchUsersAndCreateCheckboxes().then(() => console.log('Page rendered'))
}); });
Binary file not shown.