1 import * as createTorrent from 'create-torrent'
2 import { createWriteStream, ensureDir, remove, writeFile } from 'fs-extra'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { dirname, join } from 'path'
6 import * as WebTorrent from 'webtorrent'
7 import { isArray } from '@server/helpers/custom-validators/misc'
8 import { WEBSERVER } from '@server/initializers/constants'
9 import { generateTorrentFileName, getVideoFilePath } from '@server/lib/video-paths'
10 import { MVideo, MVideoWithHost } from '@server/types/models/video/video'
11 import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/types/models/video/video-file'
12 import { MStreamingPlaylistVideo } from '@server/types/models/video/video-streaming-playlist'
13 import { CONFIG } from '../initializers/config'
14 import { promisify2 } from './core-utils'
15 import { logger } from './logger'
16 import { generateVideoImportTmpPath } from './utils'
18 const createTorrentPromise = promisify2<string, any, any>(createTorrent)
20 async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
21 const id = target.magnetUri || target.torrentName
24 const path = generateVideoImportTmpPath(id)
25 logger.info('Importing torrent video %s', id)
27 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
28 await ensureDir(directoryPath)
30 return new Promise<string>((res, rej) => {
31 const webtorrent = new WebTorrent()
32 let file: WebTorrent.TorrentFile
34 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
36 const options = { path: directoryPath }
37 const torrent = webtorrent.add(torrentId, options, torrent => {
38 if (torrent.files.length !== 1) {
39 if (timer) clearTimeout(timer)
41 for (const file of torrent.files) {
42 deleteDownloadedFile({ directoryPath, filepath: file.path })
45 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
46 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
49 file = torrent.files[0]
51 // FIXME: avoid creating another stream when https://github.com/webtorrent/webtorrent/issues/1517 is fixed
52 const writeStream = createWriteStream(path)
53 writeStream.on('finish', () => {
54 if (timer) clearTimeout(timer)
56 safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
57 .then(() => res(path))
58 .catch(err => logger.error('Cannot destroy webtorrent.', { err }))
61 file.createReadStream().pipe(writeStream)
64 torrent.on('error', err => rej(err))
66 timer = setTimeout(() => {
67 const err = new Error('Webtorrent download timeout.')
69 safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
71 .catch(destroyErr => {
72 logger.error('Cannot destroy webtorrent.', { err: destroyErr })
80 // FIXME: refactor/merge videoOrPlaylist and video arguments
81 async function createTorrentAndSetInfoHash (
82 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
83 video: MVideoWithHost,
87 // Keep the extname, it's used by the client to stream the file inside a web browser
88 name: `${video.name} ${videoFile.resolution}p${videoFile.extname}`,
89 createdBy: 'PeerTube',
91 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
92 [ WEBSERVER.URL + '/tracker/announce' ]
94 urlList: [ videoFile.getFileUrl(video) ]
97 const torrent = await createTorrentPromise(getVideoFilePath(videoOrPlaylist, videoFile), options)
99 const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
100 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename)
101 logger.info('Creating torrent %s.', torrentPath)
103 await writeFile(torrentPath, torrent)
105 const parsedTorrent = parseTorrent(torrent)
106 videoFile.infoHash = parsedTorrent.infoHash
107 videoFile.torrentFilename = torrentFilename
110 // FIXME: merge/refactor videoOrPlaylist and video arguments
111 function generateMagnetUri (
112 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
113 video: MVideoWithHost,
114 videoFile: MVideoFileRedundanciesOpt,
118 const xs = videoFile.getTorrentUrl()
119 const announce = videoOrPlaylist.getTrackerUrls(baseUrlHttp, baseUrlWs)
120 let urlList = [ videoFile.getFileUrl(video) ]
122 const redundancies = videoFile.RedundancyVideos
123 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
129 infoHash: videoFile.infoHash,
133 return magnetUtil.encode(magnetHash)
136 // ---------------------------------------------------------------------------
139 createTorrentPromise,
140 createTorrentAndSetInfoHash,
142 downloadWebTorrentVideo
145 // ---------------------------------------------------------------------------
147 function safeWebtorrentDestroy (
148 webtorrent: WebTorrent.Instance,
150 downloadedFile?: { directoryPath: string, filepath: string },
153 return new Promise<void>(res => {
154 webtorrent.destroy(err => {
155 // Delete torrent file
157 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
159 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
162 // Delete downloaded file
163 if (downloadedFile) deleteDownloadedFile(downloadedFile)
165 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
172 function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
173 // We want to delete the base directory
174 let pathToDelete = dirname(downloadedFile.filepath)
175 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
177 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
179 logger.debug('Removing %s after webtorrent download.', toRemovePath)
181 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))