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.

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