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.

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