const net = require('net'); const { sleep } = require('../libs/util'); const Message = require('./Message'); class Audiostream { constructor(eventParser) { this.eventParser = eventParser; this.#handleEvents(); } getHost() { return this.host; } getPort() { return this.port; } getTag() { return this.getHost() + ':' + this.getPort(); } #initialize(data) { this.host = config?.server?.host || "127.0.0.1"; this.port = data.port; this.clientId = data.clientId; this.size = data.size; this.threshold = data.threshold; this.#handleSocket(net.connect({ host: this.getHost(), port: this.getPort() })); } #handleEvents() { this.eventParser.on('audio:initialize', (data) => { logger.debug('handling event \'audio:initialize\'...'); this.#initialize(data); }); this.eventParser.on('audio:play', (data) => { logger.debug('handling event \'audio:play\'...'); global.player.play(data?.position); }); this.eventParser.on('audio:pause', (data) => { logger.debug('handling event \'audio:pause\'...'); global.player.pause(); }); this.eventParser.on('audio:stop', () => { logger.debug('handling event \'audio:stop\'...'); global.player.stop(); }); global.player.on('statechange', (data) => { new Message('audio:state', { clientId: this.clientId, state: data.state, position: global.player.getPosition() }).send(); }); } #handleSocket(socket) { socket.on('connect', async () => { logger.debug('connected to audio server \'' + this.getTag() + '\'...'); await global.player.prepare(this.size, this.threshold); new Message('audio:register', { clientId: this.clientId, port: socket.localPort }).send(); }); socket.on('error', (error) => { logger.error('error connecting to audio server \'' + this.getTag() + '\': ' + error); }); socket.on('timeout', () => { logger.warn('connection to audio server \'' + this.getTag() + '\' timed out'); }); socket.on('data', (data) => { global.player.feed(data); }); socket.on('end', () => { logger.info('connection to audio server \'' + this.getTag() + '\' ended'); }); socket.on('close', () => { logger.info('connection to audio server \'' + this.getTag() + '\' closed'); global.player.stopFeed(); }); } } module.exports = Audiostream;