1 import { decode, encode } from 'bencode'
2 import createTorrent from 'create-torrent'
3 import { createWriteStream, ensureDir, readFile, remove, writeFile } from 'fs-extra'
4 import magnetUtil from 'magnet-uri'
5 import parseTorrent from 'parse-torrent'
6 import { dirname, join } from 'path'
7 import { pipeline } from 'stream'
8 import WebTorrent, { Instance, TorrentFile } from 'webtorrent'
9 import { isArray } from '@server/helpers/custom-validators/misc'
10 import { WEBSERVER } from '@server/initializers/constants'
11 import { generateTorrentFileName } from '@server/lib/paths'
12 import { VideoPathManager } from '@server/lib/video-path-manager'
13 import { MVideo } from '@server/types/models/video/video'
14 import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/types/models/video/video-file'
15 import { MStreamingPlaylistVideo } from '@server/types/models/video/video-streaming-playlist'
16 import { sha1 } from '@shared/extra-utils'
17 import { CONFIG } from '../initializers/config'
18 import { promisify2 } from './core-utils'
19 import { logger } from './logger'
20 import { generateVideoImportTmpPath } from './utils'
21 import { extractVideo } from './video'
23 const createTorrentPromise = promisify2<string, any, any>(createTorrent)
25 async function downloadWebTorrentVideo (target: { uri: string, torrentName?: string }, timeout: number) {
26 const id = target.uri || target.torrentName
29 const path = generateVideoImportTmpPath(id)
30 logger.info('Importing torrent video %s', id)
32 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
33 await ensureDir(directoryPath)
35 return new Promise<string>((res, rej) => {
36 const webtorrent = new WebTorrent()
39 const torrentId = target.uri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
41 const options = { path: directoryPath }
42 const torrent = webtorrent.add(torrentId, options, torrent => {
43 if (torrent.files.length !== 1) {
44 if (timer) clearTimeout(timer)
46 for (const file of torrent.files) {
47 deleteDownloadedFile({ directoryPath, filepath: file.path })
50 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
51 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
54 logger.debug('Got torrent from webtorrent %s.', id, { infoHash: torrent.infoHash })
56 file = torrent.files[0]
58 // FIXME: avoid creating another stream when https://github.com/webtorrent/webtorrent/issues/1517 is fixed
59 const writeStream = createWriteStream(path)
60 writeStream.on('finish', () => {
61 if (timer) clearTimeout(timer)
63 safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
64 .then(() => res(path))
65 .catch(err => logger.error('Cannot destroy webtorrent.', { err }))
69 file.createReadStream(),
77 torrent.on('error', err => rej(err))
79 timer = setTimeout(() => {
80 const err = new Error('Webtorrent download timeout.')
82 safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
84 .catch(destroyErr => {
85 logger.error('Cannot destroy webtorrent.', { err: destroyErr })
93 function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
94 return VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(videoOrPlaylist), videoPath => {
95 return createTorrentAndSetInfoHashFromPath(videoOrPlaylist, videoFile, videoPath)
99 async function createTorrentAndSetInfoHashFromPath (
100 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
101 videoFile: MVideoFile,
104 const video = extractVideo(videoOrPlaylist)
107 // Keep the extname, it's used by the client to stream the file inside a web browser
108 name: buildInfoName(video, videoFile),
109 createdBy: 'PeerTube',
110 announceList: buildAnnounceList(),
111 urlList: buildUrlList(video, videoFile)
114 const torrentContent = await createTorrentPromise(filePath, options)
116 const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
117 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename)
118 logger.info('Creating torrent %s.', torrentPath)
120 await writeFile(torrentPath, torrentContent)
122 // Remove old torrent file if it existed
123 if (videoFile.hasTorrent()) {
124 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
127 const parsedTorrent = parseTorrent(torrentContent)
128 videoFile.infoHash = parsedTorrent.infoHash
129 videoFile.torrentFilename = torrentFilename
132 async function updateTorrentMetadata (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
133 const video = extractVideo(videoOrPlaylist)
135 const oldTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename)
137 const torrentContent = await readFile(oldTorrentPath)
138 const decoded = decode(torrentContent)
140 decoded['announce-list'] = buildAnnounceList()
141 decoded.announce = decoded['announce-list'][0][0]
143 decoded['url-list'] = buildUrlList(video, videoFile)
145 decoded.info.name = buildInfoName(video, videoFile)
146 decoded['creation date'] = Math.ceil(Date.now() / 1000)
148 const newTorrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
149 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, newTorrentFilename)
151 logger.info('Updating torrent metadata %s -> %s.', oldTorrentPath, newTorrentPath)
153 await writeFile(newTorrentPath, encode(decoded))
154 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
156 videoFile.torrentFilename = newTorrentFilename
157 videoFile.infoHash = sha1(encode(decoded.info))
160 function generateMagnetUri (
162 videoFile: MVideoFileRedundanciesOpt,
163 trackerUrls: string[]
165 const xs = videoFile.getTorrentUrl()
166 const announce = trackerUrls
167 let urlList = [ videoFile.getFileUrl(video) ]
169 const redundancies = videoFile.RedundancyVideos
170 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
176 infoHash: videoFile.infoHash,
180 return magnetUtil.encode(magnetHash)
183 // ---------------------------------------------------------------------------
186 createTorrentPromise,
187 updateTorrentMetadata,
189 createTorrentAndSetInfoHash,
190 createTorrentAndSetInfoHashFromPath,
193 downloadWebTorrentVideo
196 // ---------------------------------------------------------------------------
198 function safeWebtorrentDestroy (
199 webtorrent: Instance,
201 downloadedFile?: { directoryPath: string, filepath: string },
204 return new Promise<void>(res => {
205 webtorrent.destroy(err => {
206 // Delete torrent file
208 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
210 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
213 // Delete downloaded file
214 if (downloadedFile) deleteDownloadedFile(downloadedFile)
216 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
223 function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
224 // We want to delete the base directory
225 let pathToDelete = dirname(downloadedFile.filepath)
226 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
228 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
230 logger.debug('Removing %s after webtorrent download.', toRemovePath)
232 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
235 function buildAnnounceList () {
237 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
238 [ WEBSERVER.URL + '/tracker/announce' ]
242 function buildUrlList (video: MVideo, videoFile: MVideoFile) {
243 return [ videoFile.getFileUrl(video) ]
246 function buildInfoName (video: MVideo, videoFile: MVideoFile) {
247 return `${video.name} ${videoFile.resolution}p${videoFile.extname}`