download.py 11.2 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
import os
import re
import sys
rgaudin's avatar
rgaudin committed
7
import time
rgaudin's avatar
rgaudin committed
8
9
10
11
12
13
import shutil
import zipfile
import subprocess

import requests

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

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

if sys.platform == "win32":
    aria2_exe = os.path.join(data_dir, "aria2c.exe")
else:
    aria2_exe = os.path.join(data_dir, "aria2c")
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
52


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
53
54
55


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

rgaudin's avatar
rgaudin committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    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
83
    def from_disk(cls, url, fpath, checksum=None):
rgaudin's avatar
rgaudin committed
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
114
        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):
115
        return self.present and (
116
117
            get_checksum(self.fpath) == self.checksum or self.checksum is None
        )
rgaudin's avatar
rgaudin committed
118
119


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

122
123
124
125
126
127
128
129
130
131
132
133
    """ 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)
rgaudin's avatar
rgaudin committed
134
    args = [aria2_exe, "--dir={}".format(output_dir), "--out={}".format(fname)]
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    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()),
rgaudin's avatar
rgaudin committed
151
        "--ca-certificate={}".format(os.path.join(data_dir, "ca-certificates.crt")),
152
    ]
rgaudin's avatar
rgaudin committed
153
154
155
    # zip* files might send incorrect gzip header and get auto-extracted by aria2
    if not fname.endswith("zip"):
        args += ["--http-accept-gzip=true"]
156
157
    args += [url]

rgaudin's avatar
rgaudin committed
158
159
160
    aria2c = subprocess.Popen(
        args, stdout=subprocess.PIPE, universal_newlines=True, **startup_info_args()
    )
rgaudin's avatar
rgaudin committed
161
162
    if debug:
        logger.std(" ".join(args))
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184

    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)
185
        # parse filename from progress report
rgaudin's avatar
rgaudin committed
186
187
188
189
190
191
192
193
        if (
            metalink_target is None
            and line.startswith("FILE:")
            and "[MEMORY]" not in line
        ):
            metalink_target = os.path.join(
                output_dir, os.path.basename(line.split(":")[-1].strip())
            )
194

195
196
197
198
199
200
201
        # parse metalink filename from results summary (if not caught before)
        if metalink_target is None and "|OK  |" in line and "[MEMORY]" not in line:

            metalink_target = os.path.join(
                output_dir, os.path.basename(line.split("|", 4)[-1].strip())
            )

202
203
204
205
206
207
208
209
210
211
212
213
214
215
    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,
216
        )
rgaudin's avatar
rgaudin committed
217

rgaudin's avatar
rgaudin committed
218
219
220
221
    if metalink_target is not None and metalink_target != fpath:
        logger.std("mv {src} {dst}".format(src=metalink_target, dst=fpath))
        time.sleep(5)
        os.replace(metalink_target, fpath)
rgaudin's avatar
rgaudin committed
222

223
    return RequestedFile.from_download(url, fpath, os.path.getsize(fpath))
rgaudin's avatar
rgaudin committed
224
225
226


def download_if_missing(url, fpath, logger, checksum=None):
227
    """ returns local file if existing and matching sum otherwise download """
rgaudin's avatar
rgaudin committed
228
229
230

    # file already downloaded
    if checksum and os.path.exists(fpath):
231
        logger.std("calculating sum for {}...".format(fpath), "")
rgaudin's avatar
rgaudin committed
232
233
234
235
        if get_checksum(fpath) == checksum:
            logger.std("MATCH.")
            return RequestedFile.from_disk(url, fpath, checksum)
        logger.std("MISMATCH.")
236
237
    elif os.path.exists(fpath):
        return RequestedFile.from_disk(url, fpath)
rgaudin's avatar
rgaudin committed
238

rgaudin's avatar
rgaudin committed
239
    return download_file(url, fpath, logger, checksum, debug=True)
rgaudin's avatar
rgaudin committed
240
241


242
def test_connection(proxies=None):
243
244
245
246
247
248
249
    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
250
251


rgaudin's avatar
rgaudin committed
252
def get_content_cache(content, folder, is_cache_folder=False):
253
    """ shortcut to content's fpath from build_folder or cache_folder """
rgaudin's avatar
rgaudin committed
254
255

    cache_folder = folder if is_cache_folder else get_cache(folder)
256
    return os.path.join(cache_folder, content.get("name"))
rgaudin's avatar
rgaudin committed
257
258
259


def download_content(content, logger, build_folder):
260
261
262
263
264
265
266
    """ 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
267
268
269


def unzip_file(archive_fpath, src_fname, build_folder, dest_fpath=None):
270
271
    """ extracts an expected filename from a ZIP archive """
    with zipfile.ZipFile(archive_fpath, "r") as zip_archive:
rgaudin's avatar
rgaudin committed
272
273
274
275
276
277
        extraction = zip_archive.extract(src_fname, build_folder)
        if dest_fpath:
            shutil.move(extraction, dest_fpath)


def unzip_archive(archive_fpath, dest_folder):
278
    """ extracts a ZIP archive (all files) """
rgaudin's avatar
rgaudin committed
279
280
281
282
283
    with zipfile.ZipFile(archive_fpath) as zip_archive:
        zip_archive.extractall(dest_folder)


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

286
287
288
289
290
    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
291

292
    if archive_fpath.endswith(".zip"):
rgaudin's avatar
rgaudin committed
293
294
295
        unzip_archive(archive_fpath, dest_folder)
        return

296
    if sys.platform == "win32":
rgaudin's avatar
rgaudin committed
297
        # 7z does not natively support uncompressing tar.xx in one step
298
299
        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
300
301
            return

302
        command = [szip_exe, "x", "-o{}".format(dest_folder), archive_fpath]
rgaudin's avatar
rgaudin committed
303
    else:
304
        tar_exe = "/usr/bin/tar" if sys.platform == "darwin" else "/bin/tar"
305
        # using -o and -m as exfat dont support mod times and ownership is different
306
        command = [tar_exe, "-C", dest_folder, "-x", "-m", "-o", "-f", archive_fpath]
rgaudin's avatar
rgaudin committed
307
308
309
310
311

    subprocess_pretty_check_call(command, logger)


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

    # 7z extraction to stdout
315
316
317
318
    uncompress = subprocess.Popen(
        [szip_exe, "x", "-so", archive_fpath],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
rgaudin's avatar
rgaudin committed
319
        **startup_info_args()
320
    )
rgaudin's avatar
rgaudin committed
321
322
323
    logger.std("Call: " + str(uncompress.args))

    # 7x tar extraction using stdin (piping other process' stdout)
324
325
326
327
328
    untar = subprocess.Popen(
        [szip_exe, "x", "-si", "-ttar", "-o{}".format(dest_folder)],
        stdin=uncompress.stdout,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
rgaudin's avatar
rgaudin committed
329
        **startup_info_args()
330
    )
rgaudin's avatar
rgaudin committed
331
332
333
334
335
336
337
338
339
340
341
342
    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):
343
    """ uncompress tar.[bz2|gz] on windows using two passes """
rgaudin's avatar
rgaudin committed
344
345

    # uncompress first
346
347
348
    subprocess_pretty_check_call(
        [szip_exe, "x", "-o{}".format(dest_folder), archive_fpath], logger
    )
rgaudin's avatar
rgaudin committed
349
350

    # retrieve extracted tar fpath
351
352
353
    tar_fname = [fname for fname in os.listdir(dest_folder) if fname.endswith(".tar")][
        -1
    ]
rgaudin's avatar
rgaudin committed
354
355
356
    tar_fpath = os.path.join(dest_folder, tar_fname)

    # untar
357
358
359
    subprocess_pretty_check_call(
        [szip_exe, "x", "-ttar", "-o{}".format(dest_folder), tar_fpath], logger
    )
rgaudin's avatar
rgaudin committed
360
361
    # remove tar
    os.remove(tar_fpath)