2 # -*- coding: utf-8 -*-
4 from __future__
import unicode_literals
6 __license__
= 'Public Domain'
15 from .options
import (
22 workaround_optparse_bug9161
,
38 from .update
import update_self
39 from .downloader
import (
42 from .extractor
import gen_extractors
, list_extractors
43 from .YoutubeDL
import YoutubeDL
46 def _real_main(argv
=None):
47 # Compatibility fixes for Windows
48 if sys
.platform
== 'win32':
49 # https://github.com/rg3/youtube-dl/issues/820
50 codecs
.register(lambda name
: codecs
.lookup('utf-8') if name
== 'cp65001' else None)
52 workaround_optparse_bug9161()
54 setproctitle('youtube-dl')
56 parser
, opts
, args
= parseOpts(argv
)
59 if opts
.user_agent
is not None:
60 std_headers
['User-Agent'] = opts
.user_agent
63 if opts
.referer
is not None:
64 std_headers
['Referer'] = opts
.referer
67 if opts
.headers
is not None:
68 for h
in opts
.headers
:
69 if h
.find(':', 1) < 0:
70 parser
.error('wrong header formatting, it should be key:value, not "%s"' % h
)
71 key
, value
= h
.split(':', 2)
73 write_string('[debug] Adding header from command line option %s:%s\n' % (key
, value
))
74 std_headers
[key
] = value
77 if opts
.dump_user_agent
:
78 compat_print(std_headers
['User-Agent'])
81 # Batch file verification
83 if opts
.batchfile
is not None:
85 if opts
.batchfile
== '-':
88 batchfd
= io
.open(opts
.batchfile
, 'r', encoding
='utf-8', errors
='ignore')
89 batch_urls
= read_batch_urls(batchfd
)
91 write_string('[debug] Batch file urls: ' + repr(batch_urls
) + '\n')
93 sys
.exit('ERROR: batch file could not be read')
94 all_urls
= batch_urls
+ args
95 all_urls
= [url
.strip() for url
in all_urls
]
96 _enc
= preferredencoding()
97 all_urls
= [url
.decode(_enc
, 'ignore') if isinstance(url
, bytes) else url
for url
in all_urls
]
99 if opts
.list_extractors
:
100 for ie
in list_extractors(opts
.age_limit
):
101 compat_print(ie
.IE_NAME
+ (' (CURRENTLY BROKEN)' if not ie
._WORKING
else ''))
102 matchedUrls
= [url
for url
in all_urls
if ie
.suitable(url
)]
103 for mu
in matchedUrls
:
104 compat_print(' ' + mu
)
106 if opts
.list_extractor_descriptions
:
107 for ie
in list_extractors(opts
.age_limit
):
110 desc
= getattr(ie
, 'IE_DESC', ie
.IE_NAME
)
113 if hasattr(ie
, 'SEARCH_KEY'):
114 _SEARCHES
= ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
115 _COUNTS
= ('', '5', '10', 'all')
116 desc
+= ' (Example: "%s%s:%s" )' % (ie
.SEARCH_KEY
, random
.choice(_COUNTS
), random
.choice(_SEARCHES
))
120 # Conflicting, missing and erroneous options
121 if opts
.usenetrc
and (opts
.username
is not None or opts
.password
is not None):
122 parser
.error('using .netrc conflicts with giving username/password')
123 if opts
.password
is not None and opts
.username
is None:
124 parser
.error('account username missing\n')
125 if opts
.outtmpl
is not None and (opts
.usetitle
or opts
.autonumber
or opts
.useid
):
126 parser
.error('using output template conflicts with using title, video ID or auto number')
127 if opts
.usetitle
and opts
.useid
:
128 parser
.error('using title conflicts with using video ID')
129 if opts
.username
is not None and opts
.password
is None:
130 opts
.password
= compat_getpass('Type account password and press [Return]: ')
131 if opts
.ratelimit
is not None:
132 numeric_limit
= FileDownloader
.parse_bytes(opts
.ratelimit
)
133 if numeric_limit
is None:
134 parser
.error('invalid rate limit specified')
135 opts
.ratelimit
= numeric_limit
136 if opts
.min_filesize
is not None:
137 numeric_limit
= FileDownloader
.parse_bytes(opts
.min_filesize
)
138 if numeric_limit
is None:
139 parser
.error('invalid min_filesize specified')
140 opts
.min_filesize
= numeric_limit
141 if opts
.max_filesize
is not None:
142 numeric_limit
= FileDownloader
.parse_bytes(opts
.max_filesize
)
143 if numeric_limit
is None:
144 parser
.error('invalid max_filesize specified')
145 opts
.max_filesize
= numeric_limit
146 if opts
.retries
is not None:
147 if opts
.retries
in ('inf', 'infinite'):
148 opts_retries
= float('inf')
151 opts_retries
= int(opts
.retries
)
152 except (TypeError, ValueError):
153 parser
.error('invalid retry count specified')
154 if opts
.buffersize
is not None:
155 numeric_buffersize
= FileDownloader
.parse_bytes(opts
.buffersize
)
156 if numeric_buffersize
is None:
157 parser
.error('invalid buffer size specified')
158 opts
.buffersize
= numeric_buffersize
159 if opts
.playliststart
<= 0:
160 raise ValueError('Playlist start must be positive')
161 if opts
.playlistend
not in (-1, None) and opts
.playlistend
< opts
.playliststart
:
162 raise ValueError('Playlist end must be greater than playlist start')
163 if opts
.extractaudio
:
164 if opts
.audioformat
not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
165 parser
.error('invalid audio format specified')
166 if opts
.audioquality
:
167 opts
.audioquality
= opts
.audioquality
.strip('k').strip('K')
168 if not opts
.audioquality
.isdigit():
169 parser
.error('invalid audio quality specified')
170 if opts
.recodevideo
is not None:
171 if opts
.recodevideo
not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
172 parser
.error('invalid video recode format specified')
173 if opts
.convertsubtitles
is not None:
174 if opts
.convertsubtitles
not in ['srt', 'vtt', 'ass']:
175 parser
.error('invalid subtitle format specified')
177 if opts
.date
is not None:
178 date
= DateRange
.day(opts
.date
)
180 date
= DateRange(opts
.dateafter
, opts
.datebefore
)
182 # Do not download videos when there are audio-only formats
183 if opts
.extractaudio
and not opts
.keepvideo
and opts
.format
is None:
184 opts
.format
= 'bestaudio/best'
186 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
187 # this was the old behaviour if only --all-sub was given.
188 if opts
.allsubtitles
and not opts
.writeautomaticsub
:
189 opts
.writesubtitles
= True
191 if sys
.version_info
< (3,):
192 # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
193 if opts
.outtmpl
is not None:
194 opts
.outtmpl
= opts
.outtmpl
.decode(preferredencoding())
195 outtmpl
= ((opts
.outtmpl
is not None and opts
.outtmpl
) or
196 (opts
.format
== '-1' and opts
.usetitle
and '%(title)s-%(id)s-%(format)s.%(ext)s') or
197 (opts
.format
== '-1' and '%(id)s-%(format)s.%(ext)s') or
198 (opts
.usetitle
and opts
.autonumber
and '%(autonumber)s-%(title)s-%(id)s.%(ext)s') or
199 (opts
.usetitle
and '%(title)s-%(id)s.%(ext)s') or
200 (opts
.useid
and '%(id)s.%(ext)s') or
201 (opts
.autonumber
and '%(autonumber)s-%(id)s.%(ext)s') or
203 if not os
.path
.splitext(outtmpl
)[1] and opts
.extractaudio
:
204 parser
.error('Cannot download a video and extract audio into the same'
205 ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
206 ' template'.format(outtmpl
))
208 any_getting
= opts
.geturl
or opts
.gettitle
or opts
.getid
or opts
.getthumbnail
or opts
.getdescription
or opts
.getfilename
or opts
.getformat
or opts
.getduration
or opts
.dumpjson
or opts
.dump_single_json
209 any_printing
= opts
.print_json
210 download_archive_fn
= compat_expanduser(opts
.download_archive
) if opts
.download_archive
is not None else opts
.download_archive
214 # Add the metadata pp first, the other pps will copy it
216 postprocessors
.append({'key': 'FFmpegMetadata'})
217 if opts
.extractaudio
:
218 postprocessors
.append({
219 'key': 'FFmpegExtractAudio',
220 'preferredcodec': opts
.audioformat
,
221 'preferredquality': opts
.audioquality
,
222 'nopostoverwrites': opts
.nopostoverwrites
,
225 postprocessors
.append({
226 'key': 'FFmpegVideoConvertor',
227 'preferedformat': opts
.recodevideo
,
229 if opts
.convertsubtitles
:
230 postprocessors
.append({
231 'key': 'FFmpegSubtitlesConvertor',
232 'format': opts
.convertsubtitles
,
234 if opts
.embedsubtitles
:
235 postprocessors
.append({
236 'key': 'FFmpegEmbedSubtitle',
239 postprocessors
.append({'key': 'XAttrMetadata'})
240 if opts
.embedthumbnail
:
241 if not opts
.addmetadata
:
242 postprocessors
.append({'key': 'FFmpegAudioFix'})
243 postprocessors
.append({'key': 'AtomicParsley'})
244 # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
245 # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
247 postprocessors
.append({
248 'key': 'ExecAfterDownload',
249 'verboseOutput': opts
.verbose
,
250 'exec_cmd': opts
.exec_cmd
,
252 if opts
.xattr_set_filesize
:
255 xattr
# Confuse flake8
257 parser
.error('setting filesize xattr requested but python-xattr is not available')
259 None if opts
.match_filter
is None
260 else match_filter_func(opts
.match_filter
))
263 'usenetrc': opts
.usenetrc
,
264 'username': opts
.username
,
265 'password': opts
.password
,
266 'twofactor': opts
.twofactor
,
267 'videopassword': opts
.videopassword
,
268 'quiet': (opts
.quiet
or any_getting
or any_printing
),
269 'no_warnings': opts
.no_warnings
,
270 'forceurl': opts
.geturl
,
271 'forcetitle': opts
.gettitle
,
272 'forceid': opts
.getid
,
273 'forcethumbnail': opts
.getthumbnail
,
274 'forcedescription': opts
.getdescription
,
275 'forceduration': opts
.getduration
,
276 'forcefilename': opts
.getfilename
,
277 'forceformat': opts
.getformat
,
278 'forcejson': opts
.dumpjson
or opts
.print_json
,
279 'dump_single_json': opts
.dump_single_json
,
280 'simulate': opts
.simulate
or any_getting
,
281 'skip_download': opts
.skip_download
,
282 'format': opts
.format
,
283 'format_limit': opts
.format_limit
,
284 'listformats': opts
.listformats
,
286 'autonumber_size': opts
.autonumber_size
,
287 'restrictfilenames': opts
.restrictfilenames
,
288 'ignoreerrors': opts
.ignoreerrors
,
289 'ratelimit': opts
.ratelimit
,
290 'nooverwrites': opts
.nooverwrites
,
291 'retries': opts_retries
,
292 'buffersize': opts
.buffersize
,
293 'noresizebuffer': opts
.noresizebuffer
,
294 'continuedl': opts
.continue_dl
,
295 'noprogress': opts
.noprogress
,
296 'progress_with_newline': opts
.progress_with_newline
,
297 'playliststart': opts
.playliststart
,
298 'playlistend': opts
.playlistend
,
299 'playlistreverse': opts
.playlist_reverse
,
300 'noplaylist': opts
.noplaylist
,
301 'logtostderr': opts
.outtmpl
== '-',
302 'consoletitle': opts
.consoletitle
,
303 'nopart': opts
.nopart
,
304 'updatetime': opts
.updatetime
,
305 'writedescription': opts
.writedescription
,
306 'writeannotations': opts
.writeannotations
,
307 'writeinfojson': opts
.writeinfojson
,
308 'writethumbnail': opts
.writethumbnail
,
309 'write_all_thumbnails': opts
.write_all_thumbnails
,
310 'writesubtitles': opts
.writesubtitles
,
311 'writeautomaticsub': opts
.writeautomaticsub
,
312 'allsubtitles': opts
.allsubtitles
,
313 'listsubtitles': opts
.listsubtitles
,
314 'subtitlesformat': opts
.subtitlesformat
,
315 'subtitleslangs': opts
.subtitleslangs
,
316 'matchtitle': decodeOption(opts
.matchtitle
),
317 'rejecttitle': decodeOption(opts
.rejecttitle
),
318 'max_downloads': opts
.max_downloads
,
319 'prefer_free_formats': opts
.prefer_free_formats
,
320 'verbose': opts
.verbose
,
321 'dump_intermediate_pages': opts
.dump_intermediate_pages
,
322 'write_pages': opts
.write_pages
,
324 'keepvideo': opts
.keepvideo
,
325 'min_filesize': opts
.min_filesize
,
326 'max_filesize': opts
.max_filesize
,
327 'min_views': opts
.min_views
,
328 'max_views': opts
.max_views
,
330 'cachedir': opts
.cachedir
,
331 'youtube_print_sig_code': opts
.youtube_print_sig_code
,
332 'age_limit': opts
.age_limit
,
333 'download_archive': download_archive_fn
,
334 'cookiefile': opts
.cookiefile
,
335 'nocheckcertificate': opts
.no_check_certificate
,
336 'prefer_insecure': opts
.prefer_insecure
,
338 'socket_timeout': opts
.socket_timeout
,
339 'bidi_workaround': opts
.bidi_workaround
,
340 'debug_printtraffic': opts
.debug_printtraffic
,
341 'prefer_ffmpeg': opts
.prefer_ffmpeg
,
342 'include_ads': opts
.include_ads
,
343 'default_search': opts
.default_search
,
344 'youtube_include_dash_manifest': opts
.youtube_include_dash_manifest
,
345 'encoding': opts
.encoding
,
346 'exec_cmd': opts
.exec_cmd
,
347 'extract_flat': opts
.extract_flat
,
348 'merge_output_format': opts
.merge_output_format
,
349 'postprocessors': postprocessors
,
351 'source_address': opts
.source_address
,
352 'call_home': opts
.call_home
,
353 'sleep_interval': opts
.sleep_interval
,
354 'external_downloader': opts
.external_downloader
,
355 'list_thumbnails': opts
.list_thumbnails
,
356 'playlist_items': opts
.playlist_items
,
357 'xattr_set_filesize': opts
.xattr_set_filesize
,
358 'match_filter': match_filter
,
359 'no_color': opts
.no_color
,
360 'ffmpeg_location': opts
.ffmpeg_location
,
361 'hls_prefer_native': opts
.hls_prefer_native
,
364 with YoutubeDL(ydl_opts
) as ydl
:
367 update_self(ydl
.to_screen
, opts
.verbose
)
374 if (len(all_urls
) < 1) and (opts
.load_info_filename
is None):
375 if opts
.update_self
or opts
.rm_cachedir
:
378 ydl
.warn_if_short_id(sys
.argv
[1:] if argv
is None else argv
)
380 'You must provide at least one URL.\n'
381 'Type youtube-dl --help to see a list of all options.')
384 if opts
.load_info_filename
is not None:
385 retcode
= ydl
.download_with_info_file(opts
.load_info_filename
)
387 retcode
= ydl
.download(all_urls
)
388 except MaxDownloadsReached
:
389 ydl
.to_screen('--max-download limit reached, aborting.')
398 except DownloadError
:
400 except SameFileError
:
401 sys
.exit('ERROR: fixed output name but more than one file to download')
402 except KeyboardInterrupt:
403 sys
.exit('\nERROR: Interrupted by user')
405 __all__
= ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']