All files / node-play-mp3 index.js

100% Statements 41/41
50% Branches 1/2
100% Functions 14/14
100% Lines 41/41
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    11x 11x 11x     11x 11x 11x 12x 9x 9x 9x 9x 9x 9x 9x       11x 11x       11x 12x 12x 12x 12x 3x     12x 12x           11x 11x   2x 2x     1x 1x     5x 5x     4x 4x           11x 11x 11x 11x 11x 11x       11x  
'use strict'
 
const uuid = require('uuid/v4')
const JSONStream = require('JSONStream')
const spawn = require('electron-spawn')
 
function initElectron (pending) {
  const objects = JSONStream.parse()
  const electron = spawn(`${__dirname}/lib/electron.js`)
  objects.on('data', (data) => {
    Object.keys(data).forEach(command => {
      const params = data[command]
      const { val, commandId } = params
      Eif (pending[commandId]) {
        const { resolve, rejectTimeout } = pending[commandId]
        resolve(val)
        clearTimeout(rejectTimeout)
        delete pending[commandId]
      }
    })
  })
  electron.stdout.pipe(objects)
  return electron
}
 
function commandInstruction ({pending, id, electron}) {
  return function sendCommand (commandName, val) {
    return new Promise((resolve, reject) => {
      const commandId = uuid()
      const command = {[commandName]: {id, commandId, val}}
      const rejectTimeout = setTimeout(
        () => reject(new Error('timed out waiting for electron process')),
        500
      ) // TODO: config override
      pending[commandId] = {resolve, rejectTimeout}
      electron.stdin.write(JSON.stringify(command))
    })
  }
}
 
function api ({path, id, electron, pending}) {
  const sendCommand = commandInstruction({pending, id, electron})
  return {
    play: () => {
      const commandName = 'play'
      return sendCommand(commandName)
    },
    stop: () => {
      const commandName = 'stop'
      return sendCommand(commandName)
    },
    loop: (val) => {
      const commandName = 'loop'
      return sendCommand(commandName, val)
    },
    volume: (val) => {
      const commandName = 'volume'
      return sendCommand(commandName, val)
    }
  }
}
 
function createAudio () {
  let pending = []
  const electron = initElectron(pending)
  return function Audio (path) {
    const id = uuid()
    electron.stdin.write(JSON.stringify({open: {path, id}}))
    return api({path, id, electron, pending})
  }
}
 
module.exports = createAudio