YoutubeDL.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import io
  5. import os
  6. import re
  7. import shutil
  8. import socket
  9. import sys
  10. import time
  11. import traceback
  12. from .utils import *
  13. from .extractor import get_info_extractor, gen_extractors
  14. from .FileDownloader import FileDownloader
  15. class YoutubeDL(object):
  16. """YoutubeDL class.
  17. YoutubeDL objects are the ones responsible of downloading the
  18. actual video file and writing it to disk if the user has requested
  19. it, among some other tasks. In most cases there should be one per
  20. program. As, given a video URL, the downloader doesn't know how to
  21. extract all the needed information, task that InfoExtractors do, it
  22. has to pass the URL to one of them.
  23. For this, YoutubeDL objects have a method that allows
  24. InfoExtractors to be registered in a given order. When it is passed
  25. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  26. finds that reports being able to handle it. The InfoExtractor extracts
  27. all the information about the video or videos the URL refers to, and
  28. YoutubeDL process the extracted information, possibly using a File
  29. Downloader to download the video.
  30. YoutubeDL objects accept a lot of parameters. In order not to saturate
  31. the object constructor with arguments, it receives a dictionary of
  32. options instead. These options are available through the params
  33. attribute for the InfoExtractors to use. The YoutubeDL also
  34. registers itself as the downloader in charge for the InfoExtractors
  35. that are added to it, so this is a "mutual registration".
  36. Available options:
  37. username: Username for authentication purposes.
  38. password: Password for authentication purposes.
  39. videopassword: Password for acces a video.
  40. usenetrc: Use netrc for authentication instead.
  41. verbose: Print additional info to stdout.
  42. quiet: Do not print messages to stdout.
  43. forceurl: Force printing final URL.
  44. forcetitle: Force printing title.
  45. forceid: Force printing ID.
  46. forcethumbnail: Force printing thumbnail URL.
  47. forcedescription: Force printing description.
  48. forcefilename: Force printing final filename.
  49. simulate: Do not download the video files.
  50. format: Video format code.
  51. format_limit: Highest quality format to try.
  52. outtmpl: Template for output names.
  53. restrictfilenames: Do not allow "&" and spaces in file names
  54. ignoreerrors: Do not stop on download errors.
  55. nooverwrites: Prevent overwriting files.
  56. playliststart: Playlist item to start at.
  57. playlistend: Playlist item to end at.
  58. matchtitle: Download only matching titles.
  59. rejecttitle: Reject downloads for matching titles.
  60. logtostderr: Log messages to stderr instead of stdout.
  61. writedescription: Write the video description to a .description file
  62. writeinfojson: Write the video description to a .info.json file
  63. writethumbnail: Write the thumbnail image to a file
  64. writesubtitles: Write the video subtitles to a file
  65. writeautomaticsub: Write the automatic subtitles to a file
  66. allsubtitles: Downloads all the subtitles of the video
  67. (requires writesubtitles or writeautomaticsub)
  68. listsubtitles: Lists all available subtitles for the video
  69. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  70. subtitleslangs: List of languages of the subtitles to download
  71. keepvideo: Keep the video file after post-processing
  72. daterange: A DateRange object, download only if the upload_date is in the range.
  73. skip_download: Skip the actual download of the video file
  74. cachedir: Location of the cache files in the filesystem.
  75. None to disable filesystem cache.
  76. noplaylist: Download single video instead of a playlist if in doubt.
  77. age_limit: An integer representing the user's age in years.
  78. Unsuitable videos for the given age are skipped.
  79. The following parameters are not used by YoutubeDL itself, they are used by
  80. the FileDownloader:
  81. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  82. noresizebuffer, retries, continuedl, noprogress, consoletitle
  83. """
  84. params = None
  85. _ies = []
  86. _pps = []
  87. _download_retcode = None
  88. _num_downloads = None
  89. _screen_file = None
  90. def __init__(self, params):
  91. """Create a FileDownloader object with the given options."""
  92. self._ies = []
  93. self._ies_instances = {}
  94. self._pps = []
  95. self._progress_hooks = []
  96. self._download_retcode = 0
  97. self._num_downloads = 0
  98. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  99. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  100. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  101. and not params['restrictfilenames']):
  102. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  103. self.report_warning(
  104. u'Assuming --restrict-filenames isnce file system encoding '
  105. u'cannot encode all charactes. '
  106. u'Set the LC_ALL environment variable to fix this.')
  107. params['restrictfilenames'] = True
  108. self.params = params
  109. self.fd = FileDownloader(self, self.params)
  110. if '%(stitle)s' in self.params['outtmpl']:
  111. 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.')
  112. def add_info_extractor(self, ie):
  113. """Add an InfoExtractor object to the end of the list."""
  114. self._ies.append(ie)
  115. self._ies_instances[ie.ie_key()] = ie
  116. ie.set_downloader(self)
  117. def get_info_extractor(self, ie_key):
  118. """
  119. Get an instance of an IE with name ie_key, it will try to get one from
  120. the _ies list, if there's no instance it will create a new one and add
  121. it to the extractor list.
  122. """
  123. ie = self._ies_instances.get(ie_key)
  124. if ie is None:
  125. ie = get_info_extractor(ie_key)()
  126. self.add_info_extractor(ie)
  127. return ie
  128. def add_default_info_extractors(self):
  129. """
  130. Add the InfoExtractors returned by gen_extractors to the end of the list
  131. """
  132. for ie in gen_extractors():
  133. self.add_info_extractor(ie)
  134. def add_post_processor(self, pp):
  135. """Add a PostProcessor object to the end of the chain."""
  136. self._pps.append(pp)
  137. pp.set_downloader(self)
  138. def to_screen(self, message, skip_eol=False):
  139. """Print message to stdout if not in quiet mode."""
  140. if not self.params.get('quiet', False):
  141. terminator = [u'\n', u''][skip_eol]
  142. output = message + terminator
  143. write_string(output, self._screen_file)
  144. def to_stderr(self, message):
  145. """Print message to stderr."""
  146. assert type(message) == type(u'')
  147. output = message + u'\n'
  148. 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
  149. output = output.encode(preferredencoding())
  150. sys.stderr.write(output)
  151. def fixed_template(self):
  152. """Checks if the output template is fixed."""
  153. return (re.search(u'(?u)%\\(.+?\\)s', self.params['outtmpl']) is None)
  154. def trouble(self, message=None, tb=None):
  155. """Determine action to take when a download problem appears.
  156. Depending on if the downloader has been configured to ignore
  157. download errors or not, this method may throw an exception or
  158. not when errors are found, after printing the message.
  159. tb, if given, is additional traceback information.
  160. """
  161. if message is not None:
  162. self.to_stderr(message)
  163. if self.params.get('verbose'):
  164. if tb is None:
  165. if sys.exc_info()[0]: # if .trouble has been called from an except block
  166. tb = u''
  167. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  168. tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  169. tb += compat_str(traceback.format_exc())
  170. else:
  171. tb_data = traceback.format_list(traceback.extract_stack())
  172. tb = u''.join(tb_data)
  173. self.to_stderr(tb)
  174. if not self.params.get('ignoreerrors', False):
  175. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  176. exc_info = sys.exc_info()[1].exc_info
  177. else:
  178. exc_info = sys.exc_info()
  179. raise DownloadError(message, exc_info)
  180. self._download_retcode = 1
  181. def report_warning(self, message):
  182. '''
  183. Print the message to stderr, it will be prefixed with 'WARNING:'
  184. If stderr is a tty file the 'WARNING:' will be colored
  185. '''
  186. if sys.stderr.isatty() and os.name != 'nt':
  187. _msg_header=u'\033[0;33mWARNING:\033[0m'
  188. else:
  189. _msg_header=u'WARNING:'
  190. warning_message=u'%s %s' % (_msg_header,message)
  191. self.to_stderr(warning_message)
  192. def report_error(self, message, tb=None):
  193. '''
  194. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  195. in red if stderr is a tty file.
  196. '''
  197. if sys.stderr.isatty() and os.name != 'nt':
  198. _msg_header = u'\033[0;31mERROR:\033[0m'
  199. else:
  200. _msg_header = u'ERROR:'
  201. error_message = u'%s %s' % (_msg_header, message)
  202. self.trouble(error_message, tb)
  203. def slow_down(self, start_time, byte_counter):
  204. """Sleep if the download speed is over the rate limit."""
  205. rate_limit = self.params.get('ratelimit', None)
  206. if rate_limit is None or byte_counter == 0:
  207. return
  208. now = time.time()
  209. elapsed = now - start_time
  210. if elapsed <= 0.0:
  211. return
  212. speed = float(byte_counter) / elapsed
  213. if speed > rate_limit:
  214. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  215. def report_writedescription(self, descfn):
  216. """ Report that the description file is being written """
  217. self.to_screen(u'[info] Writing video description to: ' + descfn)
  218. def report_writesubtitles(self, sub_filename):
  219. """ Report that the subtitles file is being written """
  220. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  221. def report_writeinfojson(self, infofn):
  222. """ Report that the metadata file has been written """
  223. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  224. def report_file_already_downloaded(self, file_name):
  225. """Report file has already been fully downloaded."""
  226. try:
  227. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  228. except (UnicodeEncodeError) as err:
  229. self.to_screen(u'[download] The file has already been downloaded')
  230. def increment_downloads(self):
  231. """Increment the ordinal that assigns a number to each file."""
  232. self._num_downloads += 1
  233. def prepare_filename(self, info_dict):
  234. """Generate the output filename."""
  235. try:
  236. template_dict = dict(info_dict)
  237. template_dict['epoch'] = int(time.time())
  238. autonumber_size = self.params.get('autonumber_size')
  239. if autonumber_size is None:
  240. autonumber_size = 5
  241. autonumber_templ = u'%0' + str(autonumber_size) + u'd'
  242. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  243. if template_dict['playlist_index'] is not None:
  244. template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
  245. sanitize = lambda k,v: sanitize_filename(
  246. u'NA' if v is None else compat_str(v),
  247. restricted=self.params.get('restrictfilenames'),
  248. is_id=(k==u'id'))
  249. template_dict = dict((k, sanitize(k, v)) for k,v in template_dict.items())
  250. filename = self.params['outtmpl'] % template_dict
  251. return filename
  252. except KeyError as err:
  253. self.report_error(u'Erroneous output template')
  254. return None
  255. except ValueError as err:
  256. self.report_error(u'Error in output template: ' + str(err) + u' (encoding: ' + repr(preferredencoding()) + ')')
  257. return None
  258. def _match_entry(self, info_dict):
  259. """ Returns None iff the file should be downloaded """
  260. title = info_dict['title']
  261. matchtitle = self.params.get('matchtitle', False)
  262. if matchtitle:
  263. if not re.search(matchtitle, title, re.IGNORECASE):
  264. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  265. rejecttitle = self.params.get('rejecttitle', False)
  266. if rejecttitle:
  267. if re.search(rejecttitle, title, re.IGNORECASE):
  268. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  269. date = info_dict.get('upload_date', None)
  270. if date is not None:
  271. dateRange = self.params.get('daterange', DateRange())
  272. if date not in dateRange:
  273. return u'[download] %s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  274. age_limit = self.params.get('age_limit')
  275. if age_limit is not None:
  276. if age_limit < info_dict.get('age_restriction', 0):
  277. return u'Skipping "' + title + '" because it is age restricted'
  278. return None
  279. def extract_info(self, url, download=True, ie_key=None, extra_info={}):
  280. '''
  281. Returns a list with a dictionary for each video we find.
  282. If 'download', also downloads the videos.
  283. extra_info is a dict containing the extra values to add to each result
  284. '''
  285. if ie_key:
  286. ies = [self.get_info_extractor(ie_key)]
  287. else:
  288. ies = self._ies
  289. for ie in ies:
  290. if not ie.suitable(url):
  291. continue
  292. if not ie.working():
  293. self.report_warning(u'The program functionality for this site has been marked as broken, '
  294. u'and will probably not work.')
  295. try:
  296. ie_result = ie.extract(url)
  297. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  298. break
  299. if isinstance(ie_result, list):
  300. # Backwards compatibility: old IE result format
  301. for result in ie_result:
  302. result.update(extra_info)
  303. ie_result = {
  304. '_type': 'compat_list',
  305. 'entries': ie_result,
  306. }
  307. else:
  308. ie_result.update(extra_info)
  309. if 'extractor' not in ie_result:
  310. ie_result['extractor'] = ie.IE_NAME
  311. return self.process_ie_result(ie_result, download=download)
  312. except ExtractorError as de: # An error we somewhat expected
  313. self.report_error(compat_str(de), de.format_traceback())
  314. break
  315. except Exception as e:
  316. if self.params.get('ignoreerrors', False):
  317. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  318. break
  319. else:
  320. raise
  321. else:
  322. self.report_error(u'no suitable InfoExtractor: %s' % url)
  323. def process_ie_result(self, ie_result, download=True, extra_info={}):
  324. """
  325. Take the result of the ie(may be modified) and resolve all unresolved
  326. references (URLs, playlist items).
  327. It will also download the videos if 'download'.
  328. Returns the resolved ie_result.
  329. """
  330. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  331. if result_type == 'video':
  332. ie_result.update(extra_info)
  333. if 'playlist' not in ie_result:
  334. # It isn't part of a playlist
  335. ie_result['playlist'] = None
  336. ie_result['playlist_index'] = None
  337. if download:
  338. self.process_info(ie_result)
  339. return ie_result
  340. elif result_type == 'url':
  341. # We have to add extra_info to the results because it may be
  342. # contained in a playlist
  343. return self.extract_info(ie_result['url'],
  344. download,
  345. ie_key=ie_result.get('ie_key'),
  346. extra_info=extra_info)
  347. elif result_type == 'playlist':
  348. # We process each entry in the playlist
  349. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  350. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  351. playlist_results = []
  352. n_all_entries = len(ie_result['entries'])
  353. playliststart = self.params.get('playliststart', 1) - 1
  354. playlistend = self.params.get('playlistend', -1)
  355. if playlistend == -1:
  356. entries = ie_result['entries'][playliststart:]
  357. else:
  358. entries = ie_result['entries'][playliststart:playlistend]
  359. n_entries = len(entries)
  360. self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  361. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  362. for i,entry in enumerate(entries,1):
  363. self.to_screen(u'[download] Downloading video #%s of %s' %(i, n_entries))
  364. extra = {
  365. 'playlist': playlist,
  366. 'playlist_index': i + playliststart,
  367. }
  368. if not 'extractor' in entry:
  369. # We set the extractor, if it's an url it will be set then to
  370. # the new extractor, but if it's already a video we must make
  371. # sure it's present: see issue #877
  372. entry['extractor'] = ie_result['extractor']
  373. entry_result = self.process_ie_result(entry,
  374. download=download,
  375. extra_info=extra)
  376. playlist_results.append(entry_result)
  377. ie_result['entries'] = playlist_results
  378. return ie_result
  379. elif result_type == 'compat_list':
  380. def _fixup(r):
  381. r.setdefault('extractor', ie_result['extractor'])
  382. return r
  383. ie_result['entries'] = [
  384. self.process_ie_result(_fixup(r), download=download)
  385. for r in ie_result['entries']
  386. ]
  387. return ie_result
  388. else:
  389. raise Exception('Invalid result type: %s' % result_type)
  390. def process_info(self, info_dict):
  391. """Process a single resolved IE result."""
  392. assert info_dict.get('_type', 'video') == 'video'
  393. #We increment the download the download count here to match the previous behaviour.
  394. self.increment_downloads()
  395. info_dict['fulltitle'] = info_dict['title']
  396. if len(info_dict['title']) > 200:
  397. info_dict['title'] = info_dict['title'][:197] + u'...'
  398. # Keep for backwards compatibility
  399. info_dict['stitle'] = info_dict['title']
  400. if not 'format' in info_dict:
  401. info_dict['format'] = info_dict['ext']
  402. reason = self._match_entry(info_dict)
  403. if reason is not None:
  404. self.to_screen(u'[download] ' + reason)
  405. return
  406. max_downloads = self.params.get('max_downloads')
  407. if max_downloads is not None:
  408. if self._num_downloads > int(max_downloads):
  409. raise MaxDownloadsReached()
  410. filename = self.prepare_filename(info_dict)
  411. # Forced printings
  412. if self.params.get('forcetitle', False):
  413. compat_print(info_dict['title'])
  414. if self.params.get('forceid', False):
  415. compat_print(info_dict['id'])
  416. if self.params.get('forceurl', False):
  417. # For RTMP URLs, also include the playpath
  418. compat_print(info_dict['url'] + info_dict.get('play_path', u''))
  419. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  420. compat_print(info_dict['thumbnail'])
  421. if self.params.get('forcedescription', False) and 'description' in info_dict:
  422. compat_print(info_dict['description'])
  423. if self.params.get('forcefilename', False) and filename is not None:
  424. compat_print(filename)
  425. if self.params.get('forceformat', False):
  426. compat_print(info_dict['format'])
  427. # Do nothing else if in simulate mode
  428. if self.params.get('simulate', False):
  429. return
  430. if filename is None:
  431. return
  432. try:
  433. dn = os.path.dirname(encodeFilename(filename))
  434. if dn != '' and not os.path.exists(dn):
  435. os.makedirs(dn)
  436. except (OSError, IOError) as err:
  437. self.report_error(u'unable to create directory ' + compat_str(err))
  438. return
  439. if self.params.get('writedescription', False):
  440. try:
  441. descfn = filename + u'.description'
  442. self.report_writedescription(descfn)
  443. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  444. descfile.write(info_dict['description'])
  445. except (KeyError, TypeError):
  446. self.report_warning(u'There\'s no description to write.')
  447. except (OSError, IOError):
  448. self.report_error(u'Cannot write description file ' + descfn)
  449. return
  450. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  451. self.params.get('writeautomaticsub')])
  452. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  453. # subtitles download errors are already managed as troubles in relevant IE
  454. # that way it will silently go on when used with unsupporting IE
  455. subtitles = info_dict['subtitles']
  456. sub_format = self.params.get('subtitlesformat')
  457. for sub_lang in subtitles.keys():
  458. sub = subtitles[sub_lang]
  459. if sub is None:
  460. continue
  461. try:
  462. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  463. self.report_writesubtitles(sub_filename)
  464. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  465. subfile.write(sub)
  466. except (OSError, IOError):
  467. self.report_error(u'Cannot write subtitles file ' + descfn)
  468. return
  469. if self.params.get('writeinfojson', False):
  470. infofn = filename + u'.info.json'
  471. self.report_writeinfojson(infofn)
  472. try:
  473. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  474. write_json_file(json_info_dict, encodeFilename(infofn))
  475. except (OSError, IOError):
  476. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  477. return
  478. if self.params.get('writethumbnail', False):
  479. if info_dict.get('thumbnail') is not None:
  480. thumb_format = determine_ext(info_dict['thumbnail'], u'jpg')
  481. thumb_filename = filename.rpartition('.')[0] + u'.' + thumb_format
  482. self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
  483. (info_dict['extractor'], info_dict['id']))
  484. try:
  485. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  486. with open(thumb_filename, 'wb') as thumbf:
  487. shutil.copyfileobj(uf, thumbf)
  488. self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
  489. (info_dict['extractor'], info_dict['id'], thumb_filename))
  490. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  491. self.report_warning(u'Unable to download thumbnail "%s": %s' %
  492. (info_dict['thumbnail'], compat_str(err)))
  493. if not self.params.get('skip_download', False):
  494. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  495. success = True
  496. else:
  497. try:
  498. success = self.fd._do_download(filename, info_dict)
  499. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  500. self.report_error(u'unable to download video data: %s' % str(err))
  501. return
  502. except (OSError, IOError) as err:
  503. raise UnavailableVideoError(err)
  504. except (ContentTooShortError, ) as err:
  505. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  506. return
  507. if success:
  508. try:
  509. self.post_process(filename, info_dict)
  510. except (PostProcessingError) as err:
  511. self.report_error(u'postprocessing: %s' % str(err))
  512. return
  513. def download(self, url_list):
  514. """Download a given list of URLs."""
  515. if len(url_list) > 1 and self.fixed_template():
  516. raise SameFileError(self.params['outtmpl'])
  517. for url in url_list:
  518. try:
  519. #It also downloads the videos
  520. videos = self.extract_info(url)
  521. except UnavailableVideoError:
  522. self.report_error(u'unable to download video')
  523. except MaxDownloadsReached:
  524. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  525. raise
  526. return self._download_retcode
  527. def post_process(self, filename, ie_info):
  528. """Run all the postprocessors on the given file."""
  529. info = dict(ie_info)
  530. info['filepath'] = filename
  531. keep_video = None
  532. for pp in self._pps:
  533. try:
  534. keep_video_wish,new_info = pp.run(info)
  535. if keep_video_wish is not None:
  536. if keep_video_wish:
  537. keep_video = keep_video_wish
  538. elif keep_video is None:
  539. # No clear decision yet, let IE decide
  540. keep_video = keep_video_wish
  541. except PostProcessingError as e:
  542. self.report_error(e.msg)
  543. if keep_video is False and not self.params.get('keepvideo', False):
  544. try:
  545. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  546. os.remove(encodeFilename(filename))
  547. except (IOError, OSError):
  548. self.report_warning(u'Unable to remove downloaded video file')