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