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.

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