YoutubeDL.py 46 KB

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