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.

363 lines
14 KiB

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