]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/webtorrent.ts
Don't crash on youtube-dl update write error
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
CommitLineData
ce33919c 1import { logger } from './logger'
6040f87d 2import { generateVideoImportTmpPath } from './utils'
ce33919c 3import * as WebTorrent from 'webtorrent'
d7a25329 4import { createWriteStream, ensureDir, remove, writeFile } from 'fs-extra'
6dd9de95 5import { CONFIG } from '../initializers/config'
d0b52b52 6import { dirname, join } from 'path'
30ff39e7
C
7import * as createTorrent from 'create-torrent'
8import { promisify2 } from './core-utils'
26d6bf65
C
9import { MVideo } from '@server/types/models/video/video'
10import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/types/models/video/video-file'
11import { isStreamingPlaylist, MStreamingPlaylistVideo } from '@server/types/models/video/video-streaming-playlist'
b764380a 12import { WEBSERVER } from '@server/initializers/constants'
d7a25329
C
13import * as parseTorrent from 'parse-torrent'
14import * as magnetUtil from 'magnet-uri'
15import { isArray } from '@server/helpers/custom-validators/misc'
b764380a 16import { getTorrentFileName, getVideoFilePath } from '@server/lib/video-paths'
8dc8a34e 17import { extractVideo } from '@server/helpers/video'
d7a25329
C
18
19const createTorrentPromise = promisify2<string, any, any>(createTorrent)
ce33919c 20
cf9166cf 21async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
990b6a0b 22 const id = target.magnetUri || target.torrentName
c48e82b5 23 let timer
ce33919c 24
6040f87d 25 const path = generateVideoImportTmpPath(id)
990b6a0b 26 logger.info('Importing torrent video %s', id)
ce33919c 27
6040f87d 28 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
a71de50b
C
29 await ensureDir(directoryPath)
30
ce33919c
C
31 return new Promise<string>((res, rej) => {
32 const webtorrent = new WebTorrent()
c48e82b5 33 let file: WebTorrent.TorrentFile
ce33919c 34
990b6a0b 35 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
541006e3 36
a71de50b 37 const options = { path: directoryPath }
541006e3 38 const torrent = webtorrent.add(torrentId, options, torrent => {
c48e82b5
C
39 if (torrent.files.length !== 1) {
40 if (timer) clearTimeout(timer)
ce33919c 41
a1587156 42 for (const file of torrent.files) {
e37c85e9
C
43 deleteDownloadedFile({ directoryPath, filepath: file.path })
44 }
45
46 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
dae4a1c0 47 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
c48e82b5
C
48 }
49
a1587156 50 file = torrent.files[0]
a71de50b
C
51
52 // FIXME: avoid creating another stream when https://github.com/webtorrent/webtorrent/issues/1517 is fixed
53 const writeStream = createWriteStream(path)
54 writeStream.on('finish', () => {
55 if (timer) clearTimeout(timer)
56
a1587156 57 safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
a71de50b 58 .then(() => res(path))
a1587156 59 .catch(err => logger.error('Cannot destroy webtorrent.', { err }))
69fa54a0 60 })
a71de50b
C
61
62 file.createReadStream().pipe(writeStream)
3e17515e 63 })
ce33919c
C
64
65 torrent.on('error', err => rej(err))
c48e82b5 66
a1587156
C
67 timer = setTimeout(() => {
68 const err = new Error('Webtorrent download timeout.')
69
70 safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
71 .then(() => rej(err))
72 .catch(destroyErr => {
73 logger.error('Cannot destroy webtorrent.', { err: destroyErr })
74 rej(err)
75 })
76
cf9166cf 77 }, timeout)
ce33919c
C
78 })
79}
80
d7a25329
C
81async function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
82 const video = extractVideo(videoOrPlaylist)
d441f2ed 83 const { baseUrlHttp } = video.getBaseUrls()
d7a25329
C
84
85 const options = {
86 // Keep the extname, it's used by the client to stream the file inside a web browser
87 name: `${video.name} ${videoFile.resolution}p${videoFile.extname}`,
88 createdBy: 'PeerTube',
89 announceList: [
90 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
91 [ WEBSERVER.URL + '/tracker/announce' ]
92 ],
d441f2ed 93 urlList: [ videoOrPlaylist.getVideoFileUrl(videoFile, baseUrlHttp) ]
d7a25329
C
94 }
95
96 const torrent = await createTorrentPromise(getVideoFilePath(videoOrPlaylist, videoFile), options)
97
98 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, getTorrentFileName(videoOrPlaylist, videoFile))
99 logger.info('Creating torrent %s.', filePath)
100
101 await writeFile(filePath, torrent)
102
103 const parsedTorrent = parseTorrent(torrent)
104 videoFile.infoHash = parsedTorrent.infoHash
105}
106
107function generateMagnetUri (
108 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
109 videoFile: MVideoFileRedundanciesOpt,
110 baseUrlHttp: string,
111 baseUrlWs: string
112) {
113 const video = isStreamingPlaylist(videoOrPlaylist)
114 ? videoOrPlaylist.Video
115 : videoOrPlaylist
116
117 const xs = videoOrPlaylist.getTorrentUrl(videoFile, baseUrlHttp)
118 const announce = videoOrPlaylist.getTrackerUrls(baseUrlHttp, baseUrlWs)
119 let urlList = [ videoOrPlaylist.getVideoFileUrl(videoFile, baseUrlHttp) ]
120
121 const redundancies = videoFile.RedundancyVideos
122 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
123
124 const magnetHash = {
125 xs,
126 announce,
127 urlList,
128 infoHash: videoFile.infoHash,
129 name: video.name
130 }
131
132 return magnetUtil.encode(magnetHash)
133}
30ff39e7 134
ce33919c
C
135// ---------------------------------------------------------------------------
136
137export {
d441f2ed 138 createTorrentPromise,
d7a25329
C
139 createTorrentAndSetInfoHash,
140 generateMagnetUri,
ce33919c
C
141 downloadWebTorrentVideo
142}
c48e82b5
C
143
144// ---------------------------------------------------------------------------
145
d0b52b52
C
146function safeWebtorrentDestroy (
147 webtorrent: WebTorrent.Instance,
148 torrentId: string,
149 downloadedFile?: { directoryPath: string, filepath: string },
150 torrentName?: string
151) {
c48e82b5
C
152 return new Promise(res => {
153 webtorrent.destroy(err => {
154 // Delete torrent file
155 if (torrentName) {
d0b52b52 156 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
c48e82b5
C
157 remove(torrentId)
158 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
159 }
160
161 // Delete downloaded file
e37c85e9 162 if (downloadedFile) deleteDownloadedFile(downloadedFile)
c48e82b5 163
e37c85e9 164 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
c48e82b5
C
165
166 return res()
167 })
168 })
169}
e37c85e9
C
170
171function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
172 // We want to delete the base directory
173 let pathToDelete = dirname(downloadedFile.filepath)
174 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
175
176 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
177
178 logger.debug('Removing %s after webtorrent download.', toRemovePath)
179 remove(toRemovePath)
180 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
181}