-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
204 lines (169 loc) · 8.94 KB
/
server.js
File metadata and controls
204 lines (169 loc) · 8.94 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
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
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const RustPlus = require('@liamcottle/rustplus.js');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.use(express.static('public'));
// Store user clients by their socket ID
const userClients = {};
// Create a RustPlus client for a specific camera
function createRustClient(ip, port, playerId, playerToken) {
return new RustPlus(ip, port, playerId, playerToken);
}
// WebSocket connection handler
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
// Event to set the Rust+ connection for this user (general connection, if needed)
socket.on('set_connection', async (data) => {
const { ip, port, playerId, playerToken } = data;
try {
// Initialize an empty cameras array for the user if not already present
if (!userClients[socket.id]) {
console.log("Initialize UserClient for " + socket.id)
userClients[socket.id] = {
rustPlusInstance: createRustClient(ip, port, playerId, playerToken),
cameras: []
};
}
// Notify the frontend that the connection was successful
socket.emit('connection_status', { success: true });
} catch (error) {
// Send failure response to the client with proper error message
console.error('Connection error:', error?.error || JSON.stringify(error));
socket.emit('connection_status', { success: false, error: error.error || JSON.stringify(error) });
}
});
// Event to fetch camera feed for this user's camera
socket.on('fetch_camera_feed', async (data) => {
const { cameraId, cameraIndex, ip, port, playerId, playerToken } = data;
// Ensure the user has an initialized client entry
const userClient = userClients[socket.id];
if (!userClient) {
socket.emit(`camera_feed_${cameraId}`, { hasSignal: false, error: 'Rust+ client not initialized' });
return;
}
// Check if this camera is already subscribed
const existingCamera = userClient.cameras.find((camera) => camera.camera.identifier === cameraId);
if (existingCamera) {
socket.emit(`camera_feed_${cameraId}`, { hasSignal: false, error: 'camera_already_subscribed' });
return;
}
try {
// Create a separate Rust+ instance for this camera
const cameraControllerInstance = createRustClient(ip, port, playerId, playerToken);
// Connect and subscribe to the camera
await new Promise((resolve, reject) => {
cameraControllerInstance.connect();
cameraControllerInstance.on('connected', async () => {
try {
console.log(`Connected to Rust+ server for camera ${cameraId}`);
// Subscribe to the camera feed
const camera = cameraControllerInstance.getCamera(cameraId);
camera.on('render', (frame) => {
const feed = `data:image/png;base64,${frame.toString('base64')}`;
socket.emit(`camera_feed_${cameraId}`, { cameraId, cameraIndex, feed, hasSignal: true });
});
// Subscribe and catch errors
await camera.subscribe().catch((error) => {
if (error && error.error === "player_online") {
socket.emit(`camera_feed_${cameraId}`, { cameraId, cameraIndex, feed: null, hasSignal: false, error: "player_online" });
return;
}
console.log("Subscribe error: " + JSON.stringify(error));
throw new Error(`Error subscribing to camera: ${error.error || JSON.stringify(error)}`);
});
// Add the camera to the user's list of cameras
userClient.cameras.push({
cameraControllerInstance,
camera: camera // Store the actual camera instance
});
resolve();
} catch (error) {
console.error(`Failed to fetch camera ${cameraId} for user ${socket.id}:`, error.error || JSON.stringify(error));
socket.emit(`camera_feed_${cameraId}`, { hasSignal: false, error: error.error || error });
}
});
cameraControllerInstance.on('error', (err) => {
console.error(`Error connecting to Rust+ for camera ${cameraId}:`, err);
reject(err);
});
});
} catch (error) {
console.error(`Failed to fetch camera ${cameraId} for user ${socket.id}:`, error.error || JSON.stringify(error));
socket.emit(`camera_feed_${cameraId}`, { hasSignal: false, error: error.error || error });
}
});
// Event to remove the camera feed for this user
socket.on('remove_camera_feed', async (data) => {
const { cameraId } = data;
// Get the user client
const userClient = userClients[socket.id];
if (!userClient) {
return;
}
// Find and remove the camera from the user's camera list
const cameraIndex = userClient.cameras.findIndex((camera) => camera.camera.identifier === cameraId);
if (cameraIndex !== -1) {
const cameraInstance = userClient.cameras[cameraIndex];
try {
// Unsubscribe and disconnect the camera
cameraInstance.camera.unsubscribe().then(() => {
console.log(`Unsubscribed from camera ${cameraInstance.camera.identifier}`);
// Remove the camera from the list
userClient.cameras.splice(cameraIndex, 1);
socket.emit(`camera_feed_${cameraInstance.camera.identifier}`, { cameraId: cameraInstance.camera.identifier, feed: null, hasSignal: false, error: "camera_removed" });
//TODO: Waiting for https://github.com/liamcottle/rustplus.js/pull/70
// try {
// cameraInstance.cameraControllerInstance.disconnect();
// } catch (error) {
// console.log("Error disconnecting WebSocket:", error.message);
// }
}).catch((error) => {
console.error(`Error unsubscribing from camera ${cameraInstance.camera.identifier}:`, error);
});
} catch (error) {
console.error(`Failed to remove camera ${cameraInstance.camera.identifier} for user ${socket.id}:`, error.error || JSON.stringify(error));
}
}
});
// Handle client disconnect and cleanup
socket.on('disconnect', async () => {
console.log(`Client disconnected: ${socket.id}`);
// Get the Rust+ client for this user and disconnect all cameras
const userClient = userClients[socket.id];
if (userClient) {
try {
// Disconnect all camera instances for this user
for (const camera of userClient.cameras) {
const cameraInstance = camera.camera;
cameraInstance.unsubscribe().then(() => {
console.log(`Unsubscribed from camera ${cameraInstance.identifier}`);
socket.emit(`camera_feed_${cameraInstance.identifier}`, { cameraId: cameraInstance.identifier, feed: null, hasSignal: false, error: "camera_removed" });
}).catch((error) => {
console.error(`Error unsubscribing from camera ${cameraInstance.identifier}:`, error);
});
//TODO: Waiting for https://github.com/liamcottle/rustplus.js/pull/70
// try {
// camera.cameraControllerInstance.disconnect();
// } catch (error) {
// console.log("Error disconnecting WebSocket:", error.message);
// }
}
//TODO: Waiting for https://github.com/liamcottle/rustplus.js/pull/70
// userClient.rustPlusInstance.disconnect();
// Clean up the user's client
delete userClients[socket.id];
console.log(`Cleaned up Rust+ client for user ${socket.id}`);
} catch (error) {
console.error(`Error during cleanup for user ${socket.id}:`, error.error || JSON.stringify(error));
}
}
});
});
// Start the server
const port = 6587;
server.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});