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
+57 -41
View File
@@ -1,15 +1,15 @@
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 {decryptFileInPlace, encryptFileInPlace} = require("../src/main/aes_encrypt");
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 = [];
@@ -93,66 +93,82 @@ 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);
}
}
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const baseDir = path.join(__dirname, '..', 'uploads', req.body.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
app.use('/share_file', express.raw({
type: 'application/octet-stream',
limit: '50mb'
}));
async function getShareDir(filePath) {
try {
await lockFile(filePath);
const fileContent = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(fileContent);
const path = jsonData.path;
await unlockFile(filePath);
return path;
} catch (error) {
console.error('An error occurred:', error);
return null;
}
});
}
const upload = multer({ storage: storage }).single('file');
// Route for file upload
app.post('/upload', async (req, res) => {
const shareFileSchema = Joi.object({
idUser: Joi.string().required(),
nameOfFile: Joi.string().required(),
sizeOfFile: Joi.number().required()
});
app.post('/share_file', async (req, res) => {
// Extract metadata from headers
const idUser = req.headers['x-iduser'];
const nameOfFile = req.headers['x-nameoffile'];
const sizeOfFile = req.headers['x-sizeoffile'];
// You might want to validate the metadata here
if (!idUser || !nameOfFile || !sizeOfFile) {
return res.status(httpStatus.BAD_REQUEST).json({message: 'Missing metadata headers'});
}
// Construct the file path using the metadata
const shareDirPath = await getShareDir(path.join(__dirname, '..', 'dirShare.json'));
const baseDir = path.join(shareDirPath, idUser);
fsExtra.ensureDirSync(baseDir);
const filePath = path.join(baseDir, nameOfFile);
try {
const { error, value } = shareFileSchema.validate(req.body);
if (error) {
return res.status(httpStatus.BAD_REQUEST).send(`Validation error: ${error.message}`);
}
await 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(`Upload error: ${err.message}`);
return;
}
// File upload logic
res.status(httpStatus.OK).json({ message: 'Upload successful.' });
});
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);
res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ message: 'Internal server error.' });