« 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: 0e8759b31f3e5faa7c04c1028778ada86ce0f70b (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
// 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

import EventEmitter from 'node:events'
import * as net from 'node:net'

import {
  restoreBackend,
  saveBackend,
  updateRestoredTracksUsingPlaylists,
} from './serialized-backend.js'

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'
      }
      break
    case 'client':
      break
  }

  return false
}

export 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(data) {
    // Parse data as a command and validate it. If invalid, drop this data.

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

    if (!validateCommand(command)) {
      return
    }

    // Relay the data to client sockets.

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

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

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

    socket.on('data', receivedData)

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

  return server
}

export 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.

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

    if (!validateCommand(command)) {
      return
    }

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

  return client
}

export 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())
            break
        }
        break
    }
  })
}

export 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
}