-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
154 lines (124 loc) · 3.78 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
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const path = require("path");
const multer = require("multer");
const fs = require("fs");
const os = require("os");
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const PORT = process.env.PORT || 3000;
let connectedDevices = {};
// Setup multer for file uploads
const upload = multer({ dest: "uploads/" });
// Fetch ipv4 address
function getIPv4Address() {
const interfaces = os.networkInterfaces();
let ipv4Address = "";
for (const interfaceName in interfaces) {
const iface = interfaces[interfaceName];
for (const alias of iface) {
if (alias.family === "IPv4" && !alias.internal) {
ipv4Address = alias.address;
break;
}
}
if (ipv4Address) {
break;
}
}
return ipv4Address;
}
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, "public")));
// Handle file uploads
app.post("/upload", upload.array("files", 10), (req, res) => {
const files = req.files;
if (!files) {
return res.status(400).send("No files uploaded.");
}
files.forEach((file) => {
console.log(`File received: ${file.originalname}`);
// Emit a socket event for each file
io.emit("fileUploaded", {
fileName: file.originalname,
filePath: `/uploads/${file.filename}`,
deviceName: connectedDevices[req.body.socketId]?.name || undefined,
});
});
res.send("Files uploaded successfully.");
});
// Serve uploaded files
app.use("/uploads", express.static(path.join(__dirname, "uploads")));
// Clear the uploads directory
function clearUploadsDirectory() {
const directory = "uploads";
fs.readdir(directory, (err, files) => {
if (err) {
console.error("Unable to read uploads directory:", err);
return;
}
for (const file of files) {
fs.unlink(path.join(directory, file), (err) => {
if (err) {
console.error("Unable to delete file:", err);
}
});
}
console.log("Uploads directory cleared.");
});
}
// Handle new socket connections
io.on("connection", (socket) => {
console.log("New device connected:", socket.id);
io.emit("getDeviceType");
io.emit("sendIP", getIPv4Address(), PORT);
// Store the connected device
socket.on("sendDeviceType", (currentDeviceType) => {
connectedDevices[socket.id] = {
id: socket.id,
type: currentDeviceType,
};
// Broadcast the updated list of devices
io.emit("updateDeviceList", connectedDevices);
});
// When the client sends a device name, store it
socket.on("setDeviceName", (deviceName, deviceType) => {
connectedDevices[socket.id] = {
id: socket.id,
name: deviceName,
type: deviceType,
};
io.emit("updateDeviceList", connectedDevices);
});
// Handle disconnections
socket.on("disconnect", () => {
console.log("Device disconnected:", socket.id);
delete connectedDevices[socket.id];
io.emit("updateDeviceList", connectedDevices);
// Clear uploads directory if no devices are connected
if (Object.keys(connectedDevices).length === 0) {
clearUploadsDirectory();
}
});
});
server.listen(PORT, () => {
console.log(
`Server started at port: ${PORT} \npress Ctrl + C to stop the application\n`
);
});
// Using dynamic import of 'open' module
(async () => {
const open = (await import("open")).default;
// URL to be opened
const url = `http://${getIPv4Address()}:${PORT}`;
// Open the URL in the default web browser
open(url)
.then(() =>
console.log(
`Wi-File opened in the browser with url: ${url}\nMake sure to open the same url in other devices.\n`
)
)
.catch((err) => console.error("Error opening the URL:", err));
})();