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.

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