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.

355 lines
14 KiB

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