|
| 1 | +import sys |
| 2 | +import tempfile |
| 3 | +from wget import download |
| 4 | +from urllib.error import URLError |
| 5 | +from zipfile import ZipFile |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +def get_pypot_datadir(app_name="pypot"): |
| 9 | + """ |
| 10 | + Returns pypot's directory for peristent data. |
| 11 | + Attempt creation if create==True. |
| 12 | +
|
| 13 | + # linux: ~/.local/share |
| 14 | + # macOS: ~/Library/Application Support |
| 15 | + # windows: C:/Users/<USER>/AppData/Roaming |
| 16 | + """ |
| 17 | + home = Path.home() |
| 18 | + |
| 19 | + if sys.platform == "win32": |
| 20 | + data_dir = home / "AppData/Roaming" |
| 21 | + elif sys.platform == "linux": |
| 22 | + data_dir = home / ".local/share" |
| 23 | + elif sys.platform == "darwin": |
| 24 | + data_dir = home / "Library/Application Support" |
| 25 | + else: |
| 26 | + raise ValueError("Can't find the user data directory of your platform '{}'".format(sys.platform)) |
| 27 | + |
| 28 | + #app_name = app_name if version is None else app_name + "-" + str(version) |
| 29 | + pypot_dir = data_dir / app_name |
| 30 | + return pypot_dir |
| 31 | + |
| 32 | + |
| 33 | +def download_vpl_interactively(vpl_app_name, vpl_app_url, extract=False): |
| 34 | + """ |
| 35 | + Download the specified Visual Programming langage web app and returns its path. |
| 36 | + If it couldn't be downloaded, return None |
| 37 | + """ |
| 38 | + pypot_datadir = get_pypot_datadir() |
| 39 | + vpl_dir = pypot_datadir / vpl_app_name |
| 40 | + actual_vpl_dir = vpl_dir / vpl_app_name if extract else vpl_dir |
| 41 | + |
| 42 | + if vpl_dir.is_dir(): |
| 43 | + return actual_vpl_dir |
| 44 | + else: |
| 45 | + while True: |
| 46 | + response = input("This is the first time you are launching {}, it needs to be downloaded first. Proceed? [Y/n] ".format(vpl_app_name)) |
| 47 | + if response.lower() in ["y", ""]: |
| 48 | + try: |
| 49 | + vpl_dir.mkdir(parents=True) |
| 50 | + except FileExistsError: |
| 51 | + pass |
| 52 | + print("Downloading...") |
| 53 | + try: |
| 54 | + downloaded_app = download(vpl_app_url, tempfile.gettempdir()) |
| 55 | + except URLError as e: |
| 56 | + print("Cannot download the {] app from {}: {}".format(vpl_app_name, vpl_app_url, str(e)), file=sys.stderr) |
| 57 | + else: |
| 58 | + try: |
| 59 | + with ZipFile(downloaded_app, 'r') as archive: |
| 60 | + archive.extractall(vpl_dir) |
| 61 | + except FileNotFoundError: |
| 62 | + print("Couldn't extract {} from zipfile".format(vpl_app_name)) |
| 63 | + else: |
| 64 | + return actual_vpl_dir |
| 65 | + else: |
| 66 | + print("Download aborted by user", file=sys.stderr) |
| 67 | + return None |
0 commit comments