1 import { logger } from './logger'
2 import { generateVideoTmpPath } from './utils'
3 import * as WebTorrent from 'webtorrent'
4 import { createWriteStream, remove } from 'fs-extra'
5 import { CONFIG } from '../initializers'
6 import { join } from 'path'
8 function downloadWebTorrentVideo (target: { magnetUri: string, torrentName: string }) {
9 const id = target.magnetUri || target.torrentName
11 const path = generateVideoTmpPath(id)
12 logger.info('Importing torrent video %s', id)
14 return new Promise<string>((res, rej) => {
15 const webtorrent = new WebTorrent()
17 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
19 const options = { path: CONFIG.STORAGE.VIDEOS_DIR }
20 const torrent = webtorrent.add(torrentId, options, torrent => {
21 if (torrent.files.length !== 1) return rej(new Error('The number of files is not equal to 1 for ' + torrentId))
23 const file = torrent.files[ 0 ]
25 const writeStream = createWriteStream(path)
26 writeStream.on('finish', () => {
27 webtorrent.destroy(async err => {
28 if (err) return rej(err)
30 if (target.torrentName) {
32 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
35 remove(join(CONFIG.STORAGE.VIDEOS_DIR, file.name))
36 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', file.name, { err }))
42 file.createReadStream().pipe(writeStream)
45 torrent.on('error', err => rej(err))
49 // ---------------------------------------------------------------------------
52 downloadWebTorrentVideo