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