]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/webtorrent.ts
04b3ac71b57f4cc4ec51444ed555ad9ccad4850e
[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 } from 'fs'
5 import { Instance as ParseTorrent } from 'parse-torrent'
6 import { CONFIG } from '../initializers'
7 import { join } from 'path'
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 const torrent = webtorrent.add(torrentId, torrent => {
20 if (torrent.files.length !== 1) return rej(new Error('The number of files is not equal to 1 for ' + torrentId))
21
22 const file = torrent.files[ 0 ]
23 file.createReadStream().pipe(createWriteStream(path))
24 })
25
26 torrent.on('done', () => res(path))
27
28 torrent.on('error', err => rej(err))
29 })
30 }
31
32 // ---------------------------------------------------------------------------
33
34 export {
35 downloadWebTorrentVideo
36 }