]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/webtorrent.ts
3c9a0b96ae87b21d942da729634c1e4250b4766a
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
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'
6 import { dirname, join } from 'path'
7
8 async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
9 const id = target.magnetUri || target.torrentName
10 let timer
11
12 const path = generateVideoImportTmpPath(id)
13 logger.info('Importing torrent video %s', id)
14
15 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
16 await ensureDir(directoryPath)
17
18 return new Promise<string>((res, rej) => {
19 const webtorrent = new WebTorrent()
20 let file: WebTorrent.TorrentFile
21
22 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
23
24 const options = { path: directoryPath }
25 const torrent = webtorrent.add(torrentId, options, torrent => {
26 if (torrent.files.length !== 1) {
27 if (timer) clearTimeout(timer)
28
29 for (let file of torrent.files) {
30 deleteDownloadedFile({ directoryPath, filepath: file.path })
31 }
32
33 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
34 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
35 }
36
37 file = torrent.files[ 0 ]
38
39 // FIXME: avoid creating another stream when https://github.com/webtorrent/webtorrent/issues/1517 is fixed
40 const writeStream = createWriteStream(path)
41 writeStream.on('finish', () => {
42 if (timer) clearTimeout(timer)
43
44 return safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
45 .then(() => res(path))
46 })
47
48 file.createReadStream().pipe(writeStream)
49 })
50
51 torrent.on('error', err => rej(err))
52
53 timer = setTimeout(async () => {
54 return safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
55 .then(() => rej(new Error('Webtorrent download timeout.')))
56 }, timeout)
57 })
58 }
59
60 // ---------------------------------------------------------------------------
61
62 export {
63 downloadWebTorrentVideo
64 }
65
66 // ---------------------------------------------------------------------------
67
68 function safeWebtorrentDestroy (
69 webtorrent: WebTorrent.Instance,
70 torrentId: string,
71 downloadedFile?: { directoryPath: string, filepath: string },
72 torrentName?: string
73 ) {
74 return new Promise(res => {
75 webtorrent.destroy(err => {
76 // Delete torrent file
77 if (torrentName) {
78 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
79 remove(torrentId)
80 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
81 }
82
83 // Delete downloaded file
84 if (downloadedFile) deleteDownloadedFile(downloadedFile)
85
86 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
87
88 return res()
89 })
90 })
91 }
92
93 function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
94 // We want to delete the base directory
95 let pathToDelete = dirname(downloadedFile.filepath)
96 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
97
98 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
99
100 logger.debug('Removing %s after webtorrent download.', toRemovePath)
101 remove(toRemovePath)
102 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
103 }