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.

367 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
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. 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. extractors = gen_extractors()
  83. if opts.list_extractors:
  84. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  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 sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  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')
  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. try:
  131. opts.retries = int(opts.retries)
  132. except (TypeError, ValueError):
  133. parser.error('invalid retry count specified')
  134. if opts.buffersize is not None:
  135. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  136. if numeric_buffersize is None:
  137. parser.error('invalid buffer size specified')
  138. opts.buffersize = numeric_buffersize
  139. if opts.playliststart <= 0:
  140. raise ValueError('Playlist start must be positive')
  141. if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
  142. raise ValueError('Playlist end must be greater than playlist start')
  143. if opts.extractaudio:
  144. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  145. parser.error('invalid audio format specified')
  146. if opts.audioquality:
  147. opts.audioquality = opts.audioquality.strip('k').strip('K')
  148. if not opts.audioquality.isdigit():
  149. parser.error('invalid audio quality specified')
  150. if opts.recodevideo is not None:
  151. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
  152. parser.error('invalid video recode format specified')
  153. if opts.date is not None:
  154. date = DateRange.day(opts.date)
  155. else:
  156. date = DateRange(opts.dateafter, opts.datebefore)
  157. # Do not download videos when there are audio-only formats
  158. if opts.extractaudio and not opts.keepvideo and opts.format is None:
  159. opts.format = 'bestaudio/best'
  160. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  161. # this was the old behaviour if only --all-sub was given.
  162. if opts.allsubtitles and not opts.writeautomaticsub:
  163. opts.writesubtitles = True
  164. if sys.version_info < (3,):
  165. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  166. if opts.outtmpl is not None:
  167. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  168. outtmpl = ((opts.outtmpl is not None and opts.outtmpl)
  169. or (opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s')
  170. or (opts.format == '-1' and '%(id)s-%(format)s.%(ext)s')
  171. or (opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  172. or (opts.usetitle and '%(title)s-%(id)s.%(ext)s')
  173. or (opts.useid and '%(id)s.%(ext)s')
  174. or (opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s')
  175. or DEFAULT_OUTTMPL)
  176. if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
  177. parser.error('Cannot download a video and extract audio into the same'
  178. ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
  179. ' template'.format(outtmpl))
  180. 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
  181. download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
  182. # PostProcessors
  183. postprocessors = []
  184. # Add the metadata pp first, the other pps will copy it
  185. if opts.addmetadata:
  186. postprocessors.append({'key': 'FFmpegMetadata'})
  187. if opts.extractaudio:
  188. postprocessors.append({
  189. 'key': 'FFmpegExtractAudio',
  190. 'preferredcodec': opts.audioformat,
  191. 'preferredquality': opts.audioquality,
  192. 'nopostoverwrites': opts.nopostoverwrites,
  193. })
  194. if opts.recodevideo:
  195. postprocessors.append({
  196. 'key': 'FFmpegVideoConvertor',
  197. 'preferedformat': opts.recodevideo,
  198. })
  199. if opts.embedsubtitles:
  200. postprocessors.append({
  201. 'key': 'FFmpegEmbedSubtitle',
  202. 'subtitlesformat': opts.subtitlesformat,
  203. })
  204. if opts.xattrs:
  205. postprocessors.append({'key': 'XAttrMetadata'})
  206. if opts.embedthumbnail:
  207. if not opts.addmetadata:
  208. postprocessors.append({'key': 'FFmpegAudioFix'})
  209. postprocessors.append({'key': 'AtomicParsley'})
  210. # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
  211. # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
  212. if opts.exec_cmd:
  213. postprocessors.append({
  214. 'key': 'ExecAfterDownload',
  215. 'verboseOutput': opts.verbose,
  216. 'exec_cmd': opts.exec_cmd,
  217. })
  218. ydl_opts = {
  219. 'usenetrc': opts.usenetrc,
  220. 'username': opts.username,
  221. 'password': opts.password,
  222. 'twofactor': opts.twofactor,
  223. 'videopassword': opts.videopassword,
  224. 'quiet': (opts.quiet or any_printing),
  225. 'no_warnings': opts.no_warnings,
  226. 'forceurl': opts.geturl,
  227. 'forcetitle': opts.gettitle,
  228. 'forceid': opts.getid,
  229. 'forcethumbnail': opts.getthumbnail,
  230. 'forcedescription': opts.getdescription,
  231. 'forceduration': opts.getduration,
  232. 'forcefilename': opts.getfilename,
  233. 'forceformat': opts.getformat,
  234. 'forcejson': opts.dumpjson,
  235. 'dump_single_json': opts.dump_single_json,
  236. 'simulate': opts.simulate or any_printing,
  237. 'skip_download': opts.skip_download,
  238. 'format': opts.format,
  239. 'format_limit': opts.format_limit,
  240. 'listformats': opts.listformats,
  241. 'outtmpl': outtmpl,
  242. 'autonumber_size': opts.autonumber_size,
  243. 'restrictfilenames': opts.restrictfilenames,
  244. 'ignoreerrors': opts.ignoreerrors,
  245. 'ratelimit': opts.ratelimit,
  246. 'nooverwrites': opts.nooverwrites,
  247. 'retries': opts.retries,
  248. 'buffersize': opts.buffersize,
  249. 'noresizebuffer': opts.noresizebuffer,
  250. 'continuedl': opts.continue_dl,
  251. 'noprogress': opts.noprogress,
  252. 'progress_with_newline': opts.progress_with_newline,
  253. 'playliststart': opts.playliststart,
  254. 'playlistend': opts.playlistend,
  255. 'playlistreverse': opts.playlist_reverse,
  256. 'noplaylist': opts.noplaylist,
  257. 'logtostderr': opts.outtmpl == '-',
  258. 'consoletitle': opts.consoletitle,
  259. 'nopart': opts.nopart,
  260. 'updatetime': opts.updatetime,
  261. 'writedescription': opts.writedescription,
  262. 'writeannotations': opts.writeannotations,
  263. 'writeinfojson': opts.writeinfojson,
  264. 'writethumbnail': opts.writethumbnail,
  265. 'writesubtitles': opts.writesubtitles,
  266. 'writeautomaticsub': opts.writeautomaticsub,
  267. 'allsubtitles': opts.allsubtitles,
  268. 'listsubtitles': opts.listsubtitles,
  269. 'subtitlesformat': opts.subtitlesformat,
  270. 'subtitleslangs': opts.subtitleslangs,
  271. 'matchtitle': decodeOption(opts.matchtitle),
  272. 'rejecttitle': decodeOption(opts.rejecttitle),
  273. 'max_downloads': opts.max_downloads,
  274. 'prefer_free_formats': opts.prefer_free_formats,
  275. 'verbose': opts.verbose,
  276. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  277. 'write_pages': opts.write_pages,
  278. 'test': opts.test,
  279. 'keepvideo': opts.keepvideo,
  280. 'min_filesize': opts.min_filesize,
  281. 'max_filesize': opts.max_filesize,
  282. 'min_views': opts.min_views,
  283. 'max_views': opts.max_views,
  284. 'daterange': date,
  285. 'cachedir': opts.cachedir,
  286. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  287. 'age_limit': opts.age_limit,
  288. 'download_archive': download_archive_fn,
  289. 'cookiefile': opts.cookiefile,
  290. 'nocheckcertificate': opts.no_check_certificate,
  291. 'prefer_insecure': opts.prefer_insecure,
  292. 'proxy': opts.proxy,
  293. 'socket_timeout': opts.socket_timeout,
  294. 'bidi_workaround': opts.bidi_workaround,
  295. 'debug_printtraffic': opts.debug_printtraffic,
  296. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  297. 'include_ads': opts.include_ads,
  298. 'default_search': opts.default_search,
  299. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  300. 'encoding': opts.encoding,
  301. 'exec_cmd': opts.exec_cmd,
  302. 'extract_flat': opts.extract_flat,
  303. 'postprocessors': postprocessors,
  304. }
  305. with YoutubeDL(ydl_opts) as ydl:
  306. # Update version
  307. if opts.update_self:
  308. update_self(ydl.to_screen, opts.verbose)
  309. # Remove cache dir
  310. if opts.rm_cachedir:
  311. ydl.cache.remove()
  312. # Maybe do nothing
  313. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  314. if opts.update_self or opts.rm_cachedir:
  315. sys.exit()
  316. ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
  317. parser.error('you must provide at least one URL')
  318. try:
  319. if opts.load_info_filename is not None:
  320. retcode = ydl.download_with_info_file(opts.load_info_filename)
  321. else:
  322. retcode = ydl.download(all_urls)
  323. except MaxDownloadsReached:
  324. ydl.to_screen('--max-download limit reached, aborting.')
  325. retcode = 101
  326. sys.exit(retcode)
  327. def main(argv=None):
  328. try:
  329. _real_main(argv)
  330. except DownloadError:
  331. sys.exit(1)
  332. except SameFileError:
  333. sys.exit('ERROR: fixed output name but more than one file to download')
  334. except KeyboardInterrupt:
  335. sys.exit('\nERROR: Interrupted by user')