]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/webtorrent.ts
Merge branch 'release/4.0.0' into develop
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
CommitLineData
41fb13c3
C
1import { decode, encode } from 'bencode'
2import createTorrent from 'create-torrent'
1f6125be 3import { createWriteStream, ensureDir, readFile, remove, writeFile } from 'fs-extra'
41fb13c3
C
4import magnetUtil from 'magnet-uri'
5import parseTorrent from 'parse-torrent'
90a8bd30 6import { dirname, join } from 'path'
41fb13c3
C
7import { pipeline } from 'stream'
8import WebTorrent, { Instance, TorrentFile } from 'webtorrent'
d7a25329 9import { isArray } from '@server/helpers/custom-validators/misc'
90a8bd30 10import { WEBSERVER } from '@server/initializers/constants'
0305db28
JB
11import { generateTorrentFileName } from '@server/lib/paths'
12import { VideoPathManager } from '@server/lib/video-path-manager'
8efc27bf 13import { MVideo } from '@server/types/models/video/video'
90a8bd30
C
14import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/types/models/video/video-file'
15import { MStreamingPlaylistVideo } from '@server/types/models/video/video-streaming-playlist'
f304a158 16import { sha1 } from '@shared/extra-utils'
90a8bd30 17import { CONFIG } from '../initializers/config'
06aad801 18import { promisify2 } from './core-utils'
90a8bd30
C
19import { logger } from './logger'
20import { generateVideoImportTmpPath } from './utils'
8efc27bf 21import { extractVideo } from './video'
d7a25329
C
22
23const createTorrentPromise = promisify2<string, any, any>(createTorrent)
ce33919c 24
02b286f8
C
25async function downloadWebTorrentVideo (target: { uri: string, torrentName?: string }, timeout: number) {
26 const id = target.uri || target.torrentName
c48e82b5 27 let timer
ce33919c 28
6040f87d 29 const path = generateVideoImportTmpPath(id)
990b6a0b 30 logger.info('Importing torrent video %s', id)
ce33919c 31
6040f87d 32 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
a71de50b
C
33 await ensureDir(directoryPath)
34
ce33919c
C
35 return new Promise<string>((res, rej) => {
36 const webtorrent = new WebTorrent()
41fb13c3 37 let file: TorrentFile
ce33919c 38
02b286f8 39 const torrentId = target.uri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
541006e3 40
a71de50b 41 const options = { path: directoryPath }
541006e3 42 const torrent = webtorrent.add(torrentId, options, torrent => {
c48e82b5
C
43 if (torrent.files.length !== 1) {
44 if (timer) clearTimeout(timer)
ce33919c 45
a1587156 46 for (const file of torrent.files) {
e37c85e9
C
47 deleteDownloadedFile({ directoryPath, filepath: file.path })
48 }
49
50 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
dae4a1c0 51 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
c48e82b5
C
52 }
53
09509487 54 logger.debug('Got torrent from webtorrent %s.', id, { infoHash: torrent.infoHash })
0bae6663 55
a1587156 56 file = torrent.files[0]
a71de50b
C
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
a1587156 63 safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
a71de50b 64 .then(() => res(path))
a1587156 65 .catch(err => logger.error('Cannot destroy webtorrent.', { err }))
69fa54a0 66 })
a71de50b 67
0bae6663
C
68 pipeline(
69 file.createReadStream(),
70 writeStream,
e111a5a3
C
71 err => {
72 if (err) rej(err)
73 }
0bae6663 74 )
3e17515e 75 })
ce33919c
C
76
77 torrent.on('error', err => rej(err))
c48e82b5 78
a1587156
C
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
cf9166cf 89 }, timeout)
ce33919c
C
90 })
91}
92
1f6125be 93function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
8efc27bf
C
94 const video = extractVideo(videoOrPlaylist)
95
d7a25329
C
96 const options = {
97 // Keep the extname, it's used by the client to stream the file inside a web browser
9b293cd6 98 name: buildInfoName(video, videoFile),
d7a25329 99 createdBy: 'PeerTube',
1f6125be
C
100 announceList: buildAnnounceList(),
101 urlList: buildUrlList(video, videoFile)
d7a25329
C
102 }
103
ad5db104 104 return VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(videoOrPlaylist), async videoPath => {
1f6125be 105 const torrentContent = await createTorrentPromise(videoPath, options)
d7a25329 106
0305db28
JB
107 const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
108 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename)
109 logger.info('Creating torrent %s.', torrentPath)
d7a25329 110
1f6125be 111 await writeFile(torrentPath, torrentContent)
d7a25329 112
0305db28
JB
113 // Remove old torrent file if it existed
114 if (videoFile.hasTorrent()) {
115 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
116 }
764b1a14 117
1f6125be 118 const parsedTorrent = parseTorrent(torrentContent)
0305db28
JB
119 videoFile.infoHash = parsedTorrent.infoHash
120 videoFile.torrentFilename = torrentFilename
121 })
d7a25329
C
122}
123
9b293cd6 124async function updateTorrentMetadata (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
1f6125be
C
125 const video = extractVideo(videoOrPlaylist)
126
127 const oldTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename)
128
129 const torrentContent = await readFile(oldTorrentPath)
41fb13c3 130 const decoded = decode(torrentContent)
1f6125be
C
131
132 decoded['announce-list'] = buildAnnounceList()
133 decoded.announce = decoded['announce-list'][0][0]
134
135 decoded['url-list'] = buildUrlList(video, videoFile)
136
9b293cd6
C
137 decoded.info.name = buildInfoName(video, videoFile)
138 decoded['creation date'] = Math.ceil(Date.now() / 1000)
139
1f6125be
C
140 const newTorrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
141 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, newTorrentFilename)
142
9b293cd6 143 logger.info('Updating torrent metadata %s -> %s.', oldTorrentPath, newTorrentPath)
1f6125be 144
41fb13c3 145 await writeFile(newTorrentPath, encode(decoded))
f645af43 146 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
1f6125be
C
147
148 videoFile.torrentFilename = newTorrentFilename
38d69d65 149 videoFile.infoHash = sha1(encode(decoded.info))
1f6125be
C
150}
151
d7a25329 152function generateMagnetUri (
8efc27bf 153 video: MVideo,
d7a25329 154 videoFile: MVideoFileRedundanciesOpt,
d9a2a031 155 trackerUrls: string[]
d7a25329 156) {
90a8bd30 157 const xs = videoFile.getTorrentUrl()
d9a2a031 158 const announce = trackerUrls
90a8bd30 159 let urlList = [ videoFile.getFileUrl(video) ]
d7a25329
C
160
161 const redundancies = videoFile.RedundancyVideos
162 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
163
164 const magnetHash = {
165 xs,
166 announce,
167 urlList,
168 infoHash: videoFile.infoHash,
169 name: video.name
170 }
171
172 return magnetUtil.encode(magnetHash)
173}
30ff39e7 174
ce33919c
C
175// ---------------------------------------------------------------------------
176
177export {
d441f2ed 178 createTorrentPromise,
9b293cd6 179 updateTorrentMetadata,
d7a25329
C
180 createTorrentAndSetInfoHash,
181 generateMagnetUri,
ce33919c
C
182 downloadWebTorrentVideo
183}
c48e82b5
C
184
185// ---------------------------------------------------------------------------
186
d0b52b52 187function safeWebtorrentDestroy (
41fb13c3 188 webtorrent: Instance,
d0b52b52
C
189 torrentId: string,
190 downloadedFile?: { directoryPath: string, filepath: string },
191 torrentName?: string
192) {
ba5a8d89 193 return new Promise<void>(res => {
c48e82b5
C
194 webtorrent.destroy(err => {
195 // Delete torrent file
196 if (torrentName) {
d0b52b52 197 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
c48e82b5
C
198 remove(torrentId)
199 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
200 }
201
202 // Delete downloaded file
e37c85e9 203 if (downloadedFile) deleteDownloadedFile(downloadedFile)
c48e82b5 204
e37c85e9 205 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
c48e82b5
C
206
207 return res()
208 })
209 })
210}
e37c85e9
C
211
212function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
213 // We want to delete the base directory
214 let pathToDelete = dirname(downloadedFile.filepath)
215 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
216
217 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
218
219 logger.debug('Removing %s after webtorrent download.', toRemovePath)
220 remove(toRemovePath)
221 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
222}
1f6125be
C
223
224function buildAnnounceList () {
225 return [
226 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
227 [ WEBSERVER.URL + '/tracker/announce' ]
228 ]
229}
230
231function buildUrlList (video: MVideo, videoFile: MVideoFile) {
232 return [ videoFile.getFileUrl(video) ]
233}
9b293cd6
C
234
235function buildInfoName (video: MVideo, videoFile: MVideoFile) {
236 return `${video.name} ${videoFile.resolution}p${videoFile.extname}`
237}