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.

357 lines
14 KiB

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