]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/webtorrent.ts
Add upload/import/go live video attributes hooks
[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'
16import { CONFIG } from '../initializers/config'
38d69d65 17import { promisify2, sha1 } from './core-utils'
90a8bd30
C
18import { logger } from './logger'
19import { generateVideoImportTmpPath } from './utils'
8efc27bf 20import { extractVideo } from './video'
d7a25329
C
21
22const createTorrentPromise = promisify2<string, any, any>(createTorrent)
ce33919c 23
02b286f8
C
24async function downloadWebTorrentVideo (target: { uri: string, torrentName?: string }, timeout: number) {
25 const id = target.uri || 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()
41fb13c3 36 let file: TorrentFile
ce33919c 37
02b286f8 38 const torrentId = target.uri || 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
09509487 53 logger.debug('Got torrent from webtorrent %s.', id, { infoHash: torrent.infoHash })
0bae6663 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,
e111a5a3
C
70 err => {
71 if (err) rej(err)
72 }
0bae6663 73 )
3e17515e 74 })
ce33919c
C
75
76 torrent.on('error', err => rej(err))
c48e82b5 77
a1587156
C
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
cf9166cf 88 }, timeout)
ce33919c
C
89 })
90}
91
1f6125be 92function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
8efc27bf
C
93 const video = extractVideo(videoOrPlaylist)
94
d7a25329
C
95 const options = {
96 // Keep the extname, it's used by the client to stream the file inside a web browser
9b293cd6 97 name: buildInfoName(video, videoFile),
d7a25329 98 createdBy: 'PeerTube',
1f6125be
C
99 announceList: buildAnnounceList(),
100 urlList: buildUrlList(video, videoFile)
d7a25329
C
101 }
102
ad5db104 103 return VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(videoOrPlaylist), async videoPath => {
1f6125be 104 const torrentContent = await createTorrentPromise(videoPath, options)
d7a25329 105
0305db28
JB
106 const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
107 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename)
108 logger.info('Creating torrent %s.', torrentPath)
d7a25329 109
1f6125be 110 await writeFile(torrentPath, torrentContent)
d7a25329 111
0305db28
JB
112 // Remove old torrent file if it existed
113 if (videoFile.hasTorrent()) {
114 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
115 }
764b1a14 116
1f6125be 117 const parsedTorrent = parseTorrent(torrentContent)
0305db28
JB
118 videoFile.infoHash = parsedTorrent.infoHash
119 videoFile.torrentFilename = torrentFilename
120 })
d7a25329
C
121}
122
9b293cd6 123async function updateTorrentMetadata (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
1f6125be
C
124 const video = extractVideo(videoOrPlaylist)
125
126 const oldTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename)
127
128 const torrentContent = await readFile(oldTorrentPath)
41fb13c3 129 const decoded = decode(torrentContent)
1f6125be
C
130
131 decoded['announce-list'] = buildAnnounceList()
132 decoded.announce = decoded['announce-list'][0][0]
133
134 decoded['url-list'] = buildUrlList(video, videoFile)
135
9b293cd6
C
136 decoded.info.name = buildInfoName(video, videoFile)
137 decoded['creation date'] = Math.ceil(Date.now() / 1000)
138
1f6125be
C
139 const newTorrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
140 const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, newTorrentFilename)
141
9b293cd6 142 logger.info('Updating torrent metadata %s -> %s.', oldTorrentPath, newTorrentPath)
1f6125be 143
41fb13c3 144 await writeFile(newTorrentPath, encode(decoded))
f645af43 145 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
1f6125be
C
146
147 videoFile.torrentFilename = newTorrentFilename
38d69d65 148 videoFile.infoHash = sha1(encode(decoded.info))
1f6125be
C
149}
150
d7a25329 151function generateMagnetUri (
8efc27bf 152 video: MVideo,
d7a25329 153 videoFile: MVideoFileRedundanciesOpt,
d9a2a031 154 trackerUrls: string[]
d7a25329 155) {
90a8bd30 156 const xs = videoFile.getTorrentUrl()
d9a2a031 157 const announce = trackerUrls
90a8bd30 158 let urlList = [ videoFile.getFileUrl(video) ]
d7a25329
C
159
160 const redundancies = videoFile.RedundancyVideos
161 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
162
163 const magnetHash = {
164 xs,
165 announce,
166 urlList,
167 infoHash: videoFile.infoHash,
168 name: video.name
169 }
170
171 return magnetUtil.encode(magnetHash)
172}
30ff39e7 173
ce33919c
C
174// ---------------------------------------------------------------------------
175
176export {
d441f2ed 177 createTorrentPromise,
9b293cd6 178 updateTorrentMetadata,
d7a25329
C
179 createTorrentAndSetInfoHash,
180 generateMagnetUri,
ce33919c
C
181 downloadWebTorrentVideo
182}
c48e82b5
C
183
184// ---------------------------------------------------------------------------
185
d0b52b52 186function safeWebtorrentDestroy (
41fb13c3 187 webtorrent: Instance,
d0b52b52
C
188 torrentId: string,
189 downloadedFile?: { directoryPath: string, filepath: string },
190 torrentName?: string
191) {
ba5a8d89 192 return new Promise<void>(res => {
c48e82b5
C
193 webtorrent.destroy(err => {
194 // Delete torrent file
195 if (torrentName) {
d0b52b52 196 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
c48e82b5
C
197 remove(torrentId)
198 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
199 }
200
201 // Delete downloaded file
e37c85e9 202 if (downloadedFile) deleteDownloadedFile(downloadedFile)
c48e82b5 203
e37c85e9 204 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
c48e82b5
C
205
206 return res()
207 })
208 })
209}
e37c85e9
C
210
211function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
212 // We want to delete the base directory
213 let pathToDelete = dirname(downloadedFile.filepath)
214 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
215
216 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
217
218 logger.debug('Removing %s after webtorrent download.', toRemovePath)
219 remove(toRemovePath)
220 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
221}
1f6125be
C
222
223function buildAnnounceList () {
224 return [
225 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
226 [ WEBSERVER.URL + '/tracker/announce' ]
227 ]
228}
229
230function buildUrlList (video: MVideo, videoFile: MVideoFile) {
231 return [ videoFile.getFileUrl(video) ]
232}
9b293cd6
C
233
234function buildInfoName (video: MVideo, videoFile: MVideoFile) {
235 return `${video.name} ${videoFile.resolution}p${videoFile.extname}`
236}