-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
224 lines (191 loc) · 6.28 KB
/
server.js
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import express from 'express';
import multer from 'multer';
import http from 'http';
import { Server as SocketIoServer } from 'socket.io';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import minimist from 'minimist';
import os from 'os';
import bodyParser from 'body-parser';
import sanitizeFilename from 'sanitize-filename';
// Fix __dirname and __filename in ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Parse command-line arguments
const args = minimist(process.argv.slice(2));
const host = args.a || process.env.HOST || '0.0.0.0';
const port = args.p || process.env.PORT || 8088;
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir);
}
const removeAccents = (str) => {
return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-zA-Z0-9-]/g, '_');
};
// Setup storage for multer with sanitized filename
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadsDir);
},
filename: (req, file, cb) => {
let originalName = file.originalname.replace(/\.[^.]+$/, ''); // Remove file extension
originalName = removeAccents(originalName); // Remove accents and special characters
originalName = sanitizeFilename(originalName); // Sanitize the filename
const randomSuffix = Math.floor(1000 + Math.random() * 9000).toString();
cb(null, `${originalName}-${randomSuffix}${path.extname(file.originalname)}`);
}
});
const app = express();
const server = http.createServer(app);
const io = new SocketIoServer(server);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/uploads', express.static(uploadsDir));
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.text());
let sharedText = '';
const readSharedTextFromFile = () => {
try {
sharedText = fs.readFileSync('sharedText.txt', 'utf8');
} catch (err) {
if (err.code === 'ENOENT') {
fs.writeFileSync('sharedText.txt', '', 'utf8');
sharedText = '';
} else {
console.error('Error reading sharedText file:', err);
sharedText = '';
}
}
};
const writeSharedTextToFile = (text) => {
fs.writeFileSync('sharedText.txt', text, 'utf8');
};
readSharedTextFromFile();
app.use(express.static(__dirname + '/views'));
app.get('/', (req, res) => {
const userAgent = req.headers['user-agent'] || '';
if (userAgent.includes('curl') || userAgent.includes('wget') || userAgent.includes('PowerShell') || req.query.textonly) {
res.send(sharedText + '\n');
} else {
fs.readdir(uploadsDir, (err, files) => {
res.render('index', { files });
});
}
});
app.put('/', (req, res) => {
const [key, newText] = Object.entries(req.body)[0];
if (typeof key === 'string') {
sharedText = key;
writeSharedTextToFile(key);
io.emit('textUpdate', key);
res.status(200).send('Text updated successfully' + '\n');
} else {
res.status(400).send('Invalid input' + '\n');
}
});
app.get('/files', (req, res) => {
fs.readdir(uploadsDir, (err, files) => {
if (req.query.json) {
res.json(files);
} else {
res.send(files.join('\n') + '\n');
}
});
});
app.get('/files/:filename', (req, res) => {
const filename = sanitizeFilename(req.params.filename);
const filepath = path.join(uploadsDir, filename);
fs.access(filepath, fs.constants.F_OK, (err) => {
if (err) {
return res.status(404).send('File not found' + '\n');
}
res.download(filepath, (err) => {
if (err) {
console.error('Error downloading the file:', err);
if (!res.headersSent) {
res.status(500).send('Error downloading the file' + '\n');
}
}
});
});
});
const upload = multer({ storage }).any();
app.post('/upload', (req, res) => {
const userAgent = req.headers['user-agent'] || '';
upload(req, res, (err) => {
if (err) {
return res.status(500).send('Error uploading file(s): ' + err.message + '\n');
}
if (req.files.length === 0) {
return res.status(400).send('No files uploaded' + '\n');
}
if (req.files.length === 1) {
io.emit('fileUpdate');
if (req.headers['user-agent'] && (req.headers['user-agent'].includes('curl')) || userAgent.includes('wget')) {
return res.status(200).send('Single file uploaded successfully' + '\n');
} else {
return res.redirect('/');
}
} else {
io.emit('fileUpdate');
if (req.headers['user-agent'] && (req.headers['user-agent'].includes('curl') || userAgent.includes('wget'))) {
return res.status(200).send('Multiple files uploaded successfully' + '\n');
} else {
return res.redirect('/');
}
}
});
});
app.delete('/files/:filename', (req, res) => {
const filename = sanitizeFilename(req.params.filename);
const filePath = path.join(uploadsDir, filename);
fs.unlink(filePath, (err) => {
if (err) {
if (err.code === 'ENOENT') {
// File doesn't exist
console.warn(`File not found: ${filePath}`);
res.status(404).send('File not found' + '\n');
} else {
// Other errors
console.error('Error deleting the file:', err);
res.status(500).send('Error deleting the file' + '\n');
}
} else {
io.emit('fileUpdate');
res.status(200).send('File deleted successfully' + '\n');
}
});
});
io.on('connection', (socket) => {
socket.emit('textUpdate', sharedText);
socket.on('textChange', (text) => {
sharedText = text;
writeSharedTextToFile(text);
socket.broadcast.emit('textUpdate', text);
});
socket.on('fileUpdate', () => {
fs.readdir(uploadsDir, (err, files) => {
io.emit('fileList', files);
});
});
});
const getLocalIPAddress = () => {
const interfaces = os.networkInterfaces();
for (const iface of Object.values(interfaces)) {
for (const { family, address, internal } of iface) {
if (family === 'IPv4' && !internal) {
return address;
}
}
}
return 'localhost';
};
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
if (host === '0.0.0.0') {
const localIP = getLocalIPAddress();
console.log(`Access it using http://${localIP}:${port}`);
}
});
export default app; // Export the app for testing