This commit is contained in:
andrei-mihnea-cerbu
2024-04-25 00:29:16 +03:00
parent e47a991d72
commit 5ebdc1b69a
15 changed files with 327 additions and 220 deletions
+23 -13
View File
@@ -93,24 +93,35 @@ app.post('/file_path', async (req, res) => {
async function addFilePathToJson(filePath) {
const jsonFilePath = path.join(__dirname, '..', 'filesReceived.json');
let data = { receivedFiles: [] };
try {
let data = { receivedFiles: [] };
if (await fsExtra.pathExists(jsonFilePath)) {
// Check if the JSON file exists
const fileExists = await fsExtra.pathExists(jsonFilePath);
if (fileExists) {
await lockFile(jsonFilePath);
await decryptFileInPlace(jsonFilePath);
data = await fsExtra.readJson(jsonFilePath);
}else{
} else {
await fsExtra.writeJson(jsonFilePath, data, { spaces: 2 });
await lockFile(jsonFilePath);
}
data.receivedFiles.push(filePath);
if (data.receivedFiles.findIndex(existingFilePath => existingFilePath === filePath) === -1) {
data.receivedFiles.push(filePath);
}
// Write the updated data back to the file
await fsExtra.writeJson(jsonFilePath, data, { spaces: 2 });
// Unlock the file after updating
await unlockFile(jsonFilePath);
await encryptFileInPlace(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
await encryptFileInPlace(jsonFilePath);
await unlockFile(jsonFilePath);
}
}
@@ -119,18 +130,16 @@ app.use('/share_file', express.raw({
limit: '50mb'
}));
async function decryptAndGetShareDir(filePath) {
async function getShareDir(filePath) {
try {
await lockFile(filePath);
await decryptFileInPlace(filePath);
const fileContent = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(fileContent);
const serverIP = jsonData.path;
const path = jsonData.path;
await encryptFileInPlace(filePath)
await unlockFile(filePath);
return serverIP;
return path;
} catch (error) {
console.error('An error occurred:', error);
return null;
@@ -146,18 +155,19 @@ app.post('/share_file', async (req, res) => {
// You might want to validate the metadata here
if (!idUser || !nameOfFile || !sizeOfFile) {
return res.status(httpStatus.BAD_REQUEST).send('Missing metadata headers');
return res.status(httpStatus.BAD_REQUEST).json({message: 'Missing metadata headers'});
}
// Construct the file path using the metadata
const shareDirPath = await decryptAndGetShareDir(path.join(__dirname, '..', 'shareDir.json'));
const shareDirPath = await getShareDir(path.join(__dirname, '..', 'dirShare.json'));
const baseDir = path.join(shareDirPath, idUser);
fsExtra.ensureDirSync(baseDir);
const filePath = path.join(shareDirPath, nameOfFile);
const filePath = path.join(baseDir, nameOfFile);
try {
fs.writeFileSync(filePath, req.body);
await addFilePathToJson(filePath);
res.status(httpStatus.OK).json({ message: 'Upload successful.' });
} catch (error) {
console.error('Error during file upload:', error);