__init__.py 14 KB

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