2
0

YoutubeDL.py 40 KB

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