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.

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