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.

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