CEO updated

This commit is contained in:
andrei-mihnea-cerbu
2024-04-20 03:18:44 +03:00
parent 869305a491
commit 57c2c7ec55
81 changed files with 3517 additions and 1035 deletions
+1 -1
View File
@@ -2,6 +2,6 @@
"4659e71f-9bb4-4902-97d8-097efa138333": {
"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\"]}}}",
"totalSize": 6197
"totalSize": 8482
}
}
+1 -1
View File
@@ -14,5 +14,5 @@
}
}
},
"size": 6197
"size": 8482
}
+3
View File
@@ -0,0 +1,3 @@
{
"path": "C:\\Users\\Andrei Cerbu\\Documents\\department_shared_files"
}
+3
View File
@@ -0,0 +1,3 @@
{
"path": "C:\\Users\\Andrei Cerbu\\Documents\\share_directory"
}
+172 -24
View File
@@ -1,8 +1,27 @@
const fs = require('fs').promises; // Ensure you use the promise-based API
const fsPromises = require('fs').promises; // Ensure you use the promise-based API
const fs = require('fs');
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);
await decryptFileInPlace(filePath);
const fileContent = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(fileContent);
const serverIP = jsonData.ip;
await encryptFileInPlace(filePath)
await unlockFile(filePath);
return serverIP;
} catch (error) {
console.error('An error occurred:', error);
return null;
}
}
function extractFilePaths(directoryStructure) {
let paths = [];
const traverse = (dir, currentPath) => {
@@ -48,31 +67,32 @@ async function fetchFiles(ip, filePaths) {
async function removeDirectory(directoryPath) {
try {
// Check if the directory exists
const stats = await fs.stat(directoryPath);
const stats = await fsPromises.stat(directoryPath);
if (!stats.isDirectory()) {
console.log('The specified path is not a directory.');
return;
}
// Read all the contents of the directory
const files = await fs.readdir(directoryPath);
const files = await fsPromises.readdir(directoryPath);
// Loop through each file/directory and delete them
for (const file of files) {
const currentPath = path.join(directoryPath, file);
const currentStats = await fs.stat(currentPath);
const currentStats = await fsPromises.stat(currentPath);
if (currentStats.isDirectory()) {
// Recursive call for directories
await removeDirectory(currentPath);
} else {
// Delete file
await fs.unlink(currentPath);
await lockFile(currentPath);
await unlockFile(currentPath);
await fsPromises.unlink(currentPath);
}
}
// Finally, delete the directory itself
await fs.rmdir(directoryPath);
await fsPromises.rmdir(directoryPath);
//console.log(`Directory removed: ${directoryPath}`);
} catch (error) {
console.error(`Error removing directory: ${error.message}`);
@@ -87,23 +107,28 @@ async function decryptUserSystemConfig() {
async function encryptUserSystemConfig(){
const configPath = path.join(__dirname, '..', 'usersInSystem.json');
await unlockFile(configPath);
await encryptFileInPlace(configPath);
await unlockFile(configPath);
}
async function processBackup() {
await decryptUserSystemConfig();
const usersConfigPath = path.join(__dirname, '..', 'usersInSystem.json');
const backupConfigPath = path.join(__dirname, '..', 'backupSchemes.json');
const baseBackupDirPath = path.join(__dirname, '..', 'backup_directories');
if(!fs.existsSync(backupConfigPath) || !fs.existsSync(usersConfigPath)){
console.log('Can\'t start backup system: necessary files missing!');
return;
}
await decryptUserSystemConfig();
try {
// Read and parse the users configuration
const usersData = await fs.readFile(usersConfigPath, 'utf8');
const usersData = await fsPromises.readFile(usersConfigPath, 'utf8');
const usersConfig = JSON.parse(usersData);
// Read and parse the backup configuration
const backupData = await fs.readFile(backupConfigPath, 'utf8');
const backupData = await fsPromises.readFile(backupConfigPath, 'utf8');
const jsonData = JSON.parse(backupData);
for (const key in jsonData) {
@@ -115,7 +140,7 @@ async function processBackup() {
const filePaths = extractFilePaths(directoryStructure);
const files = await fetchFiles(node.ip, filePaths);
await fs.mkdir(userBackupDir, { recursive: true });
await fsPromises.mkdir(userBackupDir, { recursive: true });
// Find the encryption key for the user's department
let encryptionKey = '';
@@ -129,8 +154,8 @@ async function processBackup() {
for (const file in files) {
if (files[file]) {
const fullPath = path.join(userBackupDir, file);
await fs.mkdir(path.dirname(fullPath), { recursive: true });
await fs.writeFile(fullPath, files[file]); // Write the binary data
await fsPromises.mkdir(path.dirname(fullPath), { recursive: true });
await fsPromises.writeFile(fullPath, files[file]); // Write the binary data
// Encrypt the file in place after writing it
if (encryptionKey) {
@@ -149,7 +174,7 @@ async function processBackup() {
async function getAllFilePaths(dirPath) {
let filePaths = [];
async function recurse(currentPath) {
const entries = await fs.readdir(currentPath, { withFileTypes: true });
const entries = await fsPromises.readdir(currentPath, { withFileTypes: true });
// Create promises for each entry and process them in parallel
const entryPromises = entries.map(async (entry) => {
const resolvedPath = path.join(currentPath, entry.name);
@@ -168,12 +193,19 @@ async function getAllFilePaths(dirPath) {
return filePaths;
}
async function decryptUserFilesToDirectory(destinationDir) {
await decryptUserSystemConfig(); // Ensure user config is decrypted
async function decryptBackupFilesToDirectory(destinationDir) {
await decryptUserSystemConfig();
const usersConfigPath = path.join(__dirname, '..', 'usersInSystem.json');
const usersConfig = JSON.parse(await fs.readFile(usersConfigPath, 'utf8'));
if(!fs.existsSync(usersConfigPath)){
return false;
}
const usersConfig = JSON.parse(await fsPromises.readFile(usersConfigPath, 'utf8'));
const sourceDir = path.join(__dirname, '..', 'backup_directories');
await removeDirectory(destinationDir);
try {
for (const department in usersConfig) {
const { key, users } = usersConfig[department];
@@ -182,36 +214,152 @@ async function decryptUserFilesToDirectory(destinationDir) {
try {
const files = await getAllFilePaths(userDir);
for (const filePath of files) {
const stats = await fs.stat(filePath);
const stats = await fsPromises.stat(filePath);
if (stats.isFile()) {
// Extract the part of the file path after the userId
const relativePath = path.relative(userDir, filePath);
// Construct the destination file path
const destinationFilePath = path.join(destinationDir, userId, relativePath);
await fs.mkdir(path.dirname(destinationFilePath), { recursive: true });
await fsPromises.mkdir(path.dirname(destinationFilePath), { recursive: true });
await lockFile(filePath);
// Decrypt the file in its original location
await decryptFileWithKey(filePath, key);
// Copy the decrypted file to the destination directory
await fs.copyFile(filePath, destinationFilePath);
await fsPromises.copyFile(filePath, destinationFilePath);
console.log(`Decrypted file copied to: ${destinationFilePath}`);
// Re-encrypt the file in its original location (optional)
await encryptFileWithKey(filePath, key);
await unlockFile(filePath);
}
}
} catch (error) {
console.error(`Error processing files for user ${userId}: ${error.message}`);
await encryptUserSystemConfig();
return false;
}
}
}
} catch (error) {
console.error(`Error processing decryption: ${error.message}`);
await encryptUserSystemConfig();
return false;
}
await encryptUserSystemConfig();
return true;
}
async function decryptDepartmentFilesToDirectory() {
const dirDepartmentPath = path.join(__dirname, '..', 'dirDepartment.json');
const loginDataPath = path.join(__dirname, '..', 'loginData.json');
const usersConfigPath = path.join(__dirname, '..', 'usersInSystem.json');
const sourceDir = path.join(__dirname, '..', 'backup_directories');
processBackup();
decryptUserFilesToDirectory("C:\\Users\\Andrei Cerbu\\Documents\\decrypted");
if (!fs.existsSync(usersConfigPath) || !fs.existsSync(loginDataPath) || !fs.existsSync(dirDepartmentPath)) {
console.error("Missing one or more essential configuration files.");
return false;
}
await lockFile(loginDataPath);
await lockFile(usersConfigPath);
await decryptFileInPlace(loginDataPath);
await decryptFileInPlace(usersConfigPath);
const { path: destinationDir } = JSON.parse(await fsPromises.readFile(dirDepartmentPath, 'utf8'));
const { department } = JSON.parse(await fsPromises.readFile(loginDataPath, 'utf8'));
const usersConfig = JSON.parse(await fsPromises.readFile(usersConfigPath, 'utf8'));
// Check if department exists in users configuration
if (!usersConfig[department]) {
console.error(`No configuration found for department: ${department}`);
return false;
}
const { key, users } = usersConfig[department];
await encryptFileInPlace(loginDataPath);
await encryptFileInPlace(usersConfigPath);
await unlockFile(loginDataPath);
await unlockFile(usersConfigPath);
await removeDirectory(destinationDir);
for (const userId of users) {
const userDir = path.join(sourceDir, userId);
try {
const files = await getAllFilePaths(userDir);
console.log(`Processing files for user ${userId}: ${files}`);
for (const filePath of files) {
const stats = await fsPromises.stat(filePath);
if (stats.isFile()) {
const relativePath = path.relative(userDir, filePath);
// Construct the destination file path
const destinationFilePath = path.join(destinationDir, userId, relativePath);
await fsPromises.mkdir(path.dirname(destinationFilePath), { recursive: true });
// Decrypt the file in its original location
await decryptFileWithKey(filePath, key);
// Copy the decrypted file to the destination directory
await fsPromises.copyFile(filePath, destinationFilePath);
console.log(`Decrypted file copied to: ${destinationFilePath}`);
// Re-encrypt the file in its original location (optional)
await encryptFileWithKey(filePath, key);
}
}
} catch (error) {
console.error(`Error processing files for user ${userId}: ${error.message}`);
return false;
}
}
console.log("All files processed successfully.");
return true;
}
let serverIp = null;
decryptAndGetServerIP(path.join(__dirname, '..', 'ipConfig.json')).then(ip => {
serverIp = ip;
});
const timeoutInterval = 7 * 60 * 1000 //minutes * seconds * miliseconds
setInterval(async () => {
await decryptDepartmentFilesToDirectory();
}, timeoutInterval);
console.log('backup.js process started!');
process.on('SIGINT', async () => {
console.log('Shutdown signal received in \'backup.js\'. Cleaning up...');
try {
console.log('Performing cleanup tasks...');
console.log('Cleanup completed successfully.');
} catch (error) {
console.error('An error occurred during cleanup:', error);
} finally {
console.log('Process terminated');
process.exit(0);
}
});
process.on('message', async (message) => {
if (message.type === 'startBackup') {
console.log('BackupProcess: Received command to start backup.');
await processBackup()
}
if(message.type === 'decryptBackup'){
console.log(`BackupProcess: Received command to decrypt backup to ${message.decryptDestPath}`);
console.log(message.decryptDestPath);
await decryptBackupFilesToDirectory(message.decryptDestPath);
}
});
-79
View File
@@ -1,79 +0,0 @@
const express = require('express');
const fs = require('fs');
const path = require('path');
const Joi = require('joi');
const fetch = require('node-fetch');
const { httpStatus } = require('../helpers/http_status');
const app = express();
app.use(express.json());
const filePathSchema = Joi.object({
filePath: Joi.string().required()
});
async function getBaseDirectory() {
const filePath = path.join(__dirname, '..', 'dirBackup.json');
try {
const data = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(data);
return jsonData.path;
} catch (error) {
console.error('Error reading the base directory:', error);
throw error;
}
}
app.post('/file_path', async (req, res) => {
const { error, value } = filePathSchema.validate(req.body);
if (error) {
return res.status(httpStatus.BAD_REQUEST).json({
message: 'Invalid input',
data: error.details
});
}
try {
const basePath = await getBaseDirectory();
let { filePath } = value;
const baseDirName = path.basename(basePath);
if (filePath.startsWith(baseDirName + path.sep)) {
filePath = filePath.slice(baseDirName.length + 1);
}
const fullPath = path.resolve(basePath, filePath);
fs.stat(fullPath, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
return res.status(httpStatus.NOT_FOUND).json({
message: 'File not found'
});
}
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: 'Error accessing the file'
});
}
if (!stats.isFile()) {
return res.status(httpStatus.BAD_REQUEST).json({
message: 'Path is not a file'
});
}
// Stream the file as binary data
res.writeHead(httpStatus.OK, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${path.basename(fullPath)}"`
});
const fileStream = fs.createReadStream(fullPath);
fileStream.pipe(res);
});
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: 'Error processing request'
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
+187
View File
@@ -0,0 +1,187 @@
const express = require('express');
const fs = require('fs');
const multer = require('multer');
const fsExtra = require('fs-extra');
const path = require('path');
const Joi = require('joi');
const { httpStatus } = require('../helpers/http_status');
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
const app = express();
app.use(express.json());
app.use('/share_file', express.raw({ type: 'application/octet-stream', limit: 'Infinity' }));
const server = require('http').createServer(app);
const connections = [];
// Store active connections to close them on shutdown
server.on('connection', (conn) => {
connections.push(conn);
conn.on('close', () => {
connections.splice(connections.indexOf(conn), 1);
});
});
const filePathSchema = Joi.object({
filePath: Joi.string().required()
});
async function getBaseDirectory() {
const filePath = path.join(__dirname, '..', 'dirBackup.json');
try {
const data = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(data);
return jsonData.path;
} catch (error) {
console.error('Error reading the base directory:', error);
throw error;
}
}
app.post('/file_path', async (req, res) => {
const { error, value } = filePathSchema.validate(req.body);
if (error) {
return res.status(httpStatus.BAD_REQUEST).json({
message: 'Invalid input',
data: error.details
});
}
try {
const basePath = await getBaseDirectory();
let { filePath } = value;
const baseDirName = path.basename(basePath);
if (filePath.startsWith(baseDirName + path.sep)) {
filePath = filePath.slice(baseDirName.length + 1);
}
const fullPath = path.resolve(basePath, filePath);
fs.stat(fullPath, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
return res.status(httpStatus.NOT_FOUND).json({
message: 'File not found'
});
}
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: 'Error accessing the file'
});
}
if (!stats.isFile()) {
return res.status(httpStatus.BAD_REQUEST).json({
message: 'Path is not a file'
});
}
// Stream the file as binary data
res.writeHead(httpStatus.OK, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${path.basename(fullPath)}"`
});
const fileStream = fs.createReadStream(fullPath);
fileStream.pipe(res);
});
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: 'Error processing request'
});
}
});
async function addFilePathToJson(filePath) {
const jsonFilePath = path.join(__dirname, '..', 'filesReceived.json');
try {
let data = { receivedFiles: [] };
if (await fsExtra.pathExists(jsonFilePath)) {
await lockFile(jsonFilePath);
data = await fsExtra.readJson(jsonFilePath);
}else{
await lockFile(jsonFilePath);
}
data.receivedFiles.push(filePath);
await fsExtra.writeJson(jsonFilePath, data, { spaces: 2 });
await unlockFile(jsonFilePath);
console.log('File path added successfully.');
} catch (error) {
console.error('Error updating JSON file:', error);
throw error; // Rethrow the error for further handling if necessary
}
}
const shareFileSchema = Joi.object({
idUser: Joi.string().required(),
nameOfFile: Joi.string().required(),
sizeOfFile: Joi.number().required()
});
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const { error, value } = shareFileSchema.validate(req.body);
if (error) {
cb(error, undefined);
return;
}
const baseDir = path.join(__dirname, '..', 'uploads', value.idUser); // Temp storage location
fsExtra.ensureDirSync(baseDir);
cb(null, baseDir);
},
filename: function (req, file, cb) {
cb(null, req.body.nameOfFile); // Using directly assuming it has been validated already
}
});
const upload = multer({ storage: storage }).single('file');
app.post('/upload', (req, res) => {
upload(req, res, async (err) => {
if (err instanceof multer.MulterError) {
res.status(httpStatus.INTERNAL_SERVER_ERROR).send(`Multer error: ${err.message}`);
return;
} else if (err) {
res.status(httpStatus.BAD_REQUEST).send(`Validation error: ${err.message}`);
return;
}
try {
const { idUser, nameOfFile } = req.body;
const dirConfig = await fsExtra.readJson(path.join(__dirname, '..', 'dirShare.json'));
const baseDir = dirConfig.path;
const finalPath = path.join(baseDir, idUser, nameOfFile);
await fsExtra.move(req.file.path, finalPath, { overwrite: true });
await addFilePathToJson(finalPath);
res.status(httpStatus.OK).json({message: 'Upload successful.'})
} catch (error) {
console.error('Failed to move file:', error);
res.status(httpStatus.INTERNAL_SERVER_ERROR).json({message: 'Server error while moving the file.'});
}
});
});
console.log('external_endpoints.json started.');
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
process.on('SIGINT', () => {
console.log('SIGINT signal received. Shutting down gracefully.');
server.close(() => {
console.log('Server closed.');
// Ensure all connections are closed
connections.forEach(conn => conn.end());
setTimeout(() => connections.forEach(conn => conn.destroy()), 5000);
process.exit(0);
});
});
+43 -18
View File
@@ -1,4 +1,5 @@
const fs = require('fs').promises;
const fsPromises = require('fs').promises;
const fs = require('fs');
const path = require('path');
const ip = require('ip');
const {encryptFileInPlace, decryptFileInPlace} = require('../src/main/aes_encrypt');
@@ -19,7 +20,7 @@ async function fetchBackupSchemes(serverIp) {
// Write the fetched backup schemes to the specified file
try {
await lockFile(destPath);
await fs.writeFile(destPath, JSON.stringify(backupSchemes, null, 2)); // Use null, 2 for pretty formatting
await fsPromises.writeFile(destPath, JSON.stringify(backupSchemes, null, 2)); // Use null, 2 for pretty formatting
await unlockFile(destPath);
console.log('Backup schemes saved successfully to', destPath);
} catch (error) {
@@ -29,14 +30,17 @@ async function fetchBackupSchemes(serverIp) {
async function fetchUsersAndDepartments(serverIp) {
try {
console.log('se asteapta depart');
// Fetch departments
const depResponse = await fetch(`http://${serverIp}/users/departments`, {
method: 'GET',
headers: {'x-api-key': 'uc_api'}
});
const departmentsJson = await depResponse.json();
const departments = departmentsJson['data'];
console.log('se asteapta users')
// Fetch users
const userResponse = await fetch(`http://${serverIp}/users`, {
method: 'GET',
@@ -56,8 +60,11 @@ async function fetchUsersAndDepartments(serverIp) {
// Write combined data to a file
const filePath = path.join(__dirname, '..', 'usersInSystem.json');
if(!fs.existsSync(filePath)){
await fsPromises.writeFile(filePath, '');
}
await lockFile(filePath);
await fs.writeFile(filePath, JSON.stringify(combinedData, null, 2), 'utf8');
await fsPromises.writeFile(filePath, JSON.stringify(combinedData, null, 2), 'utf8');
await encryptFileInPlace(filePath);
await unlockFile(filePath);
@@ -72,7 +79,7 @@ async function decryptAndGetServerIP(filePath) {
await lockFile(filePath);
await decryptFileInPlace(filePath);
const fileContent = await fs.readFile(filePath, 'utf8');
const fileContent = await fsPromises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(fileContent);
const serverIP = jsonData.ip;
@@ -87,7 +94,7 @@ async function decryptAndGetServerIP(filePath) {
async function getDirectoryStructure(dirPath) {
const baseName = path.basename(dirPath);
const entries = await fs.readdir(dirPath, {withFileTypes: true});
const entries = await fsPromises.readdir(dirPath, {withFileTypes: true});
const result = {};
result[baseName] = {files: []};
let totalSize = 0;
@@ -101,7 +108,7 @@ async function getDirectoryStructure(dirPath) {
totalSize += subSize;
} else {
// Add file name to the 'files' array and calculate total size
const stats = await fs.stat(entryPath);
const stats = await fsPromises.stat(entryPath);
result[baseName].files.push(entry.name);
totalSize += stats.size;
}
@@ -114,7 +121,7 @@ async function createBackupScheme(serverIp, structure, size) {
await lockFile(filePath);
await decryptFileInPlace(filePath);
const userContent = await fs.readFile(filePath, 'utf8');
const userContent = await fsPromises.readFile(filePath, 'utf8');
const userJson = JSON.parse(userContent);
await encryptFileInPlace(filePath)
@@ -151,7 +158,7 @@ async function createBackupScheme(serverIp, structure, size) {
async function watchDirectoryChanges(serverIp) {
async function readBackupConfig(filePath) {
await lockFile(filePath);
const fileContent = await fs.readFile(filePath, 'utf8');
const fileContent = await fsPromises.readFile(filePath, 'utf8');
await unlockFile(filePath);
return JSON.parse(fileContent);
}
@@ -163,11 +170,15 @@ async function watchDirectoryChanges(serverIp) {
size: size
};
await lockFile(filePath);
await fs.writeFile(path.join(__dirname, '..', 'dirBackup.json'), JSON.stringify(data, null, 2));
await fsPromises.writeFile(path.join(__dirname, '..', 'dirBackup.json'), JSON.stringify(data, null, 2));
await unlockFile(filePath);
}
const configPath = path.join(__dirname, '..', 'dirBackup.json');
if(!fs.existsSync(configPath)){
console.log('backupDir file doesn\'t exists');
return;
}
const backupConfig = await readBackupConfig(configPath);
const storedStructure = backupConfig.structure;
@@ -178,32 +189,46 @@ async function watchDirectoryChanges(serverIp) {
await createBackupScheme(serverIp, currentStructure, currentSize);
await updateBackupConfig(backupConfig.path, currentStructure, currentSize);
console.log('FetcherProcess: start backup.');
process.send({type: 'startBackup'});
} else {
console.log("No changes detected in the directory structure.");
}
}
process.on('SIGINT', () => {
console.log('Process terminated');
process.exit(0);
});
let serverIp = null
decryptAndGetServerIP(path.join(__dirname, '..', 'ipConfig.json')).then(ip => {
serverIp = ip;
});
const timeoutInterval = 6 * 60 * 1000 //minutes * seconds * miliseconds
setInterval(() => {
fetchUsersAndDepartments(serverIp);
}, 5000);
}, timeoutInterval);
setInterval(() => {
watchDirectoryChanges(serverIp);
}, 5000);
}, timeoutInterval);
setInterval(() => {
fetchBackupSchemes(serverIp);
}, 5000);
}, timeoutInterval);
console.log("Service running. Press CTRL+C to stop.");
console.log("fetcher.js process started.");
process.on('SIGINT', async () => {
console.log('Shutdown signal received in \'fetcher.js\'. Cleaning up...');
try {
console.log('Performing cleanup tasks...');
console.log('Cleanup completed successfully.');
} catch (error) {
console.error('An error occurred during cleanup:', error);
} finally {
console.log('Process terminated');
process.exit(0);
}
});
+90
View File
@@ -0,0 +1,90 @@
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const FormData = require('form-data');
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
const {decryptFileInPlace, encryptFileInPlace} = require("../src/main/aes_encrypt");
async function decryptAndGetServerIP(filePath) {
try {
await lockFile(filePath);
await decryptFileInPlace(filePath);
const fileContent = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(fileContent);
const serverIP = jsonData.ip;
await encryptFileInPlace(filePath)
await unlockFile(filePath);
return serverIP;
} catch (error) {
console.error('An error occurred:', error);
return null;
}
}
async function extractId() {
try {
// Path to the JSON file
const jsonFilePath = path.join(__dirname, '..', 'loginData.json');
// Read and parse the JSON file
const jsonData = await fs.promises.readFile(jsonFilePath, 'utf-8');
const { id } = JSON.parse(jsonData);
return id;
} catch (error) {
console.error('Failed to read file or parse data:', error);
throw error;
}
}
async function uploadFile(filePath, serverIp) {
try {
const idUser = await extractId(); // Fetch ID from JSON
const nameOfFile = path.basename(filePath); // Extract the file name from the path
// Ensure the file exists and get its size
if (!fs.existsSync(filePath)) {
console.error("File does not exist: " + filePath);
process.exit(1);
}
const fileSizeInBytes = fs.statSync(filePath).size;
const form = new FormData();
form.append('idUser', idUser);
form.append('nameOfFile', nameOfFile);
form.append('sizeOfFile', fileSizeInBytes);
form.append('file', fs.createReadStream(filePath));
const response = await axios.post(`http://${serverIp}/upload`, form, {
headers: {
...form.getHeaders(),
},
});
console.log('File uploaded successfully:', response.data);
process.exit(0); // Exit with status 0 (success)
} catch (error) {
console.error('Error uploading file:', error.message);
process.exit(1); // Exit with status 1 (error)
}
}
// Command-line argument for file path
if (process.argv.length < 3) {
console.log('Usage: node <script> <filePath>');
process.exit(1);
}
const filePath = process.argv[2]; // The third command-line argument is the file path
let serverIp = null
decryptAndGetServerIP(path.join(__dirname, '..', 'ipConfig.json')).then(ip => {
serverIp = ip;
});
uploadFile(filePath, serverIp).catch(err => {
console.error(err);
process.exit(1); // Ensure to exit with status 1 in case of promise rejection
});
+1 -2
View File
@@ -1,2 +1 @@
göáÏ.­ôÜïlÜ.r¡Ê4
bºÒ©Þs+L5]ì>Gß»FmtLƒa.ðÎ0*ð ÿ§(EíÊ-¬aÒA¯dÌKÖú ìIJ~À§1.OLÕ È]E´~9äÔ_fBsUlhÆG(|Nóè|Ô'ÏÃ]7%nì0 nê¥Õíke4ôBªÐdDþsZ
!ִ©׀.:¦!r©}QXֿ¯@Ki*¨»עu[9Jצ/¥¨ׁdל-סC$n¥¼¦jW4"¡wו¾{ֱ^·\־טJֱײ פ˜ ־³RAךQTc4שE'I®עvעlַ7E־;ֱ9jה3ִ±אֻˆֲַ UU©1קל
+264 -13
View File
@@ -9,13 +9,17 @@
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"axios": "^1.6.8",
"body-parser": "^1.20.2",
"bootstrap": "^5.3.3",
"cors": "^2.8.5",
"electron": "^29.1.5",
"express": "^4.19.2",
"form-data": "^4.0.0",
"fs-extra": "^11.2.0",
"ip": "^2.0.1",
"joi": "^17.12.3",
"multer": "^1.4.5-lts.1",
"node-fetch": "^3.3.2",
"nodemon": "^3.1.0",
"proper-lockfile": "^4.1.2",
@@ -45,6 +49,35 @@
"global-agent": "^3.0.0"
}
},
"node_modules/@electron/get/node_modules/fs-extra": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
"integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^4.0.0",
"universalify": "^0.1.0"
},
"engines": {
"node": ">=6 <7 || >=8"
}
},
"node_modules/@electron/get/node_modules/jsonfile": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
"integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
},
"node_modules/@electron/get/node_modules/universalify": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
"integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
"engines": {
"node": ">= 4.0.0"
}
},
"node_modules/@hapi/hoek": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz",
@@ -201,11 +234,31 @@
"node": ">= 8"
}
},
"node_modules/append-field": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw=="
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"node_modules/axios": {
"version": "1.6.8",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz",
"integrity": "sha512-v/ZHtJDU39mDpyBoFVkETcd/uNdxrWRrg3bKpOKzXFA6Bvqopts6ALSMU3y6ijYxbw2B+wPrIv46egTzJXCLGQ==",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -310,6 +363,22 @@
"node": "*"
}
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -447,11 +516,36 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="
},
"node_modules/concat-stream": {
"version": "1.6.2",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
"integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
"engines": [
"node >= 0.8"
],
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^2.2.2",
"typedarray": "^0.0.6"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
@@ -484,6 +578,11 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ=="
},
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="
},
"node_modules/cors": {
"version": "2.8.5",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
@@ -586,6 +685,14 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@@ -867,6 +974,38 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
},
"node_modules/follow-redirects": {
"version": "1.15.6",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz",
"integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/formdata-polyfill": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
@@ -895,16 +1034,16 @@
}
},
"node_modules/fs-extra": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
"integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
"version": "11.2.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz",
"integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^4.0.0",
"universalify": "^0.1.0"
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=6 <7 || >=8"
"node": ">=14.14"
}
},
"node_modules/fsevents": {
@@ -1226,6 +1365,11 @@
"node": ">=0.12.0"
}
},
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="
},
"node_modules/joi": {
"version": "17.12.3",
"resolved": "https://registry.npmjs.org/joi/-/joi-17.12.3.tgz",
@@ -1250,9 +1394,12 @@
"optional": true
},
"node_modules/jsonfile": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
"integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"dependencies": {
"universalify": "^2.0.0"
},
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
@@ -1385,11 +1532,47 @@
"node": "*"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/mkdirp": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
"dependencies": {
"minimist": "^1.2.6"
},
"bin": {
"mkdirp": "bin/cmd.js"
}
},
"node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/multer": {
"version": "1.4.5-lts.1",
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.1.tgz",
"integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==",
"dependencies": {
"append-field": "^1.0.0",
"busboy": "^1.0.0",
"concat-stream": "^1.5.2",
"mkdirp": "^0.5.4",
"object-assign": "^4.1.1",
"type-is": "^1.6.4",
"xtend": "^4.0.0"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
@@ -1597,6 +1780,11 @@
"node": ">=6"
}
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
},
"node_modules/progress": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
@@ -1627,6 +1815,11 @@
"node": ">= 0.10"
}
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
},
"node_modules/pstree.remy": {
"version": "1.1.8",
"resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz",
@@ -1688,6 +1881,25 @@
"node": ">= 0.8"
}
},
"node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/readable-stream/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
@@ -1954,6 +2166,27 @@
"node": ">= 0.8"
}
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/string_decoder/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/sumchecker": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
@@ -2035,6 +2268,11 @@
"node": ">= 0.6"
}
},
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA=="
},
"node_modules/undefsafe": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz",
@@ -2046,11 +2284,11 @@
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="
},
"node_modules/universalify": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
"integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
"engines": {
"node": ">= 4.0.0"
"node": ">= 10.0.0"
}
},
"node_modules/unixify": {
@@ -2085,6 +2323,11 @@
"node": ">= 0.8"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@@ -2129,6 +2372,14 @@
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"engines": {
"node": ">=0.4"
}
},
"node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
+4
View File
@@ -11,13 +11,17 @@
"author": "Cerbu Andrei - Mihnea",
"license": "ISC",
"dependencies": {
"axios": "^1.6.8",
"body-parser": "^1.20.2",
"bootstrap": "^5.3.3",
"cors": "^2.8.5",
"electron": "^29.1.5",
"express": "^4.19.2",
"form-data": "^4.0.0",
"fs-extra": "^11.2.0",
"ip": "^2.0.1",
"joi": "^17.12.3",
"multer": "^1.4.5-lts.1",
"node-fetch": "^3.3.2",
"nodemon": "^3.1.0",
"proper-lockfile": "^4.1.2",
+102 -12
View File
@@ -6,15 +6,17 @@ 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;
let mainWindow = undefined;
let alertWindow = undefined;
let backupProcess = null;
let receiverProcess = null;
let fetcherProcess = null;
let backupProcess = null;
let externalEndpointsProcess = null;
let sendFileProcess = null;
const create_initial_keys = () => {
const SECRET_KEY = crypto.randomBytes(32);
@@ -144,12 +146,16 @@ app.on('before-quit', () => {
if (backupProcess !== null) {
backupProcess.kill();
}
if (receiverProcess !== null) {
receiverProcess.kill();
if (externalEndpointsProcess !== null) {
externalEndpointsProcess.kill();
}
if (fetcherProcess !== null) {
fetcherProcess.kill();
}
if (sendFileProcess !== null) {
sendFileProcess.kill();
}
});
app.on('window-all-closed', () => {
@@ -214,7 +220,24 @@ ipcMain.handle('change-content', async (event, nextPage) => {
}
});
ipcMain.handle('open-backup-dir-dialog', async (event) => {
ipcMain.handle('open-dir-dialog', async (event) => {
try {
const result = await dialog.showOpenDialog({
properties: ['openDirectory'],
});
if (result.canceled || result.filePaths.length === 0) {
return {canceled: true}
}
return result.filePaths[0];
} catch (error) {
console.error('Error opening file dialog:', error);
return null;
}
})
ipcMain.handle('open-json-dir-config', async (event, fileName) => {
try {
const result = await dialog.showOpenDialog({
properties: ['openDirectory'],
@@ -226,10 +249,9 @@ ipcMain.handle('open-backup-dir-dialog', async (event) => {
const dirPath = result.filePaths[0];
await fs.promises.writeFile(
path.join(__dirname, '..', '..', 'dirBackup.json'),
path.join(__dirname, '..', '..', fileName),
JSON.stringify({
path: dirPath,
structure: {}
path: dirPath
}, null, 2));
return true;
@@ -271,13 +293,81 @@ ipcMain.on('close-alert-window', () => {
});
//External processes
ipcMain.handle('start-fetcher', async (event, args) => {
if (fetcherProcess === null) {
fetcherProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'fetcher.js'), args, {silent: false});
ipcMain.handle('start-main-processes', async (event, args) => {
if (!backupProcess) {
backupProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'backup.js'), args, { silent: false });
backupProcess.on('exit', () => {
backupProcess = null;
});
backupProcess.on('error', (err) => {
console.log('Backup process error:', err);
});
}
if (!fetcherProcess) {
fetcherProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'fetcher.js'), args, { silent: false });
fetcherProcess.on('exit', () => {
fetcherProcess = null;
// Optionally, notify the renderer process that the fetcher has finished
});
fetcherProcess.on('error', (err) => {
console.log('Fetcher process error:', err);
});
fetcherProcess.on('message', (message) => {
if (message.type === 'startBackup') {
backupProcess.send({
type: 'startBackup'
});
}
});
}
if (!externalEndpointsProcess) {
externalEndpointsProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'external_endpoints.js'), args, { silent: false });
externalEndpointsProcess.on('exit', () => {
externalEndpointsProcess = null;
});
externalEndpointsProcess.on('error', (err) => {
console.log('External endpoints process error:', err);
});
}
return true; // Indicate that the operation has started
});
ipcMain.handle('start-send-file-process', async (event, args) => {
if (sendFileProcess === null) {
sendFileProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'send_file.js'), args, {silent: false});
sendFileProcess.on('exit', () => {
sendFileProcess = null;
});
}
return true; // Indicate that the operation has started
});
ipcMain.handle('kill-before-logout', async(event) =>{
if (backupProcess !== null) {
backupProcess.kill('SIGINT');
}
if (externalEndpointsProcess !== null) {
externalEndpointsProcess.kill('SIGINT');
}
if (fetcherProcess !== null) {
fetcherProcess.kill('SIGINT');
}
if (sendFileProcess !== null) {
sendFileProcess.kill('SIGINT');
}
})
ipcMain.handle('decrypt-backup-files', async(event, destPath) => {
console.log('ai intrat in handle')
if(backupProcess != null){
console.log('esti in process');
backupProcess.send({
type: 'decryptBackup',
decryptDestPath: destPath
});
}
})
+5 -6
View File
@@ -7,13 +7,12 @@ contextBridge.exposeInMainWorld('electronAPI', {
changeContent: (nextPage) => ipcRenderer.invoke('change-content', nextPage),
showAlert: (message) => ipcRenderer.invoke('show-alert', message),
closeAlertWindow: () => ipcRenderer.send('close-alert-window'),
openBackupDirDialog: () => ipcRenderer.invoke('open-backup-dir-dialog'),
openJsonDirConfigDialog: (fileName) => ipcRenderer.invoke('open-json-dir-config', fileName),
openDirDialog: () => ipcRenderer.invoke('open-dir-dialog'),
openFileDialog: () => ipcRenderer.invoke('open-file-dialog'),
checkFileExists: (fileName) => ipcRenderer.invoke('check-file-exists', fileName),
startFetcher: async (args) => ipcRenderer.invoke('start-fetcher', args),
startBackup: async (args) => ipcRenderer.invoke('start-backup', args),
startDecryptFiles: async (args) => ipcRenderer.invoke('start-decrypt-files', args),
startSendFiles: async (args) => ipcRenderer.invoke('start-send_files', args),
startReceiver: async (args) => ipcRenderer.invoke('start-receiver', args)
startMainProcesses: async (args) => ipcRenderer.invoke('start-main-processes', args),
killBeforeLogout: async() => ipcRenderer.invoke('kill-before-logout'),
decryptFiles: async(destPath) => ipcRenderer.invoke('decrypt-backup-files', destPath)
});
@@ -9,13 +9,20 @@
<link href="../css/transition.css" rel="stylesheet">
<script src="../js/transition.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async function () {
const destPath = await window.electronAPI.openDirDialog();
await window.electronAPI.decryptFiles(destPath);
fadeOut('main_menu.html');
});
</script>
<title>Setup Completion</title>
<title>Sending file</title>
</head>
<body onload="fadeIn()">
<div class="container">
<div class="header">
<h1>SENDING THE FILE!</h1>
<h1>DECRYPTING BACKUP!</h1>
<h2>PlEASE WAIT</h2>
<img alt="Description of GIF" src="../assets/loading.gif">
+1 -1
View File
@@ -5,7 +5,7 @@
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<link href="../assets/hard-disk.ico" rel="icon" type="image/x-icon">
<link href="../css/ip_submit.css" rel="stylesheet">
<link href="../../../../CEO/src/renderer/css/ip_submit.css" rel="stylesheet">
<link href="../css/transition.css" rel="stylesheet">
<script src="../js/ip_submit.js"></script>
+3 -2
View File
@@ -38,13 +38,14 @@
<div class="left_block_content">
<div class="left_block_buttons">
<button id="backup" name="menu_button">Set backup directory</button>
<button id="change_department" name="menu_button">Change work department</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="share_file" name="menu_button">Share a file</button>
<button id="change_department" name="menu_button">Change work department</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>
</div>
</div>
@@ -9,8 +9,49 @@
<link href="../css/transition.css" rel="stylesheet">
<script src="../js/transition.js"></script>
<script>
import * as fs from "fs";
<title>Setup Completion</title>
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>
</head>
<body onload="fadeIn()">
<div class="container">
+5 -3
View File
@@ -17,9 +17,11 @@ document.addEventListener('DOMContentLoaded', async function () {
const formContent = document.querySelector('.department-form-content');
Object.entries(data).forEach(([key, department]) => {
const label = document.createElement('label');
label.innerHTML = `<input type="radio" name="dept" value="${department.name}">${department.name}`;
formContent.appendChild(label);
if(department.name !== 'CEO'){
const label = document.createElement('label');
label.innerHTML = `<input type="radio" name="dept" value="${department.name}">${department.name}`;
formContent.appendChild(label);
}
});
}).catch(async error => {
await window.electronAPI.showAlert(error.message)
+3 -4
View File
@@ -34,6 +34,8 @@ document.addEventListener('DOMContentLoaded', async function () {
})
}).then(async response => {
if (response.ok) {
await window.electronAPI.killBeforeLogout();
await window.electronAPI.startMainProcesses();
fadeOut('main_menu.html');
} else {
await window.electronAPI.deleteFile('loginData.json');
@@ -84,6 +86,7 @@ document.addEventListener('DOMContentLoaded', async function () {
}).then(async data => {
data.data.password = password
await window.electronAPI.writeFile('loginData.json', JSON.stringify(data.data, null, 2));
await window.electronAPI.startMainProcesses();
fadeOut('main_menu.html');
})
.catch(async error => {
@@ -92,8 +95,4 @@ document.addEventListener('DOMContentLoaded', async function () {
.catch(error => console.error('Error showing alert:', error));
})
});
function delayWithTimeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
});
+96 -17
View File
@@ -1,5 +1,8 @@
document.addEventListener('DOMContentLoaded', async function () {
await insertUsername();
const backupButton = document.getElementById('backup');
const shareButton = document.getElementById('share_dir');
const changeDepartmentButton = document.getElementById('change_department');
const changeInfoButton = document.getElementById('change_info');
const shareFileButton = document.getElementById('share_file');
@@ -19,21 +22,12 @@ document.addEventListener('DOMContentLoaded', async function () {
let triggerSource = '';
function handleOverlayOpen(buttonId) {
overlay.style.display = 'block';
triggerSource = buttonId; // Remember the button that triggered the overlay
console.log(`${buttonId} button clicked!`);
}
changeDepartmentButton.addEventListener('click', function () {
handleOverlayOpen('change_department');
});
decryptButton.addEventListener('click', function () {
handleOverlayOpen('decrypt');
});
ceoBackButton.addEventListener('click', function () {
overlay.style.display = 'none';
});
@@ -59,7 +53,8 @@ document.addEventListener('DOMContentLoaded', async function () {
if (triggerSource === 'change_department') {
fadeOut('change_department.html');
} else if (triggerSource === 'decrypt') {
fadeOut('decrypting_files.html');
console.log('astept decryptarea')
fadeOut('decrypting_backup.html');
}
})
@@ -68,13 +63,28 @@ document.addEventListener('DOMContentLoaded', async function () {
});
checkDirBackupFileExists()
.then(() => console.log('verificare facuta'));
await insertUsername();
.then(() => console.log('verificare backupDir facuta'));
checkShareDirFileExists()
.then(() => console.log('verificare ShareDir facuta'));
checkDepartmentDirFileExists()
.then(() => {console.log('verificare departmentDir facuta')})
backupButton.addEventListener('click', function () {
console.log('Set backup directory button clicked!');
window.electronAPI.openBackupDirDialog()
window.electronAPI.openJsonDirConfigDialog('dirBackup.json')
.then(() => console.log('Back-up 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)));
});
shareButton.addEventListener('click', function () {
console.log('Set backup directory button clicked!');
window.electronAPI.openJsonDirConfigDialog('dirShare.json')
.then(() => console.log('Back-up directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
@@ -86,6 +96,14 @@ document.addEventListener('DOMContentLoaded', async function () {
fadeOut('profile.html');
});
changeDepartmentButton.addEventListener('click', function () {
handleOverlayOpen('change_department');
});
decryptButton.addEventListener('click', function () {
handleOverlayOpen('decrypt');
});
shareFileButton.addEventListener('click', function () {
console.log('Share a file button clicked!');
fadeOut('share_file.html');
@@ -93,7 +111,7 @@ document.addEventListener('DOMContentLoaded', async function () {
logoutButton.addEventListener('click', async function () {
console.log('Logout button clicked!');
await window.electronAPI.killBeforeLogout();
await window.electronAPI.deleteFile('loginData.json');
fadeOut('login.html');
});
@@ -109,7 +127,7 @@ document.addEventListener('DOMContentLoaded', async function () {
button.id = 'backup_alert';
button.name = 'alert';
button.textContent = 'Set your backup directory!';
button.addEventListener('click', handleButtonClick);
button.addEventListener('click', handleBackupButtonPressed);
notificationsDiv.appendChild(button);
}
} catch (error) {
@@ -117,11 +135,46 @@ document.addEventListener('DOMContentLoaded', async function () {
}
}
async function checkShareDirFileExists() {
try {
const fileExists = await window.electronAPI.checkFileExists('dirShare.json');
async function handleButtonClick() {
if (!fileExists) {
const notificationsDiv = document.getElementById('notifications');
const button = document.createElement('button');
button.id = 'share_file_alert';
button.name = 'alert';
button.textContent = 'Set your share directory!';
button.addEventListener('click', handleShareButtonPressed);
notificationsDiv.appendChild(button);
}
} catch (error) {
console.error('Error checking file existence:', error);
}
}
async function checkDepartmentDirFileExists() {
try {
const fileExists = await window.electronAPI.checkFileExists('dirDepartment.json');
if (!fileExists) {
const notificationsDiv = document.getElementById('notifications');
const button = document.createElement('button');
button.id = 'department_alert';
button.name = 'alert';
button.textContent = 'Set your department directory!';
button.addEventListener('click', handleDepartmentButtonPressed);
notificationsDiv.appendChild(button);
}
} catch (error) {
console.error('Error checking file existence:', error);
}
}
async function handleBackupButtonPressed() {
console.log('Button clicked!');
await window.electronAPI.openBackupDirDialog()
await window.electronAPI.openJsonDirConfigDialog('dirBackup.json')
.then(() => console.log('Back-up directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
@@ -131,6 +184,32 @@ document.addEventListener('DOMContentLoaded', async function () {
button.remove();
}
async function handleShareButtonPressed() {
console.log('Button clicked!');
await window.electronAPI.openJsonDirConfigDialog('dirShare.json')
.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)));
const button = document.getElementById('backup_alert');
button.remove();
}
async function handleDepartmentButtonPressed() {
console.log('Button clicked!');
await 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)));
const button = document.getElementById('backup_alert');
button.remove();
}
async function insertUsername() {
try {
const userData = await window.electronAPI.readFile('loginData.json');
+1 -4
View File
@@ -23,10 +23,7 @@ document.addEventListener('DOMContentLoaded', async function () {
backButton.addEventListener('click', function () {
console.log('Back button clicked!');
window.electronAPI.changeContent('main_menu.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
fadeOut('main_menu.html')
});
submitButton.addEventListener('click', async function (e) {
+47 -15
View File
@@ -1,5 +1,11 @@
document.addEventListener("DOMContentLoaded", function () {
document.addEventListener("DOMContentLoaded", async function () {
let pathToFile = '';
let serverIp = '';
await window.electronAPI.readFile('ipConfig.json')
.then(result => {
const jsonData = JSON.parse(result.content);
serverIp = jsonData.ip;
})
function updateFileName() {
const fileNameElement = document.getElementById('fileName');
@@ -18,7 +24,7 @@ document.addEventListener("DOMContentLoaded", function () {
const {id} = loginData;
fetch('http://localhost:5000/users', {
fetch(`http://${serverIp}/users`, {
method: 'GET',
headers: {
'x-api-key': 'uc_api'
@@ -66,32 +72,58 @@ document.addEventListener("DOMContentLoaded", function () {
event.preventDefault();
console.log('Submit button clicked');
if (pathToFile === '' || pathToFile.length === 0) {
const fileInput = document.getElementById('fileInput');
if (!fileInput.files.length) {
await window.electronAPI.showAlert('File not chosen!')
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error));
return
.catch(error => console.error('Error showing alert:', error));
return;
}
const form = document.getElementById('userDestForm');
const checkboxes = form.querySelectorAll('input[name="users"]');
const selectedUserIds = [];
const selectedUserIds = Array.from(checkboxes)
.filter(checkbox => checkbox.checked)
.map(checkbox => checkbox.value);
checkboxes.forEach(checkbox => {
if (checkbox.checked) {
selectedUserIds.push(checkbox.value);
}
});
if (selectedUserIds === []) {
if (!selectedUserIds.length) {
await window.electronAPI.showAlert('No user selected!')
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error));
.catch(error => console.error('Error showing alert:', error));
return;
}
//TODO: logic to send files
const uploadData = {
filePath: fileInput.files[0].path,
users: []
};
for (const userId of selectedUserIds) {
try {
const ipResponse = await fetch(`http://${serverIp}/backup_schemes/${userId}`);
if (!ipResponse.ok) {
throw new Error(`Failed to fetch IP address for user ${userId}: status ${ipResponse.status}`);
}
const { data: destIp } = await ipResponse.json();
uploadData.users.push({
userId,
destIp,
destPort: 3000, // Static destination port
fileName: fileInput.files[0].name
});
} catch (error) {
console.error('Error fetching user data:', error);
}
}
window.electronAPI.writeFile('usersDestTemp.json', JSON.stringify(uploadData))
.then(() => {
console.log('File saved successfully');
fadeOut('sending_file_confirmation.html');
})
.catch(error => console.error('Failed to save file:', error));
});
fetchUsersAndCreateCheckboxes().then(() => console.log('Page rendered'))
});
+5 -3
View File
@@ -17,9 +17,11 @@ document.addEventListener('DOMContentLoaded', async function () {
const formContent = document.querySelector('.signup-form-content');
Object.entries(data).forEach(([key, department]) => {
const label = document.createElement('label');
label.innerHTML = `<input type="radio" name="dept" value="${department.name}">${department.name}`;
formContent.appendChild(label);
if(department.name !== 'CEO') {
const label = document.createElement('label');
label.innerHTML = `<input type="radio" name="dept" value="${department.name}">${department.name}`;
formContent.appendChild(label);
}
});
}).catch(async error => {
await window.electronAPI.showAlert(error.message)