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.

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