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.

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