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.

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