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.

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