You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

657 lines
28 KiB

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