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.

373 lines
15 KiB

10 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, 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_getting = 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. any_printing = opts.print_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_getting 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 or opts.print_json,
  235. 'dump_single_json': opts.dump_single_json,
  236. 'simulate': opts.simulate or any_getting,
  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. 'merge_output_format': opts.merge_output_format,
  304. 'postprocessors': postprocessors,
  305. 'fixup': opts.fixup,
  306. 'source_address': opts.source_address,
  307. 'call_home': opts.call_home,
  308. }
  309. with YoutubeDL(ydl_opts) as ydl:
  310. # Update version
  311. if opts.update_self:
  312. update_self(ydl.to_screen, opts.verbose)
  313. # Remove cache dir
  314. if opts.rm_cachedir:
  315. ydl.cache.remove()
  316. # Maybe do nothing
  317. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  318. if opts.update_self or opts.rm_cachedir:
  319. sys.exit()
  320. ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
  321. parser.error('you must provide at least one URL')
  322. try:
  323. if opts.load_info_filename is not None:
  324. retcode = ydl.download_with_info_file(opts.load_info_filename)
  325. else:
  326. retcode = ydl.download(all_urls)
  327. except MaxDownloadsReached:
  328. ydl.to_screen('--max-download limit reached, aborting.')
  329. retcode = 101
  330. sys.exit(retcode)
  331. def main(argv=None):
  332. try:
  333. _real_main(argv)
  334. except DownloadError:
  335. sys.exit(1)
  336. except SameFileError:
  337. sys.exit('ERROR: fixed output name but more than one file to download')
  338. except KeyboardInterrupt:
  339. sys.exit('\nERROR: Interrupted by user')
  340. __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']