Import magnets with webtorrent
[oweals/peertube.git] / server / helpers / webtorrent.ts
1 import { logger } from './logger'
2 import { generateVideoTmpPath } from './utils'
3 import * as WebTorrent from 'webtorrent'
4 import { createWriteStream } from 'fs'
5
6 function downloadWebTorrentVideo (target: string) {
7   const path = generateVideoTmpPath(target)
8
9   logger.info('Importing torrent video %s', target)
10
11   return new Promise<string>((res, rej) => {
12     const webtorrent = new WebTorrent()
13
14     const torrent = webtorrent.add(target, torrent => {
15       if (torrent.files.length !== 1) throw new Error('The number of files is not equal to 1 for ' + target)
16
17       const file = torrent.files[ 0 ]
18       file.createReadStream().pipe(createWriteStream(path))
19     })
20
21     torrent.on('done', () => res(path))
22
23     torrent.on('error', err => rej(err))
24   })
25 }
26
27 // ---------------------------------------------------------------------------
28
29 export {
30   downloadWebTorrentVideo
31 }