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.

433 lines
16 KiB

13 years ago
12 years ago
11 years ago
10 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
11 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. __authors__ = (
  4. 'Ricardo Garcia Gonzalez',
  5. 'Danny Colligan',
  6. 'Benjamin Johnson',
  7. 'Vasyl\' Vavrychuk',
  8. 'Witold Baryluk',
  9. 'Paweł Paprota',
  10. 'Gergely Imreh',
  11. 'Rogério Brito',
  12. 'Philipp Hagemeister',
  13. 'Sören Schulze',
  14. 'Kevin Ngo',
  15. 'Ori Avtalion',
  16. 'shizeeg',
  17. 'Filippo Valsorda',
  18. 'Christian Albrecht',
  19. 'Dave Vasilevsky',
  20. 'Jaime Marquínez Ferrándiz',
  21. 'Jeff Crouse',
  22. 'Osama Khalid',
  23. 'Michael Walter',
  24. 'M. Yasoob Ullah Khalid',
  25. 'Julien Fraichard',
  26. 'Johny Mo Swag',
  27. 'Axel Noack',
  28. 'Albert Kim',
  29. 'Pierre Rudloff',
  30. 'Huarong Huo',
  31. 'Ismael Mejía',
  32. 'Steffan \'Ruirize\' James',
  33. 'Andras Elso',
  34. 'Jelle van der Waa',
  35. 'Marcin Cieślak',
  36. 'Anton Larionov',
  37. 'Takuya Tsuchida',
  38. 'Sergey M.',
  39. 'Michael Orlitzky',
  40. 'Chris Gahan',
  41. 'Saimadhav Heblikar',
  42. 'Mike Col',
  43. 'Oleg Prutz',
  44. 'pulpe',
  45. 'Andreas Schmitz',
  46. 'Michael Kaiser',
  47. 'Niklas Laxström',
  48. 'David Triendl',
  49. 'Anthony Weems',
  50. 'David Wagner',
  51. 'Juan C. Olivares',
  52. 'Mattias Harrysson',
  53. 'phaer',
  54. 'Sainyam Kapoor',
  55. 'Nicolas Évrard',
  56. 'Jason Normore',
  57. 'Hoje Lee',
  58. 'Adam Thalhammer',
  59. 'Georg Jähnig',
  60. 'Ralf Haring',
  61. 'Koki Takahashi',
  62. 'Ariset Llerena',
  63. 'Adam Malcontenti-Wilson',
  64. 'Tobias Bell',
  65. 'Naglis Jonaitis',
  66. 'Charles Chen',
  67. 'Hassaan Ali',
  68. 'Dobrosław Żybort',
  69. 'David Fabijan',
  70. 'Sebastian Haas',
  71. 'Alexander Kirk',
  72. 'Erik Johnson',
  73. 'Keith Beckman',
  74. 'Ole Ernst',
  75. 'Aaron McDaniel (mcd1992)',
  76. 'Magnus Kolstad',
  77. )
  78. __license__ = 'Public Domain'
  79. import codecs
  80. import io
  81. import os
  82. import random
  83. import sys
  84. from .options import (
  85. parseOpts,
  86. )
  87. from .utils import (
  88. compat_getpass,
  89. compat_print,
  90. DateRange,
  91. DEFAULT_OUTTMPL,
  92. decodeOption,
  93. DownloadError,
  94. MaxDownloadsReached,
  95. preferredencoding,
  96. read_batch_urls,
  97. SameFileError,
  98. setproctitle,
  99. std_headers,
  100. write_string,
  101. )
  102. from .update import update_self
  103. from .downloader import (
  104. FileDownloader,
  105. )
  106. from .extractor import gen_extractors
  107. from .YoutubeDL import YoutubeDL
  108. from .postprocessor import (
  109. AtomicParsleyPP,
  110. FFmpegAudioFixPP,
  111. FFmpegMetadataPP,
  112. FFmpegVideoConvertor,
  113. FFmpegExtractAudioPP,
  114. FFmpegEmbedSubtitlePP,
  115. XAttrMetadataPP,
  116. ExecAfterDownloadPP,
  117. )
  118. def _real_main(argv=None):
  119. # Compatibility fixes for Windows
  120. if sys.platform == 'win32':
  121. # https://github.com/rg3/youtube-dl/issues/820
  122. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
  123. setproctitle(u'youtube-dl')
  124. parser, opts, args = parseOpts(argv)
  125. # Set user agent
  126. if opts.user_agent is not None:
  127. std_headers['User-Agent'] = opts.user_agent
  128. # Set referer
  129. if opts.referer is not None:
  130. std_headers['Referer'] = opts.referer
  131. # Custom HTTP headers
  132. if opts.headers is not None:
  133. for h in opts.headers:
  134. if h.find(':', 1) < 0:
  135. parser.error(u'wrong header formatting, it should be key:value, not "%s"'%h)
  136. key, value = h.split(':', 2)
  137. if opts.verbose:
  138. write_string(u'[debug] Adding header from command line option %s:%s\n'%(key, value))
  139. std_headers[key] = value
  140. # Dump user agent
  141. if opts.dump_user_agent:
  142. compat_print(std_headers['User-Agent'])
  143. sys.exit(0)
  144. # Batch file verification
  145. batch_urls = []
  146. if opts.batchfile is not None:
  147. try:
  148. if opts.batchfile == '-':
  149. batchfd = sys.stdin
  150. else:
  151. batchfd = io.open(opts.batchfile, 'r', encoding='utf-8', errors='ignore')
  152. batch_urls = read_batch_urls(batchfd)
  153. if opts.verbose:
  154. write_string(u'[debug] Batch file urls: ' + repr(batch_urls) + u'\n')
  155. except IOError:
  156. sys.exit(u'ERROR: batch file could not be read')
  157. all_urls = batch_urls + args
  158. all_urls = [url.strip() for url in all_urls]
  159. _enc = preferredencoding()
  160. all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
  161. extractors = gen_extractors()
  162. if opts.list_extractors:
  163. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  164. compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  165. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  166. for mu in matchedUrls:
  167. compat_print(u' ' + mu)
  168. sys.exit(0)
  169. if opts.list_extractor_descriptions:
  170. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  171. if not ie._WORKING:
  172. continue
  173. desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
  174. if desc is False:
  175. continue
  176. if hasattr(ie, 'SEARCH_KEY'):
  177. _SEARCHES = (u'cute kittens', u'slithering pythons', u'falling cat', u'angry poodle', u'purple fish', u'running tortoise', u'sleeping bunny')
  178. _COUNTS = (u'', u'5', u'10', u'all')
  179. desc += u' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
  180. compat_print(desc)
  181. sys.exit(0)
  182. # Conflicting, missing and erroneous options
  183. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  184. parser.error(u'using .netrc conflicts with giving username/password')
  185. if opts.password is not None and opts.username is None:
  186. parser.error(u'account username missing\n')
  187. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  188. parser.error(u'using output template conflicts with using title, video ID or auto number')
  189. if opts.usetitle and opts.useid:
  190. parser.error(u'using title conflicts with using video ID')
  191. if opts.username is not None and opts.password is None:
  192. opts.password = compat_getpass(u'Type account password and press [Return]: ')
  193. if opts.ratelimit is not None:
  194. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  195. if numeric_limit is None:
  196. parser.error(u'invalid rate limit specified')
  197. opts.ratelimit = numeric_limit
  198. if opts.min_filesize is not None:
  199. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  200. if numeric_limit is None:
  201. parser.error(u'invalid min_filesize specified')
  202. opts.min_filesize = numeric_limit
  203. if opts.max_filesize is not None:
  204. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  205. if numeric_limit is None:
  206. parser.error(u'invalid max_filesize specified')
  207. opts.max_filesize = numeric_limit
  208. if opts.retries is not None:
  209. try:
  210. opts.retries = int(opts.retries)
  211. except (TypeError, ValueError):
  212. parser.error(u'invalid retry count specified')
  213. if opts.buffersize is not None:
  214. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  215. if numeric_buffersize is None:
  216. parser.error(u'invalid buffer size specified')
  217. opts.buffersize = numeric_buffersize
  218. if opts.playliststart <= 0:
  219. raise ValueError(u'Playlist start must be positive')
  220. if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
  221. raise ValueError(u'Playlist end must be greater than playlist start')
  222. if opts.extractaudio:
  223. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  224. parser.error(u'invalid audio format specified')
  225. if opts.audioquality:
  226. opts.audioquality = opts.audioquality.strip('k').strip('K')
  227. if not opts.audioquality.isdigit():
  228. parser.error(u'invalid audio quality specified')
  229. if opts.recodevideo is not None:
  230. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
  231. parser.error(u'invalid video recode format specified')
  232. if opts.date is not None:
  233. date = DateRange.day(opts.date)
  234. else:
  235. date = DateRange(opts.dateafter, opts.datebefore)
  236. if opts.default_search not in ('auto', 'auto_warning', 'error', 'fixup_error', None) and ':' not in opts.default_search:
  237. parser.error(u'--default-search invalid; did you forget a colon (:) at the end?')
  238. # Do not download videos when there are audio-only formats
  239. if opts.extractaudio and not opts.keepvideo and opts.format is None:
  240. opts.format = 'bestaudio/best'
  241. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  242. # this was the old behaviour if only --all-sub was given.
  243. if opts.allsubtitles and (opts.writeautomaticsub == False):
  244. opts.writesubtitles = True
  245. if sys.version_info < (3,):
  246. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  247. if opts.outtmpl is not None:
  248. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  249. outtmpl =((opts.outtmpl is not None and opts.outtmpl)
  250. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  251. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  252. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  253. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  254. or (opts.useid and u'%(id)s.%(ext)s')
  255. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  256. or DEFAULT_OUTTMPL)
  257. if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
  258. parser.error(u'Cannot download a video and extract audio into the same'
  259. u' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
  260. u' template'.format(outtmpl))
  261. 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
  262. download_archive_fn = os.path.expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
  263. ydl_opts = {
  264. 'usenetrc': opts.usenetrc,
  265. 'username': opts.username,
  266. 'password': opts.password,
  267. 'twofactor': opts.twofactor,
  268. 'videopassword': opts.videopassword,
  269. 'quiet': (opts.quiet or any_printing),
  270. 'no_warnings': opts.no_warnings,
  271. 'forceurl': opts.geturl,
  272. 'forcetitle': opts.gettitle,
  273. 'forceid': opts.getid,
  274. 'forcethumbnail': opts.getthumbnail,
  275. 'forcedescription': opts.getdescription,
  276. 'forceduration': opts.getduration,
  277. 'forcefilename': opts.getfilename,
  278. 'forceformat': opts.getformat,
  279. 'forcejson': opts.dumpjson,
  280. 'simulate': opts.simulate,
  281. 'skip_download': (opts.skip_download or opts.simulate or any_printing),
  282. 'format': opts.format,
  283. 'format_limit': opts.format_limit,
  284. 'listformats': opts.listformats,
  285. 'outtmpl': outtmpl,
  286. 'autonumber_size': opts.autonumber_size,
  287. 'restrictfilenames': opts.restrictfilenames,
  288. 'ignoreerrors': opts.ignoreerrors,
  289. 'ratelimit': opts.ratelimit,
  290. 'nooverwrites': opts.nooverwrites,
  291. 'retries': opts.retries,
  292. 'buffersize': opts.buffersize,
  293. 'noresizebuffer': opts.noresizebuffer,
  294. 'continuedl': opts.continue_dl,
  295. 'noprogress': opts.noprogress,
  296. 'progress_with_newline': opts.progress_with_newline,
  297. 'playliststart': opts.playliststart,
  298. 'playlistend': opts.playlistend,
  299. 'noplaylist': opts.noplaylist,
  300. 'logtostderr': opts.outtmpl == '-',
  301. 'consoletitle': opts.consoletitle,
  302. 'nopart': opts.nopart,
  303. 'updatetime': opts.updatetime,
  304. 'writedescription': opts.writedescription,
  305. 'writeannotations': opts.writeannotations,
  306. 'writeinfojson': opts.writeinfojson,
  307. 'writethumbnail': opts.writethumbnail,
  308. 'writesubtitles': opts.writesubtitles,
  309. 'writeautomaticsub': opts.writeautomaticsub,
  310. 'allsubtitles': opts.allsubtitles,
  311. 'listsubtitles': opts.listsubtitles,
  312. 'subtitlesformat': opts.subtitlesformat,
  313. 'subtitleslangs': opts.subtitleslangs,
  314. 'matchtitle': decodeOption(opts.matchtitle),
  315. 'rejecttitle': decodeOption(opts.rejecttitle),
  316. 'max_downloads': opts.max_downloads,
  317. 'prefer_free_formats': opts.prefer_free_formats,
  318. 'verbose': opts.verbose,
  319. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  320. 'write_pages': opts.write_pages,
  321. 'test': opts.test,
  322. 'keepvideo': opts.keepvideo,
  323. 'min_filesize': opts.min_filesize,
  324. 'max_filesize': opts.max_filesize,
  325. 'min_views': opts.min_views,
  326. 'max_views': opts.max_views,
  327. 'daterange': date,
  328. 'cachedir': opts.cachedir,
  329. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  330. 'age_limit': opts.age_limit,
  331. 'download_archive': download_archive_fn,
  332. 'cookiefile': opts.cookiefile,
  333. 'nocheckcertificate': opts.no_check_certificate,
  334. 'prefer_insecure': opts.prefer_insecure,
  335. 'proxy': opts.proxy,
  336. 'socket_timeout': opts.socket_timeout,
  337. 'bidi_workaround': opts.bidi_workaround,
  338. 'debug_printtraffic': opts.debug_printtraffic,
  339. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  340. 'include_ads': opts.include_ads,
  341. 'default_search': opts.default_search,
  342. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  343. 'encoding': opts.encoding,
  344. 'exec_cmd': opts.exec_cmd,
  345. }
  346. with YoutubeDL(ydl_opts) as ydl:
  347. ydl.print_debug_header()
  348. ydl.add_default_info_extractors()
  349. # PostProcessors
  350. # Add the metadata pp first, the other pps will copy it
  351. if opts.addmetadata:
  352. ydl.add_post_processor(FFmpegMetadataPP())
  353. if opts.extractaudio:
  354. ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
  355. if opts.recodevideo:
  356. ydl.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
  357. if opts.embedsubtitles:
  358. ydl.add_post_processor(FFmpegEmbedSubtitlePP(subtitlesformat=opts.subtitlesformat))
  359. if opts.xattrs:
  360. ydl.add_post_processor(XAttrMetadataPP())
  361. if opts.embedthumbnail:
  362. if not opts.addmetadata:
  363. ydl.add_post_processor(FFmpegAudioFixPP())
  364. ydl.add_post_processor(AtomicParsleyPP())
  365. # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
  366. # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
  367. if opts.exec_cmd:
  368. ydl.add_post_processor(ExecAfterDownloadPP(
  369. verboseOutput=opts.verbose, exec_cmd=opts.exec_cmd))
  370. # Update version
  371. if opts.update_self:
  372. update_self(ydl.to_screen, opts.verbose)
  373. # Remove cache dir
  374. if opts.rm_cachedir:
  375. ydl.cache.remove()
  376. # Maybe do nothing
  377. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  378. if not (opts.update_self or opts.rm_cachedir):
  379. parser.error(u'you must provide at least one URL')
  380. else:
  381. sys.exit()
  382. try:
  383. if opts.load_info_filename is not None:
  384. retcode = ydl.download_with_info_file(opts.load_info_filename)
  385. else:
  386. retcode = ydl.download(all_urls)
  387. except MaxDownloadsReached:
  388. ydl.to_screen(u'--max-download limit reached, aborting.')
  389. retcode = 101
  390. sys.exit(retcode)
  391. def main(argv=None):
  392. try:
  393. _real_main(argv)
  394. except DownloadError:
  395. sys.exit(1)
  396. except SameFileError:
  397. sys.exit(u'ERROR: fixed output name but more than one file to download')
  398. except KeyboardInterrupt:
  399. sys.exit(u'\nERROR: Interrupted by user')