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