YoutubeDL.py 63 KB

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