All files / server service.js

100% Statements 43/43
100% Branches 4/4
100% Functions 13/13
100% Lines 41/41

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                                                                  3x     18x 18x 18x 18x 18x       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          
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 {
  join,
  extname
} from 'path'
const {
  dir: {
    publicDirectory
  },
  constants: {
    fallbackBitRate,
    englishConversation,
    bitRateDivisor
  }
} = 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
    }
  }
}