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