download.py 10.4 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
    """ 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
133
    args = [aria2_exe, "--dir={}".format(output_dir), "--out={}".format(fname)]
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
    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]

rgaudin's avatar
rgaudin committed
154
155
156
    aria2c = subprocess.Popen(
        args, stdout=subprocess.PIPE, universal_newlines=True, **startup_info_args()
    )
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
195
196
    # 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,
197
        )
rgaudin's avatar
rgaudin committed
198

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

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


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

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

    return download_file(url, fpath, logger, checksum)


221
def test_connection(proxies=None):
222
223
224
225
226
227
228
    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
229
230


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

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


def download_content(content, logger, build_folder):
239
240
241
242
243
244
245
    """ 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
246
247
248


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


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


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

265
266
267
268
269
    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
270

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

275
    if sys.platform == "win32":
rgaudin's avatar
rgaudin committed
276
        # 7z does not natively support uncompressing tar.xx in one step
277
278
        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
279
280
            return

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

    subprocess_pretty_check_call(command, logger)


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

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

    # 7x tar extraction using stdin (piping other process' stdout)
303
304
305
306
307
    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
308
        **startup_info_args()
309
    )
rgaudin's avatar
rgaudin committed
310
311
312
313
314
315
316
317
318
319
320
321
    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):
322
    """ uncompress tar.[bz2|gz] on windows using two passes """
rgaudin's avatar
rgaudin committed
323
324

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

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

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