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.

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