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