2 # -*- coding: utf-8 -*-
4 from __future__
import unicode_literals
6 __license__
= 'Public Domain'
15 from .options
import (
22 workaround_optparse_bug9161
,
37 from .update
import update_self
38 from .downloader
import (
41 from .extractor
import gen_extractors
, list_extractors
42 from .YoutubeDL
import YoutubeDL
45 def _real_main(argv
=None):
46 # Compatibility fixes for Windows
47 if sys
.platform
== 'win32':
48 # https://github.com/rg3/youtube-dl/issues/820
49 codecs
.register(lambda name
: codecs
.lookup('utf-8') if name
== 'cp65001' else None)
51 workaround_optparse_bug9161()
53 setproctitle('youtube-dl')
55 parser
, opts
, args
= parseOpts(argv
)
58 if opts
.user_agent
is not None:
59 std_headers
['User-Agent'] = opts
.user_agent
62 if opts
.referer
is not None:
63 std_headers
['Referer'] = opts
.referer
66 if opts
.headers
is not None:
67 for h
in opts
.headers
:
68 if h
.find(':', 1) < 0:
69 parser
.error('wrong header formatting, it should be key:value, not "%s"' % h
)
70 key
, value
= h
.split(':', 2)
72 write_string('[debug] Adding header from command line option %s:%s\n' % (key
, value
))
73 std_headers
[key
] = value
76 if opts
.dump_user_agent
:
77 compat_print(std_headers
['User-Agent'])
80 # Batch file verification
82 if opts
.batchfile
is not None:
84 if opts
.batchfile
== '-':
87 batchfd
= io
.open(opts
.batchfile
, 'r', encoding
='utf-8', errors
='ignore')
88 batch_urls
= read_batch_urls(batchfd
)
90 write_string('[debug] Batch file urls: ' + repr(batch_urls
) + '\n')
92 sys
.exit('ERROR: batch file could not be read')
93 all_urls
= batch_urls
+ args
94 all_urls
= [url
.strip() for url
in all_urls
]
95 _enc
= preferredencoding()
96 all_urls
= [url
.decode(_enc
, 'ignore') if isinstance(url
, bytes) else url
for url
in all_urls
]
98 if opts
.list_extractors
:
99 for ie
in list_extractors(opts
.age_limit
):
100 compat_print(ie
.IE_NAME
+ (' (CURRENTLY BROKEN)' if not ie
._WORKING
else ''))
101 matchedUrls
= [url
for url
in all_urls
if ie
.suitable(url
)]
102 for mu
in matchedUrls
:
103 compat_print(' ' + mu
)
105 if opts
.list_extractor_descriptions
:
106 for ie
in list_extractors(opts
.age_limit
):
109 desc
= getattr(ie
, 'IE_DESC', ie
.IE_NAME
)
112 if hasattr(ie
, 'SEARCH_KEY'):
113 _SEARCHES
= ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
114 _COUNTS
= ('', '5', '10', 'all')
115 desc
+= ' (Example: "%s%s:%s" )' % (ie
.SEARCH_KEY
, random
.choice(_COUNTS
), random
.choice(_SEARCHES
))
119 # Conflicting, missing and erroneous options
120 if opts
.usenetrc
and (opts
.username
is not None or opts
.password
is not None):
121 parser
.error('using .netrc conflicts with giving username/password')
122 if opts
.password
is not None and opts
.username
is None:
123 parser
.error('account username missing\n')
124 if opts
.outtmpl
is not None and (opts
.usetitle
or opts
.autonumber
or opts
.useid
):
125 parser
.error('using output template conflicts with using title, video ID or auto number')
126 if opts
.usetitle
and opts
.useid
:
127 parser
.error('using title conflicts with using video ID')
128 if opts
.username
is not None and opts
.password
is None:
129 opts
.password
= compat_getpass('Type account password and press [Return]: ')
130 if opts
.ratelimit
is not None:
131 numeric_limit
= FileDownloader
.parse_bytes(opts
.ratelimit
)
132 if numeric_limit
is None:
133 parser
.error('invalid rate limit specified')
134 opts
.ratelimit
= numeric_limit
135 if opts
.min_filesize
is not None:
136 numeric_limit
= FileDownloader
.parse_bytes(opts
.min_filesize
)
137 if numeric_limit
is None:
138 parser
.error('invalid min_filesize specified')
139 opts
.min_filesize
= numeric_limit
140 if opts
.max_filesize
is not None:
141 numeric_limit
= FileDownloader
.parse_bytes(opts
.max_filesize
)
142 if numeric_limit
is None:
143 parser
.error('invalid max_filesize specified')
144 opts
.max_filesize
= numeric_limit
145 if opts
.retries
is not None:
147 opts
.retries
= int(opts
.retries
)
148 except (TypeError, ValueError):
149 parser
.error('invalid retry count specified')
150 if opts
.buffersize
is not None:
151 numeric_buffersize
= FileDownloader
.parse_bytes(opts
.buffersize
)
152 if numeric_buffersize
is None:
153 parser
.error('invalid buffer size specified')
154 opts
.buffersize
= numeric_buffersize
155 if opts
.playliststart
<= 0:
156 raise ValueError('Playlist start must be positive')
157 if opts
.playlistend
not in (-1, None) and opts
.playlistend
< opts
.playliststart
:
158 raise ValueError('Playlist end must be greater than playlist start')
159 if opts
.extractaudio
:
160 if opts
.audioformat
not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
161 parser
.error('invalid audio format specified')
162 if opts
.audioquality
:
163 opts
.audioquality
= opts
.audioquality
.strip('k').strip('K')
164 if not opts
.audioquality
.isdigit():
165 parser
.error('invalid audio quality specified')
166 if opts
.recodevideo
is not None:
167 if opts
.recodevideo
not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
168 parser
.error('invalid video recode format specified')
169 if opts
.merge_output_format
is not None and not '+' in opts
.format
: #if merge format output is used on videos that don't require merging, ignore
170 opts
.merge_output_format
= None
172 if opts
.date
is not None:
173 date
= DateRange
.day(opts
.date
)
175 date
= DateRange(opts
.dateafter
, opts
.datebefore
)
177 # Do not download videos when there are audio-only formats
178 if opts
.extractaudio
and not opts
.keepvideo
and opts
.format
is None:
179 opts
.format
= 'bestaudio/best'
181 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
182 # this was the old behaviour if only --all-sub was given.
183 if opts
.allsubtitles
and not opts
.writeautomaticsub
:
184 opts
.writesubtitles
= True
186 if sys
.version_info
< (3,):
187 # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
188 if opts
.outtmpl
is not None:
189 opts
.outtmpl
= opts
.outtmpl
.decode(preferredencoding())
190 outtmpl
= ((opts
.outtmpl
is not None and opts
.outtmpl
)
191 or (opts
.format
== '-1' and opts
.usetitle
and '%(title)s-%(id)s-%(format)s.%(ext)s')
192 or (opts
.format
== '-1' and '%(id)s-%(format)s.%(ext)s')
193 or (opts
.usetitle
and opts
.autonumber
and '%(autonumber)s-%(title)s-%(id)s.%(ext)s')
194 or (opts
.usetitle
and '%(title)s-%(id)s.%(ext)s')
195 or (opts
.useid
and '%(id)s.%(ext)s')
196 or (opts
.autonumber
and '%(autonumber)s-%(id)s.%(ext)s')
198 if not os
.path
.splitext(outtmpl
)[1] and opts
.extractaudio
:
199 parser
.error('Cannot download a video and extract audio into the same'
200 ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
201 ' template'.format(outtmpl
))
203 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
204 any_printing
= opts
.print_json
205 download_archive_fn
= compat_expanduser(opts
.download_archive
) if opts
.download_archive
is not None else opts
.download_archive
209 # Add the metadata pp first, the other pps will copy it
211 postprocessors
.append({'key': 'FFmpegMetadata'}
)
212 if opts
.extractaudio
:
213 postprocessors
.append({
214 'key': 'FFmpegExtractAudio',
215 'preferredcodec': opts
.audioformat
,
216 'preferredquality': opts
.audioquality
,
217 'nopostoverwrites': opts
.nopostoverwrites
,
220 postprocessors
.append({
221 'key': 'FFmpegVideoConvertor',
222 'preferedformat': opts
.recodevideo
,
224 if opts
.embedsubtitles
:
225 postprocessors
.append({
226 'key': 'FFmpegEmbedSubtitle',
227 'subtitlesformat': opts
.subtitlesformat
,
230 postprocessors
.append({'key': 'XAttrMetadata'}
)
231 if opts
.embedthumbnail
:
232 if not opts
.addmetadata
:
233 postprocessors
.append({'key': 'FFmpegAudioFix'}
)
234 postprocessors
.append({'key': 'AtomicParsley'}
)
235 # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
236 # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
238 postprocessors
.append({
239 'key': 'ExecAfterDownload',
240 'verboseOutput': opts
.verbose
,
241 'exec_cmd': opts
.exec_cmd
,
245 'usenetrc': opts
.usenetrc
,
246 'username': opts
.username
,
247 'password': opts
.password
,
248 'twofactor': opts
.twofactor
,
249 'videopassword': opts
.videopassword
,
250 'quiet': (opts
.quiet
or any_getting
or any_printing
),
251 'no_warnings': opts
.no_warnings
,
252 'forceurl': opts
.geturl
,
253 'forcetitle': opts
.gettitle
,
254 'forceid': opts
.getid
,
255 'forcethumbnail': opts
.getthumbnail
,
256 'forcedescription': opts
.getdescription
,
257 'forceduration': opts
.getduration
,
258 'forcefilename': opts
.getfilename
,
259 'forceformat': opts
.getformat
,
260 'forcejson': opts
.dumpjson
or opts
.print_json
,
261 'dump_single_json': opts
.dump_single_json
,
262 'simulate': opts
.simulate
or any_getting
,
263 'skip_download': opts
.skip_download
,
264 'format': opts
.format
,
265 'format_limit': opts
.format_limit
,
266 'listformats': opts
.listformats
,
268 'autonumber_size': opts
.autonumber_size
,
269 'restrictfilenames': opts
.restrictfilenames
,
270 'ignoreerrors': opts
.ignoreerrors
,
271 'ratelimit': opts
.ratelimit
,
272 'nooverwrites': opts
.nooverwrites
,
273 'retries': opts
.retries
,
274 'buffersize': opts
.buffersize
,
275 'noresizebuffer': opts
.noresizebuffer
,
276 'continuedl': opts
.continue_dl
,
277 'noprogress': opts
.noprogress
,
278 'progress_with_newline': opts
.progress_with_newline
,
279 'playliststart': opts
.playliststart
,
280 'playlistend': opts
.playlistend
,
281 'playlistreverse': opts
.playlist_reverse
,
282 'noplaylist': opts
.noplaylist
,
283 'logtostderr': opts
.outtmpl
== '-',
284 'consoletitle': opts
.consoletitle
,
285 'nopart': opts
.nopart
,
286 'updatetime': opts
.updatetime
,
287 'writedescription': opts
.writedescription
,
288 'writeannotations': opts
.writeannotations
,
289 'writeinfojson': opts
.writeinfojson
,
290 'writethumbnail': opts
.writethumbnail
,
291 'writesubtitles': opts
.writesubtitles
,
292 'writeautomaticsub': opts
.writeautomaticsub
,
293 'allsubtitles': opts
.allsubtitles
,
294 'listsubtitles': opts
.listsubtitles
,
295 'subtitlesformat': opts
.subtitlesformat
,
296 'subtitleslangs': opts
.subtitleslangs
,
297 'matchtitle': decodeOption(opts
.matchtitle
),
298 'rejecttitle': decodeOption(opts
.rejecttitle
),
299 'max_downloads': opts
.max_downloads
,
300 'prefer_free_formats': opts
.prefer_free_formats
,
301 'verbose': opts
.verbose
,
302 'dump_intermediate_pages': opts
.dump_intermediate_pages
,
303 'write_pages': opts
.write_pages
,
305 'keepvideo': opts
.keepvideo
,
306 'min_filesize': opts
.min_filesize
,
307 'max_filesize': opts
.max_filesize
,
308 'min_views': opts
.min_views
,
309 'max_views': opts
.max_views
,
311 'cachedir': opts
.cachedir
,
312 'youtube_print_sig_code': opts
.youtube_print_sig_code
,
313 'age_limit': opts
.age_limit
,
314 'download_archive': download_archive_fn
,
315 'cookiefile': opts
.cookiefile
,
316 'nocheckcertificate': opts
.no_check_certificate
,
317 'prefer_insecure': opts
.prefer_insecure
,
319 'socket_timeout': opts
.socket_timeout
,
320 'bidi_workaround': opts
.bidi_workaround
,
321 'debug_printtraffic': opts
.debug_printtraffic
,
322 'prefer_ffmpeg': opts
.prefer_ffmpeg
,
323 'include_ads': opts
.include_ads
,
324 'default_search': opts
.default_search
,
325 'youtube_include_dash_manifest': opts
.youtube_include_dash_manifest
,
326 'encoding': opts
.encoding
,
327 'exec_cmd': opts
.exec_cmd
,
328 'extract_flat': opts
.extract_flat
,
329 'merge_output_format': opts
.merge_output_format
,
330 'postprocessors': postprocessors
,
333 with YoutubeDL(ydl_opts
) as ydl
:
336 update_self(ydl
.to_screen
, opts
.verbose
)
343 if (len(all_urls
) < 1) and (opts
.load_info_filename
is None):
344 if opts
.update_self
or opts
.rm_cachedir
:
347 ydl
.warn_if_short_id(sys
.argv
[1:] if argv
is None else argv
)
348 parser
.error('you must provide at least one URL')
351 if opts
.load_info_filename
is not None:
352 retcode
= ydl
.download_with_info_file(opts
.load_info_filename
)
354 retcode
= ydl
.download(all_urls
)
355 except MaxDownloadsReached
:
356 ydl
.to_screen('--max-download limit reached, aborting.')
365 except DownloadError
:
367 except SameFileError
:
368 sys
.exit('ERROR: fixed output name but more than one file to download')
369 except KeyboardInterrupt:
370 sys
.exit('\nERROR: Interrupted by user')
372 __all__
= ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']