]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/webtorrent.ts
Move createTorrent in webtorrent utils
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
CommitLineData
ce33919c 1import { logger } from './logger'
6040f87d 2import { generateVideoImportTmpPath } from './utils'
ce33919c 3import * as WebTorrent from 'webtorrent'
a71de50b 4import { createWriteStream, ensureDir, remove } from 'fs-extra'
6dd9de95 5import { CONFIG } from '../initializers/config'
d0b52b52 6import { dirname, join } from 'path'
30ff39e7
C
7import * as createTorrent from 'create-torrent'
8import { promisify2 } from './core-utils'
ce33919c 9
cf9166cf 10async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
990b6a0b 11 const id = target.magnetUri || target.torrentName
c48e82b5 12 let timer
ce33919c 13
6040f87d 14 const path = generateVideoImportTmpPath(id)
990b6a0b 15 logger.info('Importing torrent video %s', id)
ce33919c 16
6040f87d 17 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
a71de50b
C
18 await ensureDir(directoryPath)
19
ce33919c
C
20 return new Promise<string>((res, rej) => {
21 const webtorrent = new WebTorrent()
c48e82b5 22 let file: WebTorrent.TorrentFile
ce33919c 23
990b6a0b 24 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
541006e3 25
a71de50b 26 const options = { path: directoryPath }
541006e3 27 const torrent = webtorrent.add(torrentId, options, torrent => {
c48e82b5
C
28 if (torrent.files.length !== 1) {
29 if (timer) clearTimeout(timer)
ce33919c 30
e37c85e9
C
31 for (let file of torrent.files) {
32 deleteDownloadedFile({ directoryPath, filepath: file.path })
33 }
34
35 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
dae4a1c0 36 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
c48e82b5
C
37 }
38
a71de50b
C
39 file = torrent.files[ 0 ]
40
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)
45
d0b52b52 46 return safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
a71de50b 47 .then(() => res(path))
69fa54a0 48 })
a71de50b
C
49
50 file.createReadStream().pipe(writeStream)
3e17515e 51 })
ce33919c
C
52
53 torrent.on('error', err => rej(err))
c48e82b5 54
cf9166cf
C
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.')))
58 }, timeout)
ce33919c
C
59 })
60}
61
30ff39e7
C
62const createTorrentPromise = promisify2<string, any, any>(createTorrent)
63
ce33919c
C
64// ---------------------------------------------------------------------------
65
66export {
30ff39e7 67 createTorrentPromise,
ce33919c
C
68 downloadWebTorrentVideo
69}
c48e82b5
C
70
71// ---------------------------------------------------------------------------
72
d0b52b52
C
73function safeWebtorrentDestroy (
74 webtorrent: WebTorrent.Instance,
75 torrentId: string,
76 downloadedFile?: { directoryPath: string, filepath: string },
77 torrentName?: string
78) {
c48e82b5
C
79 return new Promise(res => {
80 webtorrent.destroy(err => {
81 // Delete torrent file
82 if (torrentName) {
d0b52b52 83 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
c48e82b5
C
84 remove(torrentId)
85 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
86 }
87
88 // Delete downloaded file
e37c85e9 89 if (downloadedFile) deleteDownloadedFile(downloadedFile)
c48e82b5 90
e37c85e9 91 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
c48e82b5
C
92
93 return res()
94 })
95 })
96}
e37c85e9
C
97
98function 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
102
103 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
104
105 logger.debug('Removing %s after webtorrent download.', toRemovePath)
106 remove(toRemovePath)
107 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
108}