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.

416 lines
16 KiB

10 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
9 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.metafromtitle:
  194. postprocessors.append({
  195. 'key': 'MetadataFromTitle',
  196. 'titleformat': opts.metafromtitle
  197. })
  198. if opts.addmetadata:
  199. postprocessors.append({'key': 'FFmpegMetadata'})
  200. if opts.extractaudio:
  201. postprocessors.append({
  202. 'key': 'FFmpegExtractAudio',
  203. 'preferredcodec': opts.audioformat,
  204. 'preferredquality': opts.audioquality,
  205. 'nopostoverwrites': opts.nopostoverwrites,
  206. })
  207. if opts.recodevideo:
  208. postprocessors.append({
  209. 'key': 'FFmpegVideoConvertor',
  210. 'preferedformat': opts.recodevideo,
  211. })
  212. if opts.convertsubtitles:
  213. postprocessors.append({
  214. 'key': 'FFmpegSubtitlesConvertor',
  215. 'format': opts.convertsubtitles,
  216. })
  217. if opts.embedsubtitles:
  218. postprocessors.append({
  219. 'key': 'FFmpegEmbedSubtitle',
  220. })
  221. if opts.xattrs:
  222. postprocessors.append({'key': 'XAttrMetadata'})
  223. if opts.embedthumbnail:
  224. if not opts.addmetadata:
  225. postprocessors.append({'key': 'FFmpegAudioFix'})
  226. postprocessors.append({'key': 'AtomicParsley'})
  227. # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
  228. # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
  229. if opts.exec_cmd:
  230. postprocessors.append({
  231. 'key': 'ExecAfterDownload',
  232. 'verboseOutput': opts.verbose,
  233. 'exec_cmd': opts.exec_cmd,
  234. })
  235. if opts.xattr_set_filesize:
  236. try:
  237. import xattr
  238. xattr # Confuse flake8
  239. except ImportError:
  240. parser.error('setting filesize xattr requested but python-xattr is not available')
  241. external_downloader_args = None
  242. if opts.external_downloader_args:
  243. external_downloader_args = shlex.split(opts.external_downloader_args)
  244. match_filter = (
  245. None if opts.match_filter is None
  246. else match_filter_func(opts.match_filter))
  247. ydl_opts = {
  248. 'usenetrc': opts.usenetrc,
  249. 'username': opts.username,
  250. 'password': opts.password,
  251. 'twofactor': opts.twofactor,
  252. 'videopassword': opts.videopassword,
  253. 'quiet': (opts.quiet or any_getting or any_printing),
  254. 'no_warnings': opts.no_warnings,
  255. 'forceurl': opts.geturl,
  256. 'forcetitle': opts.gettitle,
  257. 'forceid': opts.getid,
  258. 'forcethumbnail': opts.getthumbnail,
  259. 'forcedescription': opts.getdescription,
  260. 'forceduration': opts.getduration,
  261. 'forcefilename': opts.getfilename,
  262. 'forceformat': opts.getformat,
  263. 'forcejson': opts.dumpjson or opts.print_json,
  264. 'dump_single_json': opts.dump_single_json,
  265. 'simulate': opts.simulate or any_getting,
  266. 'skip_download': opts.skip_download,
  267. 'format': opts.format,
  268. 'format_limit': opts.format_limit,
  269. 'listformats': opts.listformats,
  270. 'outtmpl': outtmpl,
  271. 'autonumber_size': opts.autonumber_size,
  272. 'restrictfilenames': opts.restrictfilenames,
  273. 'ignoreerrors': opts.ignoreerrors,
  274. 'ratelimit': opts.ratelimit,
  275. 'nooverwrites': opts.nooverwrites,
  276. 'retries': opts_retries,
  277. 'buffersize': opts.buffersize,
  278. 'noresizebuffer': opts.noresizebuffer,
  279. 'continuedl': opts.continue_dl,
  280. 'noprogress': opts.noprogress,
  281. 'progress_with_newline': opts.progress_with_newline,
  282. 'playliststart': opts.playliststart,
  283. 'playlistend': opts.playlistend,
  284. 'playlistreverse': opts.playlist_reverse,
  285. 'noplaylist': opts.noplaylist,
  286. 'logtostderr': opts.outtmpl == '-',
  287. 'consoletitle': opts.consoletitle,
  288. 'nopart': opts.nopart,
  289. 'updatetime': opts.updatetime,
  290. 'writedescription': opts.writedescription,
  291. 'writeannotations': opts.writeannotations,
  292. 'writeinfojson': opts.writeinfojson,
  293. 'writethumbnail': opts.writethumbnail,
  294. 'write_all_thumbnails': opts.write_all_thumbnails,
  295. 'writesubtitles': opts.writesubtitles,
  296. 'writeautomaticsub': opts.writeautomaticsub,
  297. 'allsubtitles': opts.allsubtitles,
  298. 'listsubtitles': opts.listsubtitles,
  299. 'subtitlesformat': opts.subtitlesformat,
  300. 'subtitleslangs': opts.subtitleslangs,
  301. 'matchtitle': decodeOption(opts.matchtitle),
  302. 'rejecttitle': decodeOption(opts.rejecttitle),
  303. 'max_downloads': opts.max_downloads,
  304. 'prefer_free_formats': opts.prefer_free_formats,
  305. 'verbose': opts.verbose,
  306. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  307. 'write_pages': opts.write_pages,
  308. 'test': opts.test,
  309. 'keepvideo': opts.keepvideo,
  310. 'min_filesize': opts.min_filesize,
  311. 'max_filesize': opts.max_filesize,
  312. 'min_views': opts.min_views,
  313. 'max_views': opts.max_views,
  314. 'daterange': date,
  315. 'cachedir': opts.cachedir,
  316. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  317. 'age_limit': opts.age_limit,
  318. 'download_archive': download_archive_fn,
  319. 'cookiefile': opts.cookiefile,
  320. 'nocheckcertificate': opts.no_check_certificate,
  321. 'prefer_insecure': opts.prefer_insecure,
  322. 'proxy': opts.proxy,
  323. 'socket_timeout': opts.socket_timeout,
  324. 'bidi_workaround': opts.bidi_workaround,
  325. 'debug_printtraffic': opts.debug_printtraffic,
  326. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  327. 'include_ads': opts.include_ads,
  328. 'default_search': opts.default_search,
  329. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  330. 'encoding': opts.encoding,
  331. 'exec_cmd': opts.exec_cmd,
  332. 'extract_flat': opts.extract_flat,
  333. 'merge_output_format': opts.merge_output_format,
  334. 'postprocessors': postprocessors,
  335. 'fixup': opts.fixup,
  336. 'source_address': opts.source_address,
  337. 'call_home': opts.call_home,
  338. 'sleep_interval': opts.sleep_interval,
  339. 'external_downloader': opts.external_downloader,
  340. 'list_thumbnails': opts.list_thumbnails,
  341. 'playlist_items': opts.playlist_items,
  342. 'xattr_set_filesize': opts.xattr_set_filesize,
  343. 'match_filter': match_filter,
  344. 'no_color': opts.no_color,
  345. 'ffmpeg_location': opts.ffmpeg_location,
  346. 'hls_prefer_native': opts.hls_prefer_native,
  347. 'external_downloader_args': external_downloader_args,
  348. 'cn_verification_proxy': opts.cn_verification_proxy,
  349. }
  350. with YoutubeDL(ydl_opts) as ydl:
  351. # Update version
  352. if opts.update_self:
  353. update_self(ydl.to_screen, opts.verbose)
  354. # Remove cache dir
  355. if opts.rm_cachedir:
  356. ydl.cache.remove()
  357. # Maybe do nothing
  358. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  359. if opts.update_self or opts.rm_cachedir:
  360. sys.exit()
  361. ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
  362. parser.error(
  363. 'You must provide at least one URL.\n'
  364. 'Type youtube-dl --help to see a list of all options.')
  365. try:
  366. if opts.load_info_filename is not None:
  367. retcode = ydl.download_with_info_file(opts.load_info_filename)
  368. else:
  369. retcode = ydl.download(all_urls)
  370. except MaxDownloadsReached:
  371. ydl.to_screen('--max-download limit reached, aborting.')
  372. retcode = 101
  373. sys.exit(retcode)
  374. def main(argv=None):
  375. try:
  376. _real_main(argv)
  377. except DownloadError:
  378. sys.exit(1)
  379. except SameFileError:
  380. sys.exit('ERROR: fixed output name but more than one file to download')
  381. except KeyboardInterrupt:
  382. sys.exit('\nERROR: Interrupted by user')
  383. __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']