-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
189 lines (159 loc) · 5.02 KB
/
server.js
File metadata and controls
189 lines (159 loc) · 5.02 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
// server.js
import express from "express";
import { WebSocketServer } from "ws";
import cors from "cors";
import os from "os";
import qrcode from "qrcode-terminal";
import http from "http";
import path from "path";
import { fileURLToPath } from "url";
const app = express();
app.use(cors());
app.use(express.json());
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const fetch = globalThis.fetch;
const PORT = process.env.TABSYNC_PORT
? parseInt(process.env.TABSYNC_PORT)
: 3210;
let WSPORT;
/** --- Device store --- **/
const devices = {}; // { deviceId: { tabs: [], lastSeen: number } }
const CLEANUP_INTERVAL = 60 * 1000; // every minute
const DEVICE_TIMEOUT = 5 * 60 * 1000; // 5 minutes
/** --- Utility: Get local IP --- **/
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const name in interfaces) {
for (const iface of interfaces[name]) {
if (iface.family === "IPv4" && !iface.internal) return iface.address;
}
}
return "localhost";
}
/** --- Utility: Fetch title from URL --- **/
async function fetchTitle(url) {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
const res = await fetch(url, { signal: controller.signal });
clearTimeout(timeout);
if (!res.ok) return new URL(url).hostname;
const match = text.match(/<title>(.*?)<\/title>/i);
if (!match || !match[1]) {
return new URL(url).hostname; // avoid "Error"
}
return match[1].trim();
} catch {
try {
return new URL(url).hostname; // fallback to domain
} catch {
return url;
}
}
}
/** --- Utility: Simplify devices object for clients --- **/
function simplify(devices) {
const result = {};
for (const [id, data] of Object.entries(devices)) {
result[id] = data.tabs;
}
return result;
}
/** --- Broadcast to all connected clients --- **/
function broadcast() {
const payload = JSON.stringify(simplify(devices));
wss.clients.forEach((c) => {
if (c.readyState === 1) c.send(payload);
});
}
/** --- Cleanup inactive devices periodically --- **/
setInterval(() => {
const now = Date.now();
let removed = 0;
for (const [id, device] of Object.entries(devices)) {
if (now - device.lastSeen > DEVICE_TIMEOUT) {
delete devices[id];
removed++;
}
}
if (removed > 0) {
console.log(`🧹 Cleaned ${removed} inactive device(s).`);
}
}, CLEANUP_INTERVAL);
/** --- WebSocket server (dynamic port) --- **/
const wsServer = http.createServer();
let wss;
wsServer.listen(0, () => {
WSPORT = wsServer.address().port;
wss = new WebSocketServer({ server: wsServer });
wss.on("connection", (ws) => {
ws.on("message", async (msg) => {
try {
const data = JSON.parse(msg);
const { deviceId, tabs } = data;
if (!deviceId || !Array.isArray(tabs) || tabs.length === 0) return;
// Deduplicate by URL
const seen = new Set();
const processedTabs = [];
for (const tab of tabs) {
if (!tab.url || seen.has(tab.url)) continue;
seen.add(tab.url);
const title =
!tab.title || tab.title === tab.url
? await fetchTitle(tab.url)
: tab.title;
processedTabs.push({ title, url: tab.url });
}
devices[deviceId] = {
tabs: processedTabs,
lastSeen: Date.now(),
};
broadcast();
} catch (err) {
console.error("❌ WS parse error:", err.message);
}
});
ws.send(JSON.stringify(simplify(devices)));
});
/** --- Express endpoints --- **/
app.use(express.static(path.join(__dirname, "public")));
app.get("/devices", (req, res) => res.json(simplify(devices)));
app.post("/add", async (req, res) => {
try {
const { deviceId, url } = req.body;
if (!deviceId || !url)
return res.status(400).json({ error: "Missing fields" });
const title = await fetchTitle(url);
if (!devices[deviceId]) {
devices[deviceId] = { tabs: [], lastSeen: Date.now() };
}
const exists = devices[deviceId].tabs.some((t) => t.url === url);
if (!exists) {
devices[deviceId].tabs.push({ title, url });
devices[deviceId].lastSeen = Date.now();
broadcast();
}
res.json({ success: true, title });
} catch (err) {
console.error("Error adding URL:", err.message);
res.status(500).json({ error: "Failed to add URL" });
}
});
// Get local IP + WS port
app.get("/ip", (req, res) => {
res.json({ ip: getLocalIP(), wsPort: WSPORT });
});
app.listen(PORT, "0.0.0.0", () => {
const ip = getLocalIP();
const showQR = !process.env.TABSYNC_NO_QR;
const url = `http://${ip}:${PORT}`;
/** --- Logs & QR --- **/
console.log(`\n🧩 TabSync Local running at: ${url}`);
console.log(`🌐 WebSocket on ws://${ip}:${WSPORT}`);
if (showQR) {
qrcode.generate(url, { small: true });
console.log("📱 Scan the QR to connect your mobile.\n");
}
});
});