]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/webtorrent.ts
Fix peertube subtitles import
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
CommitLineData
41fb13c3
C
1import { decode, encode } from 'bencode'
2import createTorrent from 'create-torrent'
44df7025 3import { createWriteStream, ensureDir, pathExists, readFile, remove, writeFile } from 'fs-extra'
83002a82 4import { encode as magnetUriEncode } from 'magnet-uri'
41fb13c3 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'
0c9668f7 16import { promisify2 } from '@shared/core-utils'
f304a158 17import { sha1 } from '@shared/extra-utils'
90a8bd30 18import { CONFIG } from '../initializers/config'
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) {
c729caf6
C
94 return VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(videoOrPlaylist), videoPath => {
95 return createTorrentAndSetInfoHashFromPath(videoOrPlaylist, videoFile, videoPath)
96 })
97}
98
99async function createTorrentAndSetInfoHashFromPath (
100 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
101 videoFile: MVideoFile,
102 filePath: string
103) {
8efc27bf
C
104 const video = extractVideo(videoOrPlaylist)
105
d7a25329
C
106 const options = {
107 // Keep the extname, it's used by the client to stream the file inside a web browser
9b293cd6 108 name: buildInfoName(video, videoFile),
d7a25329 109 createdBy: 'PeerTube',
1f6125be
C
110 announceList: buildAnnounceList(),
111 urlList: buildUrlList(video, videoFile)
d7a25329
C
112 }
113
c729caf6 114 const torrentContent = await createTorrentPromise(filePath, options)
d7a25329 115
c729caf6
C
116 const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
117 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename)
118 logger.info('Creating torrent %s.', torrentPath)
d7a25329 119
c729caf6 120 await writeFile(torrentPath, torrentContent)
d7a25329 121
c729caf6
C
122 // Remove old torrent file if it existed
123 if (videoFile.hasTorrent()) {
124 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
125 }
764b1a14 126
c729caf6
C
127 const parsedTorrent = parseTorrent(torrentContent)
128 videoFile.infoHash = parsedTorrent.infoHash
129 videoFile.torrentFilename = torrentFilename
d7a25329
C
130}
131
9b293cd6 132async function updateTorrentMetadata (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
1f6125be
C
133 const video = extractVideo(videoOrPlaylist)
134
135 const oldTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename)
136
44df7025
C
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
1f6125be 142 const torrentContent = await readFile(oldTorrentPath)
41fb13c3 143 const decoded = decode(torrentContent)
1f6125be
C
144
145 decoded['announce-list'] = buildAnnounceList()
146 decoded.announce = decoded['announce-list'][0][0]
147
148 decoded['url-list'] = buildUrlList(video, videoFile)
149
9b293cd6
C
150 decoded.info.name = buildInfoName(video, videoFile)
151 decoded['creation date'] = Math.ceil(Date.now() / 1000)
152
1f6125be
C
153 const newTorrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
154 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, newTorrentFilename)
155
9b293cd6 156 logger.info('Updating torrent metadata %s -> %s.', oldTorrentPath, newTorrentPath)
1f6125be 157
41fb13c3 158 await writeFile(newTorrentPath, encode(decoded))
44df7025 159 await remove(oldTorrentPath)
1f6125be
C
160
161 videoFile.torrentFilename = newTorrentFilename
38d69d65 162 videoFile.infoHash = sha1(encode(decoded.info))
1f6125be
C
163}
164
d7a25329 165function generateMagnetUri (
8efc27bf 166 video: MVideo,
d7a25329 167 videoFile: MVideoFileRedundanciesOpt,
d9a2a031 168 trackerUrls: string[]
d7a25329 169) {
90a8bd30 170 const xs = videoFile.getTorrentUrl()
d9a2a031 171 const announce = trackerUrls
3545e72c 172
9ab330b9 173 let urlList = video.hasPrivateStaticPath()
3545e72c
C
174 ? []
175 : [ videoFile.getFileUrl(video) ]
d7a25329
C
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
83002a82 188 return magnetUriEncode(magnetHash)
d7a25329 189}
30ff39e7 190
ce33919c
C
191// ---------------------------------------------------------------------------
192
193export {
d441f2ed 194 createTorrentPromise,
9b293cd6 195 updateTorrentMetadata,
c729caf6 196
d7a25329 197 createTorrentAndSetInfoHash,
c729caf6
C
198 createTorrentAndSetInfoHashFromPath,
199
d7a25329 200 generateMagnetUri,
ce33919c
C
201 downloadWebTorrentVideo
202}
c48e82b5
C
203
204// ---------------------------------------------------------------------------
205
d0b52b52 206function safeWebtorrentDestroy (
41fb13c3 207 webtorrent: Instance,
d0b52b52
C
208 torrentId: string,
209 downloadedFile?: { directoryPath: string, filepath: string },
210 torrentName?: string
211) {
ba5a8d89 212 return new Promise<void>(res => {
c48e82b5
C
213 webtorrent.destroy(err => {
214 // Delete torrent file
215 if (torrentName) {
d0b52b52 216 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
c48e82b5
C
217 remove(torrentId)
218 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
219 }
220
221 // Delete downloaded file
e37c85e9 222 if (downloadedFile) deleteDownloadedFile(downloadedFile)
c48e82b5 223
e37c85e9 224 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
c48e82b5
C
225
226 return res()
227 })
228 })
229}
e37c85e9
C
230
231function 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}
1f6125be
C
242
243function buildAnnounceList () {
244 return [
245 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
246 [ WEBSERVER.URL + '/tracker/announce' ]
247 ]
248}
249
250function buildUrlList (video: MVideo, videoFile: MVideoFile) {
9ab330b9 251 if (video.hasPrivateStaticPath()) return []
3545e72c 252
1f6125be
C
253 return [ videoFile.getFileUrl(video) ]
254}
9b293cd6
C
255
256function buildInfoName (video: MVideo, videoFile: MVideoFile) {
257 return `${video.name} ${videoFile.resolution}p${videoFile.extname}`
258}