« get me outta code hell

telnet-server.js - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/telnet-server.js
blob: 4e87499d1aa0348164145eaa20089e44484d932f (plain)
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
'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, cleanTerminal, flushable, renderInterval } = await setupClient({
      backend: this.backend,
      writable: socket,
      interfacer,
      appConfig: {
        canSuspend: false,
        showLeftPane: false,
        stopPlayingUponQuit: false,
        menubarColor: 2
      }
    })

    let closed = false

    const quit = (msg = 'See you!') => {
      cleanTerminal()
      interfacer.cleanTelnetOptions()
      socket.write('\r' + msg + '\r\n')
      socket.end()
      flushable.end()
      closed = true
      this.sockets.splice(this.sockets.indexOf(socket, 1))
    }

    appElement.on('quitRequested', quit)

    socket.on('close', () => {
      if (!closed) {
        clearInterval(renderInterval)
        flushable.end()
        closed = true
        this.sockets.splice(this.sockets.indexOf(socket, 1))
      }
    })

    socket.quit = quit
    this.sockets.push(socket)
  }

  disconnectAllSockets(msg) {
    for (const socket of this.sockets) {
      socket.quit(msg)
    }
  }
}

module.exports = TelnetServer