All files / server service.js

100% Statements 66/66
100% Branches 6/6
100% Functions 18/18
100% Lines 62/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229                                                                          3x     22x 22x 22x 22x 22x       1x 1x 1x   1x               1x       1x       2x 2x                 2x   2x         4x 2x 1x           1x   1x         1x   1x   2x 1x 1x     1x     1x         1x 1x 1x 1x 1x               2x       2x         1x   1x 1x 1x                   1x 1x             2x 2x 2x   1x       1x 1x         1x 1x   1x 1x 1x   1x           1x 1x 1x         1x 1x                             1x       1x           1x           1x    
import fs from 'fs'
import fsPromises from 'fs/promises'
import {
  randomUUID
} from 'crypto'
import config from './config.js'
import {
  PassThrough,
  Writable
} from 'stream'
import {
  once
} from 'events'
import streamsPromises from 'stream/promises'
 
import Throttle from 'throttle'
import childProcess from 'child_process'
import {
  logger
} from './util.js'
import path, {
  join,
  extname
} from 'path'
const {
  dir: {
    publicDirectory,
    fxDirectory
  },
  constants: {
    fallbackBitRate,
    englishConversation,
    bitRateDivisor,
    audioMediaType,
    songVolume,
    fxVolume
  }
} = config
export class Service {
  constructor() {
    this.clientStreams = new Map()
    this.currentSong = englishConversation
    this.currentBitRate = 0
    this.throttleTransform = {}
    this.currentReadable = {}
  }
 
  createClientStream() {
    const id = randomUUID()
    const clientStream = new PassThrough()
    this.clientStreams.set(id, clientStream)
 
    return {
      id,
      clientStream
    }
 
  }
 
  removeClientStream(id) {
    this.clientStreams.delete(id)
  }
 
  _executeSoxCommand(args) {
    return childProcess.spawn('sox', args)
  }
 
  async getBitRate(song) {
    try {
      const args = [
        '--i', // info
        '-B', // bitrate
        song
      ]
      const {
        stderr, // tudo que é erro
        stdout, // tudo que é log
        // stdin // enviar dados como stream
      } = this._executeSoxCommand(args)
 
      await Promise.all([
        once(stderr, 'readable'),
        once(stdout, 'readable'),
      ])
 
      const [success, error] = [stdout, stderr].map(stream => stream.read())
      if (error) return await Promise.reject(error)
      return success
        .toString()
        .trim()
        .replace(/k/, '000')
 
    } catch (error) {
      logger.error(`deu ruim no bitrate: ${error}`)
 
      return fallbackBitRate
    }
  }
 
  broadCast() {
    return new Writable({
      write: (chunk, enc, cb) => {
        for (const [id, stream] of this.clientStreams) {
          // se o cliente descontou não devemos mais mandar dados pra ele
          if (stream.writableEnded) {
            this.clientStreams.delete(id)
            continue;
          }
 
          stream.write(chunk)
        }
 
        cb()
      }
    })
  }
  async startStreamming() {
    logger.info(`starting with ${this.currentSong}`)
    const bitRate = this.currentBitRate = (await this.getBitRate(this.currentSong)) / bitRateDivisor
    const throttleTransform = this.throttleTransform = new Throttle(bitRate)
    const songReadable = this.currentReadable = this.createFileStream(this.currentSong)
    return streamsPromises.pipeline(
      songReadable,
      throttleTransform,
      this.broadCast()
    )
  }
 
  stopStreamming() {
    this.throttleTransform?.end?.()
  }
 
  createFileStream(filename) {
    return fs.createReadStream(filename)
  }
 
  async getFileInfo(file) {
    // file = home/index.html
    const fullFilePath = join(publicDirectory, file)
    // valida se existe, se não existe estoura erro!!
    await fsPromises.access(fullFilePath)
    const fileType = extname(fullFilePath)
    return {
      type: fileType,
      name: fullFilePath
    }
  }
 
  async getFileStream(file) {
    const {
      name,
      type
    } = await this.getFileInfo(file)
    return {
      stream: this.createFileStream(name),
      type
    }
  }
 
  async readFxByName(fxName) {
    const songs = await fsPromises.readdir(fxDirectory)
    const chosenSong = songs.find(filename => filename.toLowerCase().includes(fxName))
    if (!chosenSong) return Promise.reject(`the song ${fxName} wasn't found!`)
 
    return path.join(fxDirectory, chosenSong)
  }
 
  appendFxStream(fx) {
    const throttleTransformable = new Throttle(this.currentBitRate)
    streamsPromises.pipeline(
      throttleTransformable,
      this.broadCast()
    )
 
    const unpipe = () => {
      const transformStream = this.mergeAudioStreams(fx, this.currentReadable)
 
      this.throttleTransform = throttleTransformable
      this.currentReadable = transformStream
      this.currentReadable.removeListener('unpipe', unpipe)
 
      streamsPromises.pipeline(
        transformStream,
        throttleTransformable
      )
 
    }
    this.throttleTransform.on('unpipe', unpipe)
    this.throttleTransform.pause()
    this.currentReadable.unpipe(this.throttleTransform)
  }
 
 
  mergeAudioStreams(song, readable) {
    const transformStream = PassThrough()
    const args = [
      '-t', audioMediaType,
      '-v', songVolume,
      // -m => merge -> o - é para receber como stream
      '-m', '-',
      '-t', audioMediaType,
      '-v', fxVolume,
      song,
      '-t', audioMediaType,
      '-'
    ]
 
    const {
      stdout,
      stdin
    } = this._executeSoxCommand(args)
 
    // plugamos a stream de conversacao
    // na entrada de dados do terminal
    streamsPromises.pipeline(
        readable,
        stdin
      )
      // .catch(error => logger.error(`error on sending stream to sox: ${error}`))
 
    streamsPromises.pipeline(
        stdout,
        transformStream
      )
      // .catch(error => logger.error(`error on receiving stream from sox: ${error}`))
 
    return transformStream
  }
}