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.

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