You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

610 lines
29 KiB

13 years ago
12 years ago
12 years ago
12 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. __authors__ = (
  4. 'Ricardo Garcia Gonzalez',
  5. 'Danny Colligan',
  6. 'Benjamin Johnson',
  7. 'Vasyl\' Vavrychuk',
  8. 'Witold Baryluk',
  9. 'Paweł Paprota',
  10. 'Gergely Imreh',
  11. 'Rogério Brito',
  12. 'Philipp Hagemeister',
  13. 'Sören Schulze',
  14. 'Kevin Ngo',
  15. 'Ori Avtalion',
  16. 'shizeeg',
  17. 'Filippo Valsorda',
  18. 'Christian Albrecht',
  19. 'Dave Vasilevsky',
  20. 'Jaime Marquínez Ferrándiz',
  21. 'Jeff Crouse',
  22. 'Osama Khalid',
  23. 'Michael Walter',
  24. 'M. Yasoob Ullah Khalid',
  25. 'Julien Fraichard',
  26. 'Johny Mo Swag',
  27. )
  28. __license__ = 'Public Domain'
  29. import codecs
  30. import getpass
  31. import optparse
  32. import os
  33. import re
  34. import shlex
  35. import socket
  36. import subprocess
  37. import sys
  38. import warnings
  39. import platform
  40. from .utils import *
  41. from .update import update_self
  42. from .version import __version__
  43. from .FileDownloader import *
  44. from .extractor import gen_extractors
  45. from .YoutubeDL import YoutubeDL
  46. from .PostProcessor import *
  47. def parseOpts(overrideArguments=None):
  48. def _readOptions(filename_bytes):
  49. try:
  50. optionf = open(filename_bytes)
  51. except IOError:
  52. return [] # silently skip if file is not present
  53. try:
  54. res = []
  55. for l in optionf:
  56. res += shlex.split(l, comments=True)
  57. finally:
  58. optionf.close()
  59. return res
  60. def _format_option_string(option):
  61. ''' ('-o', '--option') -> -o, --format METAVAR'''
  62. opts = []
  63. if option._short_opts:
  64. opts.append(option._short_opts[0])
  65. if option._long_opts:
  66. opts.append(option._long_opts[0])
  67. if len(opts) > 1:
  68. opts.insert(1, ', ')
  69. if option.takes_value(): opts.append(' %s' % option.metavar)
  70. return "".join(opts)
  71. def _find_term_columns():
  72. columns = os.environ.get('COLUMNS', None)
  73. if columns:
  74. return int(columns)
  75. try:
  76. sp = subprocess.Popen(['stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  77. out,err = sp.communicate()
  78. return int(out.split()[1])
  79. except:
  80. pass
  81. return None
  82. max_width = 80
  83. max_help_position = 80
  84. # No need to wrap help messages if we're on a wide console
  85. columns = _find_term_columns()
  86. if columns: max_width = columns
  87. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  88. fmt.format_option_strings = _format_option_string
  89. kw = {
  90. 'version' : __version__,
  91. 'formatter' : fmt,
  92. 'usage' : '%prog [options] url [url...]',
  93. 'conflict_handler' : 'resolve',
  94. }
  95. parser = optparse.OptionParser(**kw)
  96. # option groups
  97. general = optparse.OptionGroup(parser, 'General Options')
  98. selection = optparse.OptionGroup(parser, 'Video Selection')
  99. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  100. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  101. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  102. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  103. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  104. general.add_option('-h', '--help',
  105. action='help', help='print this help text and exit')
  106. general.add_option('-v', '--version',
  107. action='version', help='print program version and exit')
  108. general.add_option('-U', '--update',
  109. action='store_true', dest='update_self', help='update this program to latest version')
  110. general.add_option('-i', '--ignore-errors',
  111. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  112. general.add_option('-r', '--rate-limit',
  113. dest='ratelimit', metavar='LIMIT', help='maximum download rate (e.g. 50k or 44.6m)')
  114. general.add_option('-R', '--retries',
  115. dest='retries', metavar='RETRIES', help='number of retries (default is %default)', default=10)
  116. general.add_option('--buffer-size',
  117. dest='buffersize', metavar='SIZE', help='size of download buffer (e.g. 1024 or 16k) (default is %default)', default="1024")
  118. general.add_option('--no-resize-buffer',
  119. action='store_true', dest='noresizebuffer',
  120. help='do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.', default=False)
  121. general.add_option('--dump-user-agent',
  122. action='store_true', dest='dump_user_agent',
  123. help='display the current browser identification', default=False)
  124. general.add_option('--user-agent',
  125. dest='user_agent', help='specify a custom user agent', metavar='UA')
  126. general.add_option('--referer',
  127. dest='referer', help='specify a custom referer, use if the video access is restricted to one domain',
  128. metavar='REF', default=None)
  129. general.add_option('--list-extractors',
  130. action='store_true', dest='list_extractors',
  131. help='List all supported extractors and the URLs they would handle', default=False)
  132. general.add_option('--proxy', dest='proxy', default=None, help='Use the specified HTTP/HTTPS proxy', metavar='URL')
  133. general.add_option('--no-check-certificate', action='store_true', dest='no_check_certificate', default=False, help='Suppress HTTPS certificate validation.')
  134. general.add_option('--test', action='store_true', dest='test', default=False, help=optparse.SUPPRESS_HELP)
  135. selection.add_option('--playlist-start',
  136. dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is %default)', default=1)
  137. selection.add_option('--playlist-end',
  138. dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
  139. selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
  140. selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
  141. selection.add_option('--max-downloads', metavar='NUMBER', dest='max_downloads', help='Abort after downloading NUMBER files', default=None)
  142. selection.add_option('--min-filesize', metavar='SIZE', dest='min_filesize', help="Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)", default=None)
  143. selection.add_option('--max-filesize', metavar='SIZE', dest='max_filesize', help="Do not download any videos larger than SIZE (e.g. 50k or 44.6m)", default=None)
  144. selection.add_option('--date', metavar='DATE', dest='date', help='download only videos uploaded in this date', default=None)
  145. selection.add_option('--datebefore', metavar='DATE', dest='datebefore', help='download only videos uploaded before this date', default=None)
  146. selection.add_option('--dateafter', metavar='DATE', dest='dateafter', help='download only videos uploaded after this date', default=None)
  147. authentication.add_option('-u', '--username',
  148. dest='username', metavar='USERNAME', help='account username')
  149. authentication.add_option('-p', '--password',
  150. dest='password', metavar='PASSWORD', help='account password')
  151. authentication.add_option('-n', '--netrc',
  152. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  153. video_format.add_option('-f', '--format',
  154. action='store', dest='format', metavar='FORMAT',
  155. help='video format code, specifiy the order of preference using slashes: "-f 22/17/18"')
  156. video_format.add_option('--all-formats',
  157. action='store_const', dest='format', help='download all available video formats', const='all')
  158. video_format.add_option('--prefer-free-formats',
  159. action='store_true', dest='prefer_free_formats', default=False, help='prefer free video formats unless a specific one is requested')
  160. video_format.add_option('--max-quality',
  161. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  162. video_format.add_option('-F', '--list-formats',
  163. action='store_true', dest='listformats', help='list all available formats (currently youtube only)')
  164. video_format.add_option('--write-sub', '--write-srt',
  165. action='store_true', dest='writesubtitles',
  166. help='write subtitle file (currently youtube only)', default=False)
  167. video_format.add_option('--only-sub',
  168. action='store_true', dest='skip_download',
  169. help='[deprecated] alias of --skip-download', default=False)
  170. video_format.add_option('--all-subs',
  171. action='store_true', dest='allsubtitles',
  172. help='downloads all the available subtitles of the video (currently youtube only)', default=False)
  173. video_format.add_option('--list-subs',
  174. action='store_true', dest='listsubtitles',
  175. help='lists all available subtitles for the video (currently youtube only)', default=False)
  176. video_format.add_option('--sub-format',
  177. action='store', dest='subtitlesformat', metavar='FORMAT',
  178. help='subtitle format [srt/sbv] (default=srt) (currently youtube only)', default='srt')
  179. video_format.add_option('--sub-lang', '--srt-lang',
  180. action='store', dest='subtitleslang', metavar='LANG',
  181. help='language of the subtitles to download (optional) use IETF language tags like \'en\'')
  182. verbosity.add_option('-q', '--quiet',
  183. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  184. verbosity.add_option('-s', '--simulate',
  185. action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
  186. verbosity.add_option('--skip-download',
  187. action='store_true', dest='skip_download', help='do not download the video', default=False)
  188. verbosity.add_option('-g', '--get-url',
  189. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  190. verbosity.add_option('-e', '--get-title',
  191. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  192. verbosity.add_option('--get-id',
  193. action='store_true', dest='getid', help='simulate, quiet but print id', default=False)
  194. verbosity.add_option('--get-thumbnail',
  195. action='store_true', dest='getthumbnail',
  196. help='simulate, quiet but print thumbnail URL', default=False)
  197. verbosity.add_option('--get-description',
  198. action='store_true', dest='getdescription',
  199. help='simulate, quiet but print video description', default=False)
  200. verbosity.add_option('--get-filename',
  201. action='store_true', dest='getfilename',
  202. help='simulate, quiet but print output filename', default=False)
  203. verbosity.add_option('--get-format',
  204. action='store_true', dest='getformat',
  205. help='simulate, quiet but print output format', default=False)
  206. verbosity.add_option('--newline',
  207. action='store_true', dest='progress_with_newline', help='output progress bar as new lines', default=False)
  208. verbosity.add_option('--no-progress',
  209. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  210. verbosity.add_option('--console-title',
  211. action='store_true', dest='consoletitle',
  212. help='display progress in console titlebar', default=False)
  213. verbosity.add_option('-v', '--verbose',
  214. action='store_true', dest='verbose', help='print various debugging information', default=False)
  215. verbosity.add_option('--dump-intermediate-pages',
  216. action='store_true', dest='dump_intermediate_pages', default=False,
  217. help='print downloaded pages to debug problems(very verbose)')
  218. filesystem.add_option('-t', '--title',
  219. action='store_true', dest='usetitle', help='use title in file name (default)', default=False)
  220. filesystem.add_option('--id',
  221. action='store_true', dest='useid', help='use only video ID in file name', default=False)
  222. filesystem.add_option('-l', '--literal',
  223. action='store_true', dest='usetitle', help='[deprecated] alias of --title', default=False)
  224. filesystem.add_option('-A', '--auto-number',
  225. action='store_true', dest='autonumber',
  226. help='number downloaded files starting from 00000', default=False)
  227. filesystem.add_option('-o', '--output',
  228. dest='outtmpl', metavar='TEMPLATE',
  229. help=('output filename template. Use %(title)s to get the title, '
  230. '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
  231. '%(autonumber)s to get an automatically incremented number, '
  232. '%(ext)s for the filename extension, %(upload_date)s for the upload date (YYYYMMDD), '
  233. '%(extractor)s for the provider (youtube, metacafe, etc), '
  234. '%(id)s for the video id , %(playlist)s for the playlist the video is in, '
  235. '%(playlist_index)s for the position in the playlist and %% for a literal percent. '
  236. 'Use - to output to stdout. Can also be used to download to a different directory, '
  237. 'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
  238. filesystem.add_option('--autonumber-size',
  239. dest='autonumber_size', metavar='NUMBER',
  240. help='Specifies the number of digits in %(autonumber)s when it is present in output filename template or --autonumber option is given')
  241. filesystem.add_option('--restrict-filenames',
  242. action='store_true', dest='restrictfilenames',
  243. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames', default=False)
  244. filesystem.add_option('-a', '--batch-file',
  245. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  246. filesystem.add_option('-w', '--no-overwrites',
  247. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  248. filesystem.add_option('-c', '--continue',
  249. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=True)
  250. filesystem.add_option('--no-continue',
  251. action='store_false', dest='continue_dl',
  252. help='do not resume partially downloaded files (restart from beginning)')
  253. filesystem.add_option('--cookies',
  254. dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
  255. filesystem.add_option('--no-part',
  256. action='store_true', dest='nopart', help='do not use .part files', default=False)
  257. filesystem.add_option('--no-mtime',
  258. action='store_false', dest='updatetime',
  259. help='do not use the Last-modified header to set the file modification time', default=True)
  260. filesystem.add_option('--write-description',
  261. action='store_true', dest='writedescription',
  262. help='write video description to a .description file', default=False)
  263. filesystem.add_option('--write-info-json',
  264. action='store_true', dest='writeinfojson',
  265. help='write video metadata to a .info.json file', default=False)
  266. filesystem.add_option('--write-thumbnail',
  267. action='store_true', dest='writethumbnail',
  268. help='write thumbnail image to disk', default=False)
  269. postproc.add_option('-x', '--extract-audio', action='store_true', dest='extractaudio', default=False,
  270. help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  271. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  272. help='"best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; best by default')
  273. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='5',
  274. help='ffmpeg/avconv audio quality specification, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default 5)')
  275. postproc.add_option('--recode-video', metavar='FORMAT', dest='recodevideo', default=None,
  276. help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm)')
  277. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  278. help='keeps the video file on disk after the post-processing; the video is erased by default')
  279. postproc.add_option('--no-post-overwrites', action='store_true', dest='nopostoverwrites', default=False,
  280. help='do not overwrite post-processed files; the post-processed files are overwritten by default')
  281. parser.add_option_group(general)
  282. parser.add_option_group(selection)
  283. parser.add_option_group(filesystem)
  284. parser.add_option_group(verbosity)
  285. parser.add_option_group(video_format)
  286. parser.add_option_group(authentication)
  287. parser.add_option_group(postproc)
  288. if overrideArguments is not None:
  289. opts, args = parser.parse_args(overrideArguments)
  290. if opts.verbose:
  291. print(u'[debug] Override config: ' + repr(overrideArguments))
  292. else:
  293. xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
  294. if xdg_config_home:
  295. userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
  296. else:
  297. userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
  298. systemConf = _readOptions('/etc/youtube-dl.conf')
  299. userConf = _readOptions(userConfFile)
  300. commandLineConf = sys.argv[1:]
  301. argv = systemConf + userConf + commandLineConf
  302. opts, args = parser.parse_args(argv)
  303. if opts.verbose:
  304. print(u'[debug] System config: ' + repr(systemConf))
  305. print(u'[debug] User config: ' + repr(userConf))
  306. print(u'[debug] Command-line args: ' + repr(commandLineConf))
  307. return parser, opts, args
  308. def _real_main(argv=None):
  309. # Compatibility fixes for Windows
  310. if sys.platform == 'win32':
  311. # https://github.com/rg3/youtube-dl/issues/820
  312. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
  313. parser, opts, args = parseOpts(argv)
  314. # Open appropriate CookieJar
  315. if opts.cookiefile is None:
  316. jar = compat_cookiejar.CookieJar()
  317. else:
  318. try:
  319. jar = compat_cookiejar.MozillaCookieJar(opts.cookiefile)
  320. if os.access(opts.cookiefile, os.R_OK):
  321. jar.load()
  322. except (IOError, OSError) as err:
  323. if opts.verbose:
  324. traceback.print_exc()
  325. sys.stderr.write(u'ERROR: unable to open cookie file\n')
  326. sys.exit(101)
  327. # Set user agent
  328. if opts.user_agent is not None:
  329. std_headers['User-Agent'] = opts.user_agent
  330. # Set referer
  331. if opts.referer is not None:
  332. std_headers['Referer'] = opts.referer
  333. # Dump user agent
  334. if opts.dump_user_agent:
  335. print(std_headers['User-Agent'])
  336. sys.exit(0)
  337. # Batch file verification
  338. batchurls = []
  339. if opts.batchfile is not None:
  340. try:
  341. if opts.batchfile == '-':
  342. batchfd = sys.stdin
  343. else:
  344. batchfd = open(opts.batchfile, 'r')
  345. batchurls = batchfd.readlines()
  346. batchurls = [x.strip() for x in batchurls]
  347. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  348. except IOError:
  349. sys.exit(u'ERROR: batch file could not be read')
  350. all_urls = batchurls + args
  351. all_urls = [url.strip() for url in all_urls]
  352. # General configuration
  353. cookie_processor = compat_urllib_request.HTTPCookieProcessor(jar)
  354. if opts.proxy is not None:
  355. if opts.proxy == '':
  356. proxies = {}
  357. else:
  358. proxies = {'http': opts.proxy, 'https': opts.proxy}
  359. else:
  360. proxies = compat_urllib_request.getproxies()
  361. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  362. if 'http' in proxies and 'https' not in proxies:
  363. proxies['https'] = proxies['http']
  364. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  365. https_handler = make_HTTPS_handler(opts)
  366. opener = compat_urllib_request.build_opener(https_handler, proxy_handler, cookie_processor, YoutubeDLHandler())
  367. compat_urllib_request.install_opener(opener)
  368. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  369. extractors = gen_extractors()
  370. if opts.list_extractors:
  371. for ie in extractors:
  372. print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  373. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  374. all_urls = [url for url in all_urls if url not in matchedUrls]
  375. for mu in matchedUrls:
  376. print(u' ' + mu)
  377. sys.exit(0)
  378. # Conflicting, missing and erroneous options
  379. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  380. parser.error(u'using .netrc conflicts with giving username/password')
  381. if opts.password is not None and opts.username is None:
  382. print(u'WARNING: account username missing')
  383. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  384. parser.error(u'using output template conflicts with using title, video ID or auto number')
  385. if opts.usetitle and opts.useid:
  386. parser.error(u'using title conflicts with using video ID')
  387. if opts.username is not None and opts.password is None:
  388. opts.password = getpass.getpass(u'Type account password and press return:')
  389. if opts.ratelimit is not None:
  390. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  391. if numeric_limit is None:
  392. parser.error(u'invalid rate limit specified')
  393. opts.ratelimit = numeric_limit
  394. if opts.min_filesize is not None:
  395. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  396. if numeric_limit is None:
  397. parser.error(u'invalid min_filesize specified')
  398. opts.min_filesize = numeric_limit
  399. if opts.max_filesize is not None:
  400. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  401. if numeric_limit is None:
  402. parser.error(u'invalid max_filesize specified')
  403. opts.max_filesize = numeric_limit
  404. if opts.retries is not None:
  405. try:
  406. opts.retries = int(opts.retries)
  407. except (TypeError, ValueError) as err:
  408. parser.error(u'invalid retry count specified')
  409. if opts.buffersize is not None:
  410. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  411. if numeric_buffersize is None:
  412. parser.error(u'invalid buffer size specified')
  413. opts.buffersize = numeric_buffersize
  414. try:
  415. opts.playliststart = int(opts.playliststart)
  416. if opts.playliststart <= 0:
  417. raise ValueError(u'Playlist start must be positive')
  418. except (TypeError, ValueError) as err:
  419. parser.error(u'invalid playlist start number specified')
  420. try:
  421. opts.playlistend = int(opts.playlistend)
  422. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  423. raise ValueError(u'Playlist end must be greater than playlist start')
  424. except (TypeError, ValueError) as err:
  425. parser.error(u'invalid playlist end number specified')
  426. if opts.extractaudio:
  427. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  428. parser.error(u'invalid audio format specified')
  429. if opts.audioquality:
  430. opts.audioquality = opts.audioquality.strip('k').strip('K')
  431. if not opts.audioquality.isdigit():
  432. parser.error(u'invalid audio quality specified')
  433. if opts.recodevideo is not None:
  434. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg']:
  435. parser.error(u'invalid video recode format specified')
  436. if opts.date is not None:
  437. date = DateRange.day(opts.date)
  438. else:
  439. date = DateRange(opts.dateafter, opts.datebefore)
  440. if sys.version_info < (3,):
  441. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  442. if opts.outtmpl is not None:
  443. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  444. outtmpl =((opts.outtmpl is not None and opts.outtmpl)
  445. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  446. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  447. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  448. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  449. or (opts.useid and u'%(id)s.%(ext)s')
  450. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  451. or u'%(title)s-%(id)s.%(ext)s')
  452. # YoutubeDL
  453. ydl = YoutubeDL({
  454. 'usenetrc': opts.usenetrc,
  455. 'username': opts.username,
  456. 'password': opts.password,
  457. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  458. 'forceurl': opts.geturl,
  459. 'forcetitle': opts.gettitle,
  460. 'forceid': opts.getid,
  461. 'forcethumbnail': opts.getthumbnail,
  462. 'forcedescription': opts.getdescription,
  463. 'forcefilename': opts.getfilename,
  464. 'forceformat': opts.getformat,
  465. 'simulate': opts.simulate,
  466. 'skip_download': (opts.skip_download or opts.simulate or opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  467. 'format': opts.format,
  468. 'format_limit': opts.format_limit,
  469. 'listformats': opts.listformats,
  470. 'outtmpl': outtmpl,
  471. 'autonumber_size': opts.autonumber_size,
  472. 'restrictfilenames': opts.restrictfilenames,
  473. 'ignoreerrors': opts.ignoreerrors,
  474. 'ratelimit': opts.ratelimit,
  475. 'nooverwrites': opts.nooverwrites,
  476. 'retries': opts.retries,
  477. 'buffersize': opts.buffersize,
  478. 'noresizebuffer': opts.noresizebuffer,
  479. 'continuedl': opts.continue_dl,
  480. 'noprogress': opts.noprogress,
  481. 'progress_with_newline': opts.progress_with_newline,
  482. 'playliststart': opts.playliststart,
  483. 'playlistend': opts.playlistend,
  484. 'logtostderr': opts.outtmpl == '-',
  485. 'consoletitle': opts.consoletitle,
  486. 'nopart': opts.nopart,
  487. 'updatetime': opts.updatetime,
  488. 'writedescription': opts.writedescription,
  489. 'writeinfojson': opts.writeinfojson,
  490. 'writethumbnail': opts.writethumbnail,
  491. 'writesubtitles': opts.writesubtitles,
  492. 'allsubtitles': opts.allsubtitles,
  493. 'listsubtitles': opts.listsubtitles,
  494. 'subtitlesformat': opts.subtitlesformat,
  495. 'subtitleslang': opts.subtitleslang,
  496. 'matchtitle': decodeOption(opts.matchtitle),
  497. 'rejecttitle': decodeOption(opts.rejecttitle),
  498. 'max_downloads': opts.max_downloads,
  499. 'prefer_free_formats': opts.prefer_free_formats,
  500. 'verbose': opts.verbose,
  501. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  502. 'test': opts.test,
  503. 'keepvideo': opts.keepvideo,
  504. 'min_filesize': opts.min_filesize,
  505. 'max_filesize': opts.max_filesize,
  506. 'daterange': date,
  507. })
  508. if opts.verbose:
  509. ydl.to_screen(u'[debug] youtube-dl version ' + __version__)
  510. try:
  511. sp = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  512. cwd=os.path.dirname(os.path.abspath(__file__)))
  513. out, err = sp.communicate()
  514. out = out.decode().strip()
  515. if re.match('[0-9a-f]+', out):
  516. ydl.to_screen(u'[debug] Git HEAD: ' + out)
  517. except:
  518. pass
  519. ydl.to_screen(u'[debug] Python version %s - %s' %(platform.python_version(), platform.platform()))
  520. ydl.to_screen(u'[debug] Proxy map: ' + str(proxy_handler.proxies))
  521. for extractor in extractors:
  522. ydl.add_info_extractor(extractor)
  523. # PostProcessors
  524. if opts.extractaudio:
  525. ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
  526. if opts.recodevideo:
  527. ydl.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
  528. # Update version
  529. if opts.update_self:
  530. update_self(ydl.to_screen, opts.verbose, sys.argv[0])
  531. # Maybe do nothing
  532. if len(all_urls) < 1:
  533. if not opts.update_self:
  534. parser.error(u'you must provide at least one URL')
  535. else:
  536. sys.exit()
  537. try:
  538. retcode = ydl.download(all_urls)
  539. except MaxDownloadsReached:
  540. ydl.to_screen(u'--max-download limit reached, aborting.')
  541. retcode = 101
  542. # Dump cookie jar if requested
  543. if opts.cookiefile is not None:
  544. try:
  545. jar.save()
  546. except (IOError, OSError) as err:
  547. sys.exit(u'ERROR: unable to save cookie jar')
  548. sys.exit(retcode)
  549. def main(argv=None):
  550. try:
  551. _real_main(argv)
  552. except DownloadError:
  553. sys.exit(1)
  554. except SameFileError:
  555. sys.exit(u'ERROR: fixed output name but more than one file to download')
  556. except KeyboardInterrupt:
  557. sys.exit(u'\nERROR: Interrupted by user')