v2.7
This commit is contained in:
@@ -1,15 +1,15 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const multer = require('multer');
|
|
||||||
const fsExtra = require('fs-extra');
|
const fsExtra = require('fs-extra');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const Joi = require('joi');
|
const Joi = require('joi');
|
||||||
const { httpStatus } = require('../helpers/http_status');
|
const { httpStatus } = require('../helpers/http_status');
|
||||||
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
|
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
|
||||||
|
const {decryptFileInPlace, encryptFileInPlace} = require("../src/main/aes_encrypt");
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
app.use('/share_file', express.raw({ type: 'application/octet-stream', limit: 'Infinity' }));
|
|
||||||
|
|
||||||
const server = require('http').createServer(app);
|
const server = require('http').createServer(app);
|
||||||
const connections = [];
|
const connections = [];
|
||||||
@@ -114,45 +114,51 @@ async function addFilePathToJson(filePath) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const storage = multer.diskStorage({
|
app.use('/share_file', express.raw({
|
||||||
destination: function (req, file, cb) {
|
type: 'application/octet-stream',
|
||||||
const baseDir = path.join(__dirname, '..', 'uploads', req.body.idUser); // Temp storage location
|
limit: '50mb'
|
||||||
fsExtra.ensureDirSync(baseDir);
|
}));
|
||||||
cb(null, baseDir);
|
|
||||||
},
|
async function decryptAndGetShareDir(filePath) {
|
||||||
filename: function (req, file, cb) {
|
try {
|
||||||
cb(null, req.body.nameOfFile); // Using directly assuming it has been validated already
|
await lockFile(filePath);
|
||||||
|
await decryptFileInPlace(filePath);
|
||||||
|
|
||||||
|
const fileContent = await fs.promises.readFile(filePath, 'utf8');
|
||||||
|
const jsonData = JSON.parse(fileContent);
|
||||||
|
const serverIP = jsonData.path;
|
||||||
|
|
||||||
|
await encryptFileInPlace(filePath)
|
||||||
|
await unlockFile(filePath);
|
||||||
|
return serverIP;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('An error occurred:', error);
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
|
||||||
const upload = multer({ storage: storage }).single('file');
|
|
||||||
|
|
||||||
// Route for file upload
|
app.post('/share_file', async (req, res) => {
|
||||||
app.post('/upload', async (req, res) => {
|
// Extract metadata from headers
|
||||||
const shareFileSchema = Joi.object({
|
const idUser = req.headers['x-iduser'];
|
||||||
idUser: Joi.string().required(),
|
const nameOfFile = req.headers['x-nameoffile'];
|
||||||
nameOfFile: Joi.string().required(),
|
const sizeOfFile = req.headers['x-sizeoffile'];
|
||||||
sizeOfFile: Joi.number().required()
|
|
||||||
});
|
// You might want to validate the metadata here
|
||||||
|
if (!idUser || !nameOfFile || !sizeOfFile) {
|
||||||
|
return res.status(httpStatus.BAD_REQUEST).send('Missing metadata headers');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Construct the file path using the metadata
|
||||||
|
const shareDirPath = await decryptAndGetShareDir(path.join(__dirname, '..', 'shareDir.json'));
|
||||||
|
const baseDir = path.join(shareDirPath, idUser);
|
||||||
|
fsExtra.ensureDirSync(baseDir);
|
||||||
|
|
||||||
|
const filePath = path.join(shareDirPath, nameOfFile);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { error, value } = shareFileSchema.validate(req.body);
|
fs.writeFileSync(filePath, 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.' });
|
res.status(httpStatus.OK).json({ message: 'Upload successful.' });
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error during file upload:', error);
|
console.error('Error during file upload:', error);
|
||||||
res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ message: 'Internal server error.' });
|
res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ message: 'Internal server error.' });
|
||||||
|
|||||||
@@ -6,22 +6,28 @@ document.addEventListener("DOMContentLoaded", async function () {
|
|||||||
|
|
||||||
const uploadPromises = uploadData.users.map(async (user) => {
|
const uploadPromises = uploadData.users.map(async (user) => {
|
||||||
try {
|
try {
|
||||||
const formData = new FormData();
|
const fileResponse = await fetch(uploadData.filePath);
|
||||||
const file = await fetch(uploadData.filePath).then(response => response.blob());
|
if (!fileResponse.ok) {
|
||||||
formData.append('file', file);
|
throw new Error(`HTTP error when trying to fetch the file: status ${fileResponse.statusText}`);
|
||||||
formData.append('idUser', user.userId);
|
}
|
||||||
formData.append('nameOfFile', user.fileName);
|
const fileBlob = await fileResponse.blob();
|
||||||
formData.append('sizeOfFile', file.size);
|
|
||||||
|
|
||||||
await timeout(5000); // Timeout to simulate delay or wait
|
await timeout(5000); // Timeout to simulate delay or wait
|
||||||
const url = `http://${user.destIp}:${user.destPort}/upload`;
|
const url = `http://${user.destIp}:${user.destPort}/share_file`;
|
||||||
|
|
||||||
const uploadResponse = await fetch(url, {
|
const uploadResponse = await fetch(url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: formData
|
headers: {
|
||||||
|
'Content-Type': 'application/octet-stream',
|
||||||
|
'X-IdUser': user.userId,
|
||||||
|
'X-NameOfFile': user.fileName,
|
||||||
|
'X-SizeOfFile': fileBlob.size
|
||||||
|
},
|
||||||
|
body: fileBlob
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!uploadResponse.ok) {
|
if (!uploadResponse.ok) {
|
||||||
const response = await uploadResponse.json()
|
const response = await uploadResponse.json();
|
||||||
throw new Error(`HTTP error during file upload to ${user.userId}: status ${response.message}`);
|
throw new Error(`HTTP error during file upload to ${user.userId}: status ${response.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,6 +42,8 @@ document.addEventListener("DOMContentLoaded", async function () {
|
|||||||
results.forEach(result => {
|
results.forEach(result => {
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
console.log(result.message);
|
console.log(result.message);
|
||||||
|
} else {
|
||||||
|
console.error(result.message);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
console.log('All files processed. Check the console for detailed results.');
|
console.log('All files processed. Check the console for detailed results.');
|
||||||
@@ -52,5 +60,6 @@ document.addEventListener("DOMContentLoaded", async function () {
|
|||||||
|
|
||||||
await performUploads();
|
await performUploads();
|
||||||
await timeout(10000);
|
await timeout(10000);
|
||||||
fadeOut('main_menu.html');
|
fadeOut('main_menu.html'); // Make sure this function is properly defined or available in your context
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user