YoutubeDL.py 38 KB

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