]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/webtorrent.ts
f4b44bc4ff6c452ca352cd77ccba41ac1580dba5
[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 { createWriteStream, 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 const path = generateVideoTmpPath(id)
13 logger.info('Importing torrent video %s', id)
14
15 return new Promise<string>((res, rej) => {
16 const webtorrent = new WebTorrent()
17 let file: WebTorrent.TorrentFile
18
19 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
20
21 const options = { path: CONFIG.STORAGE.VIDEOS_DIR }
22 const torrent = webtorrent.add(torrentId, options, torrent => {
23 if (torrent.files.length !== 1) {
24 if (timer) clearTimeout(timer)
25
26 return safeWebtorrentDestroy(webtorrent, torrentId, file.name, target.torrentName)
27 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
28 }
29
30 file = torrent.files[ 0 ]
31
32 const writeStream = createWriteStream(path)
33 writeStream.on('finish', () => {
34 if (timer) clearTimeout(timer)
35
36 return safeWebtorrentDestroy(webtorrent, torrentId, file.name, target.torrentName)
37 .then(() => res(path))
38 })
39
40 file.createReadStream().pipe(writeStream)
41 })
42
43 torrent.on('error', err => rej(err))
44
45 if (timeout) {
46 timer = setTimeout(async () => {
47 return safeWebtorrentDestroy(webtorrent, torrentId, file ? file.name : undefined, target.torrentName)
48 .then(() => rej(new Error('Webtorrent download timeout.')))
49 }, timeout)
50 }
51 })
52 }
53
54 // ---------------------------------------------------------------------------
55
56 export {
57 downloadWebTorrentVideo
58 }
59
60 // ---------------------------------------------------------------------------
61
62 function safeWebtorrentDestroy (webtorrent: WebTorrent.Instance, torrentId: string, filename?: string, torrentName?: string) {
63 return new Promise(res => {
64 webtorrent.destroy(err => {
65 // Delete torrent file
66 if (torrentName) {
67 remove(torrentId)
68 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
69 }
70
71 // Delete downloaded file
72 if (filename) {
73 remove(join(CONFIG.STORAGE.VIDEOS_DIR, filename))
74 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', filename, { err }))
75 }
76
77 if (err) {
78 logger.warn('Cannot destroy webtorrent in timeout.', { err })
79 }
80
81 return res()
82 })
83 })
84 }