« get me outta code hell

mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/telnet-server.js
diff options
context:
space:
mode:
Diffstat (limited to 'telnet-server.js')
-rw-r--r--telnet-server.js67
1 files changed, 67 insertions, 0 deletions
diff --git a/telnet-server.js b/telnet-server.js
new file mode 100644
index 0000000..6cee554
--- /dev/null
+++ b/telnet-server.js
@@ -0,0 +1,67 @@
+'use strict'
+
+const net = require('net')
+const setupClient = require('./client')
+
+const {
+  util: {
+    TelnetInterfacer
+  }
+} = require('./tui-lib')
+
+class TelnetServer {
+  constructor(backend) {
+    this.backend = backend
+    this.server = new net.Server(socket => this.handleConnection(socket))
+    this.sockets = []
+  }
+
+  listen(port) {
+    this.server.listen(port)
+  }
+
+  async handleConnection(socket) {
+    const interfacer = new TelnetInterfacer(socket)
+    const { appElement, renderInterval, cleanTerminal } = await setupClient({
+      backend: this.backend,
+      writable: socket,
+      interfacer,
+      appConfig: {
+        stopPlayingUponQuit: false,
+        menubarColor: 2
+      }
+    })
+
+    let closed = false
+
+    const quit = (msg = 'See you!') => {
+      cleanTerminal()
+      interfacer.cleanTelnetOptions()
+      socket.write('\r' + msg + '\r\n')
+      socket.end()
+      this.sockets.splice(this.sockets.indexOf(socket, 1))
+      closed = true
+    }
+
+    appElement.on('quitRequested', quit)
+
+    socket.on('close', () => {
+      if (!closed) {
+        clearInterval(renderInterval)
+        this.sockets.splice(this.sockets.indexOf(socket, 1))
+        closed = true
+      }
+    })
+
+    socket.quit = quit
+    this.sockets.push(socket)
+  }
+
+  disconnectAllSockets(msg) {
+    for (const socket of this.sockets) {
+      socket.quit(msg)
+    }
+  }
+}
+
+module.exports = TelnetServer