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.

434 lines
16 KiB

13 years ago
12 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
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. 'Hari Padmanaban',
  78. )
  79. __license__ = 'Public Domain'
  80. import codecs
  81. import io
  82. import os
  83. import random
  84. import sys
  85. from .options import (
  86. parseOpts,
  87. )
  88. from .utils import (
  89. compat_getpass,
  90. compat_print,
  91. DateRange,
  92. DEFAULT_OUTTMPL,
  93. decodeOption,
  94. DownloadError,
  95. MaxDownloadsReached,
  96. preferredencoding,
  97. read_batch_urls,
  98. SameFileError,
  99. setproctitle,
  100. std_headers,
  101. write_string,
  102. )
  103. from .update import update_self
  104. from .downloader import (
  105. FileDownloader,
  106. )
  107. from .extractor import gen_extractors
  108. from .YoutubeDL import YoutubeDL
  109. from .postprocessor import (
  110. AtomicParsleyPP,
  111. FFmpegAudioFixPP,
  112. FFmpegMetadataPP,
  113. FFmpegVideoConvertor,
  114. FFmpegExtractAudioPP,
  115. FFmpegEmbedSubtitlePP,
  116. XAttrMetadataPP,
  117. ExecAfterDownloadPP,
  118. )
  119. def _real_main(argv=None):
  120. # Compatibility fixes for Windows
  121. if sys.platform == 'win32':
  122. # https://github.com/rg3/youtube-dl/issues/820
  123. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
  124. setproctitle(u'youtube-dl')
  125. parser, opts, args = parseOpts(argv)
  126. # Set user agent
  127. if opts.user_agent is not None:
  128. std_headers['User-Agent'] = opts.user_agent
  129. # Set referer
  130. if opts.referer is not None:
  131. std_headers['Referer'] = opts.referer
  132. # Custom HTTP headers
  133. if opts.headers is not None:
  134. for h in opts.headers:
  135. if h.find(':', 1) < 0:
  136. parser.error(u'wrong header formatting, it should be key:value, not "%s"'%h)
  137. key, value = h.split(':', 2)
  138. if opts.verbose:
  139. write_string(u'[debug] Adding header from command line option %s:%s\n'%(key, value))
  140. std_headers[key] = value
  141. # Dump user agent
  142. if opts.dump_user_agent:
  143. compat_print(std_headers['User-Agent'])
  144. sys.exit(0)
  145. # Batch file verification
  146. batch_urls = []
  147. if opts.batchfile is not None:
  148. try:
  149. if opts.batchfile == '-':
  150. batchfd = sys.stdin
  151. else:
  152. batchfd = io.open(opts.batchfile, 'r', encoding='utf-8', errors='ignore')
  153. batch_urls = read_batch_urls(batchfd)
  154. if opts.verbose:
  155. write_string(u'[debug] Batch file urls: ' + repr(batch_urls) + u'\n')
  156. except IOError:
  157. sys.exit(u'ERROR: batch file could not be read')
  158. all_urls = batch_urls + args
  159. all_urls = [url.strip() for url in all_urls]
  160. _enc = preferredencoding()
  161. all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
  162. extractors = gen_extractors()
  163. if opts.list_extractors:
  164. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  165. compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  166. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  167. for mu in matchedUrls:
  168. compat_print(u' ' + mu)
  169. sys.exit(0)
  170. if opts.list_extractor_descriptions:
  171. for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
  172. if not ie._WORKING:
  173. continue
  174. desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
  175. if desc is False:
  176. continue
  177. if hasattr(ie, 'SEARCH_KEY'):
  178. _SEARCHES = (u'cute kittens', u'slithering pythons', u'falling cat', u'angry poodle', u'purple fish', u'running tortoise', u'sleeping bunny')
  179. _COUNTS = (u'', u'5', u'10', u'all')
  180. desc += u' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
  181. compat_print(desc)
  182. sys.exit(0)
  183. # Conflicting, missing and erroneous options
  184. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  185. parser.error(u'using .netrc conflicts with giving username/password')
  186. if opts.password is not None and opts.username is None:
  187. parser.error(u'account username missing\n')
  188. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  189. parser.error(u'using output template conflicts with using title, video ID or auto number')
  190. if opts.usetitle and opts.useid:
  191. parser.error(u'using title conflicts with using video ID')
  192. if opts.username is not None and opts.password is None:
  193. opts.password = compat_getpass(u'Type account password and press [Return]: ')
  194. if opts.ratelimit is not None:
  195. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  196. if numeric_limit is None:
  197. parser.error(u'invalid rate limit specified')
  198. opts.ratelimit = numeric_limit
  199. if opts.min_filesize is not None:
  200. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  201. if numeric_limit is None:
  202. parser.error(u'invalid min_filesize specified')
  203. opts.min_filesize = numeric_limit
  204. if opts.max_filesize is not None:
  205. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  206. if numeric_limit is None:
  207. parser.error(u'invalid max_filesize specified')
  208. opts.max_filesize = numeric_limit
  209. if opts.retries is not None:
  210. try:
  211. opts.retries = int(opts.retries)
  212. except (TypeError, ValueError):
  213. parser.error(u'invalid retry count specified')
  214. if opts.buffersize is not None:
  215. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  216. if numeric_buffersize is None:
  217. parser.error(u'invalid buffer size specified')
  218. opts.buffersize = numeric_buffersize
  219. if opts.playliststart <= 0:
  220. raise ValueError(u'Playlist start must be positive')
  221. if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
  222. raise ValueError(u'Playlist end must be greater than playlist start')
  223. if opts.extractaudio:
  224. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  225. parser.error(u'invalid audio format specified')
  226. if opts.audioquality:
  227. opts.audioquality = opts.audioquality.strip('k').strip('K')
  228. if not opts.audioquality.isdigit():
  229. parser.error(u'invalid audio quality specified')
  230. if opts.recodevideo is not None:
  231. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
  232. parser.error(u'invalid video recode format specified')
  233. if opts.date is not None:
  234. date = DateRange.day(opts.date)
  235. else:
  236. date = DateRange(opts.dateafter, opts.datebefore)
  237. if opts.default_search not in ('auto', 'auto_warning', 'error', 'fixup_error', None) and ':' not in opts.default_search:
  238. parser.error(u'--default-search invalid; did you forget a colon (:) at the end?')
  239. # Do not download videos when there are audio-only formats
  240. if opts.extractaudio and not opts.keepvideo and opts.format is None:
  241. opts.format = 'bestaudio/best'
  242. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  243. # this was the old behaviour if only --all-sub was given.
  244. if opts.allsubtitles and (opts.writeautomaticsub == False):
  245. opts.writesubtitles = True
  246. if sys.version_info < (3,):
  247. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  248. if opts.outtmpl is not None:
  249. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  250. outtmpl =((opts.outtmpl is not None and opts.outtmpl)
  251. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  252. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  253. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  254. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  255. or (opts.useid and u'%(id)s.%(ext)s')
  256. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  257. or DEFAULT_OUTTMPL)
  258. if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
  259. parser.error(u'Cannot download a video and extract audio into the same'
  260. u' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
  261. u' template'.format(outtmpl))
  262. 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
  263. download_archive_fn = os.path.expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
  264. ydl_opts = {
  265. 'usenetrc': opts.usenetrc,
  266. 'username': opts.username,
  267. 'password': opts.password,
  268. 'twofactor': opts.twofactor,
  269. 'videopassword': opts.videopassword,
  270. 'quiet': (opts.quiet or any_printing),
  271. 'no_warnings': opts.no_warnings,
  272. 'forceurl': opts.geturl,
  273. 'forcetitle': opts.gettitle,
  274. 'forceid': opts.getid,
  275. 'forcethumbnail': opts.getthumbnail,
  276. 'forcedescription': opts.getdescription,
  277. 'forceduration': opts.getduration,
  278. 'forcefilename': opts.getfilename,
  279. 'forceformat': opts.getformat,
  280. 'forcejson': opts.dumpjson,
  281. 'simulate': opts.simulate,
  282. 'skip_download': (opts.skip_download or opts.simulate or any_printing),
  283. 'format': opts.format,
  284. 'format_limit': opts.format_limit,
  285. 'listformats': opts.listformats,
  286. 'outtmpl': outtmpl,
  287. 'autonumber_size': opts.autonumber_size,
  288. 'restrictfilenames': opts.restrictfilenames,
  289. 'ignoreerrors': opts.ignoreerrors,
  290. 'ratelimit': opts.ratelimit,
  291. 'nooverwrites': opts.nooverwrites,
  292. 'retries': opts.retries,
  293. 'buffersize': opts.buffersize,
  294. 'noresizebuffer': opts.noresizebuffer,
  295. 'continuedl': opts.continue_dl,
  296. 'noprogress': opts.noprogress,
  297. 'progress_with_newline': opts.progress_with_newline,
  298. 'playliststart': opts.playliststart,
  299. 'playlistend': opts.playlistend,
  300. 'noplaylist': opts.noplaylist,
  301. 'logtostderr': opts.outtmpl == '-',
  302. 'consoletitle': opts.consoletitle,
  303. 'nopart': opts.nopart,
  304. 'updatetime': opts.updatetime,
  305. 'writedescription': opts.writedescription,
  306. 'writeannotations': opts.writeannotations,
  307. 'writeinfojson': opts.writeinfojson,
  308. 'writethumbnail': opts.writethumbnail,
  309. 'writesubtitles': opts.writesubtitles,
  310. 'writeautomaticsub': opts.writeautomaticsub,
  311. 'allsubtitles': opts.allsubtitles,
  312. 'listsubtitles': opts.listsubtitles,
  313. 'subtitlesformat': opts.subtitlesformat,
  314. 'subtitleslangs': opts.subtitleslangs,
  315. 'matchtitle': decodeOption(opts.matchtitle),
  316. 'rejecttitle': decodeOption(opts.rejecttitle),
  317. 'max_downloads': opts.max_downloads,
  318. 'prefer_free_formats': opts.prefer_free_formats,
  319. 'verbose': opts.verbose,
  320. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  321. 'write_pages': opts.write_pages,
  322. 'test': opts.test,
  323. 'keepvideo': opts.keepvideo,
  324. 'min_filesize': opts.min_filesize,
  325. 'max_filesize': opts.max_filesize,
  326. 'min_views': opts.min_views,
  327. 'max_views': opts.max_views,
  328. 'daterange': date,
  329. 'cachedir': opts.cachedir,
  330. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  331. 'age_limit': opts.age_limit,
  332. 'download_archive': download_archive_fn,
  333. 'cookiefile': opts.cookiefile,
  334. 'nocheckcertificate': opts.no_check_certificate,
  335. 'prefer_insecure': opts.prefer_insecure,
  336. 'proxy': opts.proxy,
  337. 'socket_timeout': opts.socket_timeout,
  338. 'bidi_workaround': opts.bidi_workaround,
  339. 'debug_printtraffic': opts.debug_printtraffic,
  340. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  341. 'include_ads': opts.include_ads,
  342. 'default_search': opts.default_search,
  343. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  344. 'encoding': opts.encoding,
  345. 'exec_cmd': opts.exec_cmd,
  346. }
  347. with YoutubeDL(ydl_opts) as ydl:
  348. ydl.print_debug_header()
  349. ydl.add_default_info_extractors()
  350. # PostProcessors
  351. # Add the metadata pp first, the other pps will copy it
  352. if opts.addmetadata:
  353. ydl.add_post_processor(FFmpegMetadataPP())
  354. if opts.extractaudio:
  355. ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
  356. if opts.recodevideo:
  357. ydl.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
  358. if opts.embedsubtitles:
  359. ydl.add_post_processor(FFmpegEmbedSubtitlePP(subtitlesformat=opts.subtitlesformat))
  360. if opts.xattrs:
  361. ydl.add_post_processor(XAttrMetadataPP())
  362. if opts.embedthumbnail:
  363. if not opts.addmetadata:
  364. ydl.add_post_processor(FFmpegAudioFixPP())
  365. ydl.add_post_processor(AtomicParsleyPP())
  366. # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
  367. # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
  368. if opts.exec_cmd:
  369. ydl.add_post_processor(ExecAfterDownloadPP(
  370. verboseOutput=opts.verbose, exec_cmd=opts.exec_cmd))
  371. # Update version
  372. if opts.update_self:
  373. update_self(ydl.to_screen, opts.verbose)
  374. # Remove cache dir
  375. if opts.rm_cachedir:
  376. ydl.cache.remove()
  377. # Maybe do nothing
  378. if (len(all_urls) < 1) and (opts.load_info_filename is None):
  379. if not (opts.update_self or opts.rm_cachedir):
  380. parser.error(u'you must provide at least one URL')
  381. else:
  382. sys.exit()
  383. try:
  384. if opts.load_info_filename is not None:
  385. retcode = ydl.download_with_info_file(opts.load_info_filename)
  386. else:
  387. retcode = ydl.download(all_urls)
  388. except MaxDownloadsReached:
  389. ydl.to_screen(u'--max-download limit reached, aborting.')
  390. retcode = 101
  391. sys.exit(retcode)
  392. def main(argv=None):
  393. try:
  394. _real_main(argv)
  395. except DownloadError:
  396. sys.exit(1)
  397. except SameFileError:
  398. sys.exit(u'ERROR: fixed output name but more than one file to download')
  399. except KeyboardInterrupt:
  400. sys.exit(u'\nERROR: Interrupted by user')