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.

1009 lines
42 KiB

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