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.

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