-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsocket.js
202 lines (167 loc) · 5.92 KB
/
socket.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
const express = require('express');
const http = require('http');
const redis = require('redis');
const { Pool } = require('pg');
const net = require('net');
const dns = require('dns/promises'); // Use the DNS promises API for hostname resolution
require('dotenv').config()
const app = express();
const server = http.createServer(app);
const io = require("socket.io")(server, {
cors: {
origin: [process.env.APP_URL],
methods: ["GET"]
}
});
const pool = new Pool({
user: process.env.DB_USERNAME,
host: process.env.DB_HOST,
database: process.env.DB_DATABASE,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
});
pool.query('SELECT id FROM cameras order by id').then(async (res) => {
const cameraTopics = [];
res.rows.forEach(row => {
cameraTopics.push('home_sauron_camera_stream:' + row.id)
});
await main(cameraTopics)
});
const subscribeToCameraTopic = async (topic, message) => {
const parsedMessage = JSON.parse(message);
const data = {
camera: {
id: parsedMessage.camera.id,
name: parsedMessage.camera.name,
url: parsedMessage.camera.url,
},
frame: parsedMessage.frame
}
io.to(topic).emit('frame', data);
}
async function scanHosts(socket) {
const baseIP = process.env.SOCKET_IP.split('.').slice(0, -1).join('.'); // Remove the last segment
const start = 1;
const end = 255;
const port = 81;
console.log(`Scanning for alive hosts in ${baseIP}.${start}-${end}...`);
for (let i = start; i <= end; i++) {
const host = `${baseIP}.${i}`;
if (!socket.is_in_network_scan) {
console.log('Scanning cancelled');
return;
}
if (await checkHost(host, port)) {
try {
const hostnames = await dns.reverse(host); // Perform reverse DNS lookup
if (hostnames.length > 0 && hostnames[0].startsWith('home-sauron-')) {
console.log(`Found camera at ${host}`);
socket.emit('cameras-discovery:result', {
host: `${host}:${port}`,
hostname: hostnames[0],
});
}
} catch (error) {
console.log(`Error resolving hostname for ${host}: ${error.message}`);
}
}
if (i === end) {
console.log('Camera scan finished');
socket.is_in_network_scan = false;
socket.emit('cameras-discovery:finished');
}
}
}
async function checkHost(host, port) {
return new Promise((resolve) => {
const socket = new net.Socket();
socket.setTimeout(100); // Adjust timeout as needed
socket.on('connect', () => {
socket.end();
resolve(true);
});
socket.on('timeout', () => {
socket.destroy();
resolve(false);
});
socket.on('error', (err) => {
resolve(false);
});
socket.connect(port, host);
});
}
const main = async (cameraTopics) => {
const redisClient = redis.createClient({
socket: {
host: 'home_sauron_redis',
},
password: 'root'
});
const redisSubscriber = redisClient.duplicate();
await redisSubscriber.connect();
io.on('connection', (socket) => {
socket.is_in_network_scan = false;
const cameraId = socket.handshake.query.camera_id;
console.log(`User connected: ${socket.id}`);
if (cameraId) {
if (cameraId === 'all') {
cameraTopics.forEach((topic) => {
socket.join(topic);
console.log(`User ${socket.id} joined room ${topic}`);
});
} else {
socket.join('home_sauron_camera_stream:' + cameraId);
}
}
socket.on('disconnect', () => {
console.log(`User disconnected: ${socket.id}`);
});
socket.on('cameras-discovery:start', () => {
if (socket.is_in_network_scan) {
return;
}
socket.is_in_network_scan = true;
scanHosts(socket);
});
socket.on('cameras-discovery:stop', () => {
if (!socket.is_in_network_scan) {
return;
}
socket.is_in_network_scan = false;
});
});
for (const topic of cameraTopics) {
await redisSubscriber.subscribe(topic, async (message) => {
await subscribeToCameraTopic(topic, message)
});
}
await redisSubscriber.subscribe('home_sauron_camera_added', async (camera) => {
camera = JSON.parse(camera);
const topic = 'home_sauron_camera_stream:' + camera.id;
cameraTopics.push(topic);
await redisSubscriber.subscribe(topic, async (message) => {
await subscribeToCameraTopic(topic, message)
});
console.log(`Camera ${camera.id} was added`)
});
await redisSubscriber.subscribe('home_sauron_camera_deleted', async (camera) => {
camera = JSON.parse(camera);
const topic = 'home_sauron_camera_stream:' + camera.id;
// Find the index of the topic in the cameraTopics array
const topicIndex = cameraTopics.indexOf(topic);
// If the topic exists in the array, remove it
if (topicIndex > -1) {
cameraTopics.splice(topicIndex, 1);
// Unsubscribe from the topic
await redisSubscriber.unsubscribe(topic);
io.of('/').in(topic).socketsLeave(topic);
console.log(`Camera ${camera.id} was removed and unsubscribed from topic ${topic}`);
} else {
console.log(`Topic ${topic} not found in cameraTopics array, but marked as deleted`);
}
});
const PORT = process.env.SOCKET_PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
}