YoutubeDL.py 74 KB

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