aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/webtorrent.ts
blob: fce88a1f64f5356e736516d4fa13a7ed7225ae95 (plain) (blame)
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
import { logger } from './logger'
import { generateVideoTmpPath } from './utils'
import * as WebTorrent from 'webtorrent'
import { createWriteStream } from 'fs'

function downloadWebTorrentVideo (target: string) {
  const path = generateVideoTmpPath(target)

  logger.info('Importing torrent video %s', target)

  return new Promise<string>((res, rej) => {
    const webtorrent = new WebTorrent()

    const torrent = webtorrent.add(target, torrent => {
      if (torrent.files.length !== 1) throw new Error('The number of files is not equal to 1 for ' + target)

      const file = torrent.files[ 0 ]
      file.createReadStream().pipe(createWriteStream(path))
    })

    torrent.on('done', () => res(path))

    torrent.on('error', err => rej(err))
  })
}

// ---------------------------------------------------------------------------

export {
  downloadWebTorrentVideo
}