__init__.py 15 KB

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