Refractor user quota SQL queries
[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, remove } from 'fs-extra'
5 import { CONFIG } from '../initializers'
6 import { join } from 'path'
7
8 function downloadWebTorrentVideo (target: { magnetUri: string, torrentName: string }) {
9   const id = target.magnetUri || target.torrentName
10
11   const path = generateVideoTmpPath(id)
12   logger.info('Importing torrent video %s', id)
13
14   return new Promise<string>((res, rej) => {
15     const webtorrent = new WebTorrent()
16
17     const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
18
19     const options = { path: CONFIG.STORAGE.VIDEOS_DIR }
20     const torrent = webtorrent.add(torrentId, options, torrent => {
21       if (torrent.files.length !== 1) return rej(new Error('The number of files is not equal to 1 for ' + torrentId))
22
23       const file = torrent.files[ 0 ]
24
25       const writeStream = createWriteStream(path)
26       writeStream.on('finish', () => {
27         webtorrent.destroy(async err => {
28           if (err) return rej(err)
29
30           if (target.torrentName) {
31             remove(torrentId)
32               .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
33           }
34
35           remove(join(CONFIG.STORAGE.VIDEOS_DIR, file.name))
36             .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', file.name, { err }))
37
38           res(path)
39         })
40       })
41
42       file.createReadStream().pipe(writeStream)
43     })
44
45     torrent.on('error', err => rej(err))
46   })
47 }
48
49 // ---------------------------------------------------------------------------
50
51 export {
52   downloadWebTorrentVideo
53 }