Jonell01 commited on
Commit
554d74d
·
verified ·
1 Parent(s): 010fe91

Create index.js

Browse files
Files changed (1) hide show
  1. index.js +71 -0
index.js ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const http = require('http');
3
+ const socketIo = require('socket.io');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+
7
+ const app = express();
8
+ const server = http.createServer(app);
9
+ const io = socketIo(server);
10
+
11
+ const uploadDir = path.join(__dirname, 'uploads');
12
+ if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir);
13
+
14
+ app.use(express.static('public'));
15
+
16
+ let receivers = 0;
17
+ const fileExpiryTime = 5 * 60 * 60 * 1000;
18
+ const fileMetadata = new Map();
19
+
20
+ setInterval(() => {
21
+ const now = Date.now();
22
+ fs.readdirSync(uploadDir).forEach(file => {
23
+ const filePath = path.join(uploadDir, file);
24
+ const stats = fs.statSync(filePath);
25
+ const fileAge = now - stats.birthtimeMs;
26
+
27
+ if (fileAge > fileExpiryTime) {
28
+ fs.unlinkSync(filePath);
29
+ fileMetadata.delete(file);
30
+ }
31
+ });
32
+ }, 60 * 60 * 1000);
33
+
34
+ io.on('connection', (socket) => {
35
+ socket.on('setMode', (mode) => {
36
+ socket.mode = mode;
37
+ if (mode === 'receiver') {
38
+ receivers++;
39
+ io.emit('onlineCount', receivers);
40
+ }
41
+ });
42
+
43
+ socket.on('disconnect', () => {
44
+ if (socket.mode === 'receiver') {
45
+ receivers--;
46
+ io.emit('onlineCount', receivers);
47
+ }
48
+ });
49
+
50
+ socket.on('upload', ({ fileName, fileData }) => {
51
+ const filePath = path.join(uploadDir, fileName);
52
+ const buffer = Buffer.from(fileData, 'base64');
53
+ fs.writeFileSync(filePath, buffer);
54
+ fileMetadata.set(fileName, { uploadedAt: Date.now() });
55
+ socket.emit('uploadComplete');
56
+ io.emit('fileReady', { fileName });
57
+ });
58
+
59
+ socket.on('requestFile', ({ fileName }) => {
60
+ const filePath = path.join(uploadDir, fileName);
61
+ if (fs.existsSync(filePath)) {
62
+ const fileBuffer = fs.readFileSync(filePath);
63
+ socket.emit('fileData', { fileName, fileData: fileBuffer.toString('base64') });
64
+ } else {
65
+ socket.emit('error', { message: 'File not found' });
66
+ }
67
+ });
68
+ });
69
+
70
+ const PORT = 7860;
71
+ server.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));