]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/webtorrent.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
1 import { decode, encode } from 'bencode'
2 import createTorrent from 'create-torrent'
3 import { createWriteStream, ensureDir, pathExists, readFile, remove, writeFile } from 'fs-extra'
4 import { encode as magnetUriEncode } 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 { promisify2 } from '@shared/core-utils'
17 import { sha1 } from '@shared/extra-utils'
18 import { CONFIG } from '../initializers/config'
19 import { logger } from './logger'
20 import { generateVideoImportTmpPath } from './utils'
21 import { extractVideo } from './video'
22
23 const createTorrentPromise = promisify2<string, any, any>(createTorrent)
24
25 async function downloadWebTorrentVideo (target: { uri: string, torrentName?: string }, timeout: number) {
26 const id = target.uri || target.torrentName
27 let timer
28
29 const path = generateVideoImportTmpPath(id)
30 logger.info('Importing torrent video %s', id)
31
32 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
33 await ensureDir(directoryPath)
34
35 return new Promise<string>((res, rej) => {
36 const webtorrent = new WebTorrent()
37 let file: TorrentFile
38
39 const torrentId = target.uri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
40
41 const options = { path: directoryPath }
42 const torrent = webtorrent.add(torrentId, options, torrent => {
43 if (torrent.files.length !== 1) {
44 if (timer) clearTimeout(timer)
45
46 for (const file of torrent.files) {
47 deleteDownloadedFile({ directoryPath, filepath: file.path })
48 }
49
50 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
51 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
52 }
53
54 logger.debug('Got torrent from webtorrent %s.', id, { infoHash: torrent.infoHash })
55
56 file = torrent.files[0]
57
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)
62
63 safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
64 .then(() => res(path))
65 .catch(err => logger.error('Cannot destroy webtorrent.', { err }))
66 })
67
68 pipeline(
69 file.createReadStream(),
70 writeStream,
71 err => {
72 if (err) rej(err)
73 }
74 )
75 })
76
77 torrent.on('error', err => rej(err))
78
79 timer = setTimeout(() => {
80 const err = new Error('Webtorrent download timeout.')
81
82 safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
83 .then(() => rej(err))
84 .catch(destroyErr => {
85 logger.error('Cannot destroy webtorrent.', { err: destroyErr })
86 rej(err)
87 })
88
89 }, timeout)
90 })
91 }
92
93 function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
94 return VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(videoOrPlaylist), videoPath => {
95 return createTorrentAndSetInfoHashFromPath(videoOrPlaylist, videoFile, videoPath)
96 })
97 }
98
99 async function createTorrentAndSetInfoHashFromPath (
100 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
101 videoFile: MVideoFile,
102 filePath: string
103 ) {
104 const video = extractVideo(videoOrPlaylist)
105
106 const options = {
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)
112 }
113
114 const torrentContent = await createTorrentPromise(filePath, options)
115
116 const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
117 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename)
118 logger.info('Creating torrent %s.', torrentPath)
119
120 await writeFile(torrentPath, torrentContent)
121
122 // Remove old torrent file if it existed
123 if (videoFile.hasTorrent()) {
124 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
125 }
126
127 const parsedTorrent = parseTorrent(torrentContent)
128 videoFile.infoHash = parsedTorrent.infoHash
129 videoFile.torrentFilename = torrentFilename
130 }
131
132 async function updateTorrentMetadata (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
133 const video = extractVideo(videoOrPlaylist)
134
135 const oldTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename)
136
137 if (!await pathExists(oldTorrentPath)) {
138 logger.info('Do not update torrent metadata %s of video %s because the file does not exist anymore.', video.uuid, oldTorrentPath)
139 return
140 }
141
142 const torrentContent = await readFile(oldTorrentPath)
143 const decoded = decode(torrentContent)
144
145 decoded['announce-list'] = buildAnnounceList()
146 decoded.announce = decoded['announce-list'][0][0]
147
148 decoded['url-list'] = buildUrlList(video, videoFile)
149
150 decoded.info.name = buildInfoName(video, videoFile)
151 decoded['creation date'] = Math.ceil(Date.now() / 1000)
152
153 const newTorrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
154 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, newTorrentFilename)
155
156 logger.info('Updating torrent metadata %s -> %s.', oldTorrentPath, newTorrentPath)
157
158 await writeFile(newTorrentPath, encode(decoded))
159 await remove(oldTorrentPath)
160
161 videoFile.torrentFilename = newTorrentFilename
162 videoFile.infoHash = sha1(encode(decoded.info))
163 }
164
165 function generateMagnetUri (
166 video: MVideo,
167 videoFile: MVideoFileRedundanciesOpt,
168 trackerUrls: string[]
169 ) {
170 const xs = videoFile.getTorrentUrl()
171 const announce = trackerUrls
172
173 let urlList = video.hasPrivateStaticPath()
174 ? []
175 : [ videoFile.getFileUrl(video) ]
176
177 const redundancies = videoFile.RedundancyVideos
178 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
179
180 const magnetHash = {
181 xs,
182 announce,
183 urlList,
184 infoHash: videoFile.infoHash,
185 name: video.name
186 }
187
188 return magnetUriEncode(magnetHash)
189 }
190
191 // ---------------------------------------------------------------------------
192
193 export {
194 createTorrentPromise,
195 updateTorrentMetadata,
196
197 createTorrentAndSetInfoHash,
198 createTorrentAndSetInfoHashFromPath,
199
200 generateMagnetUri,
201 downloadWebTorrentVideo
202 }
203
204 // ---------------------------------------------------------------------------
205
206 function safeWebtorrentDestroy (
207 webtorrent: Instance,
208 torrentId: string,
209 downloadedFile?: { directoryPath: string, filepath: string },
210 torrentName?: string
211 ) {
212 return new Promise<void>(res => {
213 webtorrent.destroy(err => {
214 // Delete torrent file
215 if (torrentName) {
216 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
217 remove(torrentId)
218 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
219 }
220
221 // Delete downloaded file
222 if (downloadedFile) deleteDownloadedFile(downloadedFile)
223
224 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
225
226 return res()
227 })
228 })
229 }
230
231 function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
232 // We want to delete the base directory
233 let pathToDelete = dirname(downloadedFile.filepath)
234 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
235
236 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
237
238 logger.debug('Removing %s after webtorrent download.', toRemovePath)
239 remove(toRemovePath)
240 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
241 }
242
243 function buildAnnounceList () {
244 return [
245 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
246 [ WEBSERVER.URL + '/tracker/announce' ]
247 ]
248 }
249
250 function buildUrlList (video: MVideo, videoFile: MVideoFile) {
251 if (video.hasPrivateStaticPath()) return []
252
253 return [ videoFile.getFileUrl(video) ]
254 }
255
256 function buildInfoName (video: MVideo, videoFile: MVideoFile) {
257 return `${video.name} ${videoFile.resolution}p${videoFile.extname}`
258 }