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.

762 lines
36 KiB

13 years ago
12 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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. 'Axel Noack',
  28. 'Albert Kim',
  29. 'Pierre Rudloff',
  30. 'Huarong Huo',
  31. 'Ismael Mejía',
  32. 'Steffan \'Ruirize\' James',
  33. 'Andras Elso',
  34. )
  35. __license__ = 'Public Domain'
  36. import codecs
  37. import collections
  38. import getpass
  39. import optparse
  40. import os
  41. import random
  42. import re
  43. import shlex
  44. import socket
  45. import subprocess
  46. import sys
  47. import traceback
  48. import platform
  49. from .utils import (
  50. compat_cookiejar,
  51. compat_print,
  52. compat_str,
  53. compat_urllib_request,
  54. DateRange,
  55. decodeOption,
  56. determine_ext,
  57. DownloadError,
  58. get_cachedir,
  59. make_HTTPS_handler,
  60. MaxDownloadsReached,
  61. platform_name,
  62. preferredencoding,
  63. SameFileError,
  64. std_headers,
  65. write_string,
  66. YoutubeDLHandler,
  67. )
  68. from .update import update_self
  69. from .version import __version__
  70. from .FileDownloader import (
  71. FileDownloader,
  72. )
  73. from .extractor import gen_extractors
  74. from .YoutubeDL import YoutubeDL
  75. from .PostProcessor import (
  76. FFmpegMetadataPP,
  77. FFmpegVideoConvertor,
  78. FFmpegExtractAudioPP,
  79. FFmpegEmbedSubtitlePP,
  80. )
  81. def parseOpts(overrideArguments=None):
  82. def _readOptions(filename_bytes):
  83. try:
  84. optionf = open(filename_bytes)
  85. except IOError:
  86. return [] # silently skip if file is not present
  87. try:
  88. res = []
  89. for l in optionf:
  90. res += shlex.split(l, comments=True)
  91. finally:
  92. optionf.close()
  93. return res
  94. def _format_option_string(option):
  95. ''' ('-o', '--option') -> -o, --format METAVAR'''
  96. opts = []
  97. if option._short_opts:
  98. opts.append(option._short_opts[0])
  99. if option._long_opts:
  100. opts.append(option._long_opts[0])
  101. if len(opts) > 1:
  102. opts.insert(1, ', ')
  103. if option.takes_value(): opts.append(' %s' % option.metavar)
  104. return "".join(opts)
  105. def _comma_separated_values_options_callback(option, opt_str, value, parser):
  106. setattr(parser.values, option.dest, value.split(','))
  107. def _find_term_columns():
  108. columns = os.environ.get('COLUMNS', None)
  109. if columns:
  110. return int(columns)
  111. try:
  112. sp = subprocess.Popen(['stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  113. out,err = sp.communicate()
  114. return int(out.split()[1])
  115. except:
  116. pass
  117. return None
  118. def _hide_login_info(opts):
  119. opts = list(opts)
  120. for private_opt in ['-p', '--password', '-u', '--username']:
  121. try:
  122. i = opts.index(private_opt)
  123. opts[i+1] = '<PRIVATE>'
  124. except ValueError:
  125. pass
  126. return opts
  127. max_width = 80
  128. max_help_position = 80
  129. # No need to wrap help messages if we're on a wide console
  130. columns = _find_term_columns()
  131. if columns: max_width = columns
  132. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  133. fmt.format_option_strings = _format_option_string
  134. kw = {
  135. 'version' : __version__,
  136. 'formatter' : fmt,
  137. 'usage' : '%prog [options] url [url...]',
  138. 'conflict_handler' : 'resolve',
  139. }
  140. parser = optparse.OptionParser(**kw)
  141. # option groups
  142. general = optparse.OptionGroup(parser, 'General Options')
  143. selection = optparse.OptionGroup(parser, 'Video Selection')
  144. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  145. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  146. subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
  147. downloader = optparse.OptionGroup(parser, 'Download Options')
  148. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  149. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  150. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  151. general.add_option('-h', '--help',
  152. action='help', help='print this help text and exit')
  153. general.add_option('-v', '--version',
  154. action='version', help='print program version and exit')
  155. general.add_option('-U', '--update',
  156. action='store_true', dest='update_self', help='update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
  157. general.add_option('-i', '--ignore-errors',
  158. action='store_true', dest='ignoreerrors', help='continue on download errors, for example to to skip unavailable videos in a playlist', default=False)
  159. general.add_option('--dump-user-agent',
  160. action='store_true', dest='dump_user_agent',
  161. help='display the current browser identification', default=False)
  162. general.add_option('--user-agent',
  163. dest='user_agent', help='specify a custom user agent', metavar='UA')
  164. general.add_option('--referer',
  165. dest='referer', help='specify a custom referer, use if the video access is restricted to one domain',
  166. metavar='REF', default=None)
  167. general.add_option('--list-extractors',
  168. action='store_true', dest='list_extractors',
  169. help='List all supported extractors and the URLs they would handle', default=False)
  170. general.add_option('--extractor-descriptions',
  171. action='store_true', dest='list_extractor_descriptions',
  172. help='Output descriptions of all supported extractors', default=False)
  173. general.add_option('--proxy', dest='proxy', default=None, help='Use the specified HTTP/HTTPS proxy', metavar='URL')
  174. general.add_option('--no-check-certificate', action='store_true', dest='no_check_certificate', default=False, help='Suppress HTTPS certificate validation.')
  175. general.add_option(
  176. '--cache-dir', dest='cachedir', default=get_cachedir(),
  177. help='Location in the filesystem where youtube-dl can store downloaded information permanently. By default $XDG_CACHE_HOME/youtube-dl or ~/.cache/youtube-dl .')
  178. general.add_option(
  179. '--no-cache-dir', action='store_const', const=None, dest='cachedir',
  180. help='Disable filesystem caching')
  181. selection.add_option('--playlist-start',
  182. dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is %default)', default=1)
  183. selection.add_option('--playlist-end',
  184. dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
  185. selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
  186. selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
  187. selection.add_option('--max-downloads', metavar='NUMBER', dest='max_downloads', help='Abort after downloading NUMBER files', default=None)
  188. 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)
  189. 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)
  190. selection.add_option('--date', metavar='DATE', dest='date', help='download only videos uploaded in this date', default=None)
  191. selection.add_option('--datebefore', metavar='DATE', dest='datebefore', help='download only videos uploaded before this date', default=None)
  192. selection.add_option('--dateafter', metavar='DATE', dest='dateafter', help='download only videos uploaded after this date', default=None)
  193. selection.add_option('--no-playlist', action='store_true', dest='noplaylist', help='download only the currently playing video', default=False)
  194. selection.add_option('--age-limit', metavar='YEARS', dest='age_limit',
  195. help='download only videos suitable for the given age',
  196. default=None, type=int)
  197. selection.add_option('--download-archive', metavar='FILE',
  198. dest='download_archive',
  199. help='Download only videos not present in the archive file. Record all downloaded videos in it.')
  200. authentication.add_option('-u', '--username',
  201. dest='username', metavar='USERNAME', help='account username')
  202. authentication.add_option('-p', '--password',
  203. dest='password', metavar='PASSWORD', help='account password')
  204. authentication.add_option('-n', '--netrc',
  205. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  206. authentication.add_option('--video-password',
  207. dest='videopassword', metavar='PASSWORD', help='video password (vimeo only)')
  208. video_format.add_option('-f', '--format',
  209. action='store', dest='format', metavar='FORMAT', default='best',
  210. help='video format code, specifiy the order of preference using slashes: "-f 22/17/18". "-f mp4" and "-f flv" are also supported')
  211. video_format.add_option('--all-formats',
  212. action='store_const', dest='format', help='download all available video formats', const='all')
  213. video_format.add_option('--prefer-free-formats',
  214. action='store_true', dest='prefer_free_formats', default=False, help='prefer free video formats unless a specific one is requested')
  215. video_format.add_option('--max-quality',
  216. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  217. video_format.add_option('-F', '--list-formats',
  218. action='store_true', dest='listformats', help='list all available formats (currently youtube only)')
  219. subtitles.add_option('--write-sub', '--write-srt',
  220. action='store_true', dest='writesubtitles',
  221. help='write subtitle file', default=False)
  222. subtitles.add_option('--write-auto-sub', '--write-automatic-sub',
  223. action='store_true', dest='writeautomaticsub',
  224. help='write automatic subtitle file (youtube only)', default=False)
  225. subtitles.add_option('--all-subs',
  226. action='store_true', dest='allsubtitles',
  227. help='downloads all the available subtitles of the video', default=False)
  228. subtitles.add_option('--list-subs',
  229. action='store_true', dest='listsubtitles',
  230. help='lists all available subtitles for the video', default=False)
  231. subtitles.add_option('--sub-format',
  232. action='store', dest='subtitlesformat', metavar='FORMAT',
  233. help='subtitle format (default=srt) ([sbv/vtt] youtube only)', default='srt')
  234. subtitles.add_option('--sub-lang', '--sub-langs', '--srt-lang',
  235. action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
  236. default=[], callback=_comma_separated_values_options_callback,
  237. help='languages of the subtitles to download (optional) separated by commas, use IETF language tags like \'en,pt\'')
  238. downloader.add_option('-r', '--rate-limit',
  239. dest='ratelimit', metavar='LIMIT', help='maximum download rate in bytes per second (e.g. 50K or 4.2M)')
  240. downloader.add_option('-R', '--retries',
  241. dest='retries', metavar='RETRIES', help='number of retries (default is %default)', default=10)
  242. downloader.add_option('--buffer-size',
  243. dest='buffersize', metavar='SIZE', help='size of download buffer (e.g. 1024 or 16K) (default is %default)', default="1024")
  244. downloader.add_option('--no-resize-buffer',
  245. action='store_true', dest='noresizebuffer',
  246. help='do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.', default=False)
  247. downloader.add_option('--test', action='store_true', dest='test', default=False, help=optparse.SUPPRESS_HELP)
  248. verbosity.add_option('-q', '--quiet',
  249. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  250. verbosity.add_option('-s', '--simulate',
  251. action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
  252. verbosity.add_option('--skip-download',
  253. action='store_true', dest='skip_download', help='do not download the video', default=False)
  254. verbosity.add_option('-g', '--get-url',
  255. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  256. verbosity.add_option('-e', '--get-title',
  257. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  258. verbosity.add_option('--get-id',
  259. action='store_true', dest='getid', help='simulate, quiet but print id', default=False)
  260. verbosity.add_option('--get-thumbnail',
  261. action='store_true', dest='getthumbnail',
  262. help='simulate, quiet but print thumbnail URL', default=False)
  263. verbosity.add_option('--get-description',
  264. action='store_true', dest='getdescription',
  265. help='simulate, quiet but print video description', default=False)
  266. verbosity.add_option('--get-filename',
  267. action='store_true', dest='getfilename',
  268. help='simulate, quiet but print output filename', default=False)
  269. verbosity.add_option('--get-format',
  270. action='store_true', dest='getformat',
  271. help='simulate, quiet but print output format', default=False)
  272. verbosity.add_option('--newline',
  273. action='store_true', dest='progress_with_newline', help='output progress bar as new lines', default=False)
  274. verbosity.add_option('--no-progress',
  275. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  276. verbosity.add_option('--console-title',
  277. action='store_true', dest='consoletitle',
  278. help='display progress in console titlebar', default=False)
  279. verbosity.add_option('-v', '--verbose',
  280. action='store_true', dest='verbose', help='print various debugging information', default=False)
  281. verbosity.add_option('--dump-intermediate-pages',
  282. action='store_true', dest='dump_intermediate_pages', default=False,
  283. help='print downloaded pages to debug problems(very verbose)')
  284. verbosity.add_option('--youtube-print-sig-code',
  285. action='store_true', dest='youtube_print_sig_code', default=False,
  286. help=optparse.SUPPRESS_HELP)
  287. filesystem.add_option('-t', '--title',
  288. action='store_true', dest='usetitle', help='use title in file name (default)', default=False)
  289. filesystem.add_option('--id',
  290. action='store_true', dest='useid', help='use only video ID in file name', default=False)
  291. filesystem.add_option('-l', '--literal',
  292. action='store_true', dest='usetitle', help='[deprecated] alias of --title', default=False)
  293. filesystem.add_option('-A', '--auto-number',
  294. action='store_true', dest='autonumber',
  295. help='number downloaded files starting from 00000', default=False)
  296. filesystem.add_option('-o', '--output',
  297. dest='outtmpl', metavar='TEMPLATE',
  298. help=('output filename template. Use %(title)s to get the title, '
  299. '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
  300. '%(autonumber)s to get an automatically incremented number, '
  301. '%(ext)s for the filename extension, %(upload_date)s for the upload date (YYYYMMDD), '
  302. '%(extractor)s for the provider (youtube, metacafe, etc), '
  303. '%(id)s for the video id , %(playlist)s for the playlist the video is in, '
  304. '%(playlist_index)s for the position in the playlist and %% for a literal percent. '
  305. 'Use - to output to stdout. Can also be used to download to a different directory, '
  306. 'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
  307. filesystem.add_option('--autonumber-size',
  308. dest='autonumber_size', metavar='NUMBER',
  309. help='Specifies the number of digits in %(autonumber)s when it is present in output filename template or --autonumber option is given')
  310. filesystem.add_option('--restrict-filenames',
  311. action='store_true', dest='restrictfilenames',
  312. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames', default=False)
  313. filesystem.add_option('-a', '--batch-file',
  314. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  315. filesystem.add_option('-w', '--no-overwrites',
  316. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  317. filesystem.add_option('-c', '--continue',
  318. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=True)
  319. filesystem.add_option('--no-continue',
  320. action='store_false', dest='continue_dl',
  321. help='do not resume partially downloaded files (restart from beginning)')
  322. filesystem.add_option('--cookies',
  323. dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
  324. filesystem.add_option('--no-part',
  325. action='store_true', dest='nopart', help='do not use .part files', default=False)
  326. filesystem.add_option('--no-mtime',
  327. action='store_false', dest='updatetime',
  328. help='do not use the Last-modified header to set the file modification time', default=True)
  329. filesystem.add_option('--write-description',
  330. action='store_true', dest='writedescription',
  331. help='write video description to a .description file', default=False)
  332. filesystem.add_option('--write-info-json',
  333. action='store_true', dest='writeinfojson',
  334. help='write video metadata to a .info.json file', default=False)
  335. filesystem.add_option('--write-annotations',
  336. action='store_true', dest='writeannotations',
  337. help='write video annotations to a .annotation file', default=False)
  338. filesystem.add_option('--write-thumbnail',
  339. action='store_true', dest='writethumbnail',
  340. help='write thumbnail image to disk', default=False)
  341. postproc.add_option('-x', '--extract-audio', action='store_true', dest='extractaudio', default=False,
  342. help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  343. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  344. help='"best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; best by default')
  345. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='5',
  346. 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)')
  347. postproc.add_option('--recode-video', metavar='FORMAT', dest='recodevideo', default=None,
  348. help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm)')
  349. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  350. help='keeps the video file on disk after the post-processing; the video is erased by default')
  351. postproc.add_option('--no-post-overwrites', action='store_true', dest='nopostoverwrites', default=False,
  352. help='do not overwrite post-processed files; the post-processed files are overwritten by default')
  353. postproc.add_option('--embed-subs', action='store_true', dest='embedsubtitles', default=False,
  354. help='embed subtitles in the video (only for mp4 videos)')
  355. postproc.add_option('--add-metadata', action='store_true', dest='addmetadata', default=False,
  356. help='add metadata to the files')
  357. parser.add_option_group(general)
  358. parser.add_option_group(selection)
  359. parser.add_option_group(downloader)
  360. parser.add_option_group(filesystem)
  361. parser.add_option_group(verbosity)
  362. parser.add_option_group(video_format)
  363. parser.add_option_group(subtitles)
  364. parser.add_option_group(authentication)
  365. parser.add_option_group(postproc)
  366. if overrideArguments is not None:
  367. opts, args = parser.parse_args(overrideArguments)
  368. if opts.verbose:
  369. write_string(u'[debug] Override config: ' + repr(overrideArguments) + '\n')
  370. else:
  371. xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
  372. if xdg_config_home:
  373. userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
  374. if not os.path.isfile(userConfFile):
  375. userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
  376. else:
  377. userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl', 'config')
  378. if not os.path.isfile(userConfFile):
  379. userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
  380. systemConf = _readOptions('/etc/youtube-dl.conf')
  381. userConf = _readOptions(userConfFile)
  382. commandLineConf = sys.argv[1:]
  383. argv = systemConf + userConf + commandLineConf
  384. opts, args = parser.parse_args(argv)
  385. if opts.verbose:
  386. write_string(u'[debug] System config: ' + repr(_hide_login_info(systemConf)) + '\n')
  387. write_string(u'[debug] User config: ' + repr(_hide_login_info(userConf)) + '\n')
  388. write_string(u'[debug] Command-line args: ' + repr(_hide_login_info(commandLineConf)) + '\n')
  389. return parser, opts, args
  390. def _real_main(argv=None):
  391. # Compatibility fixes for Windows
  392. if sys.platform == 'win32':
  393. # https://github.com/rg3/youtube-dl/issues/820
  394. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
  395. parser, opts, args = parseOpts(argv)
  396. # Open appropriate CookieJar
  397. if opts.cookiefile is None:
  398. jar = compat_cookiejar.CookieJar()
  399. else:
  400. try:
  401. jar = compat_cookiejar.MozillaCookieJar(opts.cookiefile)
  402. if os.access(opts.cookiefile, os.R_OK):
  403. jar.load()
  404. except (IOError, OSError) as err:
  405. if opts.verbose:
  406. traceback.print_exc()
  407. write_string(u'ERROR: unable to open cookie file\n')
  408. sys.exit(101)
  409. # Set user agent
  410. if opts.user_agent is not None:
  411. std_headers['User-Agent'] = opts.user_agent
  412. # Set referer
  413. if opts.referer is not None:
  414. std_headers['Referer'] = opts.referer
  415. # Dump user agent
  416. if opts.dump_user_agent:
  417. compat_print(std_headers['User-Agent'])
  418. sys.exit(0)
  419. # Batch file verification
  420. batchurls = []
  421. if opts.batchfile is not None:
  422. try:
  423. if opts.batchfile == '-':
  424. batchfd = sys.stdin
  425. else:
  426. batchfd = open(opts.batchfile, 'r')
  427. batchurls = batchfd.readlines()
  428. batchurls = [x.strip() for x in batchurls]
  429. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  430. if opts.verbose:
  431. write_string(u'[debug] Batch file urls: ' + repr(batchurls) + u'\n')
  432. except IOError:
  433. sys.exit(u'ERROR: batch file could not be read')
  434. all_urls = batchurls + args
  435. all_urls = [url.strip() for url in all_urls]
  436. opener = _setup_opener(jar=jar, opts=opts)
  437. extractors = gen_extractors()
  438. if opts.list_extractors:
  439. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  440. compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  441. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  442. all_urls = [url for url in all_urls if url not in matchedUrls]
  443. for mu in matchedUrls:
  444. compat_print(u' ' + mu)
  445. sys.exit(0)
  446. if opts.list_extractor_descriptions:
  447. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  448. if not ie._WORKING:
  449. continue
  450. desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
  451. if desc is False:
  452. continue
  453. if hasattr(ie, 'SEARCH_KEY'):
  454. _SEARCHES = (u'cute kittens', u'slithering pythons', u'falling cat', u'angry poodle', u'purple fish', u'running tortoise')
  455. _COUNTS = (u'', u'5', u'10', u'all')
  456. desc += u' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
  457. compat_print(desc)
  458. sys.exit(0)
  459. # Conflicting, missing and erroneous options
  460. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  461. parser.error(u'using .netrc conflicts with giving username/password')
  462. if opts.password is not None and opts.username is None:
  463. parser.error(u' account username missing\n')
  464. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  465. parser.error(u'using output template conflicts with using title, video ID or auto number')
  466. if opts.usetitle and opts.useid:
  467. parser.error(u'using title conflicts with using video ID')
  468. if opts.username is not None and opts.password is None:
  469. opts.password = getpass.getpass(u'Type account password and press return:')
  470. if opts.ratelimit is not None:
  471. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  472. if numeric_limit is None:
  473. parser.error(u'invalid rate limit specified')
  474. opts.ratelimit = numeric_limit
  475. if opts.min_filesize is not None:
  476. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  477. if numeric_limit is None:
  478. parser.error(u'invalid min_filesize specified')
  479. opts.min_filesize = numeric_limit
  480. if opts.max_filesize is not None:
  481. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  482. if numeric_limit is None:
  483. parser.error(u'invalid max_filesize specified')
  484. opts.max_filesize = numeric_limit
  485. if opts.retries is not None:
  486. try:
  487. opts.retries = int(opts.retries)
  488. except (TypeError, ValueError) as err:
  489. parser.error(u'invalid retry count specified')
  490. if opts.buffersize is not None:
  491. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  492. if numeric_buffersize is None:
  493. parser.error(u'invalid buffer size specified')
  494. opts.buffersize = numeric_buffersize
  495. try:
  496. opts.playliststart = int(opts.playliststart)
  497. if opts.playliststart <= 0:
  498. raise ValueError(u'Playlist start must be positive')
  499. except (TypeError, ValueError) as err:
  500. parser.error(u'invalid playlist start number specified')
  501. try:
  502. opts.playlistend = int(opts.playlistend)
  503. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  504. raise ValueError(u'Playlist end must be greater than playlist start')
  505. except (TypeError, ValueError) as err:
  506. parser.error(u'invalid playlist end number specified')
  507. if opts.extractaudio:
  508. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  509. parser.error(u'invalid audio format specified')
  510. if opts.audioquality:
  511. opts.audioquality = opts.audioquality.strip('k').strip('K')
  512. if not opts.audioquality.isdigit():
  513. parser.error(u'invalid audio quality specified')
  514. if opts.recodevideo is not None:
  515. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg']:
  516. parser.error(u'invalid video recode format specified')
  517. if opts.date is not None:
  518. date = DateRange.day(opts.date)
  519. else:
  520. date = DateRange(opts.dateafter, opts.datebefore)
  521. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  522. # this was the old behaviour if only --all-sub was given.
  523. if opts.allsubtitles and (opts.writeautomaticsub == False):
  524. opts.writesubtitles = True
  525. if sys.version_info < (3,):
  526. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  527. if opts.outtmpl is not None:
  528. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  529. outtmpl =((opts.outtmpl is not None and opts.outtmpl)
  530. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  531. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  532. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  533. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  534. or (opts.useid and u'%(id)s.%(ext)s')
  535. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  536. or u'%(title)s-%(id)s.%(ext)s')
  537. if '%(ext)s' not in outtmpl and opts.extractaudio:
  538. parser.error(u'Cannot download a video and extract audio into the same'
  539. u' file! Use "%%(ext)s" instead of %r' %
  540. determine_ext(outtmpl, u''))
  541. # YoutubeDL
  542. ydl = YoutubeDL({
  543. 'usenetrc': opts.usenetrc,
  544. 'username': opts.username,
  545. 'password': opts.password,
  546. 'videopassword': opts.videopassword,
  547. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  548. 'forceurl': opts.geturl,
  549. 'forcetitle': opts.gettitle,
  550. 'forceid': opts.getid,
  551. 'forcethumbnail': opts.getthumbnail,
  552. 'forcedescription': opts.getdescription,
  553. 'forcefilename': opts.getfilename,
  554. 'forceformat': opts.getformat,
  555. 'simulate': opts.simulate,
  556. '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),
  557. 'format': opts.format,
  558. 'format_limit': opts.format_limit,
  559. 'listformats': opts.listformats,
  560. 'outtmpl': outtmpl,
  561. 'autonumber_size': opts.autonumber_size,
  562. 'restrictfilenames': opts.restrictfilenames,
  563. 'ignoreerrors': opts.ignoreerrors,
  564. 'ratelimit': opts.ratelimit,
  565. 'nooverwrites': opts.nooverwrites,
  566. 'retries': opts.retries,
  567. 'buffersize': opts.buffersize,
  568. 'noresizebuffer': opts.noresizebuffer,
  569. 'continuedl': opts.continue_dl,
  570. 'noprogress': opts.noprogress,
  571. 'progress_with_newline': opts.progress_with_newline,
  572. 'playliststart': opts.playliststart,
  573. 'playlistend': opts.playlistend,
  574. 'noplaylist': opts.noplaylist,
  575. 'logtostderr': opts.outtmpl == '-',
  576. 'consoletitle': opts.consoletitle,
  577. 'nopart': opts.nopart,
  578. 'updatetime': opts.updatetime,
  579. 'writedescription': opts.writedescription,
  580. 'writeannotations': opts.writeannotations,
  581. 'writeinfojson': opts.writeinfojson,
  582. 'writethumbnail': opts.writethumbnail,
  583. 'writesubtitles': opts.writesubtitles,
  584. 'writeautomaticsub': opts.writeautomaticsub,
  585. 'allsubtitles': opts.allsubtitles,
  586. 'listsubtitles': opts.listsubtitles,
  587. 'subtitlesformat': opts.subtitlesformat,
  588. 'subtitleslangs': opts.subtitleslangs,
  589. 'matchtitle': decodeOption(opts.matchtitle),
  590. 'rejecttitle': decodeOption(opts.rejecttitle),
  591. 'max_downloads': opts.max_downloads,
  592. 'prefer_free_formats': opts.prefer_free_formats,
  593. 'verbose': opts.verbose,
  594. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  595. 'test': opts.test,
  596. 'keepvideo': opts.keepvideo,
  597. 'min_filesize': opts.min_filesize,
  598. 'max_filesize': opts.max_filesize,
  599. 'daterange': date,
  600. 'cachedir': opts.cachedir,
  601. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  602. 'age_limit': opts.age_limit,
  603. 'download_archive': opts.download_archive,
  604. })
  605. if opts.verbose:
  606. write_string(u'[debug] youtube-dl version ' + __version__ + u'\n')
  607. try:
  608. sp = subprocess.Popen(
  609. ['git', 'rev-parse', '--short', 'HEAD'],
  610. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  611. cwd=os.path.dirname(os.path.abspath(__file__)))
  612. out, err = sp.communicate()
  613. out = out.decode().strip()
  614. if re.match('[0-9a-f]+', out):
  615. write_string(u'[debug] Git HEAD: ' + out + u'\n')
  616. except:
  617. try:
  618. sys.exc_clear()
  619. except:
  620. pass
  621. write_string(u'[debug] Python version %s - %s' %(platform.python_version(), platform_name()) + u'\n')
  622. proxy_map = {}
  623. for handler in opener.handlers:
  624. if hasattr(handler, 'proxies'):
  625. proxy_map.update(handler.proxies)
  626. write_string(u'[debug] Proxy map: ' + compat_str(proxy_map) + u'\n')
  627. ydl.add_default_info_extractors()
  628. # PostProcessors
  629. # Add the metadata pp first, the other pps will copy it
  630. if opts.addmetadata:
  631. ydl.add_post_processor(FFmpegMetadataPP())
  632. if opts.extractaudio:
  633. ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
  634. if opts.recodevideo:
  635. ydl.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
  636. if opts.embedsubtitles:
  637. ydl.add_post_processor(FFmpegEmbedSubtitlePP(subtitlesformat=opts.subtitlesformat))
  638. # Update version
  639. if opts.update_self:
  640. update_self(ydl.to_screen, opts.verbose)
  641. # Maybe do nothing
  642. if len(all_urls) < 1:
  643. if not opts.update_self:
  644. parser.error(u'you must provide at least one URL')
  645. else:
  646. sys.exit()
  647. try:
  648. retcode = ydl.download(all_urls)
  649. except MaxDownloadsReached:
  650. ydl.to_screen(u'--max-download limit reached, aborting.')
  651. retcode = 101
  652. # Dump cookie jar if requested
  653. if opts.cookiefile is not None:
  654. try:
  655. jar.save()
  656. except (IOError, OSError):
  657. sys.exit(u'ERROR: unable to save cookie jar')
  658. sys.exit(retcode)
  659. def _setup_opener(jar=None, opts=None, timeout=300):
  660. if opts is None:
  661. FakeOptions = collections.namedtuple(
  662. 'FakeOptions', ['proxy', 'no_check_certificate'])
  663. opts = FakeOptions(proxy=None, no_check_certificate=False)
  664. cookie_processor = compat_urllib_request.HTTPCookieProcessor(jar)
  665. if opts.proxy is not None:
  666. if opts.proxy == '':
  667. proxies = {}
  668. else:
  669. proxies = {'http': opts.proxy, 'https': opts.proxy}
  670. else:
  671. proxies = compat_urllib_request.getproxies()
  672. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  673. if 'http' in proxies and 'https' not in proxies:
  674. proxies['https'] = proxies['http']
  675. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  676. https_handler = make_HTTPS_handler(opts)
  677. opener = compat_urllib_request.build_opener(
  678. https_handler, proxy_handler, cookie_processor, YoutubeDLHandler())
  679. # Delete the default user-agent header, which would otherwise apply in
  680. # cases where our custom HTTP handler doesn't come into play
  681. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  682. opener.addheaders = []
  683. compat_urllib_request.install_opener(opener)
  684. socket.setdefaulttimeout(timeout)
  685. return opener
  686. def main(argv=None):
  687. try:
  688. _real_main(argv)
  689. except DownloadError:
  690. sys.exit(1)
  691. except SameFileError:
  692. sys.exit(u'ERROR: fixed output name but more than one file to download')
  693. except KeyboardInterrupt:
  694. sys.exit(u'\nERROR: Interrupted by user')