-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
158 lines (140 loc) · 4.98 KB
/
app.js
File metadata and controls
158 lines (140 loc) · 4.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
require('dotenv').config();
var qrcode = require('qrcode-terminal');
const express = require('express');
const fs = require('fs');
const path = require('path');
const os = require('os');
const multer = require('multer');
const newEvent = require('./public/components/achieve/index');
const app = express();
const PORT = process.env.PORT || 2345;
const publicPath = path.join(__dirname, 'public');
// console.log("Serving static files from: ", publicPath);
app.use(express.static(publicPath));
let filesInDirectory=[]
const logData =()=>{
console.log("Polyshare is ready to send and receive files")
console.log(`Upload more files to the server at: http://${resolvedIP}:${PORT}/new`)
console.log(`Share files with others http://${resolvedIP}:${PORT}`);
console.log(`Files in: ${FILE_DIRECTORY} will be hosted on the server`);
qrcode.generate(`http://${resolvedIP}:${PORT}`, { small: true });
}
// Configure multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, FILE_DIRECTORY);
},
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({ storage: storage });
// To Ensure the shared_files directory exists
const FILE_DIRECTORY = path.join(process.cwd(), 'shared_files');
if (!fs.existsSync(FILE_DIRECTORY)) {
// If it does not exist the it will create it at runtime
fs.mkdirSync(FILE_DIRECTORY);
}
// Function to update the local IP address
let localIP ='localhost';
let resolvedIP = localIP || 'localhost';
const updateLocalIP=()=> {
const networkInterfaces = os.networkInterfaces();
for (const netInterface of Object.values(networkInterfaces)) {
if (!netInterface) continue;
for (const iface of netInterface) {
if (iface.family === 'IPv4' && !iface.internal) {
localIP = iface.address;
break;
}
}
if (localIP) break;
}
if (localIP !== resolvedIP) {
resolvedIP = localIP || 'localhost';
process.stdout.write('\x1Bc');
logData(); // Update QR code if IP has changed
}
}
// Update the IP one time then every 30 seconds
setInterval(updateLocalIP, 3000);
const calculateFileSize=(sizeInBytes)=>{
const units =["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"];
let unitIndex =0;
while (sizeInBytes >= 1024 && unitIndex <units.length-1){
sizeInBytes /= 1024;
unitIndex++
}
return `${sizeInBytes.toFixed(2)} ${units[unitIndex]}`
}
// API route to fetch available files (selected of course)
app.get('/api/files', (req, res) => {
fs.readdir(FILE_DIRECTORY, (err, files) => {
if (err) {
return res.status(500).json({ error: 'Unable to list files' });
}
let filesWithSizes=[];
files.forEach((currentFileName)=>{
const file = path.join(FILE_DIRECTORY, currentFileName);
let fileSizeInByte = fs.statSync(file).size;
let fileSize = calculateFileSize(fileSizeInByte)
let fileInfo = {fileName:currentFileName,fileSize}
filesWithSizes.push(fileInfo)
})
filesInDirectory=filesWithSizes;
res.status(200).json(filesWithSizes);
});
});
// Dynamic route for download of specific files
app.get('/download/:filename', (req, res) => {
const file = path.join(FILE_DIRECTORY, req.params.filename);
// fancy way to checks if the file exists
fs.access(file, fs.constants.F_OK, (err) => {
if (err) {
if (!res.headersSent) {
return res.status(404).send('File not found');
}
} else {
res.download(file, (err) => {
console.log("Downloading: ",req.params.filename)
if (err) {
newEvent("Download error",{
url: `http://${resolvedIP}:${PORT}`,
file,
files: filesInDirectory
});
if (!res.headersSent) {
console.error('Error during file download:', err);
return res.status(500).send('Error downloading file');
}
}
});
}
});
req.on('aborted', () => {
console.log('Request/download aborted, Retrying');
if (!res.headersSent) {
newEvent("Download Cancellation",{
url: `http://${resolvedIP}:${PORT}`,
file,
files: filesInDirectory
});
res.end();
}
});
});
// Endpoint to upload files
app.post('/upload', upload.single('file'), (req, res) => {
res.json({ message: 'File uploaded successfully', filename: req.file.originalname });
});
// Serve the index.html on the root URL
app.get('/', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
app.get('/new', (req, res) => {
res.sendFile(path.join(publicPath, 'upload.html'));
});
// Start the server
app.listen(PORT, () => {
logData();
});