1 import { logger } from './logger'
2 import { generateVideoImportTmpPath } from './utils'
3 import * as WebTorrent from 'webtorrent'
4 import { createWriteStream, ensureDir, remove } from 'fs-extra'
5 import { CONFIG } from '../initializers/config'
6 import { dirname, join } from 'path'
7 import * as createTorrent from 'create-torrent'
8 import { promisify2 } from './core-utils'
10 async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
11 const id = target.magnetUri || target.torrentName
14 const path = generateVideoImportTmpPath(id)
15 logger.info('Importing torrent video %s', id)
17 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
18 await ensureDir(directoryPath)
20 return new Promise<string>((res, rej) => {
21 const webtorrent = new WebTorrent()
22 let file: WebTorrent.TorrentFile
24 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
26 const options = { path: directoryPath }
27 const torrent = webtorrent.add(torrentId, options, torrent => {
28 if (torrent.files.length !== 1) {
29 if (timer) clearTimeout(timer)
31 for (let file of torrent.files) {
32 deleteDownloadedFile({ directoryPath, filepath: file.path })
35 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
36 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
39 file = torrent.files[ 0 ]
41 // FIXME: avoid creating another stream when https://github.com/webtorrent/webtorrent/issues/1517 is fixed
42 const writeStream = createWriteStream(path)
43 writeStream.on('finish', () => {
44 if (timer) clearTimeout(timer)
46 return safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
47 .then(() => res(path))
50 file.createReadStream().pipe(writeStream)
53 torrent.on('error', err => rej(err))
55 timer = setTimeout(async () => {
56 return safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
57 .then(() => rej(new Error('Webtorrent download timeout.')))
62 const createTorrentPromise = promisify2<string, any, any>(createTorrent)
64 // ---------------------------------------------------------------------------
68 downloadWebTorrentVideo
71 // ---------------------------------------------------------------------------
73 function safeWebtorrentDestroy (
74 webtorrent: WebTorrent.Instance,
76 downloadedFile?: { directoryPath: string, filepath: string },
79 return new Promise(res => {
80 webtorrent.destroy(err => {
81 // Delete torrent file
83 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
85 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
88 // Delete downloaded file
89 if (downloadedFile) deleteDownloadedFile(downloadedFile)
91 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
98 function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
99 // We want to delete the base directory
100 let pathToDelete = dirname(downloadedFile.filepath)
101 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
103 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
105 logger.debug('Removing %s after webtorrent download.', toRemovePath)
107 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))