« get me outta code hell

move data-handling code inside connection handler - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
diff options
context:
space:
mode:
authorFlorrie <towerofnix@gmail.com>2020-07-12 17:38:06 -0300
committer(quasar) nebula <qznebula@protonmail.com>2024-05-16 19:03:13 -0300
commita0c63e60f80d5d8a881fa98015b54b9803529bb9 (patch)
treeca904d779aafc4fddb88a569a2e2d3d3f80aba3f
parent50a70ed6a332ec1e8a2e17ca94e74252e1a8cdcb (diff)
move data-handling code inside connection handler
This should make it easier to add state for individual sockets, which
will be needed in coding better data handling.

(Update: Actually, that wasn't necessary, because I wrote it as a more
general wrapper function which contains its own state. Still, this could
come in useful in the future, and it arguably reduces the code
complexity anyway.)
-rw-r--r--socket.js136
1 files changed, 67 insertions, 69 deletions
diff --git a/socket.js b/socket.js
index 61d3a62..52efb4d 100644
--- a/socket.js
+++ b/socket.js
@@ -191,97 +191,95 @@ export function makeSocketServer() {
   // readyToResume -> queue player id -> array: socket
   const readyToResume = {}
 
-  function receivedData(socket, data) {
-    // Parse data as a command and validate it. If invalid, drop this data.
+  server.on('connection', socket => {
+    sockets.push(socket)
 
-    for (const line of data.toString().trim().split('\n')) {
-      let command
-      try {
-        command = deserializeDataToCommand(line)
-      } catch (error) {
-        return
+    socket.on('close', () => {
+      if (sockets.includes(socket)) {
+        sockets.splice(sockets.indexOf(socket), 1)
       }
+    })
 
-      command.sender = 'client'
+    socket.on('data', data => {
+      // Parse data as a command and validate it. If invalid, drop this data.
 
-      if (!validateCommand(command)) {
-        return
-      }
+      for (const line of data.toString().trim().split('\n')) {
+        let command
+        try {
+          command = deserializeDataToCommand(line)
+        } catch (error) {
+          return
+        }
+
+        command.sender = 'client'
 
-      // If it's a status command, respond appropriately, and return so that it
-      // is not relayed.
-
-      if (command.code === 'status') {
-        switch (command.status) {
-          case 'ready-to-resume': {
-            const readySockets = readyToResume[command.queuePlayer]
-            if (readySockets && !readySockets.includes(socket)) {
-              readySockets.push(socket)
-              if (readySockets.length === sockets.length) {
-                for (const socket of sockets) {
+        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 'ready-to-resume': {
+              const readySockets = readyToResume[command.queuePlayer]
+              if (readySockets && !readySockets.includes(socket)) {
+                readySockets.push(socket)
+                if (readySockets.length === sockets.length) {
+                  for (const socket of sockets) {
+                    socket.write(JSON.stringify({
+                      sender: 'server',
+                      code: 'set-pause',
+                      queuePlayer: command.queuePlayer,
+                      startingTrack: true,
+                      paused: false
+                    }) + '\n')
+                  }
+                  delete readyToResume[command.queuePlayer]
+                }
+              }
+              break
+            }
+            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: command.queuePlayer,
+                    queuePlayer: QP.id,
                     startingTrack: true,
-                    paused: false
+                    paused: QP.player.isPaused
                   }) + '\n')
                 }
-                delete readyToResume[command.queuePlayer]
               }
-            }
-            break
+              break
           }
-          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,
-                  startingTrack: true,
-                  paused: QP.player.isPaused
-                }) + '\n')
-              }
-            }
-            break
+          return
         }
-        return
-      }
-
-      // If it's a 'play' command, set up a new readyToResume array.
-
-      if (command.code === 'play') {
-        readyToResume[command.queuePlayer] = []
-      }
 
-      // Relay the command to client sockets besides the sender.
+        // If it's a 'play' command, set up a new readyToResume array.
 
-      const otherSockets = sockets.filter(s => s !== socket)
+        if (command.code === 'play') {
+          readyToResume[command.queuePlayer] = []
+        }
 
-      for (const socket of otherSockets) {
-        socket.write(JSON.stringify(command) + '\n')
-      }
-    }
-  }
+        // Relay the command to client sockets besides the sender.
 
-  server.on('connection', socket => {
-    sockets.push(socket)
+        const otherSockets = sockets.filter(s => s !== socket)
 
-    socket.on('close', () => {
-      if (sockets.includes(socket)) {
-        sockets.splice(sockets.indexOf(socket), 1)
+        for (const socket of otherSockets) {
+          socket.write(JSON.stringify(command) + '\n')
+        }
       }
     })
 
-    socket.on('data', data => receivedData(socket, data))
-
     const savedBackend = saveBackend(server.canonicalBackend)
 
     for (const qpData of savedBackend.queuePlayers) {