download.py 10.3 KB
Newer Older
1
2
3
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu

rgaudin's avatar
rgaudin committed
4
5
6
7
8
9
10
11
12
import os
import re
import sys
import shutil
import zipfile
import subprocess

import requests

13
from data import data_dir, http_proxy_test_url, https_proxy_test_url
14
from util import get_checksum, get_cache, get_prefs
rgaudin's avatar
rgaudin committed
15
16
from backend.util import subprocess_pretty_check_call, startup_info_args

17
PROXIES = None
18
FAILURE_RETRIES = 6
19
szip_exe = os.path.join(data_dir, "7za.exe")
20
21
22
23
24

if sys.platform == "win32":
    aria2_exe = os.path.join(data_dir, "aria2c.exe")
else:
    aria2_exe = os.path.join(data_dir, "aria2c")
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


def read_proxies(load_env=True):
    """ read proxy configuration from pref file or ENV """

    proxies = {}
    if get_prefs().get("HTTP_PROXY", None):
        proxies.update({"http": get_prefs().get("HTTP_PROXY")})
    if get_prefs().get("HTTPS_PROXY", None):
        proxies.update({"https": get_prefs().get("HTTPS_PROXY")})

    if load_env:
        # environment variables overwrites preferences
        if os.getenv("HTTP_PROXY", None):
            proxies.update({"http": os.getenv("HTTP_PROXY")})
        if os.getenv("HTTPS_PROXY", None):
            proxies.update({"https": os.getenv("HTTPS_PROXY")})

    return proxies


def get_proxies(load_env=True, force_reload=False):
    """ cached-shortcut to PROXIES """
    global PROXIES
    if PROXIES is None or force_reload:
        PROXIES = read_proxies()
    return PROXIES
rgaudin's avatar
rgaudin committed
52
53
54


class RequestedFile(object):
55
56
    """ interface to harmonize result of file request """

rgaudin's avatar
rgaudin committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    PENDING = 0
    FAILED = 1
    FOUND = 2
    DOWNLOADED = 3

    def __init__(self, url, fpath):
        self.url = url
        self.fpath = fpath
        self.status = self.PENDING

        self.checksum = None
        self.exception = None
        self.downloaded_size = None

    def set(self, status):
        self.status = status

    @classmethod
    def from_download(cls, url, fpath, downloaded_size):
        rf = cls(url, fpath)
        rf.set(cls.DOWNLOADED)
        rf.downloaded_size = downloaded_size
        return rf

    @classmethod
82
    def from_disk(cls, url, fpath, checksum=None):
rgaudin's avatar
rgaudin committed
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
        rf = cls(url, fpath)
        rf.checksum = checksum
        rf.set(cls.FOUND)
        return rf

    @classmethod
    def from_failure(cls, url, fpath, exception, checksum=None):
        rf = cls(url, fpath)
        rf.set(cls.FAILED)
        rf.exception = exception
        rf.checksum = checksum
        return rf

    @property
    def successful(self):
        return self.status in (self.DOWNLOADED, self.FOUND)

    @property
    def found(self):
        return self.status == self.FOUND

    @property
    def downloaded(self):
        return self.status == self.DOWNLOADED

    @property
    def present(self):
        return os.path.exists(self.fpath)

    @property
    def verified(self):
114
        return self.present and (
115
116
            get_checksum(self.fpath) == self.checksum or self.checksum is None
        )
rgaudin's avatar
rgaudin committed
117
118


119
def download_file(url, fpath, logger, checksum=None):
rgaudin's avatar
rgaudin committed
120

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
    """ download an URL into a named path and reports progress to logger

        download is externalized to aria2c binary and progress extracted
        from periodic summary

        downloads are resumed if possible

        supports metalink. if link is metalink, downloads both then replace
        actual target (aria2 doesn't allow setting target for metalink
        as it can be multiple files) """

    output_dir, fname = os.path.split(fpath)
    args = [aria2_exe, f"--dir={output_dir}", f"--out={fname}"]
    args += [
        "--connect-timeout=60",
        "--max-file-not-found=5",
        "--max-tries=5",
        "--retry-wait=60",
        "--timeout=60",
        "--follow-metalink=mem",
        "--allow-overwrite=true",
        "--always-resume=false",
        "--max-resume-failure-tries=1",
        "--auto-file-renaming=false",
        "--download-result=full",
        "--log-level=error",
        "--console-log-level=error",
        "--summary-interval=1",  # display a line with progress every X seconds
        "--human-readable={}".format(str(logger.on_tty).lower()),
    ]
    args += ["--http-accept-gzip=true"]  # only for catalog?
    args += [url]

    aria2c = subprocess.Popen(args, stdout=subprocess.PIPE, text=True)
    # logger.std(" ".join(args))

    if not logger.on_tty:
        logger.ascii_progressbar(0, 100)

    metalink_target = None
    for line in iter(aria2c.stdout.readline, ""):
        line = line.strip()
        # [#915371 5996544B/90241109B(6%) CN:4 DL:1704260B ETA:49s]
        if line.startswith("[#") and line.endswith("]"):  # quick check, no re
            if logger.on_tty:
                logger.flash(line + "          ")
            else:
                try:
                    downloaded_size, total_size = [
                        int(x)
                        for x in list(
                            re.search(r"\s([0-9]+)B\/([0-9]+)B", line).groups()
                        )
                    ]
                except Exception:
                    downloaded_size, total_size = 1, -1
                logger.ascii_progressbar(downloaded_size, total_size)
        if metalink_target is None and line.startswith("FILE:"):
            metalink_target = line.split(":")[-1].strip()

    if aria2c.poll() is None:
        try:
            aria2c.wait(timeout=2)
        except subprocess.TimeoutError:
            aria2c.terminate()

    logger.std("")  # clear last \r

    if not aria2c.returncode == 0:
        return RequestedFile.from_failure(
            url,
            fpath,
            ValueError("aria2c returned {}".format(aria2c.returncode)),
            checksum,
195
        )
rgaudin's avatar
rgaudin committed
196

197
198
    if metalink_target is not None:
        shutil.move(metalink_target, fpath)
rgaudin's avatar
rgaudin committed
199

200
    return RequestedFile.from_download(url, fpath, os.path.getsize(fpath))
rgaudin's avatar
rgaudin committed
201
202
203


def download_if_missing(url, fpath, logger, checksum=None):
204
    """ returns local file if existing and matching sum otherwise download """
rgaudin's avatar
rgaudin committed
205
206
207

    # file already downloaded
    if checksum and os.path.exists(fpath):
208
        logger.std("calculating sum for {}...".format(fpath), "")
rgaudin's avatar
rgaudin committed
209
210
211
212
        if get_checksum(fpath) == checksum:
            logger.std("MATCH.")
            return RequestedFile.from_disk(url, fpath, checksum)
        logger.std("MISMATCH.")
213
214
    elif os.path.exists(fpath):
        return RequestedFile.from_disk(url, fpath)
rgaudin's avatar
rgaudin committed
215
216
217
218

    return download_file(url, fpath, logger, checksum)


219
def test_connection(proxies=None):
220
221
222
223
224
225
226
    for kind, url in (("HTTP", http_proxy_test_url), ("HTTPS", https_proxy_test_url)):
        try:
            req = requests.head(url, proxies=proxies or PROXIES, timeout=20)
            req.raise_for_status()
        except Exception:
            return False, kind
    return True, None
227
228


rgaudin's avatar
rgaudin committed
229
def get_content_cache(content, folder, is_cache_folder=False):
230
    """ shortcut to content's fpath from build_folder or cache_folder """
rgaudin's avatar
rgaudin committed
231
232

    cache_folder = folder if is_cache_folder else get_cache(folder)
233
    return os.path.join(cache_folder, content.get("name"))
rgaudin's avatar
rgaudin committed
234
235
236


def download_content(content, logger, build_folder):
237
238
239
240
241
242
243
    """ download or retrieve an item from contents """
    return download_if_missing(
        url=content.get("url"),
        fpath=get_content_cache(content, build_folder),
        logger=logger,
        checksum=content.get("checksum"),
    )
rgaudin's avatar
rgaudin committed
244
245
246


def unzip_file(archive_fpath, src_fname, build_folder, dest_fpath=None):
247
248
    """ extracts an expected filename from a ZIP archive """
    with zipfile.ZipFile(archive_fpath, "r") as zip_archive:
rgaudin's avatar
rgaudin committed
249
250
251
252
253
254
        extraction = zip_archive.extract(src_fname, build_folder)
        if dest_fpath:
            shutil.move(extraction, dest_fpath)


def unzip_archive(archive_fpath, dest_folder):
255
    """ extracts a ZIP archive (all files) """
rgaudin's avatar
rgaudin committed
256
257
258
259
260
    with zipfile.ZipFile(archive_fpath) as zip_archive:
        zip_archive.extractall(dest_folder)


def unarchive(archive_fpath, dest_folder, logger):
261
    """ extracts a supported archive to a specified folder """
rgaudin's avatar
rgaudin committed
262

263
264
265
266
267
    supported_extensions = (".zip", ".tar", ".tar.bz2", ".tar.gz", ".tar.xz")
    if sum([1 for ext in supported_extensions if archive_fpath.endswith(ext)]) == 0:
        raise NotImplementedError(
            "Archive format extraction not supported: {}".format(archive_fpath)
        )
rgaudin's avatar
rgaudin committed
268

269
    if archive_fpath.endswith(".zip"):
rgaudin's avatar
rgaudin committed
270
271
272
        unzip_archive(archive_fpath, dest_folder)
        return

273
    if sys.platform == "win32":
rgaudin's avatar
rgaudin committed
274
        # 7z does not natively support uncompressing tar.xx in one step
275
276
        if re.match(r".*\.tar\.(bz2|gz|xz)$", archive_fpath):
            win_unarchive_compressed_tar_pipe(archive_fpath, dest_folder, logger)
rgaudin's avatar
rgaudin committed
277
278
            return

279
        command = [szip_exe, "x", "-o{}".format(dest_folder), archive_fpath]
rgaudin's avatar
rgaudin committed
280
    else:
281
        tar_exe = "/usr/bin/tar" if sys.platform == "darwin" else "/bin/tar"
282
        # using -o and -m as exfat dont support mod times and ownership is different
283
        command = [tar_exe, "-C", dest_folder, "-x", "-m", "-o", "-f", archive_fpath]
rgaudin's avatar
rgaudin committed
284
285
286
287
288

    subprocess_pretty_check_call(command, logger)


def win_unarchive_compressed_tar_pipe(archive_fpath, dest_folder, logger):
289
    """ uncompress tar.[bz2|gz] on windows in a single pass """
rgaudin's avatar
rgaudin committed
290
291

    # 7z extraction to stdout
292
293
294
295
    uncompress = subprocess.Popen(
        [szip_exe, "x", "-so", archive_fpath],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
296
        **startup_info_args(),
297
    )
rgaudin's avatar
rgaudin committed
298
299
300
    logger.std("Call: " + str(uncompress.args))

    # 7x tar extraction using stdin (piping other process' stdout)
301
302
303
304
305
    untar = subprocess.Popen(
        [szip_exe, "x", "-si", "-ttar", "-o{}".format(dest_folder)],
        stdin=uncompress.stdout,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
306
        **startup_info_args(),
307
    )
rgaudin's avatar
rgaudin committed
308
309
310
311
312
313
314
315
316
317
318
319
    logger.std("Call: " + str(untar.args))

    uncompress.wait()
    untar.wait()

    for line in untar.stdout.readlines():
        logger.raw_std(line.decode("utf-8", "ignore"))

    assert untar.returncode == 0


def win_unarchive_compressed_tar(archive_fpath, dest_folder, logger):
320
    """ uncompress tar.[bz2|gz] on windows using two passes """
rgaudin's avatar
rgaudin committed
321
322

    # uncompress first
323
324
325
    subprocess_pretty_check_call(
        [szip_exe, "x", "-o{}".format(dest_folder), archive_fpath], logger
    )
rgaudin's avatar
rgaudin committed
326
327

    # retrieve extracted tar fpath
328
329
330
    tar_fname = [fname for fname in os.listdir(dest_folder) if fname.endswith(".tar")][
        -1
    ]
rgaudin's avatar
rgaudin committed
331
332
333
    tar_fpath = os.path.join(dest_folder, tar_fname)

    # untar
334
335
336
    subprocess_pretty_check_call(
        [szip_exe, "x", "-ttar", "-o{}".format(dest_folder), tar_fpath], logger
    )
rgaudin's avatar
rgaudin committed
337
338
    # remove tar
    os.remove(tar_fpath)