]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/webtorrent.ts
Underline links in feed popover when hovering
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
CommitLineData
ce33919c
C
1import { logger } from './logger'
2import { generateVideoTmpPath } from './utils'
3import * as WebTorrent from 'webtorrent'
c9d5c64f 4import { createWriteStream } from 'fs-extra'
990b6a0b
C
5import { CONFIG } from '../initializers'
6import { join } from 'path'
541006e3 7import { unlinkPromise } from './core-utils'
ce33919c 8
990b6a0b
C
9function downloadWebTorrentVideo (target: { magnetUri: string, torrentName: string }) {
10 const id = target.magnetUri || target.torrentName
ce33919c 11
990b6a0b
C
12 const path = generateVideoTmpPath(id)
13 logger.info('Importing torrent video %s', id)
ce33919c
C
14
15 return new Promise<string>((res, rej) => {
16 const webtorrent = new WebTorrent()
17
990b6a0b 18 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
541006e3
C
19
20 const options = { path: CONFIG.STORAGE.VIDEOS_DIR }
21 const torrent = webtorrent.add(torrentId, options, torrent => {
990b6a0b 22 if (torrent.files.length !== 1) return rej(new Error('The number of files is not equal to 1 for ' + torrentId))
ce33919c
C
23
24 const file = torrent.files[ 0 ]
ce33919c 25
3e17515e 26 const writeStream = createWriteStream(path)
541006e3
C
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 })
3e17515e
C
42
43 file.createReadStream().pipe(writeStream)
44 })
ce33919c
C
45
46 torrent.on('error', err => rej(err))
47 })
48}
49
50// ---------------------------------------------------------------------------
51
52export {
53 downloadWebTorrentVideo
54}