« get me outta code hell

socket.js - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/socket.js
blob: ae8ef87444b31d68925971c405ec02a6e3b05952 (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
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
// Tools for hosting an MTUI party over a socket server. Comparable in idea to
// telnet.js, but for interfacing over commands rather than hosting all client
// UIs on one server. The intent of the code in this file is to allow clients
// to connect and interface with each other, while still running all processes
// involved in mtui on their own machines -- so mtui will download and play
// music using each connected machine's own internet connection and speakers.

// TODO: Option to display listing items which aren't available on all
// connected devices.

'use strict' // single quotes & no semicolons time babey

const EventEmitter = require('events')
const net = require('net')

const {
  saveBackend,
  restoreBackend,
  updateRestoredTracksUsingPlaylists
} = require('./serialized-backend')

function serializeCommandToData(command) {
  // Turn a command into a string/buffer that can be sent over a socket.
  return JSON.stringify(command)
}

function deserializeDataToCommand(data) {
  // Turn data received from a socket into a command that can be processed as
  // an action to apply to the mtui backend.
  return JSON.parse(data)
}

function validateCommand(command) {
  // TODO: Could be used to validate "against" a backend, but for now it just
  // checks data types.

  if (typeof command !== 'object') {
    return false
  }

  if (!['server', 'client'].includes(command.sender)) {
    return false
  }

  switch (command.sender) {
    case 'server':
      switch (command.code) {
        case 'initialize-backend':
          return typeof command.backend === 'object'
      }
      // No break here; servers can send commands which typically come from
      // clients too.
    case 'client':
      switch (command.code) {
        case 'seek-to':
          return (
            typeof command.queuePlayer === 'string' &&
            typeof command.time === 'number'
          )
        case 'set-pause':
          return (
            typeof command.queuePlayer === 'string' &&
            typeof command.paused === 'boolean'
          )
        case 'status':
          return typeof command.status === 'string'
      }
      break
  }

  return false
}

function makeSocketServer() {
  // The socket server has two functions: to maintain a "canonical" backend
  // and synchronize newly connected clients with the relevent data in this
  // backend, and to receive command data from clients and relay this to
  // other clients.
  //
  // makeSocketServer doesn't actually start the server listening on a port;
  // that's the responsibility of the caller (use server.listen()).

  const server = new net.Server()
  const sockets = []

  server.canonicalBackend = null

  function receivedData(socket, data) {
    // Parse data as a command and validate it. If invalid, drop this data.

    let command
    try {
      command = deserializeDataToCommand(data)
    } catch (error) {
      return
    }

    command.sender = 'client'

    if (!validateCommand(command)) {
      return
    }

    // If it's a status command, respond appropriately, and return so that it
    // is not relayed.

    if (command.code === 'status') {
      switch (command.status) {
        case 'sync-playback':
          for (const QP of server.canonicalBackend.queuePlayers) {
            if (QP.timeData) {
              socket.write(JSON.stringify({
                sender: 'server',
                code: 'seek-to',
                queuePlayer: QP.id,
                time: QP.timeData.curSecTotal
              }) + '\n')
              socket.write(JSON.stringify({
                sender: 'server',
                code: 'set-pause',
                queuePlayer: QP.id,
                paused: false
              }))
            }
          }

          break
      }

      return
    }

    // Relay the data to client sockets.

    for (const socket of sockets) {
      socket.write(JSON.stringify(command))
    }
  }

  server.on('connection', socket => {
    sockets.push(socket)

    socket.on('close', () => {
      if (sockets.includes(socket)) {
        sockets.splice(sockets.indexOf(socket), 1)
      }
    })

    socket.on('data', data => receivedData(socket, data))

    const savedBackend = saveBackend(server.canonicalBackend)

    for (const qpData of savedBackend.queuePlayers) {
      if (qpData.playerInfo) {
        qpData.playerInfo.isPaused = true
      }
    }

    socket.write(JSON.stringify({
      sender: 'server',
      code: 'initialize-backend',
      backend: savedBackend
    }))
  })

  return server
}

function makeSocketClient() {
  // The socket client connects to a server and sends/receives commands to/from
  // that server. This doesn't actually connect the socket to a port/host; that
  // is the caller's responsibility (use client.socket.connect()).

  const client = new EventEmitter()
  client.socket = new net.Socket()

  client.sendCommand = function(command) {
    const data = serializeCommandToData(command)
    client.socket.write(data)
  }

  client.socket.on('data', data => {
    // Same sort of "guarding" deserialization/validation as in the server
    // code, because it's possible the client and server backends mismatch.

    for (const line of data.toString().split('\n')) {
      let command
      try {
        command = deserializeDataToCommand(line)
      } catch (error) {
        return
      }

      if (!validateCommand(command)) {
        return
      }

      client.emit('command', command)
    }
  })

  return client
}

function attachBackendToSocketClient(backend, client, {
  getPlaylistSources
}) {
  // All actual logic for instances of the mtui backend interacting with each
  // other through commands lives here.

  client.on('command', async command => {
    switch (command.sender) {
      case 'server':
        switch (command.code) {
          case 'initialize-backend':
            await restoreBackend(backend, command.backend)
            // TODO: does this need to be called here?
            updateRestoredTracksUsingPlaylists(backend, getPlaylistSources())
            backend.on('playing', QP => {
              QP.once('received time data', () => {
                client.sendCommand({code: 'status', status: 'sync-playback'})
              })
            })
            return
        }
        // Again, no pause. Client commands can come from the server.
      case 'client': {
        let QP = (
          command.queuePlayer &&
          backend.queuePlayers.find(QP => QP.id === command.queuePlayer)
        )

        switch (command.code) {
          case 'seek-to':
            if (QP) QP.seekTo(command.time)
            return
          case 'set-pause':
            if (QP) QP.setPause(command.paused)
            return
        }
      }
    }
  })

  backend.on('toggle-pause', queuePlayer => {
    client.sendCommand({
      code: 'set-pause',
      queuePlayer: queuePlayer.id,
      paused: queuePlayer.player.isPaused
    })
  })

  function handleSeek(queuePlayer) {
    client.sendCommand({
      code: 'seek-to',
      queuePlayer: queuePlayer.id,
      time: queuePlayer.time
    })
  }

  backend.on('seek-ahead', handleSeek)
  backend.on('seek-back', handleSeek)
  backend.on('seek-to', handleSeek)
}

function attachSocketServerToBackend(server, backend) {
  // Unlike the function for attaching a backend to follow commands from a
  // client (attachBackendToSocketClient), this function is minimalistic.
  // It just sets the associated "canonical" backend. Actual logic for
  // de/serialization lives in serialized-backend.js.
  server.canonicalBackend = backend
}

Object.assign(module.exports, {
  makeSocketServer,
  makeSocketClient,
  attachBackendToSocketClient,
  attachSocketServerToBackend
})