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/types/models/video/video'
10 import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/types/models/video/video-file'
11 import { isStreamingPlaylist, MStreamingPlaylistVideo } from '@server/types/models/video/video-streaming-playlist'
12 import { 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 { getTorrentFileName, getVideoFilePath } from '@server/lib/video-paths'
17 import { extractVideo } from '@server/helpers/video'
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 (const 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 safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
58 .then(() => res(path))
59 .catch(err => logger.error('Cannot destroy webtorrent.', { err }))
62 file.createReadStream().pipe(writeStream)
65 torrent.on('error', err => rej(err))
67 timer = setTimeout(() => {
68 const err = new Error('Webtorrent download timeout.')
70 safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
72 .catch(destroyErr => {
73 logger.error('Cannot destroy webtorrent.', { err: destroyErr })
81 async function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
82 const video = extractVideo(videoOrPlaylist)
83 const { baseUrlHttp } = video.getBaseUrls()
86 // Keep the extname, it's used by the client to stream the file inside a web browser
87 name: `${video.name} ${videoFile.resolution}p${videoFile.extname}`,
88 createdBy: 'PeerTube',
90 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
91 [ WEBSERVER.URL + '/tracker/announce' ]
93 urlList: [ videoOrPlaylist.getVideoFileUrl(videoFile, baseUrlHttp) ]
96 const torrent = await createTorrentPromise(getVideoFilePath(videoOrPlaylist, videoFile), options)
98 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, getTorrentFileName(videoOrPlaylist, videoFile))
99 logger.info('Creating torrent %s.', filePath)
101 await writeFile(filePath, torrent)
103 const parsedTorrent = parseTorrent(torrent)
104 videoFile.infoHash = parsedTorrent.infoHash
107 function generateMagnetUri (
108 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
109 videoFile: MVideoFileRedundanciesOpt,
113 const video = isStreamingPlaylist(videoOrPlaylist)
114 ? videoOrPlaylist.Video
117 const xs = videoOrPlaylist.getTorrentUrl(videoFile, baseUrlHttp)
118 const announce = videoOrPlaylist.getTrackerUrls(baseUrlHttp, baseUrlWs)
119 let urlList = [ videoOrPlaylist.getVideoFileUrl(videoFile, baseUrlHttp) ]
121 const redundancies = videoFile.RedundancyVideos
122 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
128 infoHash: videoFile.infoHash,
132 return magnetUtil.encode(magnetHash)
135 // ---------------------------------------------------------------------------
138 createTorrentPromise,
139 createTorrentAndSetInfoHash,
141 downloadWebTorrentVideo
144 // ---------------------------------------------------------------------------
146 function safeWebtorrentDestroy (
147 webtorrent: WebTorrent.Instance,
149 downloadedFile?: { directoryPath: string, filepath: string },
152 return new Promise(res => {
153 webtorrent.destroy(err => {
154 // Delete torrent file
156 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
158 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
161 // Delete downloaded file
162 if (downloadedFile) deleteDownloadedFile(downloadedFile)
164 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
171 function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
172 // We want to delete the base directory
173 let pathToDelete = dirname(downloadedFile.filepath)
174 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
176 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
178 logger.debug('Removing %s after webtorrent download.', toRemovePath)
180 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))