File: download.py

package info (click to toggle)
game-data-packager 63
  • links: PTS, VCS
  • area: contrib
  • in suites: buster
  • size: 15,920 kB
  • sloc: python: 10,537; sh: 515; makefile: 497
file content (198 lines) | stat: -rw-r--r-- 6,674 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
52
53
54
55
56
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
82
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
114
115
116
117
118
119
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
195
196
197
198
#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2014-2017 Simon McVittie <smcv@debian.org>
# Copyright © 2015-2016 Alexandre Detiste <alexandre@detiste.be>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# You can find the GPL license text on a Debian system under
# /usr/share/common-licenses/GPL-2.

import logging
import os
import random
import urllib.request

from .data import (HashedFile)
from .paths import (ETCDIR)
from .util import (AGENT, mkdir_p)

logging.basicConfig()
logger = logging.getLogger(__name__)


class NotDownloadable(Exception):
    pass


class OutOfSpace(Exception):
    pass


class Downloader:

    def __init__(self, progress_factory=None):
        self.download_failed = set()

        if progress_factory is None:
            self.progress_factory = lambda info=None: None
        else:
            self.progress_factory = progress_factory

    @staticmethod
    def choose_mirror(wanted):
        mirrors = []
        mirror = os.environ.get('GDP_MIRROR')
        if mirror:
            if mirror.startswith('/'):
                mirror = 'file://' + mirror
            elif mirror.split(':')[0] not in ('http', 'https', 'ftp', 'file'):
                mirror = 'http://' + mirror
            if not mirror.endswith('/'):
                mirror = mirror + '/'

        if type(wanted.download) is str:
            if not mirror:
                return [wanted.download]
            url_basename = os.path.basename(wanted.download)
            if '?' not in url_basename:
                mirrors.append(mirror + url_basename)
            wanted.name = wanted.name.replace(' ','%20')
            if wanted.name != url_basename and '?' not in wanted.name:
                mirrors.append(mirror + wanted.name)
            mirrors.append(wanted.download)
            return mirrors

        for mirror_list, details in wanted.download.items():
            try:
                f = open(os.path.join(ETCDIR, mirror_list), encoding='utf-8')
                for line in f:
                    url = line.strip()
                    if not url:
                        continue
                    if url.startswith('#'):
                        continue
                    if details.get('path', '.') != '.':
                        if not url.endswith('/'):
                            url = url + '/'
                        url = url + details['path']
                    if not url.endswith('/'):
                        url = url + '/'
                    url = url + details.get('name', wanted.filename)
                    mirrors.append(url)
            except:
                logger.warning('Could not open mirror list "%s"', mirror_list,
                        exc_info=True)
        random.shuffle(mirrors)
        if mirror:
            if mirrors and '?' not in mirrors[0]:
                mirrors.insert(0, mirror + os.path.basename(mirrors[0]))
            elif '?' not in wanted.name:
                mirrors.insert(0, mirror + wanted.name)
        if not mirrors:
            logger.error('Could not select a mirror for "%s"', wanted.name)
            return []
        return mirrors

    def download(self, wanted, dest):
        logger.debug('trying to download %s...', wanted.name)
        statvfs = os.statvfs(dest)
        if wanted.size > statvfs.f_frsize * statvfs.f_bavail:
            logger.error("Out of space on %s, can't download %s.",
                          dest, wanted.name)
            self.download_failed |= set(self.choose_mirror(wanted))
            raise OutOfSpace

        urls = self.choose_mirror(wanted)
        for url in urls:
            if url in self.download_failed:
                logger.debug('... no, it already failed')
                continue

            logger.debug('... %s', url)

            tmp = None
            try:
                rf = urllib.request.urlopen(urllib.request.Request(
                                 url,headers={'User-Agent': AGENT}))
                if rf is None:
                    continue

                try:
                    size = int(rf.info().get('Content-Length'))
                except:
                    size = None
                if size and size != wanted.size:
                    logger.warning("File doesn't have expected size"
                                   " (%s vs %s), skipping %s",
                                   size, wanted.size, url)
                    self.download_failed.add(url)
                    continue

                tmp = os.path.join(dest, wanted.name)
                mkdir_p(os.path.dirname(tmp))

                wf = open(tmp, 'wb')
                logger.info('downloading %s', url)
                hf = HashedFile.from_file(url, rf, wf,
                        size=wanted.size,
                        progress=self.progress_factory())
                wf.close()

                return tmp, hf
            except Exception as e:
                logger.warning('Failed to download "%s": %s', url,
                        e)
                self.download_failed.add(url)
                if tmp is not None:
                    os.remove(tmp)
        else:
            raise NotDownloadable

if __name__ == '__main__':
    # Usage:
    # GDP_UNINSTALLED=1 \
    # PYTHONPATH=$(pwd) \
    # python3 -m game_data_packager.download \
    # unreal skaarj_logo.jpg .

    import sys

    from .game import (load_games)

    game = sys.argv[1]
    filename = sys.argv[2]
    dest = sys.argv[3]

    games = load_games(game=game)
    game = games[game]
    game.load_file_data()
    wanted = game.files[filename]

    path, hasher = Downloader().download(wanted, dest)

    if path is None:
        logger.error('Unable to download "%s"', filename)
    else:
        logger.info('Downloaded "%s" to "%s"', filename, path)

        if hasher.size != wanted.size:
            logger.info('size: %s, expected %s', hasher.size, wanted.size)

        if hasher.md5 != wanted.md5:
            logger.info('md5: %s, expected %s', hasher.md5, wanted.md5)

        if hasher.sha1 != wanted.sha1:
            logger.info('sha1: %s, expected %s', hasher.sha1, wanted.sha1)

        if hasher.sha256 != wanted.sha256:
            logger.info(
                'sha256: %s, expected %s', hasher.sha256, wanted.sha256)