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.

1042 lines
44 KiB

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