Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

schach / schach / downloads.py · 2.4 KB · at 3c63b1d52560 · raw

Outline: 3 definitions
1
"""Einmalige Downloads (Maia-Modell, Stockfish) in den Cache, mit Fortsetzen und Prüfsumme."""
2
3
import hashlib
4
import os
5
import sys
6
7
USER_AGENT = "schach-gtk/1.0"
8
9
10
def cache_dir():
11
    """Cache-Ordner des Programms, je nach System (``~/.cache/schach`` unter Linux)."""
12
    base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")
13
    if sys.platform == "win32":
14
        base = os.environ.get("LOCALAPPDATA", base)
15
    elif sys.platform == "darwin":
16
        base = os.path.join(os.path.expanduser("~"), "Library", "Caches")
17
    return os.path.join(base, "schach")
18
19
20
def download(url, target, sha256, progress=None, chunk=1 << 20, what="Download"):
21
    """Datei laden, nach ``target.part``; ein abgebrochener Download wird fortgesetzt.
22
    Erst nach geprüfter Prüfsumme heißt die Datei ``target``. Kein Gesamt-Zeitlimit –
23
    nur eine Frist, falls die Verbindung minutenlang steht.
24
25
    ``progress("download", fertig, gesamt)`` in Bytes; gesamt kann None sein."""
26
    import requests
27
28
    os.makedirs(os.path.dirname(target), exist_ok=True)
29
    partial = target + ".part"
30
    have = os.path.getsize(partial) if os.path.exists(partial) else 0
31
    headers = {"User-Agent": USER_AGENT}
32
    if have:
33
        headers["Range"] = f"bytes={have}-"
34
    with requests.get(url, headers=headers, stream=True, timeout=(20, 120)) as resp:
35
        if resp.status_code == 416:  # schon vollständig
36
            have, mode = os.path.getsize(partial), None
37
        elif resp.status_code == 206:
38
            mode = "ab"
39
        else:
40
            resp.raise_for_status()
41
            have, mode = 0, "wb"  # Server kann nicht fortsetzen: von vorn
42
        if mode:
43
            total = have + int(resp.headers.get("Content-Length", 0)) or None
44
            with open(partial, mode) as fh:
45
                for block in resp.iter_content(chunk):
46
                    fh.write(block)
47
                    have += len(block)
48
                    if progress:
49
                        progress("download", have, total)
50
    if file_sha256(partial, chunk) != sha256:
51
        os.remove(partial)
52
        raise ValueError(f"{what}: Prüfsumme stimmt nicht – Download verworfen")
53
    os.replace(partial, target)
54
55
56
def file_sha256(path, chunk=1 << 20):
57
    digest = hashlib.sha256()
58
    with open(path, "rb") as fh:
59
        while block := fh.read(chunk):
60
            digest.update(block)
61
    return digest.hexdigest()