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 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_str,
  22. compat_urllib_error,
  23. compat_urllib_request,
  24. ContentTooShortError,
  25. date_from_str,
  26. DateRange,
  27. determine_ext,
  28. DownloadError,
  29. encodeFilename,
  30. ExtractorError,
  31. format_bytes,
  32. get_term_width,
  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. bidi_workaround: Work around buggy terminals without bidirectional text
  126. support, using fridibi
  127. The following parameters are not used by YoutubeDL itself, they are used by
  128. the FileDownloader:
  129. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  130. noresizebuffer, retries, continuedl, noprogress, consoletitle
  131. """
  132. params = None
  133. _ies = []
  134. _pps = []
  135. _download_retcode = None
  136. _num_downloads = None
  137. _screen_file = None
  138. def __init__(self, params=None):
  139. """Create a FileDownloader object with the given options."""
  140. self._ies = []
  141. self._ies_instances = {}
  142. self._pps = []
  143. self._progress_hooks = []
  144. self._download_retcode = 0
  145. self._num_downloads = 0
  146. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  147. self._err_file = sys.stderr
  148. self.params = {} if params is None else params
  149. if params.get('bidi_workaround', False):
  150. try:
  151. import pty
  152. master, slave = pty.openpty()
  153. width = get_term_width()
  154. if width is None:
  155. width_args = []
  156. else:
  157. width_args = ['-w', str(width)]
  158. self._fribidi = subprocess.Popen(
  159. ['fribidi', '-c', 'UTF-8'] + width_args,
  160. stdin=subprocess.PIPE,
  161. stdout=slave,
  162. stderr=self._err_file)
  163. self._fribidi_channel = os.fdopen(master, 'rb')
  164. except OSError as ose:
  165. if ose.errno == 2:
  166. 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.')
  167. else:
  168. raise
  169. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  170. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  171. and not params['restrictfilenames']):
  172. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  173. self.report_warning(
  174. u'Assuming --restrict-filenames since file system encoding '
  175. u'cannot encode all charactes. '
  176. u'Set the LC_ALL environment variable to fix this.')
  177. self.params['restrictfilenames'] = True
  178. self.fd = FileDownloader(self, self.params)
  179. if '%(stitle)s' in self.params.get('outtmpl', ''):
  180. 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.')
  181. self._setup_opener()
  182. def add_info_extractor(self, ie):
  183. """Add an InfoExtractor object to the end of the list."""
  184. self._ies.append(ie)
  185. self._ies_instances[ie.ie_key()] = ie
  186. ie.set_downloader(self)
  187. def get_info_extractor(self, ie_key):
  188. """
  189. Get an instance of an IE with name ie_key, it will try to get one from
  190. the _ies list, if there's no instance it will create a new one and add
  191. it to the extractor list.
  192. """
  193. ie = self._ies_instances.get(ie_key)
  194. if ie is None:
  195. ie = get_info_extractor(ie_key)()
  196. self.add_info_extractor(ie)
  197. return ie
  198. def add_default_info_extractors(self):
  199. """
  200. Add the InfoExtractors returned by gen_extractors to the end of the list
  201. """
  202. for ie in gen_extractors():
  203. self.add_info_extractor(ie)
  204. def add_post_processor(self, pp):
  205. """Add a PostProcessor object to the end of the chain."""
  206. self._pps.append(pp)
  207. pp.set_downloader(self)
  208. def _bidi_workaround(self, message):
  209. if not hasattr(self, '_fribidi_channel'):
  210. return message
  211. assert type(message) == type(u'')
  212. line_count = message.count(u'\n') + 1
  213. self._fribidi.stdin.write((message + u'\n').encode('utf-8'))
  214. self._fribidi.stdin.flush()
  215. res = u''.join(self._fribidi_channel.readline().decode('utf-8')
  216. for _ in range(line_count))
  217. return res[:-len(u'\n')]
  218. def to_screen(self, message, skip_eol=False):
  219. """Print message to stdout if not in quiet mode."""
  220. return self.to_stdout(message, skip_eol, check_quiet=True)
  221. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  222. """Print message to stdout if not in quiet mode."""
  223. if self.params.get('logger'):
  224. self.params['logger'].debug(message)
  225. elif not check_quiet or not self.params.get('quiet', False):
  226. message = self._bidi_workaround(message)
  227. terminator = [u'\n', u''][skip_eol]
  228. output = message + terminator
  229. write_string(output, self._screen_file)
  230. def to_stderr(self, message):
  231. """Print message to stderr."""
  232. assert type(message) == type(u'')
  233. if self.params.get('logger'):
  234. self.params['logger'].error(message)
  235. else:
  236. message = self._bidi_workaround(message)
  237. output = message + u'\n'
  238. write_string(output, self._err_file)
  239. def to_console_title(self, message):
  240. if not self.params.get('consoletitle', False):
  241. return
  242. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  243. # c_wchar_p() might not be necessary if `message` is
  244. # already of type unicode()
  245. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  246. elif 'TERM' in os.environ:
  247. write_string(u'\033]0;%s\007' % message, self._screen_file)
  248. def save_console_title(self):
  249. if not self.params.get('consoletitle', False):
  250. return
  251. if 'TERM' in os.environ:
  252. # Save the title on stack
  253. write_string(u'\033[22;0t', self._screen_file)
  254. def restore_console_title(self):
  255. if not self.params.get('consoletitle', False):
  256. return
  257. if 'TERM' in os.environ:
  258. # Restore the title from stack
  259. write_string(u'\033[23;0t', self._screen_file)
  260. def __enter__(self):
  261. self.save_console_title()
  262. return self
  263. def __exit__(self, *args):
  264. self.restore_console_title()
  265. if self.params.get('cookiefile') is not None:
  266. self.cookiejar.save()
  267. def trouble(self, message=None, tb=None):
  268. """Determine action to take when a download problem appears.
  269. Depending on if the downloader has been configured to ignore
  270. download errors or not, this method may throw an exception or
  271. not when errors are found, after printing the message.
  272. tb, if given, is additional traceback information.
  273. """
  274. if message is not None:
  275. self.to_stderr(message)
  276. if self.params.get('verbose'):
  277. if tb is None:
  278. if sys.exc_info()[0]: # if .trouble has been called from an except block
  279. tb = u''
  280. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  281. tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  282. tb += compat_str(traceback.format_exc())
  283. else:
  284. tb_data = traceback.format_list(traceback.extract_stack())
  285. tb = u''.join(tb_data)
  286. self.to_stderr(tb)
  287. if not self.params.get('ignoreerrors', False):
  288. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  289. exc_info = sys.exc_info()[1].exc_info
  290. else:
  291. exc_info = sys.exc_info()
  292. raise DownloadError(message, exc_info)
  293. self._download_retcode = 1
  294. def report_warning(self, message):
  295. '''
  296. Print the message to stderr, it will be prefixed with 'WARNING:'
  297. If stderr is a tty file the 'WARNING:' will be colored
  298. '''
  299. if self._err_file.isatty() and os.name != 'nt':
  300. _msg_header = u'\033[0;33mWARNING:\033[0m'
  301. else:
  302. _msg_header = u'WARNING:'
  303. warning_message = u'%s %s' % (_msg_header, message)
  304. self.to_stderr(warning_message)
  305. def report_error(self, message, tb=None):
  306. '''
  307. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  308. in red if stderr is a tty file.
  309. '''
  310. if self._err_file.isatty() and os.name != 'nt':
  311. _msg_header = u'\033[0;31mERROR:\033[0m'
  312. else:
  313. _msg_header = u'ERROR:'
  314. error_message = u'%s %s' % (_msg_header, message)
  315. self.trouble(error_message, tb)
  316. def report_writedescription(self, descfn):
  317. """ Report that the description file is being written """
  318. self.to_screen(u'[info] Writing video description to: ' + descfn)
  319. def report_writesubtitles(self, sub_filename):
  320. """ Report that the subtitles file is being written """
  321. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  322. def report_writeinfojson(self, infofn):
  323. """ Report that the metadata file has been written """
  324. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  325. def report_writeannotations(self, annofn):
  326. """ Report that the annotations file has been written. """
  327. self.to_screen(u'[info] Writing video annotations to: ' + annofn)
  328. def report_file_already_downloaded(self, file_name):
  329. """Report file has already been fully downloaded."""
  330. try:
  331. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  332. except UnicodeEncodeError:
  333. self.to_screen(u'[download] The file has already been downloaded')
  334. def increment_downloads(self):
  335. """Increment the ordinal that assigns a number to each file."""
  336. self._num_downloads += 1
  337. def prepare_filename(self, info_dict):
  338. """Generate the output filename."""
  339. try:
  340. template_dict = dict(info_dict)
  341. template_dict['epoch'] = int(time.time())
  342. autonumber_size = self.params.get('autonumber_size')
  343. if autonumber_size is None:
  344. autonumber_size = 5
  345. autonumber_templ = u'%0' + str(autonumber_size) + u'd'
  346. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  347. if template_dict.get('playlist_index') is not None:
  348. template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
  349. sanitize = lambda k, v: sanitize_filename(
  350. u'NA' if v is None else compat_str(v),
  351. restricted=self.params.get('restrictfilenames'),
  352. is_id=(k == u'id'))
  353. template_dict = dict((k, sanitize(k, v))
  354. for k, v in template_dict.items())
  355. tmpl = os.path.expanduser(self.params['outtmpl'])
  356. filename = tmpl % template_dict
  357. return filename
  358. except KeyError as err:
  359. self.report_error(u'Erroneous output template')
  360. return None
  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 = filename.rpartition('.')[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)