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.

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