]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/webtorrent.ts
Fix redundancy bug with old peertube torrent
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
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'
7
8 function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout?: number) {
9 const id = target.magnetUri || target.torrentName
10 let timer
11
12 logger.info('Importing torrent video %s', id)
13
14 return new Promise<string>((res, rej) => {
15 const webtorrent = new WebTorrent()
16 let file: WebTorrent.TorrentFile
17
18 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
19
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)
24
25 return safeWebtorrentDestroy(webtorrent, torrentId, file.name, target.torrentName)
26 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
27 }
28
29 torrent.on('done', () => res(join(CONFIG.STORAGE.VIDEOS_DIR, torrent.files[ 0 ].path)))
30 })
31
32 torrent.on('error', err => rej(err))
33
34 if (timeout) {
35 timer = setTimeout(async () => {
36 return safeWebtorrentDestroy(webtorrent, torrentId, file ? file.name : undefined, target.torrentName)
37 .then(() => rej(new Error('Webtorrent download timeout.')))
38 }, timeout)
39 }
40 })
41 }
42
43 // ---------------------------------------------------------------------------
44
45 export {
46 downloadWebTorrentVideo
47 }
48
49 // ---------------------------------------------------------------------------
50
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
55 if (torrentName) {
56 remove(torrentId)
57 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
58 }
59
60 // Delete downloaded file
61 if (filename) {
62 remove(join(CONFIG.STORAGE.VIDEOS_DIR, filename))
63 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', filename, { err }))
64 }
65
66 if (err) {
67 logger.warn('Cannot destroy webtorrent in timeout.', { err })
68 }
69
70 return res()
71 })
72 })
73 }