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.

862 lines
36 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. self.to_screen('\033]0;%s\007' % message, skip_eol=True)
  191. def fixed_template(self):
  192. """Checks if the output template is fixed."""
  193. return (re.search(u'(?u)%\\(.+?\\)s', self.params['outtmpl']) is None)
  194. def trouble(self, message=None, tb=None):
  195. """Determine action to take when a download problem appears.
  196. Depending on if the downloader has been configured to ignore
  197. download errors or not, this method may throw an exception or
  198. not when errors are found, after printing the message.
  199. tb, if given, is additional traceback information.
  200. """
  201. if message is not None:
  202. self.to_stderr(message)
  203. if self.params.get('verbose'):
  204. if tb is None:
  205. if sys.exc_info()[0]: # if .trouble has been called from an except block
  206. tb = u''
  207. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  208. tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  209. tb += compat_str(traceback.format_exc())
  210. else:
  211. tb_data = traceback.format_list(traceback.extract_stack())
  212. tb = u''.join(tb_data)
  213. self.to_stderr(tb)
  214. if not self.params.get('ignoreerrors', False):
  215. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  216. exc_info = sys.exc_info()[1].exc_info
  217. else:
  218. exc_info = sys.exc_info()
  219. raise DownloadError(message, exc_info)
  220. self._download_retcode = 1
  221. def report_warning(self, message):
  222. '''
  223. Print the message to stderr, it will be prefixed with 'WARNING:'
  224. If stderr is a tty file the 'WARNING:' will be colored
  225. '''
  226. if sys.stderr.isatty() and os.name != 'nt':
  227. _msg_header = u'\033[0;33mWARNING:\033[0m'
  228. else:
  229. _msg_header = u'WARNING:'
  230. warning_message = u'%s %s' % (_msg_header, message)
  231. self.to_stderr(warning_message)
  232. def report_error(self, message, tb=None):
  233. '''
  234. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  235. in red if stderr is a tty file.
  236. '''
  237. if sys.stderr.isatty() and os.name != 'nt':
  238. _msg_header = u'\033[0;31mERROR:\033[0m'
  239. else:
  240. _msg_header = u'ERROR:'
  241. error_message = u'%s %s' % (_msg_header, message)
  242. self.trouble(error_message, tb)
  243. def report_writedescription(self, descfn):
  244. """ Report that the description file is being written """
  245. self.to_screen(u'[info] Writing video description to: ' + descfn)
  246. def report_writesubtitles(self, sub_filename):
  247. """ Report that the subtitles file is being written """
  248. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  249. def report_writeinfojson(self, infofn):
  250. """ Report that the metadata file has been written """
  251. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  252. def report_writeannotations(self, annofn):
  253. """ Report that the annotations file has been written. """
  254. self.to_screen(u'[info] Writing video annotations to: ' + annofn)
  255. def report_file_already_downloaded(self, file_name):
  256. """Report file has already been fully downloaded."""
  257. try:
  258. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  259. except UnicodeEncodeError:
  260. self.to_screen(u'[download] The file has already been downloaded')
  261. def increment_downloads(self):
  262. """Increment the ordinal that assigns a number to each file."""
  263. self._num_downloads += 1
  264. def prepare_filename(self, info_dict):
  265. """Generate the output filename."""
  266. try:
  267. template_dict = dict(info_dict)
  268. template_dict['epoch'] = int(time.time())
  269. autonumber_size = self.params.get('autonumber_size')
  270. if autonumber_size is None:
  271. autonumber_size = 5
  272. autonumber_templ = u'%0' + str(autonumber_size) + u'd'
  273. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  274. if template_dict.get('playlist_index') is not None:
  275. template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
  276. sanitize = lambda k, v: sanitize_filename(
  277. u'NA' if v is None else compat_str(v),
  278. restricted=self.params.get('restrictfilenames'),
  279. is_id=(k == u'id'))
  280. template_dict = dict((k, sanitize(k, v))
  281. for k, v in template_dict.items())
  282. tmpl = os.path.expanduser(self.params['outtmpl'])
  283. filename = tmpl % template_dict
  284. return filename
  285. except KeyError as err:
  286. self.report_error(u'Erroneous output template')
  287. return None
  288. except ValueError as err:
  289. self.report_error(u'Error in output template: ' + str(err) + u' (encoding: ' + repr(preferredencoding()) + ')')
  290. return None
  291. def _match_entry(self, info_dict):
  292. """ Returns None iff the file should be downloaded """
  293. title = info_dict['title']
  294. matchtitle = self.params.get('matchtitle', False)
  295. if matchtitle:
  296. if not re.search(matchtitle, title, re.IGNORECASE):
  297. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  298. rejecttitle = self.params.get('rejecttitle', False)
  299. if rejecttitle:
  300. if re.search(rejecttitle, title, re.IGNORECASE):
  301. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  302. date = info_dict.get('upload_date', None)
  303. if date is not None:
  304. dateRange = self.params.get('daterange', DateRange())
  305. if date not in dateRange:
  306. return u'[download] %s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  307. age_limit = self.params.get('age_limit')
  308. if age_limit is not None:
  309. if age_limit < info_dict.get('age_limit', 0):
  310. return u'Skipping "' + title + '" because it is age restricted'
  311. if self.in_download_archive(info_dict):
  312. return (u'%(title)s has already been recorded in archive'
  313. % info_dict)
  314. return None
  315. @staticmethod
  316. def add_extra_info(info_dict, extra_info):
  317. '''Set the keys from extra_info in info dict if they are missing'''
  318. for key, value in extra_info.items():
  319. info_dict.setdefault(key, value)
  320. def extract_info(self, url, download=True, ie_key=None, extra_info={}):
  321. '''
  322. Returns a list with a dictionary for each video we find.
  323. If 'download', also downloads the videos.
  324. extra_info is a dict containing the extra values to add to each result
  325. '''
  326. if ie_key:
  327. ies = [self.get_info_extractor(ie_key)]
  328. else:
  329. ies = self._ies
  330. for ie in ies:
  331. if not ie.suitable(url):
  332. continue
  333. if not ie.working():
  334. self.report_warning(u'The program functionality for this site has been marked as broken, '
  335. u'and will probably not work.')
  336. try:
  337. ie_result = ie.extract(url)
  338. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  339. break
  340. if isinstance(ie_result, list):
  341. # Backwards compatibility: old IE result format
  342. ie_result = {
  343. '_type': 'compat_list',
  344. 'entries': ie_result,
  345. }
  346. self.add_extra_info(ie_result,
  347. {
  348. 'extractor': ie.IE_NAME,
  349. 'webpage_url': url,
  350. 'extractor_key': ie.ie_key(),
  351. })
  352. return self.process_ie_result(ie_result, download, extra_info)
  353. except ExtractorError as de: # An error we somewhat expected
  354. self.report_error(compat_str(de), de.format_traceback())
  355. break
  356. except Exception as e:
  357. if self.params.get('ignoreerrors', False):
  358. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  359. break
  360. else:
  361. raise
  362. else:
  363. self.report_error(u'no suitable InfoExtractor: %s' % url)
  364. def process_ie_result(self, ie_result, download=True, extra_info={}):
  365. """
  366. Take the result of the ie(may be modified) and resolve all unresolved
  367. references (URLs, playlist items).
  368. It will also download the videos if 'download'.
  369. Returns the resolved ie_result.
  370. """
  371. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  372. if result_type == 'video':
  373. self.add_extra_info(ie_result, extra_info)
  374. return self.process_video_result(ie_result, download=download)
  375. elif result_type == 'url':
  376. # We have to add extra_info to the results because it may be
  377. # contained in a playlist
  378. return self.extract_info(ie_result['url'],
  379. download,
  380. ie_key=ie_result.get('ie_key'),
  381. extra_info=extra_info)
  382. elif result_type == 'playlist':
  383. self.add_extra_info(ie_result, extra_info)
  384. # We process each entry in the playlist
  385. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  386. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  387. playlist_results = []
  388. n_all_entries = len(ie_result['entries'])
  389. playliststart = self.params.get('playliststart', 1) - 1
  390. playlistend = self.params.get('playlistend', -1)
  391. if playlistend == -1:
  392. entries = ie_result['entries'][playliststart:]
  393. else:
  394. entries = ie_result['entries'][playliststart:playlistend]
  395. n_entries = len(entries)
  396. self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  397. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  398. for i, entry in enumerate(entries, 1):
  399. self.to_screen(u'[download] Downloading video #%s of %s' % (i, n_entries))
  400. extra = {
  401. 'playlist': playlist,
  402. 'playlist_index': i + playliststart,
  403. 'extractor': ie_result['extractor'],
  404. 'webpage_url': ie_result['webpage_url'],
  405. 'extractor_key': ie_result['extractor_key'],
  406. }
  407. entry_result = self.process_ie_result(entry,
  408. download=download,
  409. extra_info=extra)
  410. playlist_results.append(entry_result)
  411. ie_result['entries'] = playlist_results
  412. return ie_result
  413. elif result_type == 'compat_list':
  414. def _fixup(r):
  415. self.add_extra_info(r,
  416. {
  417. 'extractor': ie_result['extractor'],
  418. 'webpage_url': ie_result['webpage_url'],
  419. 'extractor_key': ie_result['extractor_key'],
  420. })
  421. return r
  422. ie_result['entries'] = [
  423. self.process_ie_result(_fixup(r), download, extra_info)
  424. for r in ie_result['entries']
  425. ]
  426. return ie_result
  427. else:
  428. raise Exception('Invalid result type: %s' % result_type)
  429. def select_format(self, format_spec, available_formats):
  430. if format_spec == 'best' or format_spec is None:
  431. return available_formats[-1]
  432. elif format_spec == 'worst':
  433. return available_formats[0]
  434. else:
  435. extensions = [u'mp4', u'flv', u'webm', u'3gp']
  436. if format_spec in extensions:
  437. filter_f = lambda f: f['ext'] == format_spec
  438. else:
  439. filter_f = lambda f: f['format_id'] == format_spec
  440. matches = list(filter(filter_f, available_formats))
  441. if matches:
  442. return matches[-1]
  443. return None
  444. def process_video_result(self, info_dict, download=True):
  445. assert info_dict.get('_type', 'video') == 'video'
  446. if 'playlist' not in info_dict:
  447. # It isn't part of a playlist
  448. info_dict['playlist'] = None
  449. info_dict['playlist_index'] = None
  450. # This extractors handle format selection themselves
  451. if info_dict['extractor'] in [u'youtube', u'Youku']:
  452. if download:
  453. self.process_info(info_dict)
  454. return info_dict
  455. # We now pick which formats have to be downloaded
  456. if info_dict.get('formats') is None:
  457. # There's only one format available
  458. formats = [info_dict]
  459. else:
  460. formats = info_dict['formats']
  461. # We check that all the formats have the format and format_id fields
  462. for (i, format) in enumerate(formats):
  463. if format.get('format_id') is None:
  464. format['format_id'] = compat_str(i)
  465. if format.get('format') is None:
  466. format['format'] = u'{id} - {res}{note}'.format(
  467. id=format['format_id'],
  468. res=self.format_resolution(format),
  469. note=u' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  470. )
  471. # Automatically determine file extension if missing
  472. if 'ext' not in format:
  473. format['ext'] = determine_ext(format['url'])
  474. if self.params.get('listformats', None):
  475. self.list_formats(info_dict)
  476. return
  477. format_limit = self.params.get('format_limit', None)
  478. if format_limit:
  479. formats = list(takewhile_inclusive(
  480. lambda f: f['format_id'] != format_limit, formats
  481. ))
  482. if self.params.get('prefer_free_formats'):
  483. def _free_formats_key(f):
  484. try:
  485. ext_ord = [u'flv', u'mp4', u'webm'].index(f['ext'])
  486. except ValueError:
  487. ext_ord = -1
  488. # We only compare the extension if they have the same height and width
  489. return (f.get('height'), f.get('width'), ext_ord)
  490. formats = sorted(formats, key=_free_formats_key)
  491. req_format = self.params.get('format', 'best')
  492. if req_format is None:
  493. req_format = 'best'
  494. formats_to_download = []
  495. # The -1 is for supporting YoutubeIE
  496. if req_format in ('-1', 'all'):
  497. formats_to_download = formats
  498. else:
  499. # We can accept formats requestd in the format: 34/5/best, we pick
  500. # the first that is available, starting from left
  501. req_formats = req_format.split('/')
  502. for rf in req_formats:
  503. selected_format = self.select_format(rf, formats)
  504. if selected_format is not None:
  505. formats_to_download = [selected_format]
  506. break
  507. if not formats_to_download:
  508. raise ExtractorError(u'requested format not available',
  509. expected=True)
  510. if download:
  511. if len(formats_to_download) > 1:
  512. self.to_screen(u'[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  513. for format in formats_to_download:
  514. new_info = dict(info_dict)
  515. new_info.update(format)
  516. self.process_info(new_info)
  517. # We update the info dict with the best quality format (backwards compatibility)
  518. info_dict.update(formats_to_download[-1])
  519. return info_dict
  520. def process_info(self, info_dict):
  521. """Process a single resolved IE result."""
  522. assert info_dict.get('_type', 'video') == 'video'
  523. #We increment the download the download count here to match the previous behaviour.
  524. self.increment_downloads()
  525. info_dict['fulltitle'] = info_dict['title']
  526. if len(info_dict['title']) > 200:
  527. info_dict['title'] = info_dict['title'][:197] + u'...'
  528. # Keep for backwards compatibility
  529. info_dict['stitle'] = info_dict['title']
  530. if not 'format' in info_dict:
  531. info_dict['format'] = info_dict['ext']
  532. reason = self._match_entry(info_dict)
  533. if reason is not None:
  534. self.to_screen(u'[download] ' + reason)
  535. return
  536. max_downloads = self.params.get('max_downloads')
  537. if max_downloads is not None:
  538. if self._num_downloads > int(max_downloads):
  539. raise MaxDownloadsReached()
  540. filename = self.prepare_filename(info_dict)
  541. # Forced printings
  542. if self.params.get('forcetitle', False):
  543. compat_print(info_dict['title'])
  544. if self.params.get('forceid', False):
  545. compat_print(info_dict['id'])
  546. if self.params.get('forceurl', False):
  547. # For RTMP URLs, also include the playpath
  548. compat_print(info_dict['url'] + info_dict.get('play_path', u''))
  549. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  550. compat_print(info_dict['thumbnail'])
  551. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  552. compat_print(info_dict['description'])
  553. if self.params.get('forcefilename', False) and filename is not None:
  554. compat_print(filename)
  555. if self.params.get('forceformat', False):
  556. compat_print(info_dict['format'])
  557. # Do nothing else if in simulate mode
  558. if self.params.get('simulate', False):
  559. return
  560. if filename is None:
  561. return
  562. try:
  563. dn = os.path.dirname(encodeFilename(filename))
  564. if dn != '' and not os.path.exists(dn):
  565. os.makedirs(dn)
  566. except (OSError, IOError) as err:
  567. self.report_error(u'unable to create directory ' + compat_str(err))
  568. return
  569. if self.params.get('writedescription', False):
  570. try:
  571. descfn = filename + u'.description'
  572. self.report_writedescription(descfn)
  573. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  574. descfile.write(info_dict['description'])
  575. except (KeyError, TypeError):
  576. self.report_warning(u'There\'s no description to write.')
  577. except (OSError, IOError):
  578. self.report_error(u'Cannot write description file ' + descfn)
  579. return
  580. if self.params.get('writeannotations', False):
  581. try:
  582. annofn = filename + u'.annotations.xml'
  583. self.report_writeannotations(annofn)
  584. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  585. annofile.write(info_dict['annotations'])
  586. except (KeyError, TypeError):
  587. self.report_warning(u'There are no annotations to write.')
  588. except (OSError, IOError):
  589. self.report_error(u'Cannot write annotations file: ' + annofn)
  590. return
  591. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  592. self.params.get('writeautomaticsub')])
  593. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  594. # subtitles download errors are already managed as troubles in relevant IE
  595. # that way it will silently go on when used with unsupporting IE
  596. subtitles = info_dict['subtitles']
  597. sub_format = self.params.get('subtitlesformat', 'srt')
  598. for sub_lang in subtitles.keys():
  599. sub = subtitles[sub_lang]
  600. if sub is None:
  601. continue
  602. try:
  603. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  604. self.report_writesubtitles(sub_filename)
  605. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  606. subfile.write(sub)
  607. except (OSError, IOError):
  608. self.report_error(u'Cannot write subtitles file ' + descfn)
  609. return
  610. if self.params.get('writeinfojson', False):
  611. infofn = filename + u'.info.json'
  612. self.report_writeinfojson(infofn)
  613. try:
  614. json_info_dict = dict((k, v) for k, v in info_dict.items() if not k in ['urlhandle'])
  615. write_json_file(json_info_dict, encodeFilename(infofn))
  616. except (OSError, IOError):
  617. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  618. return
  619. if self.params.get('writethumbnail', False):
  620. if info_dict.get('thumbnail') is not None:
  621. thumb_format = determine_ext(info_dict['thumbnail'], u'jpg')
  622. thumb_filename = filename.rpartition('.')[0] + u'.' + thumb_format
  623. self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
  624. (info_dict['extractor'], info_dict['id']))
  625. try:
  626. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  627. with open(thumb_filename, 'wb') as thumbf:
  628. shutil.copyfileobj(uf, thumbf)
  629. self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
  630. (info_dict['extractor'], info_dict['id'], thumb_filename))
  631. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  632. self.report_warning(u'Unable to download thumbnail "%s": %s' %
  633. (info_dict['thumbnail'], compat_str(err)))
  634. if not self.params.get('skip_download', False):
  635. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  636. success = True
  637. else:
  638. try:
  639. success = self.fd._do_download(filename, info_dict)
  640. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  641. self.report_error(u'unable to download video data: %s' % str(err))
  642. return
  643. except (OSError, IOError) as err:
  644. raise UnavailableVideoError(err)
  645. except (ContentTooShortError, ) as err:
  646. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  647. return
  648. if success:
  649. try:
  650. self.post_process(filename, info_dict)
  651. except (PostProcessingError) as err:
  652. self.report_error(u'postprocessing: %s' % str(err))
  653. return
  654. self.record_download_archive(info_dict)
  655. def download(self, url_list):
  656. """Download a given list of URLs."""
  657. if len(url_list) > 1 and self.fixed_template():
  658. raise SameFileError(self.params['outtmpl'])
  659. for url in url_list:
  660. try:
  661. #It also downloads the videos
  662. videos = self.extract_info(url)
  663. except UnavailableVideoError:
  664. self.report_error(u'unable to download video')
  665. except MaxDownloadsReached:
  666. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  667. raise
  668. return self._download_retcode
  669. def post_process(self, filename, ie_info):
  670. """Run all the postprocessors on the given file."""
  671. info = dict(ie_info)
  672. info['filepath'] = filename
  673. keep_video = None
  674. for pp in self._pps:
  675. try:
  676. keep_video_wish, new_info = pp.run(info)
  677. if keep_video_wish is not None:
  678. if keep_video_wish:
  679. keep_video = keep_video_wish
  680. elif keep_video is None:
  681. # No clear decision yet, let IE decide
  682. keep_video = keep_video_wish
  683. except PostProcessingError as e:
  684. self.report_error(e.msg)
  685. if keep_video is False and not self.params.get('keepvideo', False):
  686. try:
  687. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  688. os.remove(encodeFilename(filename))
  689. except (IOError, OSError):
  690. self.report_warning(u'Unable to remove downloaded video file')
  691. def in_download_archive(self, info_dict):
  692. fn = self.params.get('download_archive')
  693. if fn is None:
  694. return False
  695. vid_id = info_dict['extractor'] + u' ' + info_dict['id']
  696. try:
  697. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  698. for line in archive_file:
  699. if line.strip() == vid_id:
  700. return True
  701. except IOError as ioe:
  702. if ioe.errno != errno.ENOENT:
  703. raise
  704. return False
  705. def record_download_archive(self, info_dict):
  706. fn = self.params.get('download_archive')
  707. if fn is None:
  708. return
  709. vid_id = info_dict['extractor'] + u' ' + info_dict['id']
  710. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  711. archive_file.write(vid_id + u'\n')
  712. @staticmethod
  713. def format_resolution(format, default='unknown'):
  714. if format.get('_resolution') is not None:
  715. return format['_resolution']
  716. if format.get('height') is not None:
  717. if format.get('width') is not None:
  718. res = u'%sx%s' % (format['width'], format['height'])
  719. else:
  720. res = u'%sp' % format['height']
  721. else:
  722. res = default
  723. return res
  724. def list_formats(self, info_dict):
  725. def format_note(fdict):
  726. if fdict.get('format_note') is not None:
  727. return fdict['format_note']
  728. res = u''
  729. if fdict.get('vcodec') is not None:
  730. res += u'%-5s' % fdict['vcodec']
  731. elif fdict.get('vbr') is not None:
  732. res += u'video'
  733. if fdict.get('vbr') is not None:
  734. res += u'@%4dk' % fdict['vbr']
  735. if fdict.get('acodec') is not None:
  736. if res:
  737. res += u', '
  738. res += u'%-5s' % fdict['acodec']
  739. elif fdict.get('abr') is not None:
  740. if res:
  741. res += u', '
  742. res += 'audio'
  743. if fdict.get('abr') is not None:
  744. res += u'@%3dk' % fdict['abr']
  745. return res
  746. def line(format):
  747. return (u'%-20s%-10s%-12s%s' % (
  748. format['format_id'],
  749. format['ext'],
  750. self.format_resolution(format),
  751. format_note(format),
  752. )
  753. )
  754. formats = info_dict.get('formats', [info_dict])
  755. formats_s = list(map(line, formats))
  756. if len(formats) > 1:
  757. formats_s[0] += (' ' if format_note(formats[0]) else '') + '(worst)'
  758. formats_s[-1] += (' ' if format_note(formats[-1]) else '') + '(best)'
  759. header_line = line({
  760. 'format_id': u'format code', 'ext': u'extension',
  761. '_resolution': u'resolution', 'format_note': u'note'})
  762. self.to_screen(u'[info] Available formats for %s:\n%s\n%s' %
  763. (info_dict['id'], header_line, u"\n".join(formats_s)))