YoutubeDL.py 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import contextlib
  6. import datetime
  7. import errno
  8. import fileinput
  9. import io
  10. import itertools
  11. import json
  12. import locale
  13. import operator
  14. import os
  15. import platform
  16. import re
  17. import shutil
  18. import subprocess
  19. import socket
  20. import sys
  21. import time
  22. import tokenize
  23. import traceback
  24. if os.name == 'nt':
  25. import ctypes
  26. from .compat import (
  27. compat_basestring,
  28. compat_cookiejar,
  29. compat_expanduser,
  30. compat_get_terminal_size,
  31. compat_http_client,
  32. compat_kwargs,
  33. compat_str,
  34. compat_tokenize_tokenize,
  35. compat_urllib_error,
  36. compat_urllib_request,
  37. compat_urllib_request_DataHandler,
  38. )
  39. from .utils import (
  40. ContentTooShortError,
  41. date_from_str,
  42. DateRange,
  43. DEFAULT_OUTTMPL,
  44. determine_ext,
  45. DownloadError,
  46. encodeFilename,
  47. error_to_str,
  48. ExtractorError,
  49. format_bytes,
  50. formatSeconds,
  51. locked_file,
  52. make_HTTPS_handler,
  53. MaxDownloadsReached,
  54. PagedList,
  55. parse_filesize,
  56. PerRequestProxyHandler,
  57. PostProcessingError,
  58. platform_name,
  59. preferredencoding,
  60. render_table,
  61. SameFileError,
  62. sanitize_filename,
  63. sanitize_path,
  64. sanitized_Request,
  65. std_headers,
  66. subtitles_filename,
  67. UnavailableVideoError,
  68. url_basename,
  69. version_tuple,
  70. write_json_file,
  71. write_string,
  72. YoutubeDLCookieProcessor,
  73. YoutubeDLHandler,
  74. prepend_extension,
  75. replace_extension,
  76. args_to_str,
  77. age_restricted,
  78. )
  79. from .cache import Cache
  80. from .extractor import get_info_extractor, gen_extractors
  81. from .downloader import get_suitable_downloader
  82. from .downloader.rtmp import rtmpdump_version
  83. from .postprocessor import (
  84. FFmpegFixupM4aPP,
  85. FFmpegFixupStretchedPP,
  86. FFmpegMergerPP,
  87. FFmpegPostProcessor,
  88. get_postprocessor,
  89. )
  90. from .version import __version__
  91. class YoutubeDL(object):
  92. """YoutubeDL class.
  93. YoutubeDL objects are the ones responsible of downloading the
  94. actual video file and writing it to disk if the user has requested
  95. it, among some other tasks. In most cases there should be one per
  96. program. As, given a video URL, the downloader doesn't know how to
  97. extract all the needed information, task that InfoExtractors do, it
  98. has to pass the URL to one of them.
  99. For this, YoutubeDL objects have a method that allows
  100. InfoExtractors to be registered in a given order. When it is passed
  101. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  102. finds that reports being able to handle it. The InfoExtractor extracts
  103. all the information about the video or videos the URL refers to, and
  104. YoutubeDL process the extracted information, possibly using a File
  105. Downloader to download the video.
  106. YoutubeDL objects accept a lot of parameters. In order not to saturate
  107. the object constructor with arguments, it receives a dictionary of
  108. options instead. These options are available through the params
  109. attribute for the InfoExtractors to use. The YoutubeDL also
  110. registers itself as the downloader in charge for the InfoExtractors
  111. that are added to it, so this is a "mutual registration".
  112. Available options:
  113. username: Username for authentication purposes.
  114. password: Password for authentication purposes.
  115. videopassword: Password for accessing a video.
  116. usenetrc: Use netrc for authentication instead.
  117. verbose: Print additional info to stdout.
  118. quiet: Do not print messages to stdout.
  119. no_warnings: Do not print out anything for warnings.
  120. forceurl: Force printing final URL.
  121. forcetitle: Force printing title.
  122. forceid: Force printing ID.
  123. forcethumbnail: Force printing thumbnail URL.
  124. forcedescription: Force printing description.
  125. forcefilename: Force printing final filename.
  126. forceduration: Force printing duration.
  127. forcejson: Force printing info_dict as JSON.
  128. dump_single_json: Force printing the info_dict of the whole playlist
  129. (or video) as a single JSON line.
  130. simulate: Do not download the video files.
  131. format: Video format code. See options.py for more information.
  132. outtmpl: Template for output names.
  133. restrictfilenames: Do not allow "&" and spaces in file names
  134. ignoreerrors: Do not stop on download errors.
  135. force_generic_extractor: Force downloader to use the generic extractor
  136. nooverwrites: Prevent overwriting files.
  137. playliststart: Playlist item to start at.
  138. playlistend: Playlist item to end at.
  139. playlist_items: Specific indices of playlist to download.
  140. playlistreverse: Download playlist items in reverse order.
  141. matchtitle: Download only matching titles.
  142. rejecttitle: Reject downloads for matching titles.
  143. logger: Log messages to a logging.Logger instance.
  144. logtostderr: Log messages to stderr instead of stdout.
  145. writedescription: Write the video description to a .description file
  146. writeinfojson: Write the video description to a .info.json file
  147. writeannotations: Write the video annotations to a .annotations.xml file
  148. writethumbnail: Write the thumbnail image to a file
  149. write_all_thumbnails: Write all thumbnail formats to files
  150. writesubtitles: Write the video subtitles to a file
  151. writeautomaticsub: Write the automatically generated subtitles to a file
  152. allsubtitles: Downloads all the subtitles of the video
  153. (requires writesubtitles or writeautomaticsub)
  154. listsubtitles: Lists all available subtitles for the video
  155. subtitlesformat: The format code for subtitles
  156. subtitleslangs: List of languages of the subtitles to download
  157. keepvideo: Keep the video file after post-processing
  158. daterange: A DateRange object, download only if the upload_date is in the range.
  159. skip_download: Skip the actual download of the video file
  160. cachedir: Location of the cache files in the filesystem.
  161. False to disable filesystem cache.
  162. noplaylist: Download single video instead of a playlist if in doubt.
  163. age_limit: An integer representing the user's age in years.
  164. Unsuitable videos for the given age are skipped.
  165. min_views: An integer representing the minimum view count the video
  166. must have in order to not be skipped.
  167. Videos without view count information are always
  168. downloaded. None for no limit.
  169. max_views: An integer representing the maximum view count.
  170. Videos that are more popular than that are not
  171. downloaded.
  172. Videos without view count information are always
  173. downloaded. None for no limit.
  174. download_archive: File name of a file where all downloads are recorded.
  175. Videos already present in the file are not downloaded
  176. again.
  177. cookiefile: File name where cookies should be read from and dumped to.
  178. nocheckcertificate:Do not verify SSL certificates
  179. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  180. At the moment, this is only supported by YouTube.
  181. proxy: URL of the proxy server to use
  182. cn_verification_proxy: URL of the proxy to use for IP address verification
  183. on Chinese sites. (Experimental)
  184. socket_timeout: Time to wait for unresponsive hosts, in seconds
  185. bidi_workaround: Work around buggy terminals without bidirectional text
  186. support, using fridibi
  187. debug_printtraffic:Print out sent and received HTTP traffic
  188. include_ads: Download ads as well
  189. default_search: Prepend this string if an input url is not valid.
  190. 'auto' for elaborate guessing
  191. encoding: Use this encoding instead of the system-specified.
  192. extract_flat: Do not resolve URLs, return the immediate result.
  193. Pass in 'in_playlist' to only show this behavior for
  194. playlist items.
  195. postprocessors: A list of dictionaries, each with an entry
  196. * key: The name of the postprocessor. See
  197. youtube_dl/postprocessor/__init__.py for a list.
  198. as well as any further keyword arguments for the
  199. postprocessor.
  200. progress_hooks: A list of functions that get called on download
  201. progress, with a dictionary with the entries
  202. * status: One of "downloading", "error", or "finished".
  203. Check this first and ignore unknown values.
  204. If status is one of "downloading", or "finished", the
  205. following properties may also be present:
  206. * filename: The final filename (always present)
  207. * tmpfilename: The filename we're currently writing to
  208. * downloaded_bytes: Bytes on disk
  209. * total_bytes: Size of the whole file, None if unknown
  210. * total_bytes_estimate: Guess of the eventual file size,
  211. None if unavailable.
  212. * elapsed: The number of seconds since download started.
  213. * eta: The estimated time in seconds, None if unknown
  214. * speed: The download speed in bytes/second, None if
  215. unknown
  216. * fragment_index: The counter of the currently
  217. downloaded video fragment.
  218. * fragment_count: The number of fragments (= individual
  219. files that will be merged)
  220. Progress hooks are guaranteed to be called at least once
  221. (with status "finished") if the download is successful.
  222. merge_output_format: Extension to use when merging formats.
  223. fixup: Automatically correct known faults of the file.
  224. One of:
  225. - "never": do nothing
  226. - "warn": only emit a warning
  227. - "detect_or_warn": check whether we can do anything
  228. about it, warn otherwise (default)
  229. source_address: (Experimental) Client-side IP address to bind to.
  230. call_home: Boolean, true iff we are allowed to contact the
  231. youtube-dl servers for debugging.
  232. sleep_interval: Number of seconds to sleep before each download.
  233. listformats: Print an overview of available video formats and exit.
  234. list_thumbnails: Print a table of all thumbnails and exit.
  235. match_filter: A function that gets called with the info_dict of
  236. every video.
  237. If it returns a message, the video is ignored.
  238. If it returns None, the video is downloaded.
  239. match_filter_func in utils.py is one example for this.
  240. no_color: Do not emit color codes in output.
  241. The following options determine which downloader is picked:
  242. external_downloader: Executable of the external downloader to call.
  243. None or unset for standard (built-in) downloader.
  244. hls_prefer_native: Use the native HLS downloader instead of ffmpeg/avconv.
  245. The following parameters are not used by YoutubeDL itself, they are used by
  246. the downloader (see youtube_dl/downloader/common.py):
  247. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  248. noresizebuffer, retries, continuedl, noprogress, consoletitle,
  249. xattr_set_filesize, external_downloader_args.
  250. The following options are used by the post processors:
  251. prefer_ffmpeg: If True, use ffmpeg instead of avconv if both are available,
  252. otherwise prefer avconv.
  253. postprocessor_args: A list of additional command-line arguments for the
  254. postprocessor.
  255. """
  256. params = None
  257. _ies = []
  258. _pps = []
  259. _download_retcode = None
  260. _num_downloads = None
  261. _screen_file = None
  262. def __init__(self, params=None, auto_init=True):
  263. """Create a FileDownloader object with the given options."""
  264. if params is None:
  265. params = {}
  266. self._ies = []
  267. self._ies_instances = {}
  268. self._pps = []
  269. self._progress_hooks = []
  270. self._download_retcode = 0
  271. self._num_downloads = 0
  272. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  273. self._err_file = sys.stderr
  274. self.params = {
  275. # Default parameters
  276. 'nocheckcertificate': False,
  277. }
  278. self.params.update(params)
  279. self.cache = Cache(self)
  280. if params.get('bidi_workaround', False):
  281. try:
  282. import pty
  283. master, slave = pty.openpty()
  284. width = compat_get_terminal_size().columns
  285. if width is None:
  286. width_args = []
  287. else:
  288. width_args = ['-w', str(width)]
  289. sp_kwargs = dict(
  290. stdin=subprocess.PIPE,
  291. stdout=slave,
  292. stderr=self._err_file)
  293. try:
  294. self._output_process = subprocess.Popen(
  295. ['bidiv'] + width_args, **sp_kwargs
  296. )
  297. except OSError:
  298. self._output_process = subprocess.Popen(
  299. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  300. self._output_channel = os.fdopen(master, 'rb')
  301. except OSError as ose:
  302. if ose.errno == 2:
  303. self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
  304. else:
  305. raise
  306. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  307. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968'] and
  308. not params.get('restrictfilenames', False)):
  309. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  310. self.report_warning(
  311. 'Assuming --restrict-filenames since file system encoding '
  312. 'cannot encode all characters. '
  313. 'Set the LC_ALL environment variable to fix this.')
  314. self.params['restrictfilenames'] = True
  315. if isinstance(params.get('outtmpl'), bytes):
  316. self.report_warning(
  317. 'Parameter outtmpl is bytes, but should be a unicode string. '
  318. 'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
  319. self._setup_opener()
  320. if auto_init:
  321. self.print_debug_header()
  322. self.add_default_info_extractors()
  323. for pp_def_raw in self.params.get('postprocessors', []):
  324. pp_class = get_postprocessor(pp_def_raw['key'])
  325. pp_def = dict(pp_def_raw)
  326. del pp_def['key']
  327. pp = pp_class(self, **compat_kwargs(pp_def))
  328. self.add_post_processor(pp)
  329. for ph in self.params.get('progress_hooks', []):
  330. self.add_progress_hook(ph)
  331. def warn_if_short_id(self, argv):
  332. # short YouTube ID starting with dash?
  333. idxs = [
  334. i for i, a in enumerate(argv)
  335. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  336. if idxs:
  337. correct_argv = (
  338. ['youtube-dl'] +
  339. [a for i, a in enumerate(argv) if i not in idxs] +
  340. ['--'] + [argv[i] for i in idxs]
  341. )
  342. self.report_warning(
  343. 'Long argument string detected. '
  344. 'Use -- to separate parameters and URLs, like this:\n%s\n' %
  345. args_to_str(correct_argv))
  346. def add_info_extractor(self, ie):
  347. """Add an InfoExtractor object to the end of the list."""
  348. self._ies.append(ie)
  349. self._ies_instances[ie.ie_key()] = ie
  350. ie.set_downloader(self)
  351. def get_info_extractor(self, ie_key):
  352. """
  353. Get an instance of an IE with name ie_key, it will try to get one from
  354. the _ies list, if there's no instance it will create a new one and add
  355. it to the extractor list.
  356. """
  357. ie = self._ies_instances.get(ie_key)
  358. if ie is None:
  359. ie = get_info_extractor(ie_key)()
  360. self.add_info_extractor(ie)
  361. return ie
  362. def add_default_info_extractors(self):
  363. """
  364. Add the InfoExtractors returned by gen_extractors to the end of the list
  365. """
  366. for ie in gen_extractors():
  367. self.add_info_extractor(ie)
  368. def add_post_processor(self, pp):
  369. """Add a PostProcessor object to the end of the chain."""
  370. self._pps.append(pp)
  371. pp.set_downloader(self)
  372. def add_progress_hook(self, ph):
  373. """Add the progress hook (currently only for the file downloader)"""
  374. self._progress_hooks.append(ph)
  375. def _bidi_workaround(self, message):
  376. if not hasattr(self, '_output_channel'):
  377. return message
  378. assert hasattr(self, '_output_process')
  379. assert isinstance(message, compat_str)
  380. line_count = message.count('\n') + 1
  381. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  382. self._output_process.stdin.flush()
  383. res = ''.join(self._output_channel.readline().decode('utf-8')
  384. for _ in range(line_count))
  385. return res[:-len('\n')]
  386. def to_screen(self, message, skip_eol=False):
  387. """Print message to stdout if not in quiet mode."""
  388. return self.to_stdout(message, skip_eol, check_quiet=True)
  389. def _write_string(self, s, out=None):
  390. write_string(s, out=out, encoding=self.params.get('encoding'))
  391. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  392. """Print message to stdout if not in quiet mode."""
  393. if self.params.get('logger'):
  394. self.params['logger'].debug(message)
  395. elif not check_quiet or not self.params.get('quiet', False):
  396. message = self._bidi_workaround(message)
  397. terminator = ['\n', ''][skip_eol]
  398. output = message + terminator
  399. self._write_string(output, self._screen_file)
  400. def to_stderr(self, message):
  401. """Print message to stderr."""
  402. assert isinstance(message, compat_str)
  403. if self.params.get('logger'):
  404. self.params['logger'].error(message)
  405. else:
  406. message = self._bidi_workaround(message)
  407. output = message + '\n'
  408. self._write_string(output, self._err_file)
  409. def to_console_title(self, message):
  410. if not self.params.get('consoletitle', False):
  411. return
  412. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  413. # c_wchar_p() might not be necessary if `message` is
  414. # already of type unicode()
  415. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  416. elif 'TERM' in os.environ:
  417. self._write_string('\033]0;%s\007' % message, self._screen_file)
  418. def save_console_title(self):
  419. if not self.params.get('consoletitle', False):
  420. return
  421. if 'TERM' in os.environ:
  422. # Save the title on stack
  423. self._write_string('\033[22;0t', self._screen_file)
  424. def restore_console_title(self):
  425. if not self.params.get('consoletitle', False):
  426. return
  427. if 'TERM' in os.environ:
  428. # Restore the title from stack
  429. self._write_string('\033[23;0t', self._screen_file)
  430. def __enter__(self):
  431. self.save_console_title()
  432. return self
  433. def __exit__(self, *args):
  434. self.restore_console_title()
  435. if self.params.get('cookiefile') is not None:
  436. self.cookiejar.save()
  437. def trouble(self, message=None, tb=None):
  438. """Determine action to take when a download problem appears.
  439. Depending on if the downloader has been configured to ignore
  440. download errors or not, this method may throw an exception or
  441. not when errors are found, after printing the message.
  442. tb, if given, is additional traceback information.
  443. """
  444. if message is not None:
  445. self.to_stderr(message)
  446. if self.params.get('verbose'):
  447. if tb is None:
  448. if sys.exc_info()[0]: # if .trouble has been called from an except block
  449. tb = ''
  450. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  451. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  452. tb += compat_str(traceback.format_exc())
  453. else:
  454. tb_data = traceback.format_list(traceback.extract_stack())
  455. tb = ''.join(tb_data)
  456. self.to_stderr(tb)
  457. if not self.params.get('ignoreerrors', False):
  458. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  459. exc_info = sys.exc_info()[1].exc_info
  460. else:
  461. exc_info = sys.exc_info()
  462. raise DownloadError(message, exc_info)
  463. self._download_retcode = 1
  464. def report_warning(self, message):
  465. '''
  466. Print the message to stderr, it will be prefixed with 'WARNING:'
  467. If stderr is a tty file the 'WARNING:' will be colored
  468. '''
  469. if self.params.get('logger') is not None:
  470. self.params['logger'].warning(message)
  471. else:
  472. if self.params.get('no_warnings'):
  473. return
  474. if not self.params.get('no_color') and self._err_file.isatty() and os.name != 'nt':
  475. _msg_header = '\033[0;33mWARNING:\033[0m'
  476. else:
  477. _msg_header = 'WARNING:'
  478. warning_message = '%s %s' % (_msg_header, message)
  479. self.to_stderr(warning_message)
  480. def report_error(self, message, tb=None):
  481. '''
  482. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  483. in red if stderr is a tty file.
  484. '''
  485. if not self.params.get('no_color') and self._err_file.isatty() and os.name != 'nt':
  486. _msg_header = '\033[0;31mERROR:\033[0m'
  487. else:
  488. _msg_header = 'ERROR:'
  489. error_message = '%s %s' % (_msg_header, message)
  490. self.trouble(error_message, tb)
  491. def report_file_already_downloaded(self, file_name):
  492. """Report file has already been fully downloaded."""
  493. try:
  494. self.to_screen('[download] %s has already been downloaded' % file_name)
  495. except UnicodeEncodeError:
  496. self.to_screen('[download] The file has already been downloaded')
  497. def prepare_filename(self, info_dict):
  498. """Generate the output filename."""
  499. try:
  500. template_dict = dict(info_dict)
  501. template_dict['epoch'] = int(time.time())
  502. autonumber_size = self.params.get('autonumber_size')
  503. if autonumber_size is None:
  504. autonumber_size = 5
  505. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  506. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  507. if template_dict.get('playlist_index') is not None:
  508. template_dict['playlist_index'] = '%0*d' % (len(str(template_dict['n_entries'])), template_dict['playlist_index'])
  509. if template_dict.get('resolution') is None:
  510. if template_dict.get('width') and template_dict.get('height'):
  511. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  512. elif template_dict.get('height'):
  513. template_dict['resolution'] = '%sp' % template_dict['height']
  514. elif template_dict.get('width'):
  515. template_dict['resolution'] = '?x%d' % template_dict['width']
  516. sanitize = lambda k, v: sanitize_filename(
  517. compat_str(v),
  518. restricted=self.params.get('restrictfilenames'),
  519. is_id=(k == 'id'))
  520. template_dict = dict((k, sanitize(k, v))
  521. for k, v in template_dict.items()
  522. if v is not None)
  523. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  524. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  525. tmpl = compat_expanduser(outtmpl)
  526. filename = tmpl % template_dict
  527. # Temporary fix for #4787
  528. # 'Treat' all problem characters by passing filename through preferredencoding
  529. # to workaround encoding issues with subprocess on python2 @ Windows
  530. if sys.version_info < (3, 0) and sys.platform == 'win32':
  531. filename = encodeFilename(filename, True).decode(preferredencoding())
  532. return sanitize_path(filename)
  533. except ValueError as err:
  534. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  535. return None
  536. def _match_entry(self, info_dict, incomplete):
  537. """ Returns None iff the file should be downloaded """
  538. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  539. if 'title' in info_dict:
  540. # This can happen when we're just evaluating the playlist
  541. title = info_dict['title']
  542. matchtitle = self.params.get('matchtitle', False)
  543. if matchtitle:
  544. if not re.search(matchtitle, title, re.IGNORECASE):
  545. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  546. rejecttitle = self.params.get('rejecttitle', False)
  547. if rejecttitle:
  548. if re.search(rejecttitle, title, re.IGNORECASE):
  549. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  550. date = info_dict.get('upload_date', None)
  551. if date is not None:
  552. dateRange = self.params.get('daterange', DateRange())
  553. if date not in dateRange:
  554. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  555. view_count = info_dict.get('view_count', None)
  556. if view_count is not None:
  557. min_views = self.params.get('min_views')
  558. if min_views is not None and view_count < min_views:
  559. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  560. max_views = self.params.get('max_views')
  561. if max_views is not None and view_count > max_views:
  562. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  563. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  564. return 'Skipping "%s" because it is age restricted' % video_title
  565. if self.in_download_archive(info_dict):
  566. return '%s has already been recorded in archive' % video_title
  567. if not incomplete:
  568. match_filter = self.params.get('match_filter')
  569. if match_filter is not None:
  570. ret = match_filter(info_dict)
  571. if ret is not None:
  572. return ret
  573. return None
  574. @staticmethod
  575. def add_extra_info(info_dict, extra_info):
  576. '''Set the keys from extra_info in info dict if they are missing'''
  577. for key, value in extra_info.items():
  578. info_dict.setdefault(key, value)
  579. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  580. process=True, force_generic_extractor=False):
  581. '''
  582. Returns a list with a dictionary for each video we find.
  583. If 'download', also downloads the videos.
  584. extra_info is a dict containing the extra values to add to each result
  585. '''
  586. if not ie_key and force_generic_extractor:
  587. ie_key = 'Generic'
  588. if ie_key:
  589. ies = [self.get_info_extractor(ie_key)]
  590. else:
  591. ies = self._ies
  592. for ie in ies:
  593. if not ie.suitable(url):
  594. continue
  595. if not ie.working():
  596. self.report_warning('The program functionality for this site has been marked as broken, '
  597. 'and will probably not work.')
  598. try:
  599. ie_result = ie.extract(url)
  600. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  601. break
  602. if isinstance(ie_result, list):
  603. # Backwards compatibility: old IE result format
  604. ie_result = {
  605. '_type': 'compat_list',
  606. 'entries': ie_result,
  607. }
  608. self.add_default_extra_info(ie_result, ie, url)
  609. if process:
  610. return self.process_ie_result(ie_result, download, extra_info)
  611. else:
  612. return ie_result
  613. except ExtractorError as e: # An error we somewhat expected
  614. self.report_error(error_to_str(e), e.format_traceback())
  615. break
  616. except MaxDownloadsReached:
  617. raise
  618. except Exception as e:
  619. if self.params.get('ignoreerrors', False):
  620. self.report_error(error_to_str(e), tb=compat_str(traceback.format_exc()))
  621. break
  622. else:
  623. raise
  624. else:
  625. self.report_error('no suitable InfoExtractor for URL %s' % url)
  626. def add_default_extra_info(self, ie_result, ie, url):
  627. self.add_extra_info(ie_result, {
  628. 'extractor': ie.IE_NAME,
  629. 'webpage_url': url,
  630. 'webpage_url_basename': url_basename(url),
  631. 'extractor_key': ie.ie_key(),
  632. })
  633. def process_ie_result(self, ie_result, download=True, extra_info={}):
  634. """
  635. Take the result of the ie(may be modified) and resolve all unresolved
  636. references (URLs, playlist items).
  637. It will also download the videos if 'download'.
  638. Returns the resolved ie_result.
  639. """
  640. result_type = ie_result.get('_type', 'video')
  641. if result_type in ('url', 'url_transparent'):
  642. extract_flat = self.params.get('extract_flat', False)
  643. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) or
  644. extract_flat is True):
  645. if self.params.get('forcejson', False):
  646. self.to_stdout(json.dumps(ie_result))
  647. return ie_result
  648. if result_type == 'video':
  649. self.add_extra_info(ie_result, extra_info)
  650. return self.process_video_result(ie_result, download=download)
  651. elif result_type == 'url':
  652. # We have to add extra_info to the results because it may be
  653. # contained in a playlist
  654. return self.extract_info(ie_result['url'],
  655. download,
  656. ie_key=ie_result.get('ie_key'),
  657. extra_info=extra_info)
  658. elif result_type == 'url_transparent':
  659. # Use the information from the embedding page
  660. info = self.extract_info(
  661. ie_result['url'], ie_key=ie_result.get('ie_key'),
  662. extra_info=extra_info, download=False, process=False)
  663. force_properties = dict(
  664. (k, v) for k, v in ie_result.items() if v is not None)
  665. for f in ('_type', 'url'):
  666. if f in force_properties:
  667. del force_properties[f]
  668. new_result = info.copy()
  669. new_result.update(force_properties)
  670. assert new_result.get('_type') != 'url_transparent'
  671. return self.process_ie_result(
  672. new_result, download=download, extra_info=extra_info)
  673. elif result_type == 'playlist' or result_type == 'multi_video':
  674. # We process each entry in the playlist
  675. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  676. self.to_screen('[download] Downloading playlist: %s' % playlist)
  677. playlist_results = []
  678. playliststart = self.params.get('playliststart', 1) - 1
  679. playlistend = self.params.get('playlistend', None)
  680. # For backwards compatibility, interpret -1 as whole list
  681. if playlistend == -1:
  682. playlistend = None
  683. playlistitems_str = self.params.get('playlist_items', None)
  684. playlistitems = None
  685. if playlistitems_str is not None:
  686. def iter_playlistitems(format):
  687. for string_segment in format.split(','):
  688. if '-' in string_segment:
  689. start, end = string_segment.split('-')
  690. for item in range(int(start), int(end) + 1):
  691. yield int(item)
  692. else:
  693. yield int(string_segment)
  694. playlistitems = iter_playlistitems(playlistitems_str)
  695. ie_entries = ie_result['entries']
  696. if isinstance(ie_entries, list):
  697. n_all_entries = len(ie_entries)
  698. if playlistitems:
  699. entries = [
  700. ie_entries[i - 1] for i in playlistitems
  701. if -n_all_entries <= i - 1 < n_all_entries]
  702. else:
  703. entries = ie_entries[playliststart:playlistend]
  704. n_entries = len(entries)
  705. self.to_screen(
  706. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  707. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  708. elif isinstance(ie_entries, PagedList):
  709. if playlistitems:
  710. entries = []
  711. for item in playlistitems:
  712. entries.extend(ie_entries.getslice(
  713. item - 1, item
  714. ))
  715. else:
  716. entries = ie_entries.getslice(
  717. playliststart, playlistend)
  718. n_entries = len(entries)
  719. self.to_screen(
  720. "[%s] playlist %s: Downloading %d videos" %
  721. (ie_result['extractor'], playlist, n_entries))
  722. else: # iterable
  723. if playlistitems:
  724. entry_list = list(ie_entries)
  725. entries = [entry_list[i - 1] for i in playlistitems]
  726. else:
  727. entries = list(itertools.islice(
  728. ie_entries, playliststart, playlistend))
  729. n_entries = len(entries)
  730. self.to_screen(
  731. "[%s] playlist %s: Downloading %d videos" %
  732. (ie_result['extractor'], playlist, n_entries))
  733. if self.params.get('playlistreverse', False):
  734. entries = entries[::-1]
  735. for i, entry in enumerate(entries, 1):
  736. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  737. extra = {
  738. 'n_entries': n_entries,
  739. 'playlist': playlist,
  740. 'playlist_id': ie_result.get('id'),
  741. 'playlist_title': ie_result.get('title'),
  742. 'playlist_index': i + playliststart,
  743. 'extractor': ie_result['extractor'],
  744. 'webpage_url': ie_result['webpage_url'],
  745. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  746. 'extractor_key': ie_result['extractor_key'],
  747. }
  748. reason = self._match_entry(entry, incomplete=True)
  749. if reason is not None:
  750. self.to_screen('[download] ' + reason)
  751. continue
  752. entry_result = self.process_ie_result(entry,
  753. download=download,
  754. extra_info=extra)
  755. playlist_results.append(entry_result)
  756. ie_result['entries'] = playlist_results
  757. self.to_screen('[download] Finished downloading playlist: %s' % playlist)
  758. return ie_result
  759. elif result_type == 'compat_list':
  760. self.report_warning(
  761. 'Extractor %s returned a compat_list result. '
  762. 'It needs to be updated.' % ie_result.get('extractor'))
  763. def _fixup(r):
  764. self.add_extra_info(
  765. r,
  766. {
  767. 'extractor': ie_result['extractor'],
  768. 'webpage_url': ie_result['webpage_url'],
  769. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  770. 'extractor_key': ie_result['extractor_key'],
  771. }
  772. )
  773. return r
  774. ie_result['entries'] = [
  775. self.process_ie_result(_fixup(r), download, extra_info)
  776. for r in ie_result['entries']
  777. ]
  778. return ie_result
  779. else:
  780. raise Exception('Invalid result type: %s' % result_type)
  781. def _build_format_filter(self, filter_spec):
  782. " Returns a function to filter the formats according to the filter_spec "
  783. OPERATORS = {
  784. '<': operator.lt,
  785. '<=': operator.le,
  786. '>': operator.gt,
  787. '>=': operator.ge,
  788. '=': operator.eq,
  789. '!=': operator.ne,
  790. }
  791. operator_rex = re.compile(r'''(?x)\s*
  792. (?P<key>width|height|tbr|abr|vbr|asr|filesize|fps)
  793. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  794. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  795. $
  796. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  797. m = operator_rex.search(filter_spec)
  798. if m:
  799. try:
  800. comparison_value = int(m.group('value'))
  801. except ValueError:
  802. comparison_value = parse_filesize(m.group('value'))
  803. if comparison_value is None:
  804. comparison_value = parse_filesize(m.group('value') + 'B')
  805. if comparison_value is None:
  806. raise ValueError(
  807. 'Invalid value %r in format specification %r' % (
  808. m.group('value'), filter_spec))
  809. op = OPERATORS[m.group('op')]
  810. if not m:
  811. STR_OPERATORS = {
  812. '=': operator.eq,
  813. '!=': operator.ne,
  814. }
  815. str_operator_rex = re.compile(r'''(?x)
  816. \s*(?P<key>ext|acodec|vcodec|container|protocol)
  817. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?
  818. \s*(?P<value>[a-zA-Z0-9_-]+)
  819. \s*$
  820. ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
  821. m = str_operator_rex.search(filter_spec)
  822. if m:
  823. comparison_value = m.group('value')
  824. op = STR_OPERATORS[m.group('op')]
  825. if not m:
  826. raise ValueError('Invalid filter specification %r' % filter_spec)
  827. def _filter(f):
  828. actual_value = f.get(m.group('key'))
  829. if actual_value is None:
  830. return m.group('none_inclusive')
  831. return op(actual_value, comparison_value)
  832. return _filter
  833. def build_format_selector(self, format_spec):
  834. def syntax_error(note, start):
  835. message = (
  836. 'Invalid format specification: '
  837. '{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
  838. return SyntaxError(message)
  839. PICKFIRST = 'PICKFIRST'
  840. MERGE = 'MERGE'
  841. SINGLE = 'SINGLE'
  842. GROUP = 'GROUP'
  843. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  844. def _parse_filter(tokens):
  845. filter_parts = []
  846. for type, string, start, _, _ in tokens:
  847. if type == tokenize.OP and string == ']':
  848. return ''.join(filter_parts)
  849. else:
  850. filter_parts.append(string)
  851. def _remove_unused_ops(tokens):
  852. # Remove operators that we don't use and join them with the surrounding strings
  853. # for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  854. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  855. last_string, last_start, last_end, last_line = None, None, None, None
  856. for type, string, start, end, line in tokens:
  857. if type == tokenize.OP and string == '[':
  858. if last_string:
  859. yield tokenize.NAME, last_string, last_start, last_end, last_line
  860. last_string = None
  861. yield type, string, start, end, line
  862. # everything inside brackets will be handled by _parse_filter
  863. for type, string, start, end, line in tokens:
  864. yield type, string, start, end, line
  865. if type == tokenize.OP and string == ']':
  866. break
  867. elif type == tokenize.OP and string in ALLOWED_OPS:
  868. if last_string:
  869. yield tokenize.NAME, last_string, last_start, last_end, last_line
  870. last_string = None
  871. yield type, string, start, end, line
  872. elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  873. if not last_string:
  874. last_string = string
  875. last_start = start
  876. last_end = end
  877. else:
  878. last_string += string
  879. if last_string:
  880. yield tokenize.NAME, last_string, last_start, last_end, last_line
  881. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  882. selectors = []
  883. current_selector = None
  884. for type, string, start, _, _ in tokens:
  885. # ENCODING is only defined in python 3.x
  886. if type == getattr(tokenize, 'ENCODING', None):
  887. continue
  888. elif type in [tokenize.NAME, tokenize.NUMBER]:
  889. current_selector = FormatSelector(SINGLE, string, [])
  890. elif type == tokenize.OP:
  891. if string == ')':
  892. if not inside_group:
  893. # ')' will be handled by the parentheses group
  894. tokens.restore_last_token()
  895. break
  896. elif inside_merge and string in ['/', ',']:
  897. tokens.restore_last_token()
  898. break
  899. elif inside_choice and string == ',':
  900. tokens.restore_last_token()
  901. break
  902. elif string == ',':
  903. if not current_selector:
  904. raise syntax_error('"," must follow a format selector', start)
  905. selectors.append(current_selector)
  906. current_selector = None
  907. elif string == '/':
  908. if not current_selector:
  909. raise syntax_error('"/" must follow a format selector', start)
  910. first_choice = current_selector
  911. second_choice = _parse_format_selection(tokens, inside_choice=True)
  912. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  913. elif string == '[':
  914. if not current_selector:
  915. current_selector = FormatSelector(SINGLE, 'best', [])
  916. format_filter = _parse_filter(tokens)
  917. current_selector.filters.append(format_filter)
  918. elif string == '(':
  919. if current_selector:
  920. raise syntax_error('Unexpected "("', start)
  921. group = _parse_format_selection(tokens, inside_group=True)
  922. current_selector = FormatSelector(GROUP, group, [])
  923. elif string == '+':
  924. video_selector = current_selector
  925. audio_selector = _parse_format_selection(tokens, inside_merge=True)
  926. if not video_selector or not audio_selector:
  927. raise syntax_error('"+" must be between two format selectors', start)
  928. current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
  929. else:
  930. raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
  931. elif type == tokenize.ENDMARKER:
  932. break
  933. if current_selector:
  934. selectors.append(current_selector)
  935. return selectors
  936. def _build_selector_function(selector):
  937. if isinstance(selector, list):
  938. fs = [_build_selector_function(s) for s in selector]
  939. def selector_function(formats):
  940. for f in fs:
  941. for format in f(formats):
  942. yield format
  943. return selector_function
  944. elif selector.type == GROUP:
  945. selector_function = _build_selector_function(selector.selector)
  946. elif selector.type == PICKFIRST:
  947. fs = [_build_selector_function(s) for s in selector.selector]
  948. def selector_function(formats):
  949. for f in fs:
  950. picked_formats = list(f(formats))
  951. if picked_formats:
  952. return picked_formats
  953. return []
  954. elif selector.type == SINGLE:
  955. format_spec = selector.selector
  956. def selector_function(formats):
  957. formats = list(formats)
  958. if not formats:
  959. return
  960. if format_spec == 'all':
  961. for f in formats:
  962. yield f
  963. elif format_spec in ['best', 'worst', None]:
  964. format_idx = 0 if format_spec == 'worst' else -1
  965. audiovideo_formats = [
  966. f for f in formats
  967. if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
  968. if audiovideo_formats:
  969. yield audiovideo_formats[format_idx]
  970. # for audio only (soundcloud) or video only (imgur) urls, select the best/worst audio format
  971. elif (all(f.get('acodec') != 'none' for f in formats) or
  972. all(f.get('vcodec') != 'none' for f in formats)):
  973. yield formats[format_idx]
  974. elif format_spec == 'bestaudio':
  975. audio_formats = [
  976. f for f in formats
  977. if f.get('vcodec') == 'none']
  978. if audio_formats:
  979. yield audio_formats[-1]
  980. elif format_spec == 'worstaudio':
  981. audio_formats = [
  982. f for f in formats
  983. if f.get('vcodec') == 'none']
  984. if audio_formats:
  985. yield audio_formats[0]
  986. elif format_spec == 'bestvideo':
  987. video_formats = [
  988. f for f in formats
  989. if f.get('acodec') == 'none']
  990. if video_formats:
  991. yield video_formats[-1]
  992. elif format_spec == 'worstvideo':
  993. video_formats = [
  994. f for f in formats
  995. if f.get('acodec') == 'none']
  996. if video_formats:
  997. yield video_formats[0]
  998. else:
  999. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  1000. if format_spec in extensions:
  1001. filter_f = lambda f: f['ext'] == format_spec
  1002. else:
  1003. filter_f = lambda f: f['format_id'] == format_spec
  1004. matches = list(filter(filter_f, formats))
  1005. if matches:
  1006. yield matches[-1]
  1007. elif selector.type == MERGE:
  1008. def _merge(formats_info):
  1009. format_1, format_2 = [f['format_id'] for f in formats_info]
  1010. # The first format must contain the video and the
  1011. # second the audio
  1012. if formats_info[0].get('vcodec') == 'none':
  1013. self.report_error('The first format must '
  1014. 'contain the video, try using '
  1015. '"-f %s+%s"' % (format_2, format_1))
  1016. return
  1017. # Formats must be opposite (video+audio)
  1018. if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
  1019. self.report_error(
  1020. 'Both formats %s and %s are video-only, you must specify "-f video+audio"'
  1021. % (format_1, format_2))
  1022. return
  1023. output_ext = (
  1024. formats_info[0]['ext']
  1025. if self.params.get('merge_output_format') is None
  1026. else self.params['merge_output_format'])
  1027. return {
  1028. 'requested_formats': formats_info,
  1029. 'format': '%s+%s' % (formats_info[0].get('format'),
  1030. formats_info[1].get('format')),
  1031. 'format_id': '%s+%s' % (formats_info[0].get('format_id'),
  1032. formats_info[1].get('format_id')),
  1033. 'width': formats_info[0].get('width'),
  1034. 'height': formats_info[0].get('height'),
  1035. 'resolution': formats_info[0].get('resolution'),
  1036. 'fps': formats_info[0].get('fps'),
  1037. 'vcodec': formats_info[0].get('vcodec'),
  1038. 'vbr': formats_info[0].get('vbr'),
  1039. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  1040. 'acodec': formats_info[1].get('acodec'),
  1041. 'abr': formats_info[1].get('abr'),
  1042. 'ext': output_ext,
  1043. }
  1044. video_selector, audio_selector = map(_build_selector_function, selector.selector)
  1045. def selector_function(formats):
  1046. formats = list(formats)
  1047. for pair in itertools.product(video_selector(formats), audio_selector(formats)):
  1048. yield _merge(pair)
  1049. filters = [self._build_format_filter(f) for f in selector.filters]
  1050. def final_selector(formats):
  1051. for _filter in filters:
  1052. formats = list(filter(_filter, formats))
  1053. return selector_function(formats)
  1054. return final_selector
  1055. stream = io.BytesIO(format_spec.encode('utf-8'))
  1056. try:
  1057. tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
  1058. except tokenize.TokenError:
  1059. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  1060. class TokenIterator(object):
  1061. def __init__(self, tokens):
  1062. self.tokens = tokens
  1063. self.counter = 0
  1064. def __iter__(self):
  1065. return self
  1066. def __next__(self):
  1067. if self.counter >= len(self.tokens):
  1068. raise StopIteration()
  1069. value = self.tokens[self.counter]
  1070. self.counter += 1
  1071. return value
  1072. next = __next__
  1073. def restore_last_token(self):
  1074. self.counter -= 1
  1075. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  1076. return _build_selector_function(parsed_selector)
  1077. def _calc_headers(self, info_dict):
  1078. res = std_headers.copy()
  1079. add_headers = info_dict.get('http_headers')
  1080. if add_headers:
  1081. res.update(add_headers)
  1082. cookies = self._calc_cookies(info_dict)
  1083. if cookies:
  1084. res['Cookie'] = cookies
  1085. return res
  1086. def _calc_cookies(self, info_dict):
  1087. pr = sanitized_Request(info_dict['url'])
  1088. self.cookiejar.add_cookie_header(pr)
  1089. return pr.get_header('Cookie')
  1090. def process_video_result(self, info_dict, download=True):
  1091. assert info_dict.get('_type', 'video') == 'video'
  1092. if 'id' not in info_dict:
  1093. raise ExtractorError('Missing "id" field in extractor result')
  1094. if 'title' not in info_dict:
  1095. raise ExtractorError('Missing "title" field in extractor result')
  1096. if 'playlist' not in info_dict:
  1097. # It isn't part of a playlist
  1098. info_dict['playlist'] = None
  1099. info_dict['playlist_index'] = None
  1100. thumbnails = info_dict.get('thumbnails')
  1101. if thumbnails is None:
  1102. thumbnail = info_dict.get('thumbnail')
  1103. if thumbnail:
  1104. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  1105. if thumbnails:
  1106. thumbnails.sort(key=lambda t: (
  1107. t.get('preference'), t.get('width'), t.get('height'),
  1108. t.get('id'), t.get('url')))
  1109. for i, t in enumerate(thumbnails):
  1110. if t.get('width') and t.get('height'):
  1111. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  1112. if t.get('id') is None:
  1113. t['id'] = '%d' % i
  1114. if thumbnails and 'thumbnail' not in info_dict:
  1115. info_dict['thumbnail'] = thumbnails[-1]['url']
  1116. if 'display_id' not in info_dict and 'id' in info_dict:
  1117. info_dict['display_id'] = info_dict['id']
  1118. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  1119. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  1120. # see http://bugs.python.org/issue1646728)
  1121. try:
  1122. upload_date = datetime.datetime.utcfromtimestamp(info_dict['timestamp'])
  1123. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  1124. except (ValueError, OverflowError, OSError):
  1125. pass
  1126. subtitles = info_dict.get('subtitles')
  1127. if subtitles:
  1128. for _, subtitle in subtitles.items():
  1129. for subtitle_format in subtitle:
  1130. if 'ext' not in subtitle_format:
  1131. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  1132. if self.params.get('listsubtitles', False):
  1133. if 'automatic_captions' in info_dict:
  1134. self.list_subtitles(info_dict['id'], info_dict.get('automatic_captions'), 'automatic captions')
  1135. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  1136. return
  1137. info_dict['requested_subtitles'] = self.process_subtitles(
  1138. info_dict['id'], subtitles,
  1139. info_dict.get('automatic_captions'))
  1140. # We now pick which formats have to be downloaded
  1141. if info_dict.get('formats') is None:
  1142. # There's only one format available
  1143. formats = [info_dict]
  1144. else:
  1145. formats = info_dict['formats']
  1146. if not formats:
  1147. raise ExtractorError('No video formats found!')
  1148. formats_dict = {}
  1149. # We check that all the formats have the format and format_id fields
  1150. for i, format in enumerate(formats):
  1151. if 'url' not in format:
  1152. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  1153. if format.get('format_id') is None:
  1154. format['format_id'] = compat_str(i)
  1155. format_id = format['format_id']
  1156. if format_id not in formats_dict:
  1157. formats_dict[format_id] = []
  1158. formats_dict[format_id].append(format)
  1159. # Make sure all formats have unique format_id
  1160. for format_id, ambiguous_formats in formats_dict.items():
  1161. if len(ambiguous_formats) > 1:
  1162. for i, format in enumerate(ambiguous_formats):
  1163. format['format_id'] = '%s-%d' % (format_id, i)
  1164. for i, format in enumerate(formats):
  1165. if format.get('format') is None:
  1166. format['format'] = '{id} - {res}{note}'.format(
  1167. id=format['format_id'],
  1168. res=self.format_resolution(format),
  1169. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  1170. )
  1171. # Automatically determine file extension if missing
  1172. if 'ext' not in format:
  1173. format['ext'] = determine_ext(format['url']).lower()
  1174. # Add HTTP headers, so that external programs can use them from the
  1175. # json output
  1176. full_format_info = info_dict.copy()
  1177. full_format_info.update(format)
  1178. format['http_headers'] = self._calc_headers(full_format_info)
  1179. # TODO Central sorting goes here
  1180. if formats[0] is not info_dict:
  1181. # only set the 'formats' fields if the original info_dict list them
  1182. # otherwise we end up with a circular reference, the first (and unique)
  1183. # element in the 'formats' field in info_dict is info_dict itself,
  1184. # wich can't be exported to json
  1185. info_dict['formats'] = formats
  1186. if self.params.get('listformats'):
  1187. self.list_formats(info_dict)
  1188. return
  1189. if self.params.get('list_thumbnails'):
  1190. self.list_thumbnails(info_dict)
  1191. return
  1192. req_format = self.params.get('format')
  1193. if req_format is None:
  1194. req_format_list = []
  1195. if (self.params.get('outtmpl', DEFAULT_OUTTMPL) != '-' and
  1196. info_dict['extractor'] in ['youtube', 'ted'] and
  1197. not info_dict.get('is_live')):
  1198. merger = FFmpegMergerPP(self)
  1199. if merger.available and merger.can_merge():
  1200. req_format_list.append('bestvideo+bestaudio')
  1201. req_format_list.append('best')
  1202. req_format = '/'.join(req_format_list)
  1203. format_selector = self.build_format_selector(req_format)
  1204. formats_to_download = list(format_selector(formats))
  1205. if not formats_to_download:
  1206. raise ExtractorError('requested format not available',
  1207. expected=True)
  1208. if download:
  1209. if len(formats_to_download) > 1:
  1210. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  1211. for format in formats_to_download:
  1212. new_info = dict(info_dict)
  1213. new_info.update(format)
  1214. self.process_info(new_info)
  1215. # We update the info dict with the best quality format (backwards compatibility)
  1216. info_dict.update(formats_to_download[-1])
  1217. return info_dict
  1218. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  1219. """Select the requested subtitles and their format"""
  1220. available_subs = {}
  1221. if normal_subtitles and self.params.get('writesubtitles'):
  1222. available_subs.update(normal_subtitles)
  1223. if automatic_captions and self.params.get('writeautomaticsub'):
  1224. for lang, cap_info in automatic_captions.items():
  1225. if lang not in available_subs:
  1226. available_subs[lang] = cap_info
  1227. if (not self.params.get('writesubtitles') and not
  1228. self.params.get('writeautomaticsub') or not
  1229. available_subs):
  1230. return None
  1231. if self.params.get('allsubtitles', False):
  1232. requested_langs = available_subs.keys()
  1233. else:
  1234. if self.params.get('subtitleslangs', False):
  1235. requested_langs = self.params.get('subtitleslangs')
  1236. elif 'en' in available_subs:
  1237. requested_langs = ['en']
  1238. else:
  1239. requested_langs = [list(available_subs.keys())[0]]
  1240. formats_query = self.params.get('subtitlesformat', 'best')
  1241. formats_preference = formats_query.split('/') if formats_query else []
  1242. subs = {}
  1243. for lang in requested_langs:
  1244. formats = available_subs.get(lang)
  1245. if formats is None:
  1246. self.report_warning('%s subtitles not available for %s' % (lang, video_id))
  1247. continue
  1248. for ext in formats_preference:
  1249. if ext == 'best':
  1250. f = formats[-1]
  1251. break
  1252. matches = list(filter(lambda f: f['ext'] == ext, formats))
  1253. if matches:
  1254. f = matches[-1]
  1255. break
  1256. else:
  1257. f = formats[-1]
  1258. self.report_warning(
  1259. 'No subtitle format found matching "%s" for language %s, '
  1260. 'using %s' % (formats_query, lang, f['ext']))
  1261. subs[lang] = f
  1262. return subs
  1263. def process_info(self, info_dict):
  1264. """Process a single resolved IE result."""
  1265. assert info_dict.get('_type', 'video') == 'video'
  1266. max_downloads = self.params.get('max_downloads')
  1267. if max_downloads is not None:
  1268. if self._num_downloads >= int(max_downloads):
  1269. raise MaxDownloadsReached()
  1270. info_dict['fulltitle'] = info_dict['title']
  1271. if len(info_dict['title']) > 200:
  1272. info_dict['title'] = info_dict['title'][:197] + '...'
  1273. if 'format' not in info_dict:
  1274. info_dict['format'] = info_dict['ext']
  1275. reason = self._match_entry(info_dict, incomplete=False)
  1276. if reason is not None:
  1277. self.to_screen('[download] ' + reason)
  1278. return
  1279. self._num_downloads += 1
  1280. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1281. # Forced printings
  1282. if self.params.get('forcetitle', False):
  1283. self.to_stdout(info_dict['fulltitle'])
  1284. if self.params.get('forceid', False):
  1285. self.to_stdout(info_dict['id'])
  1286. if self.params.get('forceurl', False):
  1287. if info_dict.get('requested_formats') is not None:
  1288. for f in info_dict['requested_formats']:
  1289. self.to_stdout(f['url'] + f.get('play_path', ''))
  1290. else:
  1291. # For RTMP URLs, also include the playpath
  1292. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1293. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  1294. self.to_stdout(info_dict['thumbnail'])
  1295. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  1296. self.to_stdout(info_dict['description'])
  1297. if self.params.get('forcefilename', False) and filename is not None:
  1298. self.to_stdout(filename)
  1299. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1300. self.to_stdout(formatSeconds(info_dict['duration']))
  1301. if self.params.get('forceformat', False):
  1302. self.to_stdout(info_dict['format'])
  1303. if self.params.get('forcejson', False):
  1304. self.to_stdout(json.dumps(info_dict))
  1305. # Do nothing else if in simulate mode
  1306. if self.params.get('simulate', False):
  1307. return
  1308. if filename is None:
  1309. return
  1310. try:
  1311. dn = os.path.dirname(sanitize_path(encodeFilename(filename)))
  1312. if dn and not os.path.exists(dn):
  1313. os.makedirs(dn)
  1314. except (OSError, IOError) as err:
  1315. self.report_error('unable to create directory ' + error_to_str(err))
  1316. return
  1317. if self.params.get('writedescription', False):
  1318. descfn = replace_extension(filename, 'description', info_dict.get('ext'))
  1319. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1320. self.to_screen('[info] Video description is already present')
  1321. elif info_dict.get('description') is None:
  1322. self.report_warning('There\'s no description to write.')
  1323. else:
  1324. try:
  1325. self.to_screen('[info] Writing video description to: ' + descfn)
  1326. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1327. descfile.write(info_dict['description'])
  1328. except (OSError, IOError):
  1329. self.report_error('Cannot write description file ' + descfn)
  1330. return
  1331. if self.params.get('writeannotations', False):
  1332. annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
  1333. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1334. self.to_screen('[info] Video annotations are already present')
  1335. else:
  1336. try:
  1337. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1338. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1339. annofile.write(info_dict['annotations'])
  1340. except (KeyError, TypeError):
  1341. self.report_warning('There are no annotations to write.')
  1342. except (OSError, IOError):
  1343. self.report_error('Cannot write annotations file: ' + annofn)
  1344. return
  1345. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1346. self.params.get('writeautomaticsub')])
  1347. if subtitles_are_requested and info_dict.get('requested_subtitles'):
  1348. # subtitles download errors are already managed as troubles in relevant IE
  1349. # that way it will silently go on when used with unsupporting IE
  1350. subtitles = info_dict['requested_subtitles']
  1351. ie = self.get_info_extractor(info_dict['extractor_key'])
  1352. for sub_lang, sub_info in subtitles.items():
  1353. sub_format = sub_info['ext']
  1354. if sub_info.get('data') is not None:
  1355. sub_data = sub_info['data']
  1356. else:
  1357. try:
  1358. sub_data = ie._download_webpage(
  1359. sub_info['url'], info_dict['id'], note=False)
  1360. except ExtractorError as err:
  1361. self.report_warning('Unable to download subtitle for "%s": %s' %
  1362. (sub_lang, error_to_str(err.cause)))
  1363. continue
  1364. try:
  1365. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1366. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1367. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1368. else:
  1369. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1370. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  1371. subfile.write(sub_data)
  1372. except (OSError, IOError):
  1373. self.report_error('Cannot write subtitles file ' + sub_filename)
  1374. return
  1375. if self.params.get('writeinfojson', False):
  1376. infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
  1377. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1378. self.to_screen('[info] Video description metadata is already present')
  1379. else:
  1380. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1381. try:
  1382. write_json_file(self.filter_requested_info(info_dict), infofn)
  1383. except (OSError, IOError):
  1384. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1385. return
  1386. self._write_thumbnails(info_dict, filename)
  1387. if not self.params.get('skip_download', False):
  1388. try:
  1389. def dl(name, info):
  1390. fd = get_suitable_downloader(info, self.params)(self, self.params)
  1391. for ph in self._progress_hooks:
  1392. fd.add_progress_hook(ph)
  1393. if self.params.get('verbose'):
  1394. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1395. return fd.download(name, info)
  1396. if info_dict.get('requested_formats') is not None:
  1397. downloaded = []
  1398. success = True
  1399. merger = FFmpegMergerPP(self)
  1400. if not merger.available:
  1401. postprocessors = []
  1402. self.report_warning('You have requested multiple '
  1403. 'formats but ffmpeg or avconv are not installed.'
  1404. ' The formats won\'t be merged.')
  1405. else:
  1406. postprocessors = [merger]
  1407. def compatible_formats(formats):
  1408. video, audio = formats
  1409. # Check extension
  1410. video_ext, audio_ext = audio.get('ext'), video.get('ext')
  1411. if video_ext and audio_ext:
  1412. COMPATIBLE_EXTS = (
  1413. ('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v'),
  1414. ('webm')
  1415. )
  1416. for exts in COMPATIBLE_EXTS:
  1417. if video_ext in exts and audio_ext in exts:
  1418. return True
  1419. # TODO: Check acodec/vcodec
  1420. return False
  1421. filename_real_ext = os.path.splitext(filename)[1][1:]
  1422. filename_wo_ext = (
  1423. os.path.splitext(filename)[0]
  1424. if filename_real_ext == info_dict['ext']
  1425. else filename)
  1426. requested_formats = info_dict['requested_formats']
  1427. if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
  1428. info_dict['ext'] = 'mkv'
  1429. self.report_warning(
  1430. 'Requested formats are incompatible for merge and will be merged into mkv.')
  1431. # Ensure filename always has a correct extension for successful merge
  1432. filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
  1433. if os.path.exists(encodeFilename(filename)):
  1434. self.to_screen(
  1435. '[download] %s has already been downloaded and '
  1436. 'merged' % filename)
  1437. else:
  1438. for f in requested_formats:
  1439. new_info = dict(info_dict)
  1440. new_info.update(f)
  1441. fname = self.prepare_filename(new_info)
  1442. fname = prepend_extension(fname, 'f%s' % f['format_id'], new_info['ext'])
  1443. downloaded.append(fname)
  1444. partial_success = dl(fname, new_info)
  1445. success = success and partial_success
  1446. info_dict['__postprocessors'] = postprocessors
  1447. info_dict['__files_to_merge'] = downloaded
  1448. else:
  1449. # Just a single file
  1450. success = dl(filename, info_dict)
  1451. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1452. self.report_error('unable to download video data: %s' % str(err))
  1453. return
  1454. except (OSError, IOError) as err:
  1455. raise UnavailableVideoError(err)
  1456. except (ContentTooShortError, ) as err:
  1457. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1458. return
  1459. if success:
  1460. # Fixup content
  1461. fixup_policy = self.params.get('fixup')
  1462. if fixup_policy is None:
  1463. fixup_policy = 'detect_or_warn'
  1464. stretched_ratio = info_dict.get('stretched_ratio')
  1465. if stretched_ratio is not None and stretched_ratio != 1:
  1466. if fixup_policy == 'warn':
  1467. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1468. info_dict['id'], stretched_ratio))
  1469. elif fixup_policy == 'detect_or_warn':
  1470. stretched_pp = FFmpegFixupStretchedPP(self)
  1471. if stretched_pp.available:
  1472. info_dict.setdefault('__postprocessors', [])
  1473. info_dict['__postprocessors'].append(stretched_pp)
  1474. else:
  1475. self.report_warning(
  1476. '%s: Non-uniform pixel ratio (%s). Install ffmpeg or avconv to fix this automatically.' % (
  1477. info_dict['id'], stretched_ratio))
  1478. else:
  1479. assert fixup_policy in ('ignore', 'never')
  1480. if info_dict.get('requested_formats') is None and info_dict.get('container') == 'm4a_dash':
  1481. if fixup_policy == 'warn':
  1482. self.report_warning('%s: writing DASH m4a. Only some players support this container.' % (
  1483. info_dict['id']))
  1484. elif fixup_policy == 'detect_or_warn':
  1485. fixup_pp = FFmpegFixupM4aPP(self)
  1486. if fixup_pp.available:
  1487. info_dict.setdefault('__postprocessors', [])
  1488. info_dict['__postprocessors'].append(fixup_pp)
  1489. else:
  1490. self.report_warning(
  1491. '%s: writing DASH m4a. Only some players support this container. Install ffmpeg or avconv to fix this automatically.' % (
  1492. info_dict['id']))
  1493. else:
  1494. assert fixup_policy in ('ignore', 'never')
  1495. try:
  1496. self.post_process(filename, info_dict)
  1497. except (PostProcessingError) as err:
  1498. self.report_error('postprocessing: %s' % str(err))
  1499. return
  1500. self.record_download_archive(info_dict)
  1501. def download(self, url_list):
  1502. """Download a given list of URLs."""
  1503. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1504. if (len(url_list) > 1 and
  1505. '%' not in outtmpl and
  1506. self.params.get('max_downloads') != 1):
  1507. raise SameFileError(outtmpl)
  1508. for url in url_list:
  1509. try:
  1510. # It also downloads the videos
  1511. res = self.extract_info(
  1512. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  1513. except UnavailableVideoError:
  1514. self.report_error('unable to download video')
  1515. except MaxDownloadsReached:
  1516. self.to_screen('[info] Maximum number of downloaded files reached.')
  1517. raise
  1518. else:
  1519. if self.params.get('dump_single_json', False):
  1520. self.to_stdout(json.dumps(res))
  1521. return self._download_retcode
  1522. def download_with_info_file(self, info_filename):
  1523. with contextlib.closing(fileinput.FileInput(
  1524. [info_filename], mode='r',
  1525. openhook=fileinput.hook_encoded('utf-8'))) as f:
  1526. # FileInput doesn't have a read method, we can't call json.load
  1527. info = self.filter_requested_info(json.loads('\n'.join(f)))
  1528. try:
  1529. self.process_ie_result(info, download=True)
  1530. except DownloadError:
  1531. webpage_url = info.get('webpage_url')
  1532. if webpage_url is not None:
  1533. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1534. return self.download([webpage_url])
  1535. else:
  1536. raise
  1537. return self._download_retcode
  1538. @staticmethod
  1539. def filter_requested_info(info_dict):
  1540. return dict(
  1541. (k, v) for k, v in info_dict.items()
  1542. if k not in ['requested_formats', 'requested_subtitles'])
  1543. def post_process(self, filename, ie_info):
  1544. """Run all the postprocessors on the given file."""
  1545. info = dict(ie_info)
  1546. info['filepath'] = filename
  1547. pps_chain = []
  1548. if ie_info.get('__postprocessors') is not None:
  1549. pps_chain.extend(ie_info['__postprocessors'])
  1550. pps_chain.extend(self._pps)
  1551. for pp in pps_chain:
  1552. files_to_delete = []
  1553. try:
  1554. files_to_delete, info = pp.run(info)
  1555. except PostProcessingError as e:
  1556. self.report_error(e.msg)
  1557. if files_to_delete and not self.params.get('keepvideo', False):
  1558. for old_filename in files_to_delete:
  1559. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1560. try:
  1561. os.remove(encodeFilename(old_filename))
  1562. except (IOError, OSError):
  1563. self.report_warning('Unable to remove downloaded original file')
  1564. def _make_archive_id(self, info_dict):
  1565. # Future-proof against any change in case
  1566. # and backwards compatibility with prior versions
  1567. extractor = info_dict.get('extractor_key')
  1568. if extractor is None:
  1569. if 'id' in info_dict:
  1570. extractor = info_dict.get('ie_key') # key in a playlist
  1571. if extractor is None:
  1572. return None # Incomplete video information
  1573. return extractor.lower() + ' ' + info_dict['id']
  1574. def in_download_archive(self, info_dict):
  1575. fn = self.params.get('download_archive')
  1576. if fn is None:
  1577. return False
  1578. vid_id = self._make_archive_id(info_dict)
  1579. if vid_id is None:
  1580. return False # Incomplete video information
  1581. try:
  1582. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1583. for line in archive_file:
  1584. if line.strip() == vid_id:
  1585. return True
  1586. except IOError as ioe:
  1587. if ioe.errno != errno.ENOENT:
  1588. raise
  1589. return False
  1590. def record_download_archive(self, info_dict):
  1591. fn = self.params.get('download_archive')
  1592. if fn is None:
  1593. return
  1594. vid_id = self._make_archive_id(info_dict)
  1595. assert vid_id
  1596. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1597. archive_file.write(vid_id + '\n')
  1598. @staticmethod
  1599. def format_resolution(format, default='unknown'):
  1600. if format.get('vcodec') == 'none':
  1601. return 'audio only'
  1602. if format.get('resolution') is not None:
  1603. return format['resolution']
  1604. if format.get('height') is not None:
  1605. if format.get('width') is not None:
  1606. res = '%sx%s' % (format['width'], format['height'])
  1607. else:
  1608. res = '%sp' % format['height']
  1609. elif format.get('width') is not None:
  1610. res = '?x%d' % format['width']
  1611. else:
  1612. res = default
  1613. return res
  1614. def _format_note(self, fdict):
  1615. res = ''
  1616. if fdict.get('ext') in ['f4f', 'f4m']:
  1617. res += '(unsupported) '
  1618. if fdict.get('format_note') is not None:
  1619. res += fdict['format_note'] + ' '
  1620. if fdict.get('tbr') is not None:
  1621. res += '%4dk ' % fdict['tbr']
  1622. if fdict.get('container') is not None:
  1623. if res:
  1624. res += ', '
  1625. res += '%s container' % fdict['container']
  1626. if (fdict.get('vcodec') is not None and
  1627. fdict.get('vcodec') != 'none'):
  1628. if res:
  1629. res += ', '
  1630. res += fdict['vcodec']
  1631. if fdict.get('vbr') is not None:
  1632. res += '@'
  1633. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1634. res += 'video@'
  1635. if fdict.get('vbr') is not None:
  1636. res += '%4dk' % fdict['vbr']
  1637. if fdict.get('fps') is not None:
  1638. res += ', %sfps' % fdict['fps']
  1639. if fdict.get('acodec') is not None:
  1640. if res:
  1641. res += ', '
  1642. if fdict['acodec'] == 'none':
  1643. res += 'video only'
  1644. else:
  1645. res += '%-5s' % fdict['acodec']
  1646. elif fdict.get('abr') is not None:
  1647. if res:
  1648. res += ', '
  1649. res += 'audio'
  1650. if fdict.get('abr') is not None:
  1651. res += '@%3dk' % fdict['abr']
  1652. if fdict.get('asr') is not None:
  1653. res += ' (%5dHz)' % fdict['asr']
  1654. if fdict.get('filesize') is not None:
  1655. if res:
  1656. res += ', '
  1657. res += format_bytes(fdict['filesize'])
  1658. elif fdict.get('filesize_approx') is not None:
  1659. if res:
  1660. res += ', '
  1661. res += '~' + format_bytes(fdict['filesize_approx'])
  1662. return res
  1663. def list_formats(self, info_dict):
  1664. formats = info_dict.get('formats', [info_dict])
  1665. table = [
  1666. [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
  1667. for f in formats
  1668. if f.get('preference') is None or f['preference'] >= -1000]
  1669. if len(formats) > 1:
  1670. table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
  1671. header_line = ['format code', 'extension', 'resolution', 'note']
  1672. self.to_screen(
  1673. '[info] Available formats for %s:\n%s' %
  1674. (info_dict['id'], render_table(header_line, table)))
  1675. def list_thumbnails(self, info_dict):
  1676. thumbnails = info_dict.get('thumbnails')
  1677. if not thumbnails:
  1678. tn_url = info_dict.get('thumbnail')
  1679. if tn_url:
  1680. thumbnails = [{'id': '0', 'url': tn_url}]
  1681. else:
  1682. self.to_screen(
  1683. '[info] No thumbnails present for %s' % info_dict['id'])
  1684. return
  1685. self.to_screen(
  1686. '[info] Thumbnails for %s:' % info_dict['id'])
  1687. self.to_screen(render_table(
  1688. ['ID', 'width', 'height', 'URL'],
  1689. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  1690. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  1691. if not subtitles:
  1692. self.to_screen('%s has no %s' % (video_id, name))
  1693. return
  1694. self.to_screen(
  1695. 'Available %s for %s:' % (name, video_id))
  1696. self.to_screen(render_table(
  1697. ['Language', 'formats'],
  1698. [[lang, ', '.join(f['ext'] for f in reversed(formats))]
  1699. for lang, formats in subtitles.items()]))
  1700. def urlopen(self, req):
  1701. """ Start an HTTP download """
  1702. if isinstance(req, compat_basestring):
  1703. req = sanitized_Request(req)
  1704. return self._opener.open(req, timeout=self._socket_timeout)
  1705. def print_debug_header(self):
  1706. if not self.params.get('verbose'):
  1707. return
  1708. if type('') is not compat_str:
  1709. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1710. self.report_warning(
  1711. 'Your Python is broken! Update to a newer and supported version')
  1712. stdout_encoding = getattr(
  1713. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1714. encoding_str = (
  1715. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1716. locale.getpreferredencoding(),
  1717. sys.getfilesystemencoding(),
  1718. stdout_encoding,
  1719. self.get_encoding()))
  1720. write_string(encoding_str, encoding=None)
  1721. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1722. try:
  1723. sp = subprocess.Popen(
  1724. ['git', 'rev-parse', '--short', 'HEAD'],
  1725. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1726. cwd=os.path.dirname(os.path.abspath(__file__)))
  1727. out, err = sp.communicate()
  1728. out = out.decode().strip()
  1729. if re.match('[0-9a-f]+', out):
  1730. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1731. except Exception:
  1732. try:
  1733. sys.exc_clear()
  1734. except Exception:
  1735. pass
  1736. self._write_string('[debug] Python version %s - %s\n' % (
  1737. platform.python_version(), platform_name()))
  1738. exe_versions = FFmpegPostProcessor.get_versions(self)
  1739. exe_versions['rtmpdump'] = rtmpdump_version()
  1740. exe_str = ', '.join(
  1741. '%s %s' % (exe, v)
  1742. for exe, v in sorted(exe_versions.items())
  1743. if v
  1744. )
  1745. if not exe_str:
  1746. exe_str = 'none'
  1747. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1748. proxy_map = {}
  1749. for handler in self._opener.handlers:
  1750. if hasattr(handler, 'proxies'):
  1751. proxy_map.update(handler.proxies)
  1752. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1753. if self.params.get('call_home', False):
  1754. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1755. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1756. latest_version = self.urlopen(
  1757. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1758. if version_tuple(latest_version) > version_tuple(__version__):
  1759. self.report_warning(
  1760. 'You are using an outdated version (newest version: %s)! '
  1761. 'See https://yt-dl.org/update if you need help updating.' %
  1762. latest_version)
  1763. def _setup_opener(self):
  1764. timeout_val = self.params.get('socket_timeout')
  1765. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1766. opts_cookiefile = self.params.get('cookiefile')
  1767. opts_proxy = self.params.get('proxy')
  1768. if opts_cookiefile is None:
  1769. self.cookiejar = compat_cookiejar.CookieJar()
  1770. else:
  1771. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1772. opts_cookiefile)
  1773. if os.access(opts_cookiefile, os.R_OK):
  1774. self.cookiejar.load()
  1775. cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
  1776. if opts_proxy is not None:
  1777. if opts_proxy == '':
  1778. proxies = {}
  1779. else:
  1780. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1781. else:
  1782. proxies = compat_urllib_request.getproxies()
  1783. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1784. if 'http' in proxies and 'https' not in proxies:
  1785. proxies['https'] = proxies['http']
  1786. proxy_handler = PerRequestProxyHandler(proxies)
  1787. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1788. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1789. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1790. data_handler = compat_urllib_request_DataHandler()
  1791. opener = compat_urllib_request.build_opener(
  1792. proxy_handler, https_handler, cookie_processor, ydlh, data_handler)
  1793. # Delete the default user-agent header, which would otherwise apply in
  1794. # cases where our custom HTTP handler doesn't come into play
  1795. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1796. opener.addheaders = []
  1797. self._opener = opener
  1798. def encode(self, s):
  1799. if isinstance(s, bytes):
  1800. return s # Already encoded
  1801. try:
  1802. return s.encode(self.get_encoding())
  1803. except UnicodeEncodeError as err:
  1804. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1805. raise
  1806. def get_encoding(self):
  1807. encoding = self.params.get('encoding')
  1808. if encoding is None:
  1809. encoding = preferredencoding()
  1810. return encoding
  1811. def _write_thumbnails(self, info_dict, filename):
  1812. if self.params.get('writethumbnail', False):
  1813. thumbnails = info_dict.get('thumbnails')
  1814. if thumbnails:
  1815. thumbnails = [thumbnails[-1]]
  1816. elif self.params.get('write_all_thumbnails', False):
  1817. thumbnails = info_dict.get('thumbnails')
  1818. else:
  1819. return
  1820. if not thumbnails:
  1821. # No thumbnails present, so return immediately
  1822. return
  1823. for t in thumbnails:
  1824. thumb_ext = determine_ext(t['url'], 'jpg')
  1825. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  1826. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  1827. t['filename'] = thumb_filename = os.path.splitext(filename)[0] + suffix + '.' + thumb_ext
  1828. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  1829. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  1830. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1831. else:
  1832. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  1833. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  1834. try:
  1835. uf = self.urlopen(t['url'])
  1836. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  1837. shutil.copyfileobj(uf, thumbf)
  1838. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  1839. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  1840. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1841. self.report_warning('Unable to download thumbnail "%s": %s' %
  1842. (t['url'], error_to_str(err)))