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.

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