]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/webtorrent.ts
Add ability to disable webtorrent
[github/Chocobozzz/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, 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'
18
19 const createTorrentPromise = promisify2<string, any, any>(createTorrent)
20
21 async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
22 const id = target.magnetUri || target.torrentName
23 let timer
24
25 const path = generateVideoImportTmpPath(id)
26 logger.info('Importing torrent video %s', id)
27
28 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
29 await ensureDir(directoryPath)
30
31 return new Promise<string>((res, rej) => {
32 const webtorrent = new WebTorrent()
33 let file: WebTorrent.TorrentFile
34
35 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
36
37 const options = { path: directoryPath }
38 const torrent = webtorrent.add(torrentId, options, torrent => {
39 if (torrent.files.length !== 1) {
40 if (timer) clearTimeout(timer)
41
42 for (let file of torrent.files) {
43 deleteDownloadedFile({ directoryPath, filepath: file.path })
44 }
45
46 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
47 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
48 }
49
50 file = torrent.files[ 0 ]
51
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)
56
57 return safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
58 .then(() => res(path))
59 })
60
61 file.createReadStream().pipe(writeStream)
62 })
63
64 torrent.on('error', err => rej(err))
65
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.')))
69 }, timeout)
70 })
71 }
72
73 async function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
74 const video = extractVideo(videoOrPlaylist)
75
76 const options = {
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',
80 announceList: [
81 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
82 [ WEBSERVER.URL + '/tracker/announce' ]
83 ],
84 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + getVideoFilename(videoOrPlaylist, videoFile) ]
85 }
86
87 const torrent = await createTorrentPromise(getVideoFilePath(videoOrPlaylist, videoFile), options)
88
89 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, getTorrentFileName(videoOrPlaylist, videoFile))
90 logger.info('Creating torrent %s.', filePath)
91
92 await writeFile(filePath, torrent)
93
94 const parsedTorrent = parseTorrent(torrent)
95 videoFile.infoHash = parsedTorrent.infoHash
96 }
97
98 function generateMagnetUri (
99 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
100 videoFile: MVideoFileRedundanciesOpt,
101 baseUrlHttp: string,
102 baseUrlWs: string
103 ) {
104 const video = isStreamingPlaylist(videoOrPlaylist)
105 ? videoOrPlaylist.Video
106 : videoOrPlaylist
107
108 const xs = videoOrPlaylist.getTorrentUrl(videoFile, baseUrlHttp)
109 const announce = videoOrPlaylist.getTrackerUrls(baseUrlHttp, baseUrlWs)
110 let urlList = [ videoOrPlaylist.getVideoFileUrl(videoFile, baseUrlHttp) ]
111
112 const redundancies = videoFile.RedundancyVideos
113 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
114
115 const magnetHash = {
116 xs,
117 announce,
118 urlList,
119 infoHash: videoFile.infoHash,
120 name: video.name
121 }
122
123 return magnetUtil.encode(magnetHash)
124 }
125
126 // ---------------------------------------------------------------------------
127
128 export {
129 createTorrentAndSetInfoHash,
130 generateMagnetUri,
131 downloadWebTorrentVideo
132 }
133
134 // ---------------------------------------------------------------------------
135
136 function safeWebtorrentDestroy (
137 webtorrent: WebTorrent.Instance,
138 torrentId: string,
139 downloadedFile?: { directoryPath: string, filepath: string },
140 torrentName?: string
141 ) {
142 return new Promise(res => {
143 webtorrent.destroy(err => {
144 // Delete torrent file
145 if (torrentName) {
146 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
147 remove(torrentId)
148 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
149 }
150
151 // Delete downloaded file
152 if (downloadedFile) deleteDownloadedFile(downloadedFile)
153
154 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
155
156 return res()
157 })
158 })
159 }
160
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
165
166 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
167
168 logger.debug('Removing %s after webtorrent download.', toRemovePath)
169 remove(toRemovePath)
170 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
171 }