__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. DEFAULT_OUTTMPL,
  22. decodeOption,
  23. DownloadError,
  24. MaxDownloadsReached,
  25. preferredencoding,
  26. read_batch_urls,
  27. SameFileError,
  28. setproctitle,
  29. std_headers,
  30. write_string,
  31. )
  32. from .update import update_self
  33. from .downloader import (
  34. FileDownloader,
  35. )
  36. from .extractor import gen_extractors, list_extractors
  37. from .YoutubeDL import YoutubeDL
  38. def _real_main(argv=None):
  39. # Compatibility fixes for Windows
  40. if sys.platform == 'win32':
  41. # https://github.com/rg3/youtube-dl/issues/820
  42. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
  43. workaround_optparse_bug9161()
  44. setproctitle('youtube-dl')
  45. parser, opts, args = parseOpts(argv)
  46. # Set user agent
  47. if opts.user_agent is not None:
  48. std_headers['User-Agent'] = opts.user_agent
  49. # Set referer
  50. if opts.referer is not None:
  51. std_headers['Referer'] = opts.referer
  52. # Custom HTTP headers
  53. if opts.headers is not None:
  54. for h in opts.headers:
  55. if h.find(':', 1) < 0:
  56. parser.error('wrong header formatting, it should be key:value, not "%s"' % h)
  57. key, value = h.split(':', 2)
  58. if opts.verbose:
  59. write_string('[debug] Adding header from command line option %s:%s\n' % (key, value))
  60. std_headers[key] = value
  61. # Dump user agent
  62. if opts.dump_user_agent:
  63. compat_print(std_headers['User-Agent'])
  64. sys.exit(0)
  65. # Batch file verification
  66. batch_urls = []
  67. if opts.batchfile is not None:
  68. try:
  69. if opts.batchfile == '-':
  70. batchfd = sys.stdin
  71. else:
  72. batchfd = io.open(opts.batchfile, 'r', encoding='utf-8', errors='ignore')
  73. batch_urls = read_batch_urls(batchfd)
  74. if opts.verbose:
  75. write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
  76. except IOError:
  77. sys.exit('ERROR: batch file could not be read')
  78. all_urls = batch_urls + args
  79. all_urls = [url.strip() for url in all_urls]
  80. _enc = preferredencoding()
  81. all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
  82. if opts.list_extractors:
  83. for ie in list_extractors(opts.age_limit):
  84. compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  85. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  86. for mu in matchedUrls:
  87. compat_print(' ' + mu)
  88. sys.exit(0)
  89. if opts.list_extractor_descriptions:
  90. for ie in list_extractors(opts.age_limit):
  91. if not ie._WORKING:
  92. continue
  93. desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
  94. if desc is False:
  95. continue
  96. if hasattr(ie, 'SEARCH_KEY'):
  97. _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
  98. _COUNTS = ('', '5', '10', 'all')
  99. desc += ' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
  100. compat_print(desc)
  101. sys.exit(0)
  102. # Conflicting, missing and erroneous options
  103. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  104. parser.error('using .netrc conflicts with giving username/password')
  105. if opts.password is not None and opts.username is None:
  106. parser.error('account username missing\n')
  107. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  108. parser.error('using output template conflicts with using title, video ID or auto number')
  109. if opts.usetitle and opts.useid:
  110. parser.error('using title conflicts with using video ID')
  111. if opts.username is not None and opts.password is None:
  112. opts.password = compat_getpass('Type account password and press [Return]: ')
  113. if opts.ratelimit is not None:
  114. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  115. if numeric_limit is None:
  116. parser.error('invalid rate limit specified')
  117. opts.ratelimit = numeric_limit
  118. if opts.min_filesize is not None:
  119. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  120. if numeric_limit is None:
  121. parser.error('invalid min_filesize specified')
  122. opts.min_filesize = numeric_limit
  123. if opts.max_filesize is not None:
  124. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  125. if numeric_limit is None:
  126. parser.error('invalid max_filesize specified')
  127. opts.max_filesize = numeric_limit
  128. if opts.retries is not None:
  129. if opts.retries in ('inf', 'infinite'):
  130. opts_retries = float('inf')
  131. else:
  132. try:
  133. opts_retries = int(opts.retries)
  134. except (TypeError, ValueError):
  135. parser.error('invalid retry count specified')
  136. if opts.buffersize is not None:
  137. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  138. if numeric_buffersize is None:
  139. parser.error('invalid buffer size specified')
  140. opts.buffersize = numeric_buffersize
  141. if opts.playliststart <= 0:
  142. raise ValueError('Playlist start must be positive')
  143. if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
  144. raise ValueError('Playlist end must be greater than playlist start')
  145. if opts.extractaudio:
  146. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  147. parser.error('invalid audio format specified')
  148. if opts.audioquality:
  149. opts.audioquality = opts.audioquality.strip('k').strip('K')
  150. if not opts.audioquality.isdigit():
  151. parser.error('invalid audio quality specified')
  152. if opts.recodevideo is not None:
  153. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
  154. parser.error('invalid video recode format specified')
  155. if opts.date is not None:
  156. date = DateRange.day(opts.date)
  157. else:
  158. date = DateRange(opts.dateafter, opts.datebefore)
  159. # Do not download videos when there are audio-only formats
  160. if opts.extractaudio and not opts.keepvideo and opts.format is None:
  161. opts.format = 'bestaudio/best'
  162. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  163. # this was the old behaviour if only --all-sub was given.
  164. if opts.allsubtitles and not opts.writeautomaticsub:
  165. opts.writesubtitles = True
  166. if sys.version_info < (3,):
  167. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  168. if opts.outtmpl is not None:
  169. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  170. outtmpl = ((opts.outtmpl is not None and opts.outtmpl)
  171. or (opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s')
  172. or (opts.format == '-1' and '%(id)s-%(format)s.%(ext)s')
  173. or (opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  174. or (opts.usetitle and '%(title)s-%(id)s.%(ext)s')
  175. or (opts.useid and '%(id)s.%(ext)s')
  176. or (opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s')
  177. or DEFAULT_OUTTMPL)
  178. if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
  179. parser.error('Cannot download a video and extract audio into the same'
  180. ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
  181. ' template'.format(outtmpl))
  182. 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
  183. any_printing = opts.print_json
  184. download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
  185. # PostProcessors
  186. postprocessors = []
  187. # Add the metadata pp first, the other pps will copy it
  188. if opts.addmetadata:
  189. postprocessors.append({'key': 'FFmpegMetadata'})
  190. if opts.extractaudio:
  191. postprocessors.append({
  192. 'key': 'FFmpegExtractAudio',
  193. 'preferredcodec': opts.audioformat,
  194. 'preferredquality': opts.audioquality,
  195. 'nopostoverwrites': opts.nopostoverwrites,
  196. })
  197. if opts.recodevideo:
  198. postprocessors.append({
  199. 'key': 'FFmpegVideoConvertor',
  200. 'preferedformat': opts.recodevideo,
  201. })
  202. if opts.embedsubtitles:
  203. postprocessors.append({
  204. 'key': 'FFmpegEmbedSubtitle',
  205. 'subtitlesformat': opts.subtitlesformat,
  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. ydl_opts = {
  228. 'usenetrc': opts.usenetrc,
  229. 'username': opts.username,
  230. 'password': opts.password,
  231. 'twofactor': opts.twofactor,
  232. 'videopassword': opts.videopassword,
  233. 'quiet': (opts.quiet or any_getting or any_printing),
  234. 'no_warnings': opts.no_warnings,
  235. 'forceurl': opts.geturl,
  236. 'forcetitle': opts.gettitle,
  237. 'forceid': opts.getid,
  238. 'forcethumbnail': opts.getthumbnail,
  239. 'forcedescription': opts.getdescription,
  240. 'forceduration': opts.getduration,
  241. 'forcefilename': opts.getfilename,
  242. 'forceformat': opts.getformat,
  243. 'forcejson': opts.dumpjson or opts.print_json,
  244. 'dump_single_json': opts.dump_single_json,
  245. 'simulate': opts.simulate or any_getting,
  246. 'skip_download': opts.skip_download,
  247. 'format': opts.format,
  248. 'format_limit': opts.format_limit,
  249. 'listformats': opts.listformats,
  250. 'outtmpl': outtmpl,
  251. 'autonumber_size': opts.autonumber_size,
  252. 'restrictfilenames': opts.restrictfilenames,
  253. 'ignoreerrors': opts.ignoreerrors,
  254. 'ratelimit': opts.ratelimit,
  255. 'nooverwrites': opts.nooverwrites,
  256. 'retries': opts_retries,
  257. 'buffersize': opts.buffersize,
  258. 'noresizebuffer': opts.noresizebuffer,
  259. 'continuedl': opts.continue_dl,
  260. 'noprogress': opts.noprogress,
  261. 'progress_with_newline': opts.progress_with_newline,
  262. 'playliststart': opts.playliststart,
  263. 'playlistend': opts.playlistend,
  264. 'playlistreverse': opts.playlist_reverse,
  265. 'noplaylist': opts.noplaylist,
  266. 'logtostderr': opts.outtmpl == '-',
  267. 'consoletitle': opts.consoletitle,
  268. 'nopart': opts.nopart,
  269. 'updatetime': opts.updatetime,
  270. 'writedescription': opts.writedescription,
  271. 'writeannotations': opts.writeannotations,
  272. 'writeinfojson': opts.writeinfojson,
  273. 'writethumbnail': opts.writethumbnail,
  274. 'write_all_thumbnails': opts.write_all_thumbnails,
  275. 'writesubtitles': opts.writesubtitles,
  276. 'writeautomaticsub': opts.writeautomaticsub,
  277. 'allsubtitles': opts.allsubtitles,
  278. 'listsubtitles': opts.listsubtitles,
  279. 'subtitlesformat': opts.subtitlesformat,
  280. 'subtitleslangs': opts.subtitleslangs,
  281. 'matchtitle': decodeOption(opts.matchtitle),
  282. 'rejecttitle': decodeOption(opts.rejecttitle),
  283. 'max_downloads': opts.max_downloads,
  284. 'prefer_free_formats': opts.prefer_free_formats,
  285. 'verbose': opts.verbose,
  286. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  287. 'write_pages': opts.write_pages,
  288. 'test': opts.test,
  289. 'keepvideo': opts.keepvideo,
  290. 'min_filesize': opts.min_filesize,
  291. 'max_filesize': opts.max_filesize,
  292. 'min_views': opts.min_views,
  293. 'max_views': opts.max_views,
  294. 'daterange': date,
  295. 'cachedir': opts.cachedir,
  296. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  297. 'age_limit': opts.age_limit,
  298. 'download_archive': download_archive_fn,
  299. 'cookiefile': opts.cookiefile,
  300. 'nocheckcertificate': opts.no_check_certificate,
  301. 'prefer_insecure': opts.prefer_insecure,
  302. 'proxy': opts.proxy,
  303. 'socket_timeout': opts.socket_timeout,
  304. 'bidi_workaround': opts.bidi_workaround,
  305. 'debug_printtraffic': opts.debug_printtraffic,
  306. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  307. 'include_ads': opts.include_ads,
  308. 'default_search': opts.default_search,
  309. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  310. 'encoding': opts.encoding,
  311. 'exec_cmd': opts.exec_cmd,
  312. 'extract_flat': opts.extract_flat,
  313. 'merge_output_format': opts.merge_output_format,
  314. 'postprocessors': postprocessors,
  315. 'fixup': opts.fixup,
  316. 'source_address': opts.source_address,
  317. 'call_home': opts.call_home,
  318. 'sleep_interval': opts.sleep_interval,
  319. 'external_downloader': opts.external_downloader,
  320. 'list_thumbnails': opts.list_thumbnails,
  321. 'playlist_items': opts.playlist_items,
  322. 'xattr_set_filesize': opts.xattr_set_filesize,
  323. }
  324. with YoutubeDL(ydl_opts) as ydl:
  325. # Update version
  326. if opts.update_self:
  327. update_self(ydl.to_screen, opts.verbose)
  328. # Remove cache dir
  329. if opts.rm_cachedir:
  330. ydl.cache.remove()
  331. # Maybe do nothing
  332. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  333. if opts.update_self or opts.rm_cachedir:
  334. sys.exit()
  335. ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
  336. parser.error(
  337. 'You must provide at least one URL.\n'
  338. 'Type youtube-dl --help to see a list of all options.')
  339. try:
  340. if opts.load_info_filename is not None:
  341. retcode = ydl.download_with_info_file(opts.load_info_filename)
  342. else:
  343. retcode = ydl.download(all_urls)
  344. except MaxDownloadsReached:
  345. ydl.to_screen('--max-download limit reached, aborting.')
  346. retcode = 101
  347. sys.exit(retcode)
  348. def main(argv=None):
  349. try:
  350. _real_main(argv)
  351. except DownloadError:
  352. sys.exit(1)
  353. except SameFileError:
  354. sys.exit('ERROR: fixed output name but more than one file to download')
  355. except KeyboardInterrupt:
  356. sys.exit('\nERROR: Interrupted by user')
  357. __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']