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