~popey/phablet-tools/download-only

« back to all changes in this revision

Viewing changes to ubuntumove/downloads.py

  • Committer: Sergio Schvezov
  • Date: 2013-02-06 19:31:17 UTC
  • mfrom: (40.1.5 trunk)
  • Revision ID: sergio.schvezov@canonical.com-20130206193117-2nrqgox676i8qut5
Initial public release

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# This program is free software: you can redistribute it and/or modify it
 
2
# under the terms of the the GNU General Public License version 3, as
 
3
# published by the Free Software Foundation.
 
4
#
 
5
# This program is distributed in the hope that it will be useful, but
 
6
# WITHOUT ANY WARRANTY; without even the implied warranties of
 
7
# MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR
 
8
# PURPOSE.  See the applicable version of the GNU Lesser General Public
 
9
# License for more details.
 
10
#.
 
11
# You should have received a copy of the GNU General Public License
 
12
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
13
#
 
14
# Copyright (C) 2013 Canonical, Ltd.
 
15
 
 
16
import logging
 
17
import os
 
18
import subprocess
 
19
 
 
20
 
 
21
log = logging.getLogger()
 
22
 
 
23
 
 
24
def download(uri, target_file):
 
25
    '''Downloads an artifact into target.'''
 
26
    log.info('Downloading %s' % uri)
 
27
    subprocess.check_call(['curl', '-C', '-', uri, '-o', target_file])
 
28
 
 
29
 
 
30
class DownloadManager(object):
 
31
 
 
32
    def __init__(self, base_uri, download_dir, artifact_list):
 
33
        if not os.path.isdir(download_dir):
 
34
            raise RuntimeError('Directory %s does not exist or is not a '
 
35
                               'direcotry' % download_dir)
 
36
        self._base_uri = base_uri
 
37
        self._download_dir = download_dir
 
38
        self._artifact_list = artifact_list
 
39
        self._targets = {}
 
40
 
 
41
    @property
 
42
    def files(self):
 
43
        return self._targets
 
44
 
 
45
    def _target_file(self, artifact):
 
46
        '''Constructs the path for the file to download.'''
 
47
        uri = '%s/%s' % (self._base_uri, artifact)
 
48
        target = os.path.join(self._download_dir, '%s' % (artifact))
 
49
        self._targets[artifact] = target
 
50
        return {'uri': uri, 'target_file': target}
 
51
 
 
52
    def download(self, validate=True):
 
53
        '''Downloads arget_uri.'''
 
54
        for artifact in self._artifact_list:
 
55
            download(**self._target_file(artifact))
 
56
            if validate:
 
57
                md5file = '%s.md5sum' % artifact
 
58
                download(**self._target_file(md5file))
 
59
                self.validate(md5file)
 
60
 
 
61
    def validate(self, artifact):
 
62
        '''Validates downloaded files against md5sum.'''
 
63
        subprocess.check_call(['md5sum', '-c', '%s' % artifact],
 
64
                              cwd=self._download_dir)