]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/webtorrent.ts
More logs for webtorrent download
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
1 import * as bencode from 'bencode'
2 import * as createTorrent from 'create-torrent'
3 import { createWriteStream, ensureDir, readFile, remove, writeFile } from 'fs-extra'
4 import * as magnetUtil from 'magnet-uri'
5 import * as parseTorrent from 'parse-torrent'
6 import { dirname, join } from 'path'
7 import * as WebTorrent from 'webtorrent'
8 import { isArray } from '@server/helpers/custom-validators/misc'
9 import { WEBSERVER } from '@server/initializers/constants'
10 import { generateTorrentFileName } from '@server/lib/paths'
11 import { VideoPathManager } from '@server/lib/video-path-manager'
12 import { MVideo } from '@server/types/models/video/video'
13 import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/types/models/video/video-file'
14 import { MStreamingPlaylistVideo } from '@server/types/models/video/video-streaming-playlist'
15 import { CONFIG } from '../initializers/config'
16 import { promisify2 } from './core-utils'
17 import { logger } from './logger'
18 import { generateVideoImportTmpPath } from './utils'
19 import { extractVideo } from './video'
20 import { pipeline } from 'stream'
21
22 const createTorrentPromise = promisify2<string, any, any>(createTorrent)
23
24 async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
25 const id = target.magnetUri || 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: WebTorrent.TorrentFile
37
38 const torrentId = target.magnetUri || 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, files: torrent.files })
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 => rej(err)
71 )
72 })
73
74 torrent.on('error', err => rej(err))
75
76 timer = setTimeout(() => {
77 const err = new Error('Webtorrent download timeout.')
78
79 safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
80 .then(() => rej(err))
81 .catch(destroyErr => {
82 logger.error('Cannot destroy webtorrent.', { err: destroyErr })
83 rej(err)
84 })
85
86 }, timeout)
87 })
88 }
89
90 function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
91 const video = extractVideo(videoOrPlaylist)
92
93 const options = {
94 // Keep the extname, it's used by the client to stream the file inside a web browser
95 name: `${video.name} ${videoFile.resolution}p${videoFile.extname}`,
96 createdBy: 'PeerTube',
97 announceList: buildAnnounceList(),
98 urlList: buildUrlList(video, videoFile)
99 }
100
101 return VideoPathManager.Instance.makeAvailableVideoFile(videoOrPlaylist, videoFile, async videoPath => {
102 const torrentContent = await createTorrentPromise(videoPath, options)
103
104 const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
105 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename)
106 logger.info('Creating torrent %s.', torrentPath)
107
108 await writeFile(torrentPath, torrentContent)
109
110 // Remove old torrent file if it existed
111 if (videoFile.hasTorrent()) {
112 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
113 }
114
115 const parsedTorrent = parseTorrent(torrentContent)
116 videoFile.infoHash = parsedTorrent.infoHash
117 videoFile.torrentFilename = torrentFilename
118 })
119 }
120
121 async function updateTorrentUrls (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
122 const video = extractVideo(videoOrPlaylist)
123
124 const oldTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename)
125
126 const torrentContent = await readFile(oldTorrentPath)
127 const decoded = bencode.decode(torrentContent)
128
129 decoded['announce-list'] = buildAnnounceList()
130 decoded.announce = decoded['announce-list'][0][0]
131
132 decoded['url-list'] = buildUrlList(video, videoFile)
133
134 const newTorrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
135 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, newTorrentFilename)
136
137 logger.info('Updating torrent URLs %s -> %s.', oldTorrentPath, newTorrentPath)
138
139 await writeFile(newTorrentPath, bencode.encode(decoded))
140 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
141
142 videoFile.torrentFilename = newTorrentFilename
143 }
144
145 function generateMagnetUri (
146 video: MVideo,
147 videoFile: MVideoFileRedundanciesOpt,
148 trackerUrls: string[]
149 ) {
150 const xs = videoFile.getTorrentUrl()
151 const announce = trackerUrls
152 let urlList = [ videoFile.getFileUrl(video) ]
153
154 const redundancies = videoFile.RedundancyVideos
155 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
156
157 const magnetHash = {
158 xs,
159 announce,
160 urlList,
161 infoHash: videoFile.infoHash,
162 name: video.name
163 }
164
165 return magnetUtil.encode(magnetHash)
166 }
167
168 // ---------------------------------------------------------------------------
169
170 export {
171 createTorrentPromise,
172 updateTorrentUrls,
173 createTorrentAndSetInfoHash,
174 generateMagnetUri,
175 downloadWebTorrentVideo
176 }
177
178 // ---------------------------------------------------------------------------
179
180 function safeWebtorrentDestroy (
181 webtorrent: WebTorrent.Instance,
182 torrentId: string,
183 downloadedFile?: { directoryPath: string, filepath: string },
184 torrentName?: string
185 ) {
186 return new Promise<void>(res => {
187 webtorrent.destroy(err => {
188 // Delete torrent file
189 if (torrentName) {
190 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
191 remove(torrentId)
192 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
193 }
194
195 // Delete downloaded file
196 if (downloadedFile) deleteDownloadedFile(downloadedFile)
197
198 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
199
200 return res()
201 })
202 })
203 }
204
205 function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
206 // We want to delete the base directory
207 let pathToDelete = dirname(downloadedFile.filepath)
208 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
209
210 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
211
212 logger.debug('Removing %s after webtorrent download.', toRemovePath)
213 remove(toRemovePath)
214 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
215 }
216
217 function buildAnnounceList () {
218 return [
219 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
220 [ WEBSERVER.URL + '/tracker/announce' ]
221 ]
222 }
223
224 function buildUrlList (video: MVideo, videoFile: MVideoFile) {
225 return [ videoFile.getFileUrl(video) ]
226 }