Winterpixel
8/14/2019 - 5:00 AM

Downloads a zip folder from a URL then extracts the contents.

Downloads a zip folder from a URL then extracts the contents.

import sys
import os
import shutil
import requests
import ctypes
import getpass
from zipfile import ZipFile

# Apps directory
LOCAL_DOWNLOADS = 'C:/PythonDownloader'

# URL where to download from
# Example: https://www.libsdl.org/release/SDL2-devel-2.0.10-VC.zip
URL_DOWNLOAD = sys.argv[1]

# File name from URL
DOWNLOAD_FILE = URL_DOWNLOAD.rsplit('/', 1)[-1]


def download(url, filename):
    with open(filename, 'wb') as f:
        response = requests.get(url, stream=True)
        total = response.headers.get('content-length')

        if total is None:
            f.write(response.content)
        else:
            downloaded = 0
            total = int(total)

            for data in response.iter_content(chunk_size=max(
                    int(total / 1000), 1024 * 1024)):
                downloaded += len(data)
                f.write(data)
                done = int(50 * downloaded / total)
                sys.stdout.write('\r[{}{}]'.format(
                    '█' * done, '.' * (50 - done)))
                sys.stdout.flush()
    sys.stdout.write('\n')


# Download the zip
print('[*] Downloading latest apps from: {}...'.format(URL_DOWNLOAD))
download(URL_DOWNLOAD, DOWNLOAD_FILE)
print('[*] Downloading done!')

# Create local downloads folder if it doesn't exist
if not os.path.exists(LOCAL_DOWNLOADS):
    try:
        os.mkdir(LOCAL_DOWNLOADS)
    except OSError:
        print('Creation of the directory {} failed!'.format(LOCAL_DOWNLOADS))
else:
    # Clear contents of the directory to prevent clutter
    for root, dirs, files in os.walk(LOCAL_DOWNLOADS):
        for f in files:
            try:
                os.unlink(os.path.join(root, f))
            except Exception as e:
                print(e)
        for d in dirs:
            try:
                shutil.rmtree(os.path.join(root, d))
            except Exception as e:
                print(e)

# Unzip the download into the local downloads folder
with ZipFile(DOWNLOAD_FILE, 'r') as z:
    # Extract all the contents of zip file in current directory
    print('[*] Extracting apps to local drive...')
    z.extractall(LOCAL_DOWNLOADS)
print('[*] Extracting done!')

# Remove zip file to reduce clutter
os.remove(DOWNLOAD_FILE)

# Let the user know downloads went ok
ctypes.windll.user32.MessageBoxW(
    0,
    "QA Apps downloaded successfully to {}!"
    .format(LOCAL_DOWNLOADS),
    "Success!", 0)