You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

910 lines
38 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import errno
  5. import io
  6. import json
  7. import os
  8. import re
  9. import shutil
  10. import socket
  11. import sys
  12. import time
  13. import traceback
  14. if os.name == 'nt':
  15. import ctypes
  16. from .utils import (
  17. compat_http_client,
  18. compat_print,
  19. compat_str,
  20. compat_urllib_error,
  21. compat_urllib_request,
  22. ContentTooShortError,
  23. date_from_str,
  24. DateRange,
  25. determine_ext,
  26. DownloadError,
  27. encodeFilename,
  28. ExtractorError,
  29. locked_file,
  30. MaxDownloadsReached,
  31. PostProcessingError,
  32. preferredencoding,
  33. SameFileError,
  34. sanitize_filename,
  35. subtitles_filename,
  36. takewhile_inclusive,
  37. UnavailableVideoError,
  38. write_json_file,
  39. write_string,
  40. )
  41. from .extractor import get_info_extractor, gen_extractors
  42. from .FileDownloader import FileDownloader
  43. class YoutubeDL(object):
  44. """YoutubeDL class.
  45. YoutubeDL objects are the ones responsible of downloading the
  46. actual video file and writing it to disk if the user has requested
  47. it, among some other tasks. In most cases there should be one per
  48. program. As, given a video URL, the downloader doesn't know how to
  49. extract all the needed information, task that InfoExtractors do, it
  50. has to pass the URL to one of them.
  51. For this, YoutubeDL objects have a method that allows
  52. InfoExtractors to be registered in a given order. When it is passed
  53. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  54. finds that reports being able to handle it. The InfoExtractor extracts
  55. all the information about the video or videos the URL refers to, and
  56. YoutubeDL process the extracted information, possibly using a File
  57. Downloader to download the video.
  58. YoutubeDL objects accept a lot of parameters. In order not to saturate
  59. the object constructor with arguments, it receives a dictionary of
  60. options instead. These options are available through the params
  61. attribute for the InfoExtractors to use. The YoutubeDL also
  62. registers itself as the downloader in charge for the InfoExtractors
  63. that are added to it, so this is a "mutual registration".
  64. Available options:
  65. username: Username for authentication purposes.
  66. password: Password for authentication purposes.
  67. videopassword: Password for acces a video.
  68. usenetrc: Use netrc for authentication instead.
  69. verbose: Print additional info to stdout.
  70. quiet: Do not print messages to stdout.
  71. forceurl: Force printing final URL.
  72. forcetitle: Force printing title.
  73. forceid: Force printing ID.
  74. forcethumbnail: Force printing thumbnail URL.
  75. forcedescription: Force printing description.
  76. forcefilename: Force printing final filename.
  77. forcejson: Force printing info_dict as JSON.
  78. simulate: Do not download the video files.
  79. format: Video format code.
  80. format_limit: Highest quality format to try.
  81. outtmpl: Template for output names.
  82. restrictfilenames: Do not allow "&" and spaces in file names
  83. ignoreerrors: Do not stop on download errors.
  84. nooverwrites: Prevent overwriting files.
  85. playliststart: Playlist item to start at.
  86. playlistend: Playlist item to end at.
  87. matchtitle: Download only matching titles.
  88. rejecttitle: Reject downloads for matching titles.
  89. logger: Log messages to a logging.Logger instance.
  90. logtostderr: Log messages to stderr instead of stdout.
  91. writedescription: Write the video description to a .description file
  92. writeinfojson: Write the video description to a .info.json file
  93. writeannotations: Write the video annotations to a .annotations.xml file
  94. writethumbnail: Write the thumbnail image to a file
  95. writesubtitles: Write the video subtitles to a file
  96. writeautomaticsub: Write the automatic subtitles to a file
  97. allsubtitles: Downloads all the subtitles of the video
  98. (requires writesubtitles or writeautomaticsub)
  99. listsubtitles: Lists all available subtitles for the video
  100. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  101. subtitleslangs: List of languages of the subtitles to download
  102. keepvideo: Keep the video file after post-processing
  103. daterange: A DateRange object, download only if the upload_date is in the range.
  104. skip_download: Skip the actual download of the video file
  105. cachedir: Location of the cache files in the filesystem.
  106. None to disable filesystem cache.
  107. noplaylist: Download single video instead of a playlist if in doubt.
  108. age_limit: An integer representing the user's age in years.
  109. Unsuitable videos for the given age are skipped.
  110. downloadarchive: File name of a file where all downloads are recorded.
  111. Videos already present in the file are not downloaded
  112. again.
  113. The following parameters are not used by YoutubeDL itself, they are used by
  114. the FileDownloader:
  115. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  116. noresizebuffer, retries, continuedl, noprogress, consoletitle
  117. """
  118. params = None
  119. _ies = []
  120. _pps = []
  121. _download_retcode = None
  122. _num_downloads = None
  123. _screen_file = None
  124. def __init__(self, params):
  125. """Create a FileDownloader object with the given options."""
  126. self._ies = []
  127. self._ies_instances = {}
  128. self._pps = []
  129. self._progress_hooks = []
  130. self._download_retcode = 0
  131. self._num_downloads = 0
  132. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  133. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  134. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  135. and not params['restrictfilenames']):
  136. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  137. self.report_warning(
  138. u'Assuming --restrict-filenames since file system encoding '
  139. u'cannot encode all charactes. '
  140. u'Set the LC_ALL environment variable to fix this.')
  141. params['restrictfilenames'] = True
  142. self.params = params
  143. self.fd = FileDownloader(self, self.params)
  144. if '%(stitle)s' in self.params['outtmpl']:
  145. self.report_warning(u'%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  146. def add_info_extractor(self, ie):
  147. """Add an InfoExtractor object to the end of the list."""
  148. self._ies.append(ie)
  149. self._ies_instances[ie.ie_key()] = ie
  150. ie.set_downloader(self)
  151. def get_info_extractor(self, ie_key):
  152. """
  153. Get an instance of an IE with name ie_key, it will try to get one from
  154. the _ies list, if there's no instance it will create a new one and add
  155. it to the extractor list.
  156. """
  157. ie = self._ies_instances.get(ie_key)
  158. if ie is None:
  159. ie = get_info_extractor(ie_key)()
  160. self.add_info_extractor(ie)
  161. return ie
  162. def add_default_info_extractors(self):
  163. """
  164. Add the InfoExtractors returned by gen_extractors to the end of the list
  165. """
  166. for ie in gen_extractors():
  167. self.add_info_extractor(ie)
  168. def add_post_processor(self, pp):
  169. """Add a PostProcessor object to the end of the chain."""
  170. self._pps.append(pp)
  171. pp.set_downloader(self)
  172. def to_screen(self, message, skip_eol=False):
  173. """Print message to stdout if not in quiet mode."""
  174. if self.params.get('logger'):
  175. self.params['logger'].debug(message)
  176. elif not self.params.get('quiet', False):
  177. terminator = [u'\n', u''][skip_eol]
  178. output = message + terminator
  179. write_string(output, self._screen_file)
  180. def to_stderr(self, message):
  181. """Print message to stderr."""
  182. assert type(message) == type(u'')
  183. if self.params.get('logger'):
  184. self.params['logger'].error(message)
  185. else:
  186. output = message + u'\n'
  187. if 'b' in getattr(self._screen_file, 'mode', '') or sys.version_info[0] < 3: # Python 2 lies about the mode of sys.stdout/sys.stderr
  188. output = output.encode(preferredencoding())
  189. sys.stderr.write(output)
  190. def to_console_title(self, message):
  191. if not self.params.get('consoletitle', False):
  192. return
  193. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  194. # c_wchar_p() might not be necessary if `message` is
  195. # already of type unicode()
  196. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  197. elif 'TERM' in os.environ:
  198. write_string(u'\033]0;%s\007' % message, self._screen_file)
  199. def save_console_title(self):
  200. if not self.params.get('consoletitle', False):
  201. return
  202. if 'TERM' in os.environ:
  203. # Save the title on stack
  204. write_string(u'\033[22;0t', self._screen_file)
  205. def restore_console_title(self):
  206. if not self.params.get('consoletitle', False):
  207. return
  208. if 'TERM' in os.environ:
  209. # Restore the title from stack
  210. write_string(u'\033[23;0t', self._screen_file)
  211. def __enter__(self):
  212. self.save_console_title()
  213. return self
  214. def __exit__(self, *args):
  215. self.restore_console_title()
  216. def fixed_template(self):
  217. """Checks if the output template is fixed."""
  218. return (re.search(u'(?u)%\\(.+?\\)s', self.params['outtmpl']) is None)
  219. def trouble(self, message=None, tb=None):
  220. """Determine action to take when a download problem appears.
  221. Depending on if the downloader has been configured to ignore
  222. download errors or not, this method may throw an exception or
  223. not when errors are found, after printing the message.
  224. tb, if given, is additional traceback information.
  225. """
  226. if message is not None:
  227. self.to_stderr(message)
  228. if self.params.get('verbose'):
  229. if tb is None:
  230. if sys.exc_info()[0]: # if .trouble has been called from an except block
  231. tb = u''
  232. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  233. tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  234. tb += compat_str(traceback.format_exc())
  235. else:
  236. tb_data = traceback.format_list(traceback.extract_stack())
  237. tb = u''.join(tb_data)
  238. self.to_stderr(tb)
  239. if not self.params.get('ignoreerrors', False):
  240. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  241. exc_info = sys.exc_info()[1].exc_info
  242. else:
  243. exc_info = sys.exc_info()
  244. raise DownloadError(message, exc_info)
  245. self._download_retcode = 1
  246. def report_warning(self, message):
  247. '''
  248. Print the message to stderr, it will be prefixed with 'WARNING:'
  249. If stderr is a tty file the 'WARNING:' will be colored
  250. '''
  251. if sys.stderr.isatty() and os.name != 'nt':
  252. _msg_header = u'\033[0;33mWARNING:\033[0m'
  253. else:
  254. _msg_header = u'WARNING:'
  255. warning_message = u'%s %s' % (_msg_header, message)
  256. self.to_stderr(warning_message)
  257. def report_error(self, message, tb=None):
  258. '''
  259. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  260. in red if stderr is a tty file.
  261. '''
  262. if sys.stderr.isatty() and os.name != 'nt':
  263. _msg_header = u'\033[0;31mERROR:\033[0m'
  264. else:
  265. _msg_header = u'ERROR:'
  266. error_message = u'%s %s' % (_msg_header, message)
  267. self.trouble(error_message, tb)
  268. def report_writedescription(self, descfn):
  269. """ Report that the description file is being written """
  270. self.to_screen(u'[info] Writing video description to: ' + descfn)
  271. def report_writesubtitles(self, sub_filename):
  272. """ Report that the subtitles file is being written """
  273. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  274. def report_writeinfojson(self, infofn):
  275. """ Report that the metadata file has been written """
  276. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  277. def report_writeannotations(self, annofn):
  278. """ Report that the annotations file has been written. """
  279. self.to_screen(u'[info] Writing video annotations to: ' + annofn)
  280. def report_file_already_downloaded(self, file_name):
  281. """Report file has already been fully downloaded."""
  282. try:
  283. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  284. except UnicodeEncodeError:
  285. self.to_screen(u'[download] The file has already been downloaded')
  286. def increment_downloads(self):
  287. """Increment the ordinal that assigns a number to each file."""
  288. self._num_downloads += 1
  289. def prepare_filename(self, info_dict):
  290. """Generate the output filename."""
  291. try:
  292. template_dict = dict(info_dict)
  293. template_dict['epoch'] = int(time.time())
  294. autonumber_size = self.params.get('autonumber_size')
  295. if autonumber_size is None:
  296. autonumber_size = 5
  297. autonumber_templ = u'%0' + str(autonumber_size) + u'd'
  298. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  299. if template_dict.get('playlist_index') is not None:
  300. template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
  301. sanitize = lambda k, v: sanitize_filename(
  302. u'NA' if v is None else compat_str(v),
  303. restricted=self.params.get('restrictfilenames'),
  304. is_id=(k == u'id'))
  305. template_dict = dict((k, sanitize(k, v))
  306. for k, v in template_dict.items())
  307. tmpl = os.path.expanduser(self.params['outtmpl'])
  308. filename = tmpl % template_dict
  309. return filename
  310. except KeyError as err:
  311. self.report_error(u'Erroneous output template')
  312. return None
  313. except ValueError as err:
  314. self.report_error(u'Error in output template: ' + str(err) + u' (encoding: ' + repr(preferredencoding()) + ')')
  315. return None
  316. def _match_entry(self, info_dict):
  317. """ Returns None iff the file should be downloaded """
  318. if 'title' in info_dict:
  319. # This can happen when we're just evaluating the playlist
  320. title = info_dict['title']
  321. matchtitle = self.params.get('matchtitle', False)
  322. if matchtitle:
  323. if not re.search(matchtitle, title, re.IGNORECASE):
  324. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  325. rejecttitle = self.params.get('rejecttitle', False)
  326. if rejecttitle:
  327. if re.search(rejecttitle, title, re.IGNORECASE):
  328. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  329. date = info_dict.get('upload_date', None)
  330. if date is not None:
  331. dateRange = self.params.get('daterange', DateRange())
  332. if date not in dateRange:
  333. return u'[download] %s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  334. age_limit = self.params.get('age_limit')
  335. if age_limit is not None:
  336. if age_limit < info_dict.get('age_limit', 0):
  337. return u'Skipping "' + title + '" because it is age restricted'
  338. if self.in_download_archive(info_dict):
  339. return (u'%s has already been recorded in archive'
  340. % info_dict.get('title', info_dict.get('id', u'video')))
  341. return None
  342. @staticmethod
  343. def add_extra_info(info_dict, extra_info):
  344. '''Set the keys from extra_info in info dict if they are missing'''
  345. for key, value in extra_info.items():
  346. info_dict.setdefault(key, value)
  347. def extract_info(self, url, download=True, ie_key=None, extra_info={}):
  348. '''
  349. Returns a list with a dictionary for each video we find.
  350. If 'download', also downloads the videos.
  351. extra_info is a dict containing the extra values to add to each result
  352. '''
  353. if ie_key:
  354. ies = [self.get_info_extractor(ie_key)]
  355. else:
  356. ies = self._ies
  357. for ie in ies:
  358. if not ie.suitable(url):
  359. continue
  360. if not ie.working():
  361. self.report_warning(u'The program functionality for this site has been marked as broken, '
  362. u'and will probably not work.')
  363. try:
  364. ie_result = ie.extract(url)
  365. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  366. break
  367. if isinstance(ie_result, list):
  368. # Backwards compatibility: old IE result format
  369. ie_result = {
  370. '_type': 'compat_list',
  371. 'entries': ie_result,
  372. }
  373. self.add_extra_info(ie_result,
  374. {
  375. 'extractor': ie.IE_NAME,
  376. 'webpage_url': url,
  377. 'extractor_key': ie.ie_key(),
  378. })
  379. return self.process_ie_result(ie_result, download, extra_info)
  380. except ExtractorError as de: # An error we somewhat expected
  381. self.report_error(compat_str(de), de.format_traceback())
  382. break
  383. except Exception as e:
  384. if self.params.get('ignoreerrors', False):
  385. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  386. break
  387. else:
  388. raise
  389. else:
  390. self.report_error(u'no suitable InfoExtractor: %s' % url)
  391. def process_ie_result(self, ie_result, download=True, extra_info={}):
  392. """
  393. Take the result of the ie(may be modified) and resolve all unresolved
  394. references (URLs, playlist items).
  395. It will also download the videos if 'download'.
  396. Returns the resolved ie_result.
  397. """
  398. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  399. if result_type == 'video':
  400. self.add_extra_info(ie_result, extra_info)
  401. return self.process_video_result(ie_result, download=download)
  402. elif result_type == 'url':
  403. # We have to add extra_info to the results because it may be
  404. # contained in a playlist
  405. return self.extract_info(ie_result['url'],
  406. download,
  407. ie_key=ie_result.get('ie_key'),
  408. extra_info=extra_info)
  409. elif result_type == 'playlist':
  410. # We process each entry in the playlist
  411. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  412. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  413. playlist_results = []
  414. n_all_entries = len(ie_result['entries'])
  415. playliststart = self.params.get('playliststart', 1) - 1
  416. playlistend = self.params.get('playlistend', -1)
  417. if playlistend == -1:
  418. entries = ie_result['entries'][playliststart:]
  419. else:
  420. entries = ie_result['entries'][playliststart:playlistend]
  421. n_entries = len(entries)
  422. self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  423. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  424. for i, entry in enumerate(entries, 1):
  425. self.to_screen(u'[download] Downloading video #%s of %s' % (i, n_entries))
  426. extra = {
  427. 'playlist': playlist,
  428. 'playlist_index': i + playliststart,
  429. 'extractor': ie_result['extractor'],
  430. 'webpage_url': ie_result['webpage_url'],
  431. 'extractor_key': ie_result['extractor_key'],
  432. }
  433. reason = self._match_entry(entry)
  434. if reason is not None:
  435. self.to_screen(u'[download] ' + reason)
  436. continue
  437. entry_result = self.process_ie_result(entry,
  438. download=download,
  439. extra_info=extra)
  440. playlist_results.append(entry_result)
  441. ie_result['entries'] = playlist_results
  442. return ie_result
  443. elif result_type == 'compat_list':
  444. def _fixup(r):
  445. self.add_extra_info(r,
  446. {
  447. 'extractor': ie_result['extractor'],
  448. 'webpage_url': ie_result['webpage_url'],
  449. 'extractor_key': ie_result['extractor_key'],
  450. })
  451. return r
  452. ie_result['entries'] = [
  453. self.process_ie_result(_fixup(r), download, extra_info)
  454. for r in ie_result['entries']
  455. ]
  456. return ie_result
  457. else:
  458. raise Exception('Invalid result type: %s' % result_type)
  459. def select_format(self, format_spec, available_formats):
  460. if format_spec == 'best' or format_spec is None:
  461. return available_formats[-1]
  462. elif format_spec == 'worst':
  463. return available_formats[0]
  464. else:
  465. extensions = [u'mp4', u'flv', u'webm', u'3gp']
  466. if format_spec in extensions:
  467. filter_f = lambda f: f['ext'] == format_spec
  468. else:
  469. filter_f = lambda f: f['format_id'] == format_spec
  470. matches = list(filter(filter_f, available_formats))
  471. if matches:
  472. return matches[-1]
  473. return None
  474. def process_video_result(self, info_dict, download=True):
  475. assert info_dict.get('_type', 'video') == 'video'
  476. if 'playlist' not in info_dict:
  477. # It isn't part of a playlist
  478. info_dict['playlist'] = None
  479. info_dict['playlist_index'] = None
  480. # This extractors handle format selection themselves
  481. if info_dict['extractor'] in [u'youtube', u'Youku']:
  482. if download:
  483. self.process_info(info_dict)
  484. return info_dict
  485. # We now pick which formats have to be downloaded
  486. if info_dict.get('formats') is None:
  487. # There's only one format available
  488. formats = [info_dict]
  489. else:
  490. formats = info_dict['formats']
  491. # We check that all the formats have the format and format_id fields
  492. for (i, format) in enumerate(formats):
  493. if format.get('format_id') is None:
  494. format['format_id'] = compat_str(i)
  495. if format.get('format') is None:
  496. format['format'] = u'{id} - {res}{note}'.format(
  497. id=format['format_id'],
  498. res=self.format_resolution(format),
  499. note=u' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  500. )
  501. # Automatically determine file extension if missing
  502. if 'ext' not in format:
  503. format['ext'] = determine_ext(format['url'])
  504. if self.params.get('listformats', None):
  505. self.list_formats(info_dict)
  506. return
  507. format_limit = self.params.get('format_limit', None)
  508. if format_limit:
  509. formats = list(takewhile_inclusive(
  510. lambda f: f['format_id'] != format_limit, formats
  511. ))
  512. if self.params.get('prefer_free_formats'):
  513. def _free_formats_key(f):
  514. try:
  515. ext_ord = [u'flv', u'mp4', u'webm'].index(f['ext'])
  516. except ValueError:
  517. ext_ord = -1
  518. # We only compare the extension if they have the same height and width
  519. return (f.get('height'), f.get('width'), ext_ord)
  520. formats = sorted(formats, key=_free_formats_key)
  521. req_format = self.params.get('format', 'best')
  522. if req_format is None:
  523. req_format = 'best'
  524. formats_to_download = []
  525. # The -1 is for supporting YoutubeIE
  526. if req_format in ('-1', 'all'):
  527. formats_to_download = formats
  528. else:
  529. # We can accept formats requestd in the format: 34/5/best, we pick
  530. # the first that is available, starting from left
  531. req_formats = req_format.split('/')
  532. for rf in req_formats:
  533. selected_format = self.select_format(rf, formats)
  534. if selected_format is not None:
  535. formats_to_download = [selected_format]
  536. break
  537. if not formats_to_download:
  538. raise ExtractorError(u'requested format not available',
  539. expected=True)
  540. if download:
  541. if len(formats_to_download) > 1:
  542. self.to_screen(u'[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  543. for format in formats_to_download:
  544. new_info = dict(info_dict)
  545. new_info.update(format)
  546. self.process_info(new_info)
  547. # We update the info dict with the best quality format (backwards compatibility)
  548. info_dict.update(formats_to_download[-1])
  549. return info_dict
  550. def process_info(self, info_dict):
  551. """Process a single resolved IE result."""
  552. assert info_dict.get('_type', 'video') == 'video'
  553. #We increment the download the download count here to match the previous behaviour.
  554. self.increment_downloads()
  555. info_dict['fulltitle'] = info_dict['title']
  556. if len(info_dict['title']) > 200:
  557. info_dict['title'] = info_dict['title'][:197] + u'...'
  558. # Keep for backwards compatibility
  559. info_dict['stitle'] = info_dict['title']
  560. if not 'format' in info_dict:
  561. info_dict['format'] = info_dict['ext']
  562. reason = self._match_entry(info_dict)
  563. if reason is not None:
  564. self.to_screen(u'[download] ' + reason)
  565. return
  566. max_downloads = self.params.get('max_downloads')
  567. if max_downloads is not None:
  568. if self._num_downloads > int(max_downloads):
  569. raise MaxDownloadsReached()
  570. filename = self.prepare_filename(info_dict)
  571. # Forced printings
  572. if self.params.get('forcetitle', False):
  573. compat_print(info_dict['fulltitle'])
  574. if self.params.get('forceid', False):
  575. compat_print(info_dict['id'])
  576. if self.params.get('forceurl', False):
  577. # For RTMP URLs, also include the playpath
  578. compat_print(info_dict['url'] + info_dict.get('play_path', u''))
  579. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  580. compat_print(info_dict['thumbnail'])
  581. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  582. compat_print(info_dict['description'])
  583. if self.params.get('forcefilename', False) and filename is not None:
  584. compat_print(filename)
  585. if self.params.get('forceformat', False):
  586. compat_print(info_dict['format'])
  587. if self.params.get('forcejson', False):
  588. compat_print(json.dumps(info_dict))
  589. # Do nothing else if in simulate mode
  590. if self.params.get('simulate', False):
  591. return
  592. if filename is None:
  593. return
  594. try:
  595. dn = os.path.dirname(encodeFilename(filename))
  596. if dn != '' and not os.path.exists(dn):
  597. os.makedirs(dn)
  598. except (OSError, IOError) as err:
  599. self.report_error(u'unable to create directory ' + compat_str(err))
  600. return
  601. if self.params.get('writedescription', False):
  602. try:
  603. descfn = filename + u'.description'
  604. self.report_writedescription(descfn)
  605. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  606. descfile.write(info_dict['description'])
  607. except (KeyError, TypeError):
  608. self.report_warning(u'There\'s no description to write.')
  609. except (OSError, IOError):
  610. self.report_error(u'Cannot write description file ' + descfn)
  611. return
  612. if self.params.get('writeannotations', False):
  613. try:
  614. annofn = filename + u'.annotations.xml'
  615. self.report_writeannotations(annofn)
  616. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  617. annofile.write(info_dict['annotations'])
  618. except (KeyError, TypeError):
  619. self.report_warning(u'There are no annotations to write.')
  620. except (OSError, IOError):
  621. self.report_error(u'Cannot write annotations file: ' + annofn)
  622. return
  623. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  624. self.params.get('writeautomaticsub')])
  625. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  626. # subtitles download errors are already managed as troubles in relevant IE
  627. # that way it will silently go on when used with unsupporting IE
  628. subtitles = info_dict['subtitles']
  629. sub_format = self.params.get('subtitlesformat', 'srt')
  630. for sub_lang in subtitles.keys():
  631. sub = subtitles[sub_lang]
  632. if sub is None:
  633. continue
  634. try:
  635. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  636. self.report_writesubtitles(sub_filename)
  637. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  638. subfile.write(sub)
  639. except (OSError, IOError):
  640. self.report_error(u'Cannot write subtitles file ' + descfn)
  641. return
  642. if self.params.get('writeinfojson', False):
  643. infofn = os.path.splitext(filename)[0] + u'.info.json'
  644. self.report_writeinfojson(infofn)
  645. try:
  646. json_info_dict = dict((k, v) for k, v in info_dict.items() if not k in ['urlhandle'])
  647. write_json_file(json_info_dict, encodeFilename(infofn))
  648. except (OSError, IOError):
  649. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  650. return
  651. if self.params.get('writethumbnail', False):
  652. if info_dict.get('thumbnail') is not None:
  653. thumb_format = determine_ext(info_dict['thumbnail'], u'jpg')
  654. thumb_filename = filename.rpartition('.')[0] + u'.' + thumb_format
  655. self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
  656. (info_dict['extractor'], info_dict['id']))
  657. try:
  658. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  659. with open(thumb_filename, 'wb') as thumbf:
  660. shutil.copyfileobj(uf, thumbf)
  661. self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
  662. (info_dict['extractor'], info_dict['id'], thumb_filename))
  663. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  664. self.report_warning(u'Unable to download thumbnail "%s": %s' %
  665. (info_dict['thumbnail'], compat_str(err)))
  666. if not self.params.get('skip_download', False):
  667. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  668. success = True
  669. else:
  670. try:
  671. success = self.fd._do_download(filename, info_dict)
  672. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  673. self.report_error(u'unable to download video data: %s' % str(err))
  674. return
  675. except (OSError, IOError) as err:
  676. raise UnavailableVideoError(err)
  677. except (ContentTooShortError, ) as err:
  678. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  679. return
  680. if success:
  681. try:
  682. self.post_process(filename, info_dict)
  683. except (PostProcessingError) as err:
  684. self.report_error(u'postprocessing: %s' % str(err))
  685. return
  686. self.record_download_archive(info_dict)
  687. def download(self, url_list):
  688. """Download a given list of URLs."""
  689. if len(url_list) > 1 and self.fixed_template():
  690. raise SameFileError(self.params['outtmpl'])
  691. for url in url_list:
  692. try:
  693. #It also downloads the videos
  694. videos = self.extract_info(url)
  695. except UnavailableVideoError:
  696. self.report_error(u'unable to download video')
  697. except MaxDownloadsReached:
  698. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  699. raise
  700. return self._download_retcode
  701. def post_process(self, filename, ie_info):
  702. """Run all the postprocessors on the given file."""
  703. info = dict(ie_info)
  704. info['filepath'] = filename
  705. keep_video = None
  706. for pp in self._pps:
  707. try:
  708. keep_video_wish, new_info = pp.run(info)
  709. if keep_video_wish is not None:
  710. if keep_video_wish:
  711. keep_video = keep_video_wish
  712. elif keep_video is None:
  713. # No clear decision yet, let IE decide
  714. keep_video = keep_video_wish
  715. except PostProcessingError as e:
  716. self.report_error(e.msg)
  717. if keep_video is False and not self.params.get('keepvideo', False):
  718. try:
  719. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  720. os.remove(encodeFilename(filename))
  721. except (IOError, OSError):
  722. self.report_warning(u'Unable to remove downloaded video file')
  723. def in_download_archive(self, info_dict):
  724. fn = self.params.get('download_archive')
  725. if fn is None:
  726. return False
  727. extractor = info_dict.get('extractor_id')
  728. if extractor is None:
  729. if 'id' in info_dict:
  730. extractor = info_dict.get('ie_key') # key in a playlist
  731. if extractor is None:
  732. return False # Incomplete video information
  733. # Future-proof against any change in case
  734. # and backwards compatibility with prior versions
  735. extractor = extractor.lower()
  736. vid_id = extractor + u' ' + info_dict['id']
  737. try:
  738. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  739. for line in archive_file:
  740. if line.strip() == vid_id:
  741. return True
  742. except IOError as ioe:
  743. if ioe.errno != errno.ENOENT:
  744. raise
  745. return False
  746. def record_download_archive(self, info_dict):
  747. fn = self.params.get('download_archive')
  748. if fn is None:
  749. return
  750. vid_id = info_dict['extractor'] + u' ' + info_dict['id']
  751. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  752. archive_file.write(vid_id + u'\n')
  753. @staticmethod
  754. def format_resolution(format, default='unknown'):
  755. if format.get('_resolution') is not None:
  756. return format['_resolution']
  757. if format.get('height') is not None:
  758. if format.get('width') is not None:
  759. res = u'%sx%s' % (format['width'], format['height'])
  760. else:
  761. res = u'%sp' % format['height']
  762. else:
  763. res = default
  764. return res
  765. def list_formats(self, info_dict):
  766. def format_note(fdict):
  767. if fdict.get('format_note') is not None:
  768. return fdict['format_note']
  769. res = u''
  770. if fdict.get('vcodec') is not None:
  771. res += u'%-5s' % fdict['vcodec']
  772. elif fdict.get('vbr') is not None:
  773. res += u'video'
  774. if fdict.get('vbr') is not None:
  775. res += u'@%4dk' % fdict['vbr']
  776. if fdict.get('acodec') is not None:
  777. if res:
  778. res += u', '
  779. res += u'%-5s' % fdict['acodec']
  780. elif fdict.get('abr') is not None:
  781. if res:
  782. res += u', '
  783. res += 'audio'
  784. if fdict.get('abr') is not None:
  785. res += u'@%3dk' % fdict['abr']
  786. return res
  787. def line(format):
  788. return (u'%-20s%-10s%-12s%s' % (
  789. format['format_id'],
  790. format['ext'],
  791. self.format_resolution(format),
  792. format_note(format),
  793. )
  794. )
  795. formats = info_dict.get('formats', [info_dict])
  796. formats_s = list(map(line, formats))
  797. if len(formats) > 1:
  798. formats_s[0] += (' ' if format_note(formats[0]) else '') + '(worst)'
  799. formats_s[-1] += (' ' if format_note(formats[-1]) else '') + '(best)'
  800. header_line = line({
  801. 'format_id': u'format code', 'ext': u'extension',
  802. '_resolution': u'resolution', 'format_note': u'note'})
  803. self.to_screen(u'[info] Available formats for %s:\n%s\n%s' %
  804. (info_dict['id'], header_line, u"\n".join(formats_s)))