smooth-dl.py: use more specific exception when looking for the Clip element
[smooth-dl.git] / smooth-dl.py
index 3297102..85a0d2e 100755 (executable)
@@ -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
 
@@ -129,7 +136,7 @@ def get_manifest(url, dest_dir=tempfile.gettempdir()):
         # if some intermediate client Manifest is used, like in Rai Replay
         clip = manifest.find("Clip")
         manifest_url = clip.attrib["Url"]
-    except:
+    except AttributeError:
         pass
 
     manifest_pattern = re.compile("/manifest$", re.IGNORECASE)
@@ -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()