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.

411 lines
16 KiB

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
10 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. __license__ = 'Public Domain'
  5. import codecs
  6. import io
  7. import os
  8. import random
  9. import shlex
  10. import sys
  11. from .options import (
  12. parseOpts,
  13. )
  14. from .compat import (
  15. compat_expanduser,
  16. compat_getpass,
  17. compat_print,
  18. workaround_optparse_bug9161,
  19. )
  20. from .utils import (
  21. DateRange,
  22. decodeOption,
  23. DEFAULT_OUTTMPL,
  24. DownloadError,
  25. match_filter_func,
  26. MaxDownloadsReached,
  27. preferredencoding,
  28. read_batch_urls,
  29. SameFileError,
  30. setproctitle,
  31. std_headers,
  32. write_string,
  33. )
  34. from .update import update_self
  35. from .downloader import (
  36. FileDownloader,
  37. )
  38. from .extractor import gen_extractors, list_extractors
  39. from .YoutubeDL import YoutubeDL
  40. def _real_main(argv=None):
  41. # Compatibility fixes for Windows
  42. if sys.platform == 'win32':
  43. # https://github.com/rg3/youtube-dl/issues/820
  44. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
  45. workaround_optparse_bug9161()
  46. setproctitle('youtube-dl')
  47. parser, opts, args = parseOpts(argv)
  48. # Set user agent
  49. if opts.user_agent is not None:
  50. std_headers['User-Agent'] = opts.user_agent
  51. # Set referer
  52. if opts.referer is not None:
  53. std_headers['Referer'] = opts.referer
  54. # Custom HTTP headers
  55. if opts.headers is not None:
  56. for h in opts.headers:
  57. if h.find(':', 1) < 0:
  58. parser.error('wrong header formatting, it should be key:value, not "%s"' % h)
  59. key, value = h.split(':', 2)
  60. if opts.verbose:
  61. write_string('[debug] Adding header from command line option %s:%s\n' % (key, value))
  62. std_headers[key] = value
  63. # Dump user agent
  64. if opts.dump_user_agent:
  65. compat_print(std_headers['User-Agent'])
  66. sys.exit(0)
  67. # Batch file verification
  68. batch_urls = []
  69. if opts.batchfile is not None:
  70. try:
  71. if opts.batchfile == '-':
  72. batchfd = sys.stdin
  73. else:
  74. batchfd = io.open(opts.batchfile, 'r', encoding='utf-8', errors='ignore')
  75. batch_urls = read_batch_urls(batchfd)
  76. if opts.verbose:
  77. write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
  78. except IOError:
  79. sys.exit('ERROR: batch file could not be read')
  80. all_urls = batch_urls + args
  81. all_urls = [url.strip() for url in all_urls]
  82. _enc = preferredencoding()
  83. all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
  84. if opts.list_extractors:
  85. for ie in list_extractors(opts.age_limit):
  86. compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  87. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  88. for mu in matchedUrls:
  89. compat_print(' ' + mu)
  90. sys.exit(0)
  91. if opts.list_extractor_descriptions:
  92. for ie in list_extractors(opts.age_limit):
  93. if not ie._WORKING:
  94. continue
  95. desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
  96. if desc is False:
  97. continue
  98. if hasattr(ie, 'SEARCH_KEY'):
  99. _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
  100. _COUNTS = ('', '5', '10', 'all')
  101. desc += ' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
  102. compat_print(desc)
  103. sys.exit(0)
  104. # Conflicting, missing and erroneous options
  105. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  106. parser.error('using .netrc conflicts with giving username/password')
  107. if opts.password is not None and opts.username is None:
  108. parser.error('account username missing\n')
  109. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  110. parser.error('using output template conflicts with using title, video ID or auto number')
  111. if opts.usetitle and opts.useid:
  112. parser.error('using title conflicts with using video ID')
  113. if opts.username is not None and opts.password is None:
  114. opts.password = compat_getpass('Type account password and press [Return]: ')
  115. if opts.ratelimit is not None:
  116. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  117. if numeric_limit is None:
  118. parser.error('invalid rate limit specified')
  119. opts.ratelimit = numeric_limit
  120. if opts.min_filesize is not None:
  121. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  122. if numeric_limit is None:
  123. parser.error('invalid min_filesize specified')
  124. opts.min_filesize = numeric_limit
  125. if opts.max_filesize is not None:
  126. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  127. if numeric_limit is None:
  128. parser.error('invalid max_filesize specified')
  129. opts.max_filesize = numeric_limit
  130. if opts.retries is not None:
  131. if opts.retries in ('inf', 'infinite'):
  132. opts_retries = float('inf')
  133. else:
  134. try:
  135. opts_retries = int(opts.retries)
  136. except (TypeError, ValueError):
  137. parser.error('invalid retry count specified')
  138. if opts.buffersize is not None:
  139. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  140. if numeric_buffersize is None:
  141. parser.error('invalid buffer size specified')
  142. opts.buffersize = numeric_buffersize
  143. if opts.playliststart <= 0:
  144. raise ValueError('Playlist start must be positive')
  145. if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
  146. raise ValueError('Playlist end must be greater than playlist start')
  147. if opts.extractaudio:
  148. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  149. parser.error('invalid audio format specified')
  150. if opts.audioquality:
  151. opts.audioquality = opts.audioquality.strip('k').strip('K')
  152. if not opts.audioquality.isdigit():
  153. parser.error('invalid audio quality specified')
  154. if opts.recodevideo is not None:
  155. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
  156. parser.error('invalid video recode format specified')
  157. if opts.convertsubtitles is not None:
  158. if opts.convertsubtitles not in ['srt', 'vtt', 'ass']:
  159. parser.error('invalid subtitle format specified')
  160. if opts.date is not None:
  161. date = DateRange.day(opts.date)
  162. else:
  163. date = DateRange(opts.dateafter, opts.datebefore)
  164. # Do not download videos when there are audio-only formats
  165. if opts.extractaudio and not opts.keepvideo and opts.format is None:
  166. opts.format = 'bestaudio/best'
  167. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  168. # this was the old behaviour if only --all-sub was given.
  169. if opts.allsubtitles and not opts.writeautomaticsub:
  170. opts.writesubtitles = True
  171. if sys.version_info < (3,):
  172. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  173. if opts.outtmpl is not None:
  174. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  175. outtmpl = ((opts.outtmpl is not None and opts.outtmpl) or
  176. (opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s') or
  177. (opts.format == '-1' and '%(id)s-%(format)s.%(ext)s') or
  178. (opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s') or
  179. (opts.usetitle and '%(title)s-%(id)s.%(ext)s') or
  180. (opts.useid and '%(id)s.%(ext)s') or
  181. (opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s') or
  182. DEFAULT_OUTTMPL)
  183. if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
  184. parser.error('Cannot download a video and extract audio into the same'
  185. ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
  186. ' template'.format(outtmpl))
  187. any_getting = 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 or opts.dump_single_json
  188. any_printing = opts.print_json
  189. download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
  190. # PostProcessors
  191. postprocessors = []
  192. # Add the metadata pp first, the other pps will copy it
  193. if opts.addmetadata:
  194. postprocessors.append({'key': 'FFmpegMetadata'})
  195. if opts.extractaudio:
  196. postprocessors.append({
  197. 'key': 'FFmpegExtractAudio',
  198. 'preferredcodec': opts.audioformat,
  199. 'preferredquality': opts.audioquality,
  200. 'nopostoverwrites': opts.nopostoverwrites,
  201. })
  202. if opts.recodevideo:
  203. postprocessors.append({
  204. 'key': 'FFmpegVideoConvertor',
  205. 'preferedformat': opts.recodevideo,
  206. })
  207. if opts.convertsubtitles:
  208. postprocessors.append({
  209. 'key': 'FFmpegSubtitlesConvertor',
  210. 'format': opts.convertsubtitles,
  211. })
  212. if opts.embedsubtitles:
  213. postprocessors.append({
  214. 'key': 'FFmpegEmbedSubtitle',
  215. })
  216. if opts.xattrs:
  217. postprocessors.append({'key': 'XAttrMetadata'})
  218. if opts.embedthumbnail:
  219. if not opts.addmetadata:
  220. postprocessors.append({'key': 'FFmpegAudioFix'})
  221. postprocessors.append({'key': 'AtomicParsley'})
  222. # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
  223. # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
  224. if opts.exec_cmd:
  225. postprocessors.append({
  226. 'key': 'ExecAfterDownload',
  227. 'verboseOutput': opts.verbose,
  228. 'exec_cmd': opts.exec_cmd,
  229. })
  230. if opts.xattr_set_filesize:
  231. try:
  232. import xattr
  233. xattr # Confuse flake8
  234. except ImportError:
  235. parser.error('setting filesize xattr requested but python-xattr is not available')
  236. external_downloader_args = None
  237. if opts.external_downloader_args:
  238. external_downloader_args = shlex.split(opts.external_downloader_args)
  239. match_filter = (
  240. None if opts.match_filter is None
  241. else match_filter_func(opts.match_filter))
  242. ydl_opts = {
  243. 'usenetrc': opts.usenetrc,
  244. 'username': opts.username,
  245. 'password': opts.password,
  246. 'twofactor': opts.twofactor,
  247. 'videopassword': opts.videopassword,
  248. 'quiet': (opts.quiet or any_getting or any_printing),
  249. 'no_warnings': opts.no_warnings,
  250. 'forceurl': opts.geturl,
  251. 'forcetitle': opts.gettitle,
  252. 'forceid': opts.getid,
  253. 'forcethumbnail': opts.getthumbnail,
  254. 'forcedescription': opts.getdescription,
  255. 'forceduration': opts.getduration,
  256. 'forcefilename': opts.getfilename,
  257. 'forceformat': opts.getformat,
  258. 'forcejson': opts.dumpjson or opts.print_json,
  259. 'dump_single_json': opts.dump_single_json,
  260. 'simulate': opts.simulate or any_getting,
  261. 'skip_download': opts.skip_download,
  262. 'format': opts.format,
  263. 'format_limit': opts.format_limit,
  264. 'listformats': opts.listformats,
  265. 'outtmpl': outtmpl,
  266. 'autonumber_size': opts.autonumber_size,
  267. 'restrictfilenames': opts.restrictfilenames,
  268. 'ignoreerrors': opts.ignoreerrors,
  269. 'ratelimit': opts.ratelimit,
  270. 'nooverwrites': opts.nooverwrites,
  271. 'retries': opts_retries,
  272. 'buffersize': opts.buffersize,
  273. 'noresizebuffer': opts.noresizebuffer,
  274. 'continuedl': opts.continue_dl,
  275. 'noprogress': opts.noprogress,
  276. 'progress_with_newline': opts.progress_with_newline,
  277. 'playliststart': opts.playliststart,
  278. 'playlistend': opts.playlistend,
  279. 'playlistreverse': opts.playlist_reverse,
  280. 'noplaylist': opts.noplaylist,
  281. 'logtostderr': opts.outtmpl == '-',
  282. 'consoletitle': opts.consoletitle,
  283. 'nopart': opts.nopart,
  284. 'updatetime': opts.updatetime,
  285. 'writedescription': opts.writedescription,
  286. 'writeannotations': opts.writeannotations,
  287. 'writeinfojson': opts.writeinfojson,
  288. 'writethumbnail': opts.writethumbnail,
  289. 'write_all_thumbnails': opts.write_all_thumbnails,
  290. 'writesubtitles': opts.writesubtitles,
  291. 'writeautomaticsub': opts.writeautomaticsub,
  292. 'allsubtitles': opts.allsubtitles,
  293. 'listsubtitles': opts.listsubtitles,
  294. 'subtitlesformat': opts.subtitlesformat,
  295. 'subtitleslangs': opts.subtitleslangs,
  296. 'matchtitle': decodeOption(opts.matchtitle),
  297. 'rejecttitle': decodeOption(opts.rejecttitle),
  298. 'max_downloads': opts.max_downloads,
  299. 'prefer_free_formats': opts.prefer_free_formats,
  300. 'verbose': opts.verbose,
  301. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  302. 'write_pages': opts.write_pages,
  303. 'test': opts.test,
  304. 'keepvideo': opts.keepvideo,
  305. 'min_filesize': opts.min_filesize,
  306. 'max_filesize': opts.max_filesize,
  307. 'min_views': opts.min_views,
  308. 'max_views': opts.max_views,
  309. 'daterange': date,
  310. 'cachedir': opts.cachedir,
  311. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  312. 'age_limit': opts.age_limit,
  313. 'download_archive': download_archive_fn,
  314. 'cookiefile': opts.cookiefile,
  315. 'nocheckcertificate': opts.no_check_certificate,
  316. 'prefer_insecure': opts.prefer_insecure,
  317. 'proxy': opts.proxy,
  318. 'socket_timeout': opts.socket_timeout,
  319. 'bidi_workaround': opts.bidi_workaround,
  320. 'debug_printtraffic': opts.debug_printtraffic,
  321. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  322. 'include_ads': opts.include_ads,
  323. 'default_search': opts.default_search,
  324. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  325. 'encoding': opts.encoding,
  326. 'exec_cmd': opts.exec_cmd,
  327. 'extract_flat': opts.extract_flat,
  328. 'merge_output_format': opts.merge_output_format,
  329. 'postprocessors': postprocessors,
  330. 'fixup': opts.fixup,
  331. 'source_address': opts.source_address,
  332. 'call_home': opts.call_home,
  333. 'sleep_interval': opts.sleep_interval,
  334. 'external_downloader': opts.external_downloader,
  335. 'list_thumbnails': opts.list_thumbnails,
  336. 'playlist_items': opts.playlist_items,
  337. 'xattr_set_filesize': opts.xattr_set_filesize,
  338. 'match_filter': match_filter,
  339. 'no_color': opts.no_color,
  340. 'ffmpeg_location': opts.ffmpeg_location,
  341. 'hls_prefer_native': opts.hls_prefer_native,
  342. 'external_downloader_args': external_downloader_args,
  343. 'cn_verification_proxy': opts.cn_verification_proxy,
  344. }
  345. with YoutubeDL(ydl_opts) as ydl:
  346. # Update version
  347. if opts.update_self:
  348. update_self(ydl.to_screen, opts.verbose)
  349. # Remove cache dir
  350. if opts.rm_cachedir:
  351. ydl.cache.remove()
  352. # Maybe do nothing
  353. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  354. if opts.update_self or opts.rm_cachedir:
  355. sys.exit()
  356. ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
  357. parser.error(
  358. 'You must provide at least one URL.\n'
  359. 'Type youtube-dl --help to see a list of all options.')
  360. try:
  361. if opts.load_info_filename is not None:
  362. retcode = ydl.download_with_info_file(opts.load_info_filename)
  363. else:
  364. retcode = ydl.download(all_urls)
  365. except MaxDownloadsReached:
  366. ydl.to_screen('--max-download limit reached, aborting.')
  367. retcode = 101
  368. sys.exit(retcode)
  369. def main(argv=None):
  370. try:
  371. _real_main(argv)
  372. except DownloadError:
  373. sys.exit(1)
  374. except SameFileError:
  375. sys.exit('ERROR: fixed output name but more than one file to download')
  376. except KeyboardInterrupt:
  377. sys.exit('\nERROR: Interrupted by user')
  378. __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']