From 8e8717c86737762befa80f7e66ef39197758b9e5 Mon Sep 17 00:00:00 2001 From: Calum Lind Date: Wed, 6 Jul 2011 21:35:53 +0100 Subject: [PATCH] Fix httpdownloader error with existing filename --- deluge/httpdownloader.py | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/deluge/httpdownloader.py b/deluge/httpdownloader.py index b92bd9e06..a4b335299 100644 --- a/deluge/httpdownloader.py +++ b/deluge/httpdownloader.py @@ -51,6 +51,8 @@ class HTTPDownloader(client.HTTPDownloader): :type url: string :param filename: the filename to save the file as :type filename: string + :param force_filename: forces use of the supplied filename, regardless of header content + :type force_filename: bool :param part_callback: a function to be called when a part of data is received, it's signature should be: func(data, current_length, total_length) :type part_callback: function @@ -84,15 +86,20 @@ class HTTPDownloader(client.HTTPDownloader): self.decoder = zlib.decompressobj(zlib.MAX_WBITS + 32) if "content-disposition" in headers and not self.force_filename: - try: - new_file_name = str(headers["content-disposition"][0]).split(";")[1].split("=")[1] - new_file_name = sanitise_filename(new_file_name) - new_file_name = os.path.join(os.path.split(self.fileName)[0], new_file_name) - except Exception, e: - log.exception(e) - else: - self.fileName = new_file_name - self.value = new_file_name + new_file_name = str(headers["content-disposition"][0]).split(";")[1].split("=")[1] + new_file_name = sanitise_filename(new_file_name) + new_file_name = os.path.join(os.path.split(self.fileName)[0], new_file_name) + + count = 1 + fileroot = os.path.splitext(new_file_name)[0] + fileext = os.path.splitext(new_file_name)[1] + while os.path.isfile(new_file_name): + # Increment filename if already exists + new_file_name = "%s-%s%s" % (fileroot, count, fileext) + count += 1 + + self.fileName = new_file_name + self.value = new_file_name elif self.code in (http.MOVED_PERMANENTLY, http.FOUND, http.SEE_OTHER, http.TEMPORARY_REDIRECT): location = headers["location"][0] @@ -129,8 +136,6 @@ def sanitise_filename(filename): :type filename: string :returns: the sanitised filename :rtype: string - - :raises IOError: when the filename exists """ # Remove any quotes @@ -147,9 +152,6 @@ def sanitise_filename(filename): # Dodgy server, log it log.warning("Potentially malicious server: trying to write to file '%s'" % filename) - if os.path.exists(filename): - raise IOError, "File '%s' already exists!" % filename - return filename def download_file(url, filename, callback=None, headers=None, force_filename=False, allow_compression=True):