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 }, timeout?: number) {
9 const id = target.magnetUri || target.torrentName
12 const path = generateVideoTmpPath(id)
13 logger.info('Importing torrent video %s', id)
15 return new Promise<string>((res, rej) => {
16 const webtorrent = new WebTorrent()
17 let file: WebTorrent.TorrentFile
19 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
21 const options = { path: CONFIG.STORAGE.VIDEOS_DIR }
22 const torrent = webtorrent.add(torrentId, options, torrent => {
23 if (torrent.files.length !== 1) {
24 if (timer) clearTimeout(timer)
26 return safeWebtorrentDestroy(webtorrent, torrentId, file.name, target.torrentName)
27 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
30 file = torrent.files[ 0 ]
32 const writeStream = createWriteStream(path)
33 writeStream.on('finish', () => {
34 if (timer) clearTimeout(timer)
36 return safeWebtorrentDestroy(webtorrent, torrentId, file.name, target.torrentName)
37 .then(() => res(path))
40 file.createReadStream().pipe(writeStream)
43 torrent.on('error', err => rej(err))
46 timer = setTimeout(async () => {
47 return safeWebtorrentDestroy(webtorrent, torrentId, file ? file.name : undefined, target.torrentName)
48 .then(() => rej(new Error('Webtorrent download timeout.')))
54 // ---------------------------------------------------------------------------
57 downloadWebTorrentVideo
60 // ---------------------------------------------------------------------------
62 function safeWebtorrentDestroy (webtorrent: WebTorrent.Instance, torrentId: string, filename?: string, torrentName?: string) {
63 return new Promise(res => {
64 webtorrent.destroy(err => {
65 // Delete torrent file
68 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
71 // Delete downloaded file
73 remove(join(CONFIG.STORAGE.VIDEOS_DIR, filename))
74 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', filename, { err }))
78 logger.warn('Cannot destroy webtorrent in timeout.', { err })