__init__.py 16 KB

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