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.

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