1 import { logger } from './logger'
2 import { generateVideoTmpPath } from './utils'
3 import * as WebTorrent from 'webtorrent'
4 import { 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 logger.info('Importing torrent video %s', id)
14 return new Promise<string>((res, rej) => {
15 const webtorrent = new WebTorrent()
16 let file: WebTorrent.TorrentFile
18 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
20 const options = { path: CONFIG.STORAGE.VIDEOS_DIR }
21 const torrent = webtorrent.add(torrentId, options, torrent => {
22 if (torrent.files.length !== 1) {
23 if (timer) clearTimeout(timer)
25 return safeWebtorrentDestroy(webtorrent, torrentId, file.name, target.torrentName)
26 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
29 torrent.on('done', () => res(join(CONFIG.STORAGE.VIDEOS_DIR, torrent.files[ 0 ].path)))
32 torrent.on('error', err => rej(err))
35 timer = setTimeout(async () => {
36 return safeWebtorrentDestroy(webtorrent, torrentId, file ? file.name : undefined, target.torrentName)
37 .then(() => rej(new Error('Webtorrent download timeout.')))
43 // ---------------------------------------------------------------------------
46 downloadWebTorrentVideo
49 // ---------------------------------------------------------------------------
51 function safeWebtorrentDestroy (webtorrent: WebTorrent.Instance, torrentId: string, filename?: string, torrentName?: string) {
52 return new Promise(res => {
53 webtorrent.destroy(err => {
54 // Delete torrent file
57 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
60 // Delete downloaded file
62 remove(join(CONFIG.STORAGE.VIDEOS_DIR, filename))
63 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', filename, { err }))
67 logger.warn('Cannot destroy webtorrent in timeout.', { err })