Relax plugin package.json validation
[oweals/peertube.git] / server / helpers / webtorrent.ts
1 import { logger } from './logger'
2 import { generateVideoImportTmpPath } from './utils'
3 import * as WebTorrent from 'webtorrent'
4 import { createWriteStream, ensureDir, remove } from 'fs-extra'
5 import { CONFIG } from '../initializers/config'
6 import { dirname, join } from 'path'
7 import * as createTorrent from 'create-torrent'
8 import { promisify2 } from './core-utils'
9
10 async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
11   const id = target.magnetUri || target.torrentName
12   let timer
13
14   const path = generateVideoImportTmpPath(id)
15   logger.info('Importing torrent video %s', id)
16
17   const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
18   await ensureDir(directoryPath)
19
20   return new Promise<string>((res, rej) => {
21     const webtorrent = new WebTorrent()
22     let file: WebTorrent.TorrentFile
23
24     const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
25
26     const options = { path: directoryPath }
27     const torrent = webtorrent.add(torrentId, options, torrent => {
28       if (torrent.files.length !== 1) {
29         if (timer) clearTimeout(timer)
30
31         for (let file of torrent.files) {
32           deleteDownloadedFile({ directoryPath, filepath: file.path })
33         }
34
35         return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
36           .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
37       }
38
39       file = torrent.files[ 0 ]
40
41       // FIXME: avoid creating another stream when https://github.com/webtorrent/webtorrent/issues/1517 is fixed
42       const writeStream = createWriteStream(path)
43       writeStream.on('finish', () => {
44         if (timer) clearTimeout(timer)
45
46         return safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
47           .then(() => res(path))
48       })
49
50       file.createReadStream().pipe(writeStream)
51     })
52
53     torrent.on('error', err => rej(err))
54
55     timer = setTimeout(async () => {
56       return safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
57         .then(() => rej(new Error('Webtorrent download timeout.')))
58     }, timeout)
59   })
60 }
61
62 const createTorrentPromise = promisify2<string, any, any>(createTorrent)
63
64 // ---------------------------------------------------------------------------
65
66 export {
67   createTorrentPromise,
68   downloadWebTorrentVideo
69 }
70
71 // ---------------------------------------------------------------------------
72
73 function safeWebtorrentDestroy (
74   webtorrent: WebTorrent.Instance,
75   torrentId: string,
76   downloadedFile?: { directoryPath: string, filepath: string },
77   torrentName?: string
78 ) {
79   return new Promise(res => {
80     webtorrent.destroy(err => {
81       // Delete torrent file
82       if (torrentName) {
83         logger.debug('Removing %s torrent after webtorrent download.', torrentId)
84         remove(torrentId)
85           .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
86       }
87
88       // Delete downloaded file
89       if (downloadedFile) deleteDownloadedFile(downloadedFile)
90
91       if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
92
93       return res()
94     })
95   })
96 }
97
98 function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
99   // We want to delete the base directory
100   let pathToDelete = dirname(downloadedFile.filepath)
101   if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
102
103   const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
104
105   logger.debug('Removing %s after webtorrent download.', toRemovePath)
106   remove(toRemovePath)
107     .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
108 }