« get me outta code hell

Handle player process crashing gracefully - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
diff options
context:
space:
mode:
authorFlorrie <towerofnix@gmail.com>2018-02-23 09:01:02 -0400
committerFlorrie <towerofnix@gmail.com>2018-02-23 09:01:04 -0400
commitcd661532bcc861d177730273130768a33928ca37 (patch)
treea420c633e7813909d2d30e7d1d7e34798c733616
parentee1fb8297bbd71faa51985556232bb75cae11274 (diff)
Handle player process crashing gracefully
E.g. try pulseaudio -k, then run http-music.
-rw-r--r--src/loop-play.js35
-rw-r--r--todo.txt1
2 files changed, 34 insertions, 2 deletions
diff --git a/src/loop-play.js b/src/loop-play.js
index 83cbcfe..c702bed 100644
--- a/src/loop-play.js
+++ b/src/loop-play.js
@@ -37,6 +37,19 @@ class Player extends EventEmitter {
     this.disablePlaybackStatus = false
   }
 
+  set process(newProcess) {
+    this._process = newProcess
+    this._process.on('exit', code => {
+      if (code !== 0) {
+        this.emit('crashed', code) // TODO: HANDLE THIS
+      }
+    })
+  }
+
+  get process() {
+    return this._process
+  }
+
   playFile(file) {}
   seekAhead(secs) {}
   seekBack(secs) {}
@@ -369,6 +382,24 @@ class PlayController extends EventEmitter {
     this.stopped = false
     this.shouldMoveNext = true
     this.failedCount = 0
+    this.playFailCount = 0
+
+    this.player.on('crashed', () => {
+      console.log('\x1b[31mFailed to play track \x1b[1m' +
+        getItemPathString(this.currentTrack) + '\x1b[0m'
+      )
+      this.playFailCount++
+
+      if (this.playFailCount >= 5) {
+        console.error(
+          '\x1b[31mFailed to play 5 tracks. Halting, to prevent damage to ' +
+          'the computer.\x1b[0m'
+        )
+
+        process.exit(1)
+        throw new Error('Intentionally halted - failed to play tracks.')
+      }
+    })
 
     this.player.on('printStatusLine', playerString => {
       let fullStatusLine = ''
@@ -544,8 +575,8 @@ class PlayController extends EventEmitter {
             "prevent damage to the computer.\x1b[0m"
           )
 
-          process.exit(0)
-          throw new Error('Intentionally halted.')
+          process.exit(1)
+          throw new Error('Intentionally halted - failed to download tracks.')
         }
 
         // A little bit blecht, but.. this works.
diff --git a/todo.txt b/todo.txt
index 83ed985..073a18b 100644
--- a/todo.txt
+++ b/todo.txt
@@ -432,3 +432,4 @@ TODO: Be a bit more loose (strict?) about what means crashing... Right now if
       command fails (i.e. mpv or sox exits with code 1), THAT should also be
       counted as a failure. (An example case of the "play" command failing --
       trying to play a track when there is no audio device.)
+      (Done!)