]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/webtorrent.ts
More logs for webtorrent download
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
CommitLineData
1f6125be 1import * as bencode from 'bencode'
30ff39e7 2import * as createTorrent from 'create-torrent'
1f6125be 3import { createWriteStream, ensureDir, readFile, remove, writeFile } from 'fs-extra'
d7a25329 4import * as magnetUtil from 'magnet-uri'
90a8bd30
C
5import * as parseTorrent from 'parse-torrent'
6import { dirname, join } from 'path'
7import * as WebTorrent from 'webtorrent'
d7a25329 8import { isArray } from '@server/helpers/custom-validators/misc'
90a8bd30 9import { WEBSERVER } from '@server/initializers/constants'
0305db28
JB
10import { generateTorrentFileName } from '@server/lib/paths'
11import { VideoPathManager } from '@server/lib/video-path-manager'
8efc27bf 12import { MVideo } from '@server/types/models/video/video'
90a8bd30
C
13import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/types/models/video/video-file'
14import { MStreamingPlaylistVideo } from '@server/types/models/video/video-streaming-playlist'
15import { CONFIG } from '../initializers/config'
16import { promisify2 } from './core-utils'
17import { logger } from './logger'
18import { generateVideoImportTmpPath } from './utils'
8efc27bf 19import { extractVideo } from './video'
0bae6663 20import { pipeline } from 'stream'
d7a25329
C
21
22const createTorrentPromise = promisify2<string, any, any>(createTorrent)
ce33919c 23
cf9166cf 24async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
990b6a0b 25 const id = target.magnetUri || target.torrentName
c48e82b5 26 let timer
ce33919c 27
6040f87d 28 const path = generateVideoImportTmpPath(id)
990b6a0b 29 logger.info('Importing torrent video %s', id)
ce33919c 30
6040f87d 31 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
a71de50b
C
32 await ensureDir(directoryPath)
33
ce33919c
C
34 return new Promise<string>((res, rej) => {
35 const webtorrent = new WebTorrent()
c48e82b5 36 let file: WebTorrent.TorrentFile
ce33919c 37
990b6a0b 38 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
541006e3 39
a71de50b 40 const options = { path: directoryPath }
541006e3 41 const torrent = webtorrent.add(torrentId, options, torrent => {
c48e82b5
C
42 if (torrent.files.length !== 1) {
43 if (timer) clearTimeout(timer)
ce33919c 44
a1587156 45 for (const file of torrent.files) {
e37c85e9
C
46 deleteDownloadedFile({ directoryPath, filepath: file.path })
47 }
48
49 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
dae4a1c0 50 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
c48e82b5
C
51 }
52
0bae6663
C
53 logger.debug('Got torrent from webtorrent %s.', id, { infoHash: torrent.infoHash, files: torrent.files })
54
a1587156 55 file = torrent.files[0]
a71de50b
C
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
a1587156 62 safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
a71de50b 63 .then(() => res(path))
a1587156 64 .catch(err => logger.error('Cannot destroy webtorrent.', { err }))
69fa54a0 65 })
a71de50b 66
0bae6663
C
67 pipeline(
68 file.createReadStream(),
69 writeStream,
70 err => rej(err)
71 )
3e17515e 72 })
ce33919c
C
73
74 torrent.on('error', err => rej(err))
c48e82b5 75
a1587156
C
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
cf9166cf 86 }, timeout)
ce33919c
C
87 })
88}
89
1f6125be 90function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
8efc27bf
C
91 const video = extractVideo(videoOrPlaylist)
92
d7a25329
C
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',
1f6125be
C
97 announceList: buildAnnounceList(),
98 urlList: buildUrlList(video, videoFile)
d7a25329
C
99 }
100
0305db28 101 return VideoPathManager.Instance.makeAvailableVideoFile(videoOrPlaylist, videoFile, async videoPath => {
1f6125be 102 const torrentContent = await createTorrentPromise(videoPath, options)
d7a25329 103
0305db28
JB
104 const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
105 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename)
106 logger.info('Creating torrent %s.', torrentPath)
d7a25329 107
1f6125be 108 await writeFile(torrentPath, torrentContent)
d7a25329 109
0305db28
JB
110 // Remove old torrent file if it existed
111 if (videoFile.hasTorrent()) {
112 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
113 }
764b1a14 114
1f6125be 115 const parsedTorrent = parseTorrent(torrentContent)
0305db28
JB
116 videoFile.infoHash = parsedTorrent.infoHash
117 videoFile.torrentFilename = torrentFilename
118 })
d7a25329
C
119}
120
1f6125be
C
121async 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
f645af43 137 logger.info('Updating torrent URLs %s -> %s.', oldTorrentPath, newTorrentPath)
1f6125be
C
138
139 await writeFile(newTorrentPath, bencode.encode(decoded))
f645af43 140 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
1f6125be
C
141
142 videoFile.torrentFilename = newTorrentFilename
143}
144
d7a25329 145function generateMagnetUri (
8efc27bf 146 video: MVideo,
d7a25329 147 videoFile: MVideoFileRedundanciesOpt,
d9a2a031 148 trackerUrls: string[]
d7a25329 149) {
90a8bd30 150 const xs = videoFile.getTorrentUrl()
d9a2a031 151 const announce = trackerUrls
90a8bd30 152 let urlList = [ videoFile.getFileUrl(video) ]
d7a25329
C
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}
30ff39e7 167
ce33919c
C
168// ---------------------------------------------------------------------------
169
170export {
d441f2ed 171 createTorrentPromise,
1f6125be 172 updateTorrentUrls,
d7a25329
C
173 createTorrentAndSetInfoHash,
174 generateMagnetUri,
ce33919c
C
175 downloadWebTorrentVideo
176}
c48e82b5
C
177
178// ---------------------------------------------------------------------------
179
d0b52b52
C
180function safeWebtorrentDestroy (
181 webtorrent: WebTorrent.Instance,
182 torrentId: string,
183 downloadedFile?: { directoryPath: string, filepath: string },
184 torrentName?: string
185) {
ba5a8d89 186 return new Promise<void>(res => {
c48e82b5
C
187 webtorrent.destroy(err => {
188 // Delete torrent file
189 if (torrentName) {
d0b52b52 190 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
c48e82b5
C
191 remove(torrentId)
192 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
193 }
194
195 // Delete downloaded file
e37c85e9 196 if (downloadedFile) deleteDownloadedFile(downloadedFile)
c48e82b5 197
e37c85e9 198 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
c48e82b5
C
199
200 return res()
201 })
202 })
203}
e37c85e9
C
204
205function 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}
1f6125be
C
216
217function buildAnnounceList () {
218 return [
219 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
220 [ WEBSERVER.URL + '/tracker/announce' ]
221 ]
222}
223
224function buildUrlList (video: MVideo, videoFile: MVideoFile) {
225 return [ videoFile.getFileUrl(video) ]
226}