YoutubeDL.py 74 KB

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