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.

362 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
10 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 not opts.writeautomaticsub:
  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. 'playlistreverse': opts.playlist_reverse,
  230. 'noplaylist': opts.noplaylist,
  231. 'logtostderr': opts.outtmpl == '-',
  232. 'consoletitle': opts.consoletitle,
  233. 'nopart': opts.nopart,
  234. 'updatetime': opts.updatetime,
  235. 'writedescription': opts.writedescription,
  236. 'writeannotations': opts.writeannotations,
  237. 'writeinfojson': opts.writeinfojson,
  238. 'writethumbnail': opts.writethumbnail,
  239. 'writesubtitles': opts.writesubtitles,
  240. 'writeautomaticsub': opts.writeautomaticsub,
  241. 'allsubtitles': opts.allsubtitles,
  242. 'listsubtitles': opts.listsubtitles,
  243. 'subtitlesformat': opts.subtitlesformat,
  244. 'subtitleslangs': opts.subtitleslangs,
  245. 'matchtitle': decodeOption(opts.matchtitle),
  246. 'rejecttitle': decodeOption(opts.rejecttitle),
  247. 'max_downloads': opts.max_downloads,
  248. 'prefer_free_formats': opts.prefer_free_formats,
  249. 'verbose': opts.verbose,
  250. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  251. 'write_pages': opts.write_pages,
  252. 'test': opts.test,
  253. 'keepvideo': opts.keepvideo,
  254. 'min_filesize': opts.min_filesize,
  255. 'max_filesize': opts.max_filesize,
  256. 'min_views': opts.min_views,
  257. 'max_views': opts.max_views,
  258. 'daterange': date,
  259. 'cachedir': opts.cachedir,
  260. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  261. 'age_limit': opts.age_limit,
  262. 'download_archive': download_archive_fn,
  263. 'cookiefile': opts.cookiefile,
  264. 'nocheckcertificate': opts.no_check_certificate,
  265. 'prefer_insecure': opts.prefer_insecure,
  266. 'proxy': opts.proxy,
  267. 'socket_timeout': opts.socket_timeout,
  268. 'bidi_workaround': opts.bidi_workaround,
  269. 'debug_printtraffic': opts.debug_printtraffic,
  270. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  271. 'include_ads': opts.include_ads,
  272. 'default_search': opts.default_search,
  273. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  274. 'encoding': opts.encoding,
  275. 'exec_cmd': opts.exec_cmd,
  276. 'extract_flat': opts.extract_flat,
  277. }
  278. with YoutubeDL(ydl_opts) as ydl:
  279. # PostProcessors
  280. # Add the metadata pp first, the other pps will copy it
  281. if opts.addmetadata:
  282. ydl.add_post_processor(FFmpegMetadataPP())
  283. if opts.extractaudio:
  284. ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
  285. if opts.recodevideo:
  286. ydl.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
  287. if opts.embedsubtitles:
  288. ydl.add_post_processor(FFmpegEmbedSubtitlePP(subtitlesformat=opts.subtitlesformat))
  289. if opts.xattrs:
  290. ydl.add_post_processor(XAttrMetadataPP())
  291. if opts.embedthumbnail:
  292. if not opts.addmetadata:
  293. ydl.add_post_processor(FFmpegAudioFixPP())
  294. ydl.add_post_processor(AtomicParsleyPP())
  295. # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
  296. # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
  297. if opts.exec_cmd:
  298. ydl.add_post_processor(ExecAfterDownloadPP(
  299. verboseOutput=opts.verbose, exec_cmd=opts.exec_cmd))
  300. # Update version
  301. if opts.update_self:
  302. update_self(ydl.to_screen, opts.verbose)
  303. # Remove cache dir
  304. if opts.rm_cachedir:
  305. ydl.cache.remove()
  306. # Maybe do nothing
  307. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  308. if opts.update_self or opts.rm_cachedir:
  309. sys.exit()
  310. ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
  311. parser.error('you must provide at least one URL')
  312. try:
  313. if opts.load_info_filename is not None:
  314. retcode = ydl.download_with_info_file(opts.load_info_filename)
  315. else:
  316. retcode = ydl.download(all_urls)
  317. except MaxDownloadsReached:
  318. ydl.to_screen('--max-download limit reached, aborting.')
  319. retcode = 101
  320. sys.exit(retcode)
  321. def main(argv=None):
  322. try:
  323. _real_main(argv)
  324. except DownloadError:
  325. sys.exit(1)
  326. except SameFileError:
  327. sys.exit('ERROR: fixed output name but more than one file to download')
  328. except KeyboardInterrupt:
  329. sys.exit('\nERROR: Interrupted by user')