studiox-streamer/backend/baresip.mjs

103 lines
3 KiB
JavaScript

import p from 'path'
import split2 from 'split2'
import { Readable } from 'streamx'
import { spawn } from 'child_process'
import { fileURLToPath } from 'url';
import BaresipWrapper from './lib/baresip-wrapper.mjs'
const __dirname = p.dirname(fileURLToPath(import.meta.url))
import { action, STREAM_STATUS, LOG_MESSAGE } from './state.mjs'
export class Baresip {
constructor (opts = {}) {
this.command = opts.command || 'baresip'
this.config = opts.config || p.join(__dirname, '..', 'etc', 'baresip')
this.stream = new Readable()
this.log = []
this.stream.on('data', row => this.log.push(row))
this.id = 'baresip'
this.destinationNumber = opts.destination || 901
}
restart () {
if (!this.baresip) return this.start()
this.stop(() => {
process.nextTick(() => {
this.start()
})
})
}
stop (cb) {
// this.process.kill()
if (!this.baresip) return
this.baresip.kill(() => {
this.stream.push(action(STREAM_STATUS, { id: this.id, status: 'stopped' }))
if (cb) cb()
})
}
_onready () {
console.log('baresip onready')
}
_oncallestablished (number) {
console.log('call established to', number)
this.stream.push(action(STREAM_STATUS, { id: this.id, status: 'started' }))
}
_onhangup (number) {
console.log('remote hangup', number)
this.stream.push(action(STREAM_STATUS, { id: this.id, status: 'stopped' }))
}
_onserverconnected (...args) {
console.log('onserverconnected', args)
setTimeout(() => {
this.baresip.dial(this.destinationNumber)
}, 1000)
}
start () {
const args = ['-f', this.config]
this.baresip = new BaresipWrapper({
command: this.command,
args,
callbacks: {
ready: this._onready.bind(this),
hangUp: this._onhangup.bind(this),
callEstablished: this._oncallestablished.bind(this),
serverConnected: this._onserverconnected.bind(this)
}
})
this.baresip.stream.on('data', message => {
// console.log('BARESIP', message)
this.stream.push(action(LOG_MESSAGE, { id: this.id, type: 'stdout', message }))
})
this.baresip.connect()
// if (this.process) return
// const args = ['-c', this.config, '-v', this.logLevel]
// this.process = spawn(this.command, args)
// this.process.stdout.pipe(split2()).on('data', message => {
// this.stream.push(action(LOG_MESSAGE, { id: this.id, type: 'stdout', message }))
// // this.stream.push({ type: 'stdout', data })
// })
// this.process.stderr.pipe(split2()).on('data', message => {
// this.stream.push(action(LOG_MESSAGE, { id: this.id, type: 'stdout', message }))
// // this.stream.push({ type: 'stderr', data })
// })
// this.process.on('close', () => {
// this.stream.push(action(STREAM_STATUS, { id: this.id, status: 'stopped' }))
// this.process = null
// })
// this.stream.push(action(STREAM_STATUS, { id: this.id, status: 'started' }))
// return new Promise((resolve, reject) => {
// resolve()
// })
}
}