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.

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