smooth-dl.py: factor out a download_file() function
authorAntonio Ospite <ao2@ao2.it>
Thu, 14 Jan 2016 17:11:39 +0000 (18:11 +0100)
committerAntonio Ospite <ao2@ao2.it>
Thu, 14 Jan 2016 17:11:39 +0000 (18:11 +0100)
smooth-dl.py

index 3297102..9530392 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
 
@@ -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()