Add reason when banning a user
[oweals/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 } from 'fs'
5 import { CONFIG } from '../initializers'
6 import { join } from 'path'
7 import { unlinkPromise } from './core-utils'
8
9 function downloadWebTorrentVideo (target: { magnetUri: string, torrentName: string }) {
10   const id = target.magnetUri || target.torrentName
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
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) return rej(new Error('The number of files is not equal to 1 for ' + torrentId))
23
24       const file = torrent.files[ 0 ]
25
26       const writeStream = createWriteStream(path)
27       writeStream.on('finish', () => {
28         webtorrent.destroy(async err => {
29           if (err) return rej(err)
30
31           if (target.torrentName) {
32             unlinkPromise(torrentId)
33               .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
34           }
35
36           unlinkPromise(join(CONFIG.STORAGE.VIDEOS_DIR, file.name))
37             .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', file.name, { err }))
38
39           res(path)
40         })
41       })
42
43       file.createReadStream().pipe(writeStream)
44     })
45
46     torrent.on('error', err => rej(err))
47   })
48 }
49
50 // ---------------------------------------------------------------------------
51
52 export {
53   downloadWebTorrentVideo
54 }