From 0ea324ce10ef16ea1a781a8d473fafd1646d9596 Mon Sep 17 00:00:00 2001 From: Antonio Ospite <ao2@ao2.it> Date: Thu, 14 Jan 2016 18:11:39 +0100 Subject: [PATCH] smooth-dl.py: factor out a download_file() function --- smooth-dl.py | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/smooth-dl.py b/smooth-dl.py index 3297102..9530392 100755 --- a/smooth-dl.py +++ b/smooth-dl.py @@ -93,6 +93,20 @@ def write_wav_header(out_file, fmt, codec_private_data, data_len): out_file.write("data") out_file.write(struct.pack('<L', data_len)) +def download_file(src_url, dest_file, mode): + try: + response = urllib2.urlopen(src_url) + data = response.read() + except urllib2.HTTPError as e: + sys.stderr.write("Error while dowloading URL: %s" % src_url) + raise + + if dest_file: + f = open(dest_file, mode) + f.write(data) + f.close() + + return data def get_manifest(url, dest_dir=tempfile.gettempdir()): """Returns the manifest and the new URL if this is changed""" @@ -107,15 +121,8 @@ def get_manifest(url, dest_dir=tempfile.gettempdir()): manifest_url += '/Manifest' if manifest_url.startswith('http://'): - - response = urllib2.urlopen(manifest_url) - data = response.read() - local_manifest_path = os.path.join(dest_dir, 'Manifest') - - f = open(local_manifest_path, "w") - f.write(data) - f.close() + download_file(manifest_url, local_manifest_path, "w") else: local_manifest_path = url @@ -222,16 +229,7 @@ def download_chunks(base_url, manifest, stream_index, quality_level, dest_dir): if os.path.exists(chunk_file) == False: chunk_url = base_url + '/' + chunks_quality + '/' + chunk_name - try: - response = urllib2.urlopen(chunk_url) - data = response.read() - - f = open(chunk_file, "wb") - f.write(data) - f.close() - except Exception as e: - print e - + data = download_file(chunk_url, chunk_file, "wb") else: f = open(chunk_file, "rb") data = f.read() -- 2.1.4