v2.7
This commit is contained in:
@@ -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 = [];
|
||||
@@ -114,45 +114,51 @@ async function addFilePathToJson(filePath) {
|
||||
}
|
||||
}
|
||||
|
||||
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 decryptAndGetShareDir(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;
|
||||
|
||||
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('/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).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 {
|
||||
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
|
||||
fs.writeFileSync(filePath, req.body);
|
||||
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.' });
|
||||
|
||||
@@ -6,22 +6,28 @@ document.addEventListener("DOMContentLoaded", async function () {
|
||||
|
||||
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);
|
||||
formData.append('sizeOfFile', file.size);
|
||||
const fileResponse = await fetch(uploadData.filePath);
|
||||
if (!fileResponse.ok) {
|
||||
throw new Error(`HTTP error when trying to fetch the file: status ${fileResponse.statusText}`);
|
||||
}
|
||||
const fileBlob = await fileResponse.blob();
|
||||
|
||||
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, {
|
||||
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) {
|
||||
const response = await uploadResponse.json()
|
||||
const response = await uploadResponse.json();
|
||||
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 => {
|
||||
if (result.success) {
|
||||
console.log(result.message);
|
||||
} else {
|
||||
console.error(result.message);
|
||||
}
|
||||
});
|
||||
console.log('All files processed. Check the console for detailed results.');
|
||||
@@ -52,5 +60,6 @@ document.addEventListener("DOMContentLoaded", async function () {
|
||||
|
||||
await performUploads();
|
||||
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