1 import { logger } from './logger'
2 import { generateVideoImportTmpPath } from './utils'
3 import * as WebTorrent from 'webtorrent'
4 import { createWriteStream, ensureDir, remove, writeFile } 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 import { MVideo } from '@server/typings/models/video/video'
10 import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/typings/models/video/video-file'
11 import { isStreamingPlaylist, MStreamingPlaylistVideo } from '@server/typings/models/video/video-streaming-playlist'
12 import { STATIC_PATHS, WEBSERVER } from '@server/initializers/constants'
13 import * as parseTorrent from 'parse-torrent'
14 import * as magnetUtil from 'magnet-uri'
15 import { isArray } from '@server/helpers/custom-validators/misc'
16 import { extractVideo } from '@server/lib/videos'
17 import { getTorrentFileName, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
19 const createTorrentPromise = promisify2<string, any, any>(createTorrent)
21 async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
22 const id = target.magnetUri || target.torrentName
25 const path = generateVideoImportTmpPath(id)
26 logger.info('Importing torrent video %s', id)
28 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
29 await ensureDir(directoryPath)
31 return new Promise<string>((res, rej) => {
32 const webtorrent = new WebTorrent()
33 let file: WebTorrent.TorrentFile
35 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
37 const options = { path: directoryPath }
38 const torrent = webtorrent.add(torrentId, options, torrent => {
39 if (torrent.files.length !== 1) {
40 if (timer) clearTimeout(timer)
42 for (let file of torrent.files) {
43 deleteDownloadedFile({ directoryPath, filepath: file.path })
46 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
47 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
50 file = torrent.files[ 0 ]
52 // FIXME: avoid creating another stream when https://github.com/webtorrent/webtorrent/issues/1517 is fixed
53 const writeStream = createWriteStream(path)
54 writeStream.on('finish', () => {
55 if (timer) clearTimeout(timer)
57 return safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
58 .then(() => res(path))
61 file.createReadStream().pipe(writeStream)
64 torrent.on('error', err => rej(err))
66 timer = setTimeout(async () => {
67 return safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
68 .then(() => rej(new Error('Webtorrent download timeout.')))
73 async function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
74 const video = extractVideo(videoOrPlaylist)
77 // Keep the extname, it's used by the client to stream the file inside a web browser
78 name: `${video.name} ${videoFile.resolution}p${videoFile.extname}`,
79 createdBy: 'PeerTube',
81 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
82 [ WEBSERVER.URL + '/tracker/announce' ]
84 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + getVideoFilename(videoOrPlaylist, videoFile) ]
87 const torrent = await createTorrentPromise(getVideoFilePath(videoOrPlaylist, videoFile), options)
89 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, getTorrentFileName(videoOrPlaylist, videoFile))
90 logger.info('Creating torrent %s.', filePath)
92 await writeFile(filePath, torrent)
94 const parsedTorrent = parseTorrent(torrent)
95 videoFile.infoHash = parsedTorrent.infoHash
98 function generateMagnetUri (
99 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
100 videoFile: MVideoFileRedundanciesOpt,
104 const video = isStreamingPlaylist(videoOrPlaylist)
105 ? videoOrPlaylist.Video
108 const xs = videoOrPlaylist.getTorrentUrl(videoFile, baseUrlHttp)
109 const announce = videoOrPlaylist.getTrackerUrls(baseUrlHttp, baseUrlWs)
110 let urlList = [ videoOrPlaylist.getVideoFileUrl(videoFile, baseUrlHttp) ]
112 const redundancies = videoFile.RedundancyVideos
113 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
119 infoHash: videoFile.infoHash,
123 return magnetUtil.encode(magnetHash)
126 // ---------------------------------------------------------------------------
129 createTorrentAndSetInfoHash,
131 downloadWebTorrentVideo
134 // ---------------------------------------------------------------------------
136 function safeWebtorrentDestroy (
137 webtorrent: WebTorrent.Instance,
139 downloadedFile?: { directoryPath: string, filepath: string },
142 return new Promise(res => {
143 webtorrent.destroy(err => {
144 // Delete torrent file
146 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
148 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
151 // Delete downloaded file
152 if (downloadedFile) deleteDownloadedFile(downloadedFile)
154 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
161 function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
162 // We want to delete the base directory
163 let pathToDelete = dirname(downloadedFile.filepath)
164 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
166 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
168 logger.debug('Removing %s after webtorrent download.', toRemovePath)
170 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))