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.

427 lines
17 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. compat_shlex_split,
  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. def parse_retries(retries):
  131. if retries in ('inf', 'infinite'):
  132. parsed_retries = float('inf')
  133. else:
  134. try:
  135. parsed_retries = int(retries)
  136. except (TypeError, ValueError):
  137. parser.error('invalid retry count specified')
  138. return parsed_retries
  139. if opts.retries is not None:
  140. opts.retries = parse_retries(opts.retries)
  141. if opts.fragment_retries is not None:
  142. opts.fragment_retries = parse_retries(opts.fragment_retries)
  143. if opts.buffersize is not None:
  144. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  145. if numeric_buffersize is None:
  146. parser.error('invalid buffer size specified')
  147. opts.buffersize = numeric_buffersize
  148. if opts.playliststart <= 0:
  149. raise ValueError('Playlist start must be positive')
  150. if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
  151. raise ValueError('Playlist end must be greater than playlist start')
  152. if opts.extractaudio:
  153. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  154. parser.error('invalid audio format specified')
  155. if opts.audioquality:
  156. opts.audioquality = opts.audioquality.strip('k').strip('K')
  157. if not opts.audioquality.isdigit():
  158. parser.error('invalid audio quality specified')
  159. if opts.recodevideo is not None:
  160. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv', 'avi']:
  161. parser.error('invalid video recode format specified')
  162. if opts.convertsubtitles is not None:
  163. if opts.convertsubtitles not in ['srt', 'vtt', 'ass']:
  164. parser.error('invalid subtitle format specified')
  165. if opts.date is not None:
  166. date = DateRange.day(opts.date)
  167. else:
  168. date = DateRange(opts.dateafter, opts.datebefore)
  169. # Do not download videos when there are audio-only formats
  170. if opts.extractaudio and not opts.keepvideo and opts.format is None:
  171. opts.format = 'bestaudio/best'
  172. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  173. # this was the old behaviour if only --all-sub was given.
  174. if opts.allsubtitles and not opts.writeautomaticsub:
  175. opts.writesubtitles = True
  176. outtmpl = ((opts.outtmpl is not None and opts.outtmpl) or
  177. (opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s') or
  178. (opts.format == '-1' and '%(id)s-%(format)s.%(ext)s') or
  179. (opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s') or
  180. (opts.usetitle and '%(title)s-%(id)s.%(ext)s') or
  181. (opts.useid and '%(id)s.%(ext)s') or
  182. (opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s') or
  183. DEFAULT_OUTTMPL)
  184. if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
  185. parser.error('Cannot download a video and extract audio into the same'
  186. ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
  187. ' template'.format(outtmpl))
  188. 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
  189. any_printing = opts.print_json
  190. download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
  191. # PostProcessors
  192. postprocessors = []
  193. # Add the metadata pp first, the other pps will copy it
  194. if opts.metafromtitle:
  195. postprocessors.append({
  196. 'key': 'MetadataFromTitle',
  197. 'titleformat': opts.metafromtitle
  198. })
  199. if opts.addmetadata:
  200. postprocessors.append({'key': 'FFmpegMetadata'})
  201. if opts.extractaudio:
  202. postprocessors.append({
  203. 'key': 'FFmpegExtractAudio',
  204. 'preferredcodec': opts.audioformat,
  205. 'preferredquality': opts.audioquality,
  206. 'nopostoverwrites': opts.nopostoverwrites,
  207. })
  208. if opts.recodevideo:
  209. postprocessors.append({
  210. 'key': 'FFmpegVideoConvertor',
  211. 'preferedformat': opts.recodevideo,
  212. })
  213. if opts.convertsubtitles:
  214. postprocessors.append({
  215. 'key': 'FFmpegSubtitlesConvertor',
  216. 'format': opts.convertsubtitles,
  217. })
  218. if opts.embedsubtitles:
  219. postprocessors.append({
  220. 'key': 'FFmpegEmbedSubtitle',
  221. })
  222. if opts.xattrs:
  223. postprocessors.append({'key': 'XAttrMetadata'})
  224. if opts.embedthumbnail:
  225. already_have_thumbnail = opts.writethumbnail or opts.write_all_thumbnails
  226. postprocessors.append({
  227. 'key': 'EmbedThumbnail',
  228. 'already_have_thumbnail': already_have_thumbnail
  229. })
  230. if not already_have_thumbnail:
  231. opts.writethumbnail = True
  232. # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
  233. # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
  234. if opts.exec_cmd:
  235. postprocessors.append({
  236. 'key': 'ExecAfterDownload',
  237. 'exec_cmd': opts.exec_cmd,
  238. })
  239. if opts.xattr_set_filesize:
  240. try:
  241. import xattr
  242. xattr # Confuse flake8
  243. except ImportError:
  244. parser.error('setting filesize xattr requested but python-xattr is not available')
  245. external_downloader_args = None
  246. if opts.external_downloader_args:
  247. external_downloader_args = compat_shlex_split(opts.external_downloader_args)
  248. postprocessor_args = None
  249. if opts.postprocessor_args:
  250. postprocessor_args = compat_shlex_split(opts.postprocessor_args)
  251. match_filter = (
  252. None if opts.match_filter is None
  253. else match_filter_func(opts.match_filter))
  254. ydl_opts = {
  255. 'usenetrc': opts.usenetrc,
  256. 'username': opts.username,
  257. 'password': opts.password,
  258. 'twofactor': opts.twofactor,
  259. 'videopassword': opts.videopassword,
  260. 'quiet': (opts.quiet or any_getting or any_printing),
  261. 'no_warnings': opts.no_warnings,
  262. 'forceurl': opts.geturl,
  263. 'forcetitle': opts.gettitle,
  264. 'forceid': opts.getid,
  265. 'forcethumbnail': opts.getthumbnail,
  266. 'forcedescription': opts.getdescription,
  267. 'forceduration': opts.getduration,
  268. 'forcefilename': opts.getfilename,
  269. 'forceformat': opts.getformat,
  270. 'forcejson': opts.dumpjson or opts.print_json,
  271. 'dump_single_json': opts.dump_single_json,
  272. 'simulate': opts.simulate or any_getting,
  273. 'skip_download': opts.skip_download,
  274. 'format': opts.format,
  275. 'listformats': opts.listformats,
  276. 'outtmpl': outtmpl,
  277. 'autonumber_size': opts.autonumber_size,
  278. 'restrictfilenames': opts.restrictfilenames,
  279. 'ignoreerrors': opts.ignoreerrors,
  280. 'force_generic_extractor': opts.force_generic_extractor,
  281. 'ratelimit': opts.ratelimit,
  282. 'nooverwrites': opts.nooverwrites,
  283. 'retries': opts.retries,
  284. 'fragment_retries': opts.fragment_retries,
  285. 'buffersize': opts.buffersize,
  286. 'noresizebuffer': opts.noresizebuffer,
  287. 'continuedl': opts.continue_dl,
  288. 'noprogress': opts.noprogress,
  289. 'progress_with_newline': opts.progress_with_newline,
  290. 'playliststart': opts.playliststart,
  291. 'playlistend': opts.playlistend,
  292. 'playlistreverse': opts.playlist_reverse,
  293. 'noplaylist': opts.noplaylist,
  294. 'logtostderr': opts.outtmpl == '-',
  295. 'consoletitle': opts.consoletitle,
  296. 'nopart': opts.nopart,
  297. 'updatetime': opts.updatetime,
  298. 'writedescription': opts.writedescription,
  299. 'writeannotations': opts.writeannotations,
  300. 'writeinfojson': opts.writeinfojson,
  301. 'writethumbnail': opts.writethumbnail,
  302. 'write_all_thumbnails': opts.write_all_thumbnails,
  303. 'writesubtitles': opts.writesubtitles,
  304. 'writeautomaticsub': opts.writeautomaticsub,
  305. 'allsubtitles': opts.allsubtitles,
  306. 'listsubtitles': opts.listsubtitles,
  307. 'subtitlesformat': opts.subtitlesformat,
  308. 'subtitleslangs': opts.subtitleslangs,
  309. 'matchtitle': decodeOption(opts.matchtitle),
  310. 'rejecttitle': decodeOption(opts.rejecttitle),
  311. 'max_downloads': opts.max_downloads,
  312. 'prefer_free_formats': opts.prefer_free_formats,
  313. 'verbose': opts.verbose,
  314. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  315. 'write_pages': opts.write_pages,
  316. 'test': opts.test,
  317. 'keepvideo': opts.keepvideo,
  318. 'min_filesize': opts.min_filesize,
  319. 'max_filesize': opts.max_filesize,
  320. 'min_views': opts.min_views,
  321. 'max_views': opts.max_views,
  322. 'daterange': date,
  323. 'cachedir': opts.cachedir,
  324. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  325. 'age_limit': opts.age_limit,
  326. 'download_archive': download_archive_fn,
  327. 'cookiefile': opts.cookiefile,
  328. 'nocheckcertificate': opts.no_check_certificate,
  329. 'prefer_insecure': opts.prefer_insecure,
  330. 'proxy': opts.proxy,
  331. 'socket_timeout': opts.socket_timeout,
  332. 'bidi_workaround': opts.bidi_workaround,
  333. 'debug_printtraffic': opts.debug_printtraffic,
  334. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  335. 'include_ads': opts.include_ads,
  336. 'default_search': opts.default_search,
  337. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  338. 'encoding': opts.encoding,
  339. 'extract_flat': opts.extract_flat,
  340. 'mark_watched': opts.mark_watched,
  341. 'merge_output_format': opts.merge_output_format,
  342. 'postprocessors': postprocessors,
  343. 'fixup': opts.fixup,
  344. 'source_address': opts.source_address,
  345. 'call_home': opts.call_home,
  346. 'sleep_interval': opts.sleep_interval,
  347. 'external_downloader': opts.external_downloader,
  348. 'list_thumbnails': opts.list_thumbnails,
  349. 'playlist_items': opts.playlist_items,
  350. 'xattr_set_filesize': opts.xattr_set_filesize,
  351. 'match_filter': match_filter,
  352. 'no_color': opts.no_color,
  353. 'ffmpeg_location': opts.ffmpeg_location,
  354. 'hls_prefer_native': opts.hls_prefer_native,
  355. 'hls_use_mpegts': opts.hls_use_mpegts,
  356. 'external_downloader_args': external_downloader_args,
  357. 'postprocessor_args': postprocessor_args,
  358. 'cn_verification_proxy': opts.cn_verification_proxy,
  359. }
  360. with YoutubeDL(ydl_opts) as ydl:
  361. # Update version
  362. if opts.update_self:
  363. update_self(ydl.to_screen, opts.verbose, ydl._opener)
  364. # Remove cache dir
  365. if opts.rm_cachedir:
  366. ydl.cache.remove()
  367. # Maybe do nothing
  368. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  369. if opts.update_self or opts.rm_cachedir:
  370. sys.exit()
  371. ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
  372. parser.error(
  373. 'You must provide at least one URL.\n'
  374. 'Type youtube-dl --help to see a list of all options.')
  375. try:
  376. if opts.load_info_filename is not None:
  377. retcode = ydl.download_with_info_file(opts.load_info_filename)
  378. else:
  379. retcode = ydl.download(all_urls)
  380. except MaxDownloadsReached:
  381. ydl.to_screen('--max-download limit reached, aborting.')
  382. retcode = 101
  383. sys.exit(retcode)
  384. def main(argv=None):
  385. try:
  386. _real_main(argv)
  387. except DownloadError:
  388. sys.exit(1)
  389. except SameFileError:
  390. sys.exit('ERROR: fixed output name but more than one file to download')
  391. except KeyboardInterrupt:
  392. sys.exit('\nERROR: Interrupted by user')
  393. __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']