diff options
author | 2021-09-14 11:03:28 +0200 | |
---|---|---|
committer | 2021-09-14 11:03:28 +0200 | |
commit | 087113d8a1214ba4c7df03bfe66747d8d944280c (patch) | |
tree | 4d853a03057138dfa845cd6a7d91ccf63565a1a6 /src/electron/ipc-api/localServer.ts | |
parent | chore: codebase improvements (#1930) (diff) | |
download | ferdium-app-087113d8a1214ba4c7df03bfe66747d8d944280c.tar.gz ferdium-app-087113d8a1214ba4c7df03bfe66747d8d944280c.tar.zst ferdium-app-087113d8a1214ba4c7df03bfe66747d8d944280c.zip |
chore: convert JS to TS (#1934)
Diffstat (limited to 'src/electron/ipc-api/localServer.ts')
-rw-r--r-- | src/electron/ipc-api/localServer.ts | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/src/electron/ipc-api/localServer.ts b/src/electron/ipc-api/localServer.ts new file mode 100644 index 000000000..d318b93a5 --- /dev/null +++ b/src/electron/ipc-api/localServer.ts | |||
@@ -0,0 +1,47 @@ | |||
1 | import { ipcMain, BrowserWindow } from 'electron'; | ||
2 | import net from 'net'; | ||
3 | import { LOCAL_HOSTNAME, LOCAL_PORT } from '../../config'; | ||
4 | import { userDataPath } from '../../environment'; | ||
5 | import startServer from '../../internal-server/start'; | ||
6 | |||
7 | const portInUse = (port: number): Promise<boolean> => | ||
8 | new Promise(resolve => { | ||
9 | const server = net.createServer(socket => { | ||
10 | socket.write('Echo server\r\n'); | ||
11 | socket.pipe(socket); | ||
12 | }); | ||
13 | |||
14 | server.listen(port, LOCAL_HOSTNAME); | ||
15 | server.on('error', () => { | ||
16 | resolve(true); | ||
17 | }); | ||
18 | server.on('listening', () => { | ||
19 | server.close(); | ||
20 | resolve(false); | ||
21 | }); | ||
22 | }); | ||
23 | |||
24 | let localServerStarted = false; | ||
25 | |||
26 | export default (params: { mainWindow: BrowserWindow }) => { | ||
27 | ipcMain.on('startLocalServer', () => { | ||
28 | if (!localServerStarted) { | ||
29 | // Find next unused port for server | ||
30 | let port = LOCAL_PORT; | ||
31 | (async () => { | ||
32 | // eslint-disable-next-line no-await-in-loop | ||
33 | while ((await portInUse(port)) && port < LOCAL_PORT + 10) { | ||
34 | port += 1; | ||
35 | } | ||
36 | console.log('Starting local server on port', port); | ||
37 | |||
38 | startServer(userDataPath(), port); | ||
39 | |||
40 | params.mainWindow.webContents.send('localServerPort', { | ||
41 | port, | ||
42 | }); | ||
43 | })(); | ||
44 | localServerStarted = true; | ||
45 | } | ||
46 | }); | ||
47 | }; | ||