]>
Commit | Line | Data |
---|---|---|
1 | import execa from 'execa' | |
2 | import { ensureDir, pathExists, writeFile } from 'fs-extra' | |
3 | import { dirname, join } from 'path' | |
4 | import { CONFIG } from '@server/initializers/config' | |
5 | import { VideoResolution } from '@shared/models' | |
6 | import { logger, loggerTagsFactory } from '../logger' | |
7 | import { getProxy, isProxyEnabled } from '../proxy' | |
8 | import { isBinaryResponse, peertubeGot } from '../requests' | |
9 | ||
10 | const lTags = loggerTagsFactory('youtube-dl') | |
11 | ||
12 | const youtubeDLBinaryPath = join(CONFIG.STORAGE.BIN_DIR, CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.NAME) | |
13 | ||
14 | export class YoutubeDLCLI { | |
15 | ||
16 | static async safeGet () { | |
17 | if (!await pathExists(youtubeDLBinaryPath)) { | |
18 | await ensureDir(dirname(youtubeDLBinaryPath)) | |
19 | ||
20 | await this.updateYoutubeDLBinary() | |
21 | } | |
22 | ||
23 | return new YoutubeDLCLI() | |
24 | } | |
25 | ||
26 | static async updateYoutubeDLBinary () { | |
27 | const url = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.URL | |
28 | ||
29 | logger.info('Updating youtubeDL binary from %s.', url, lTags()) | |
30 | ||
31 | const gotOptions = { context: { bodyKBLimit: 20_000 }, responseType: 'buffer' as 'buffer' } | |
32 | ||
33 | try { | |
34 | let gotResult = await peertubeGot(url, gotOptions) | |
35 | ||
36 | if (!isBinaryResponse(gotResult)) { | |
37 | const json = JSON.parse(gotResult.body.toString()) | |
38 | const latest = json.filter(release => release.prerelease === false)[0] | |
39 | if (!latest) throw new Error('Cannot find latest release') | |
40 | ||
41 | const releaseName = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE.NAME | |
42 | const releaseAsset = latest.assets.find(a => a.name === releaseName) | |
43 | if (!releaseAsset) throw new Error(`Cannot find appropriate release with name ${releaseName} in release assets`) | |
44 | ||
45 | gotResult = await peertubeGot(releaseAsset.browser_download_url, gotOptions) | |
46 | } | |
47 | ||
48 | if (!isBinaryResponse(gotResult)) { | |
49 | throw new Error('Not a binary response') | |
50 | } | |
51 | ||
52 | await writeFile(youtubeDLBinaryPath, gotResult.body) | |
53 | ||
54 | logger.info('youtube-dl updated %s.', youtubeDLBinaryPath, lTags()) | |
55 | } catch (err) { | |
56 | logger.error('Cannot update youtube-dl from %s.', url, { err, ...lTags() }) | |
57 | } | |
58 | } | |
59 | ||
60 | static getYoutubeDLVideoFormat (enabledResolutions: VideoResolution[], useBestFormat: boolean) { | |
61 | /** | |
62 | * list of format selectors in order or preference | |
63 | * see https://github.com/ytdl-org/youtube-dl#format-selection | |
64 | * | |
65 | * case #1 asks for a mp4 using h264 (avc1) and the exact resolution in the hope | |
66 | * of being able to do a "quick-transcode" | |
67 | * case #2 is the first fallback. No "quick-transcode" means we can get anything else (like vp9) | |
68 | * case #3 is the resolution-degraded equivalent of #1, and already a pretty safe fallback | |
69 | * | |
70 | * in any case we avoid AV1, see https://github.com/Chocobozzz/PeerTube/issues/3499 | |
71 | **/ | |
72 | ||
73 | let result: string[] = [] | |
74 | ||
75 | if (!useBestFormat) { | |
76 | const resolution = enabledResolutions.length === 0 | |
77 | ? VideoResolution.H_720P | |
78 | : Math.max(...enabledResolutions) | |
79 | ||
80 | result = [ | |
81 | `bestvideo[vcodec^=avc1][height=${resolution}]+bestaudio[ext=m4a]`, // case #1 | |
82 | `bestvideo[vcodec!*=av01][vcodec!*=vp9.2][height=${resolution}]+bestaudio`, // case #2 | |
83 | `bestvideo[vcodec^=avc1][height<=${resolution}]+bestaudio[ext=m4a]` // case # | |
84 | ] | |
85 | } | |
86 | ||
87 | return result.concat([ | |
88 | 'bestvideo[vcodec!*=av01][vcodec!*=vp9.2]+bestaudio', | |
89 | 'best[vcodec!*=av01][vcodec!*=vp9.2]', // case fallback for known formats | |
90 | 'bestvideo[ext=mp4]+bestaudio[ext=m4a]', | |
91 | 'best' // Ultimate fallback | |
92 | ]).join('/') | |
93 | } | |
94 | ||
95 | private constructor () { | |
96 | ||
97 | } | |
98 | ||
99 | download (options: { | |
100 | url: string | |
101 | format: string | |
102 | output: string | |
103 | processOptions: execa.NodeOptions | |
104 | timeout?: number | |
105 | additionalYoutubeDLArgs?: string[] | |
106 | }) { | |
107 | let args = options.additionalYoutubeDLArgs || [] | |
108 | args = args.concat([ '--merge-output-format', 'mp4', '-f', options.format, '-o', options.output ]) | |
109 | ||
110 | return this.run({ | |
111 | url: options.url, | |
112 | processOptions: options.processOptions, | |
113 | timeout: options.timeout, | |
114 | args | |
115 | }) | |
116 | } | |
117 | ||
118 | async getInfo (options: { | |
119 | url: string | |
120 | format: string | |
121 | processOptions: execa.NodeOptions | |
122 | additionalYoutubeDLArgs?: string[] | |
123 | }) { | |
124 | const { url, format, additionalYoutubeDLArgs = [], processOptions } = options | |
125 | ||
126 | const completeArgs = additionalYoutubeDLArgs.concat([ '--dump-json', '-f', format ]) | |
127 | ||
128 | const data = await this.run({ url, args: completeArgs, processOptions }) | |
129 | const info = data.map(this.parseInfo) | |
130 | ||
131 | return info.length === 1 | |
132 | ? info[0] | |
133 | : info | |
134 | } | |
135 | ||
136 | getListInfo (options: { | |
137 | url: string | |
138 | latestVideosCount?: number | |
139 | processOptions: execa.NodeOptions | |
140 | }): Promise<{ upload_date: string, webpage_url: string }[]> { | |
141 | const additionalYoutubeDLArgs = [ '--skip-download', '--playlist-reverse' ] | |
142 | ||
143 | if (options.latestVideosCount !== undefined) { | |
144 | additionalYoutubeDLArgs.push('--playlist-end', options.latestVideosCount.toString()) | |
145 | } | |
146 | ||
147 | return this.getInfo({ | |
148 | url: options.url, | |
149 | format: YoutubeDLCLI.getYoutubeDLVideoFormat([], false), | |
150 | processOptions: options.processOptions, | |
151 | additionalYoutubeDLArgs | |
152 | }) | |
153 | } | |
154 | ||
155 | async getSubs (options: { | |
156 | url: string | |
157 | format: 'vtt' | |
158 | processOptions: execa.NodeOptions | |
159 | }) { | |
160 | const { url, format, processOptions } = options | |
161 | ||
162 | const args = [ '--skip-download', '--all-subs', `--sub-format=${format}` ] | |
163 | ||
164 | const data = await this.run({ url, args, processOptions }) | |
165 | const files: string[] = [] | |
166 | ||
167 | const skipString = '[info] Writing video subtitles to: ' | |
168 | ||
169 | for (let i = 0, len = data.length; i < len; i++) { | |
170 | const line = data[i] | |
171 | ||
172 | if (line.indexOf(skipString) === 0) { | |
173 | files.push(line.slice(skipString.length)) | |
174 | } | |
175 | } | |
176 | ||
177 | return files | |
178 | } | |
179 | ||
180 | private async run (options: { | |
181 | url: string | |
182 | args: string[] | |
183 | timeout?: number | |
184 | processOptions: execa.NodeOptions | |
185 | }) { | |
186 | const { url, args, timeout, processOptions } = options | |
187 | ||
188 | let completeArgs = this.wrapWithProxyOptions(args) | |
189 | completeArgs = this.wrapWithIPOptions(completeArgs) | |
190 | completeArgs = this.wrapWithFFmpegOptions(completeArgs) | |
191 | ||
192 | const { PYTHON_PATH } = CONFIG.IMPORT.VIDEOS.HTTP.YOUTUBE_DL_RELEASE | |
193 | const subProcess = execa(PYTHON_PATH, [ youtubeDLBinaryPath, ...completeArgs, url ], processOptions) | |
194 | ||
195 | if (timeout) { | |
196 | setTimeout(() => subProcess.cancel(), timeout) | |
197 | } | |
198 | ||
199 | const output = await subProcess | |
200 | ||
201 | logger.debug('Run youtube-dl command.', { command: output.command, ...lTags() }) | |
202 | ||
203 | return output.stdout | |
204 | ? output.stdout.trim().split(/\r?\n/) | |
205 | : undefined | |
206 | } | |
207 | ||
208 | private wrapWithProxyOptions (args: string[]) { | |
209 | if (isProxyEnabled()) { | |
210 | logger.debug('Using proxy %s for YoutubeDL', getProxy(), lTags()) | |
211 | ||
212 | return [ '--proxy', getProxy() ].concat(args) | |
213 | } | |
214 | ||
215 | return args | |
216 | } | |
217 | ||
218 | private wrapWithIPOptions (args: string[]) { | |
219 | if (CONFIG.IMPORT.VIDEOS.HTTP.FORCE_IPV4) { | |
220 | logger.debug('Force ipv4 for YoutubeDL') | |
221 | ||
222 | return [ '--force-ipv4' ].concat(args) | |
223 | } | |
224 | ||
225 | return args | |
226 | } | |
227 | ||
228 | private wrapWithFFmpegOptions (args: string[]) { | |
229 | if (process.env.FFMPEG_PATH) { | |
230 | logger.debug('Using ffmpeg location %s for YoutubeDL', process.env.FFMPEG_PATH, lTags()) | |
231 | ||
232 | return [ '--ffmpeg-location', process.env.FFMPEG_PATH ].concat(args) | |
233 | } | |
234 | ||
235 | return args | |
236 | } | |
237 | ||
238 | private parseInfo (data: string) { | |
239 | return JSON.parse(data) | |
240 | } | |
241 | } |