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
 
  42 from .YoutubeDL 
import YoutubeDL
 
  43 from .postprocessor 
import ( 
  49     FFmpegEmbedSubtitlePP
, 
  55 def _real_main(argv
=None): 
  56     # Compatibility fixes for Windows 
  57     if sys
.platform 
== 'win32': 
  58         # https://github.com/rg3/youtube-dl/issues/820 
  59         codecs
.register(lambda name
: codecs
.lookup('utf-8') if name 
== 'cp65001' else None) 
  61     workaround_optparse_bug9161() 
  63     setproctitle('youtube-dl') 
  65     parser
, opts
, args 
= parseOpts(argv
) 
  68     if opts
.user_agent 
is not None: 
  69         std_headers
['User-Agent'] = opts
.user_agent
 
  72     if opts
.referer 
is not None: 
  73         std_headers
['Referer'] = opts
.referer
 
  76     if opts
.headers 
is not None: 
  77         for h 
in opts
.headers
: 
  78             if h
.find(':', 1) < 0: 
  79                 parser
.error('wrong header formatting, it should be key:value, not "%s"' % h
) 
  80             key
, value 
= h
.split(':', 2) 
  82                 write_string('[debug] Adding header from command line option %s:%s\n' % (key
, value
)) 
  83             std_headers
[key
] = value
 
  86     if opts
.dump_user_agent
: 
  87         compat_print(std_headers
['User-Agent']) 
  90     # Batch file verification 
  92     if opts
.batchfile 
is not None: 
  94             if opts
.batchfile 
== '-': 
  97                 batchfd 
= io
.open(opts
.batchfile
, 'r', encoding
='utf-8', errors
='ignore') 
  98             batch_urls 
= read_batch_urls(batchfd
) 
 100                 write_string('[debug] Batch file urls: ' + repr(batch_urls
) + '\n') 
 102             sys
.exit('ERROR: batch file could not be read') 
 103     all_urls 
= batch_urls 
+ args
 
 104     all_urls 
= [url
.strip() for url 
in all_urls
] 
 105     _enc 
= preferredencoding() 
 106     all_urls 
= [url
.decode(_enc
, 'ignore') if isinstance(url
, bytes) else url 
for url 
in all_urls
] 
 108     extractors 
= gen_extractors() 
 110     if opts
.list_extractors
: 
 111         for ie 
in sorted(extractors
, key
=lambda ie
: ie
.IE_NAME
.lower()): 
 112             compat_print(ie
.IE_NAME 
+ (' (CURRENTLY BROKEN)' if not ie
._WORKING 
else '')) 
 113             matchedUrls 
= [url 
for url 
in all_urls 
if ie
.suitable(url
)] 
 114             for mu 
in matchedUrls
: 
 115                 compat_print('  ' + mu
) 
 117     if opts
.list_extractor_descriptions
: 
 118         for ie 
in sorted(extractors
, key
=lambda ie
: ie
.IE_NAME
.lower()): 
 121             desc 
= getattr(ie
, 'IE_DESC', ie
.IE_NAME
) 
 124             if hasattr(ie
, 'SEARCH_KEY'): 
 125                 _SEARCHES 
= ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny') 
 126                 _COUNTS 
= ('', '5', '10', 'all') 
 127                 desc 
+= ' (Example: "%s%s:%s" )' % (ie
.SEARCH_KEY
, random
.choice(_COUNTS
), random
.choice(_SEARCHES
)) 
 131     # Conflicting, missing and erroneous options 
 132     if opts
.usenetrc 
and (opts
.username 
is not None or opts
.password 
is not None): 
 133         parser
.error('using .netrc conflicts with giving username/password') 
 134     if opts
.password 
is not None and opts
.username 
is None: 
 135         parser
.error('account username missing\n') 
 136     if opts
.outtmpl 
is not None and (opts
.usetitle 
or opts
.autonumber 
or opts
.useid
): 
 137         parser
.error('using output template conflicts with using title, video ID or auto number') 
 138     if opts
.usetitle 
and opts
.useid
: 
 139         parser
.error('using title conflicts with using video ID') 
 140     if opts
.username 
is not None and opts
.password 
is None: 
 141         opts
.password 
= compat_getpass('Type account password and press [Return]: ') 
 142     if opts
.ratelimit 
is not None: 
 143         numeric_limit 
= FileDownloader
.parse_bytes(opts
.ratelimit
) 
 144         if numeric_limit 
is None: 
 145             parser
.error('invalid rate limit specified') 
 146         opts
.ratelimit 
= numeric_limit
 
 147     if opts
.min_filesize 
is not None: 
 148         numeric_limit 
= FileDownloader
.parse_bytes(opts
.min_filesize
) 
 149         if numeric_limit 
is None: 
 150             parser
.error('invalid min_filesize specified') 
 151         opts
.min_filesize 
= numeric_limit
 
 152     if opts
.max_filesize 
is not None: 
 153         numeric_limit 
= FileDownloader
.parse_bytes(opts
.max_filesize
) 
 154         if numeric_limit 
is None: 
 155             parser
.error('invalid max_filesize specified') 
 156         opts
.max_filesize 
= numeric_limit
 
 157     if opts
.retries 
is not None: 
 159             opts
.retries 
= int(opts
.retries
) 
 160         except (TypeError, ValueError): 
 161             parser
.error('invalid retry count specified') 
 162     if opts
.buffersize 
is not None: 
 163         numeric_buffersize 
= FileDownloader
.parse_bytes(opts
.buffersize
) 
 164         if numeric_buffersize 
is None: 
 165             parser
.error('invalid buffer size specified') 
 166         opts
.buffersize 
= numeric_buffersize
 
 167     if opts
.playliststart 
<= 0: 
 168         raise ValueError('Playlist start must be positive') 
 169     if opts
.playlistend 
not in (-1, None) and opts
.playlistend 
< opts
.playliststart
: 
 170         raise ValueError('Playlist end must be greater than playlist start') 
 171     if opts
.extractaudio
: 
 172         if opts
.audioformat 
not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']: 
 173             parser
.error('invalid audio format specified') 
 174     if opts
.audioquality
: 
 175         opts
.audioquality 
= opts
.audioquality
.strip('k').strip('K') 
 176         if not opts
.audioquality
.isdigit(): 
 177             parser
.error('invalid audio quality specified') 
 178     if opts
.recodevideo 
is not None: 
 179         if opts
.recodevideo 
not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']: 
 180             parser
.error('invalid video recode format specified') 
 181     if opts
.date 
is not None: 
 182         date 
= DateRange
.day(opts
.date
) 
 184         date 
= DateRange(opts
.dateafter
, opts
.datebefore
) 
 186     # Do not download videos when there are audio-only formats 
 187     if opts
.extractaudio 
and not opts
.keepvideo 
and opts
.format 
is None: 
 188         opts
.format 
= 'bestaudio/best' 
 190     # --all-sub automatically sets --write-sub if --write-auto-sub is not given 
 191     # this was the old behaviour if only --all-sub was given. 
 192     if opts
.allsubtitles 
and not opts
.writeautomaticsub
: 
 193         opts
.writesubtitles 
= True 
 195     if sys
.version_info 
< (3,): 
 196         # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems) 
 197         if opts
.outtmpl 
is not None: 
 198             opts
.outtmpl 
= opts
.outtmpl
.decode(preferredencoding()) 
 199     outtmpl 
= ((opts
.outtmpl 
is not None and opts
.outtmpl
) 
 200                or (opts
.format 
== '-1' and opts
.usetitle 
and '%(title)s-%(id)s-%(format)s.%(ext)s') 
 201                or (opts
.format 
== '-1' and '%(id)s-%(format)s.%(ext)s') 
 202                or (opts
.usetitle 
and opts
.autonumber 
and '%(autonumber)s-%(title)s-%(id)s.%(ext)s') 
 203                or (opts
.usetitle 
and '%(title)s-%(id)s.%(ext)s') 
 204                or (opts
.useid 
and '%(id)s.%(ext)s') 
 205                or (opts
.autonumber 
and '%(autonumber)s-%(id)s.%(ext)s') 
 207     if not os
.path
.splitext(outtmpl
)[1] and opts
.extractaudio
: 
 208         parser
.error('Cannot download a video and extract audio into the same' 
 209                      ' file! Use "{0}.%(ext)s" instead of "{0}" as the output' 
 210                      ' template'.format(outtmpl
)) 
 212     any_printing 
= 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
 
 213     download_archive_fn 
= compat_expanduser(opts
.download_archive
) if opts
.download_archive 
is not None else opts
.download_archive
 
 216         'usenetrc': opts
.usenetrc
, 
 217         'username': opts
.username
, 
 218         'password': opts
.password
, 
 219         'twofactor': opts
.twofactor
, 
 220         'videopassword': opts
.videopassword
, 
 221         'quiet': (opts
.quiet 
or any_printing
), 
 222         'no_warnings': opts
.no_warnings
, 
 223         'forceurl': opts
.geturl
, 
 224         'forcetitle': opts
.gettitle
, 
 225         'forceid': opts
.getid
, 
 226         'forcethumbnail': opts
.getthumbnail
, 
 227         'forcedescription': opts
.getdescription
, 
 228         'forceduration': opts
.getduration
, 
 229         'forcefilename': opts
.getfilename
, 
 230         'forceformat': opts
.getformat
, 
 231         'forcejson': opts
.dumpjson
, 
 232         'dump_single_json': opts
.dump_single_json
, 
 233         'simulate': opts
.simulate 
or any_printing
, 
 234         'skip_download': opts
.skip_download
, 
 235         'format': opts
.format
, 
 236         'format_limit': opts
.format_limit
, 
 237         'listformats': opts
.listformats
, 
 239         'autonumber_size': opts
.autonumber_size
, 
 240         'restrictfilenames': opts
.restrictfilenames
, 
 241         'ignoreerrors': opts
.ignoreerrors
, 
 242         'ratelimit': opts
.ratelimit
, 
 243         'nooverwrites': opts
.nooverwrites
, 
 244         'retries': opts
.retries
, 
 245         'buffersize': opts
.buffersize
, 
 246         'noresizebuffer': opts
.noresizebuffer
, 
 247         'continuedl': opts
.continue_dl
, 
 248         'noprogress': opts
.noprogress
, 
 249         'progress_with_newline': opts
.progress_with_newline
, 
 250         'playliststart': opts
.playliststart
, 
 251         'playlistend': opts
.playlistend
, 
 252         'noplaylist': opts
.noplaylist
, 
 253         'logtostderr': opts
.outtmpl 
== '-', 
 254         'consoletitle': opts
.consoletitle
, 
 255         'nopart': opts
.nopart
, 
 256         'updatetime': opts
.updatetime
, 
 257         'writedescription': opts
.writedescription
, 
 258         'writeannotations': opts
.writeannotations
, 
 259         'writeinfojson': opts
.writeinfojson
, 
 260         'writethumbnail': opts
.writethumbnail
, 
 261         'writesubtitles': opts
.writesubtitles
, 
 262         'writeautomaticsub': opts
.writeautomaticsub
, 
 263         'allsubtitles': opts
.allsubtitles
, 
 264         'listsubtitles': opts
.listsubtitles
, 
 265         'subtitlesformat': opts
.subtitlesformat
, 
 266         'subtitleslangs': opts
.subtitleslangs
, 
 267         'matchtitle': decodeOption(opts
.matchtitle
), 
 268         'rejecttitle': decodeOption(opts
.rejecttitle
), 
 269         'max_downloads': opts
.max_downloads
, 
 270         'prefer_free_formats': opts
.prefer_free_formats
, 
 271         'verbose': opts
.verbose
, 
 272         'dump_intermediate_pages': opts
.dump_intermediate_pages
, 
 273         'write_pages': opts
.write_pages
, 
 275         'keepvideo': opts
.keepvideo
, 
 276         'min_filesize': opts
.min_filesize
, 
 277         'max_filesize': opts
.max_filesize
, 
 278         'min_views': opts
.min_views
, 
 279         'max_views': opts
.max_views
, 
 281         'cachedir': opts
.cachedir
, 
 282         'youtube_print_sig_code': opts
.youtube_print_sig_code
, 
 283         'age_limit': opts
.age_limit
, 
 284         'download_archive': download_archive_fn
, 
 285         'cookiefile': opts
.cookiefile
, 
 286         'nocheckcertificate': opts
.no_check_certificate
, 
 287         'prefer_insecure': opts
.prefer_insecure
, 
 289         'socket_timeout': opts
.socket_timeout
, 
 290         'bidi_workaround': opts
.bidi_workaround
, 
 291         'debug_printtraffic': opts
.debug_printtraffic
, 
 292         'prefer_ffmpeg': opts
.prefer_ffmpeg
, 
 293         'include_ads': opts
.include_ads
, 
 294         'default_search': opts
.default_search
, 
 295         'youtube_include_dash_manifest': opts
.youtube_include_dash_manifest
, 
 296         'encoding': opts
.encoding
, 
 297         'exec_cmd': opts
.exec_cmd
, 
 298         'extract_flat': opts
.extract_flat
, 
 301     with YoutubeDL(ydl_opts
) as ydl
: 
 303         # Add the metadata pp first, the other pps will copy it 
 305             ydl
.add_post_processor(FFmpegMetadataPP()) 
 306         if opts
.extractaudio
: 
 307             ydl
.add_post_processor(FFmpegExtractAudioPP(preferredcodec
=opts
.audioformat
, preferredquality
=opts
.audioquality
, nopostoverwrites
=opts
.nopostoverwrites
)) 
 309             ydl
.add_post_processor(FFmpegVideoConvertor(preferedformat
=opts
.recodevideo
)) 
 310         if opts
.embedsubtitles
: 
 311             ydl
.add_post_processor(FFmpegEmbedSubtitlePP(subtitlesformat
=opts
.subtitlesformat
)) 
 313             ydl
.add_post_processor(XAttrMetadataPP()) 
 314         if opts
.embedthumbnail
: 
 315             if not opts
.addmetadata
: 
 316                 ydl
.add_post_processor(FFmpegAudioFixPP()) 
 317             ydl
.add_post_processor(AtomicParsleyPP()) 
 319         # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way. 
 320         # So if the user is able to remove the file before your postprocessor runs it might cause a few problems. 
 322             ydl
.add_post_processor(ExecAfterDownloadPP( 
 323                 verboseOutput
=opts
.verbose
, exec_cmd
=opts
.exec_cmd
)) 
 327             update_self(ydl
.to_screen
, opts
.verbose
) 
 334         if (len(all_urls
) < 1) and (opts
.load_info_filename 
is None): 
 335             if opts
.update_self 
or opts
.rm_cachedir
: 
 338             ydl
.warn_if_short_id(sys
.argv
[1:] if argv 
is None else argv
) 
 339             parser
.error('you must provide at least one URL') 
 342             if opts
.load_info_filename 
is not None: 
 343                 retcode 
= ydl
.download_with_info_file(opts
.load_info_filename
) 
 345                 retcode 
= ydl
.download(all_urls
) 
 346         except MaxDownloadsReached
: 
 347             ydl
.to_screen('--max-download limit reached, aborting.') 
 356     except DownloadError
: 
 358     except SameFileError
: 
 359         sys
.exit('ERROR: fixed output name but more than one file to download') 
 360     except KeyboardInterrupt: 
 361         sys
.exit('\nERROR: Interrupted by user')