Skip to content

Commit 90b9578

Browse files
committed
Added concept of clientId. Added import writer
1 parent ddf8ba3 commit 90b9578

3 files changed

Lines changed: 55 additions & 9 deletions

File tree

src/connect/http-routes/handlers/import-handler.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { spawn } from '@homebridge/node-pty-prebuilt-multiarch';
22
import { ConfigFileSchema } from 'codify-schemas';
3+
import { diffChars } from 'diff';
34
import fs from 'node:fs/promises';
45
import os from 'node:os';
56
import path from 'node:path';
@@ -41,6 +42,7 @@ export function importHandler() {
4142
const filePath = path.join(tmpDir, 'codify.jsonc');
4243
await fs.writeFile(filePath, JSON.stringify(codifyConfig, null, 2));
4344
session.additionalData.filePath = filePath;
45+
session.additionalData.existingFile = codifyConfig;
4446

4547
let args = '';
4648
switch (type as ImportType) {
@@ -70,6 +72,23 @@ export function importHandler() {
7072

7173
const onExit = async (exitCode: number, ws: WebSocket, session: Session) => {
7274
if (session.additionalData.filePath) {
75+
const updatedFile = await fs.readFile(session.additionalData.filePath as string, 'utf8')
76+
77+
// Changes were found
78+
if (diffChars(updatedFile, session.additionalData.existingFile as string).length > 0) {
79+
console.log('Writing imported changes to Codify dashboard');
80+
81+
const ws = SocketServer.get().getMainConnection(session.clientId);
82+
if (!ws) {
83+
throw new Error(`Unable to find client for clientId ${session.clientId}`);
84+
}
85+
86+
ws.send(JSON.stringify({ key: 'new_import', data: {
87+
updated: updatedFile,
88+
} }))
89+
}
90+
91+
7392
await fs.rm(session.additionalData.filePath as string, { recursive: true, force: true });
7493
}
7594
}
Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { Router } from 'express';
2-
import { v4 as uuid } from 'uuid';
32

43
import { SocketServer } from '../../socket-server.js';
54

@@ -8,13 +7,20 @@ const router = Router({
87
});
98

109
router.post('/session', (req, res) => {
11-
const sessionId = uuid();
10+
const { clientId } = req.body;
11+
if (!clientId) {
12+
throw new Error('connectionId is required');
13+
}
14+
1215
const socketServer = SocketServer.get();
16+
if (!socketServer.getMainConnection(clientId)) {
17+
throw new Error('Invalid connection id');
18+
}
1319

14-
socketServer.addSession(sessionId);
20+
const sessionId = socketServer.createSession(clientId);
1521
console.log('Terminal session created!', sessionId)
1622

1723
return res.status(200).json({ sessionId });
1824
})
1925

20-
export default router;
26+
export default router;

src/connect/socket-server.ts

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
import { IPty } from '@homebridge/node-pty-prebuilt-multiarch';
22
import { Server as HttpServer, IncomingMessage } from 'node:http';
33
import { Duplex } from 'node:stream';
4+
import { v4 as uuid } from 'uuid';
45
import WebSocket, { WebSocketServer } from 'ws';
56

67
import { config } from '../config.js';
78

89
export interface Session {
910
server: WebSocketServer;
11+
clientId: string;
1012
ws?: WebSocket;
1113
pty?: IPty;
1214
additionalData: Record<string, unknown>;
@@ -23,7 +25,8 @@ export class SocketServer {
2325

2426
private server: HttpServer;
2527
private connectionSecret: string;
26-
private sessions = new Map<string, Session>()
28+
private mainConnections = new Map<string, WebSocket>(); // These are per webpage
29+
private sessions = new Map<string, Session>();
2730

2831
static init(server: HttpServer, connectionSecret: string): SocketServer {
2932
instance = new SocketServer(server, connectionSecret);
@@ -45,11 +48,19 @@ export class SocketServer {
4548
this.server.on('upgrade', this.onUpgrade);
4649
}
4750

48-
addSession(id: string): void {
51+
getMainConnection(id: string): WebSocket | undefined {
52+
return this.mainConnections.get(id);
53+
}
54+
55+
createSession(clientId: string): string {
56+
const sessionId = uuid();
57+
4958
this.sessions.set(
50-
id,
51-
{ server: this.createWssServer(), additionalData: {} }
59+
sessionId,
60+
{ server: this.createWssServer(), clientId, additionalData: {} }
5261
)
62+
63+
return sessionId;
5364
}
5465

5566
removeSession(id: string) {
@@ -79,7 +90,7 @@ export class SocketServer {
7990
if (pathname === '/ws') {
8091
console.log('Client connected!')
8192
const wss = this.createWssServer();
82-
wss.handleUpgrade(request, socket, head, (ws: WebSocket) => {});
93+
wss.handleUpgrade(request, socket, head, this.handleClientConnected);
8394
}
8495

8596
const pathSections = pathname.split('/').filter(Boolean);
@@ -110,6 +121,16 @@ export class SocketServer {
110121
}
111122
}
112123

124+
private handleClientConnected = (ws: WebSocket) => {
125+
const clientId = uuid();
126+
this.mainConnections.set(clientId, ws);
127+
ws.send(JSON.stringify({ key: 'opened', data: { clientId: uuid } }))
128+
129+
ws.on('close', () => {
130+
this.mainConnections.delete(clientId);
131+
})
132+
}
133+
113134
private validateOrigin = (origin: string): boolean =>
114135
config.corsAllowedOrigins.includes(origin)
115136

0 commit comments

Comments
 (0)