-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
71 lines (65 loc) · 1.92 KB
/
index.js
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
'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
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 }