pkgs: update some packages
[winfreed.git] / winfreed.py
1 #!/usr/bin/env python
2 #
3 # winfreed - download a selection of Free Software for MS Windows.
4 #
5 # Copyright (C) 2011-2014  Antonio Ospite <ao2@ao2.it>
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 import os
21 import sys
22 import glob
23 import ConfigParser
24 import urllib2
25 from progressbar import Bar, ETA, FileTransferSpeed, Percentage, ProgressBar
26
27 OUTPUT_DIR = 'downloads'
28 LANGCODE = 'en-US'
29
30 # One of i386 or x64
31 ARCHITECTURE = 'x64'
32
33 PKG_DIR = 'pkgs'
34 CHUNK_SIZE = 8192
35
36
37 def get_pkg(pkg_file):
38     config = ConfigParser.SafeConfigParser({'language': LANGCODE})
39     with open(pkg_file, mode='r') as f:
40         config.readfp(f)
41         pkg = dict(config.items('Package'))
42         basename = os.path.basename(pkg_file)
43         package_name = os.path.splitext(basename)[0]
44         pkg['package_name'] = package_name
45         f.close()
46         return pkg
47
48     return None
49
50
51 def process_all(path, cb):
52     listing = sorted(glob.glob(os.path.join(path, '*.ini')))
53     for pkg_file in listing:
54         pkg = get_pkg(pkg_file)
55         if not pkg:
56             sys.stderr.write("Error: cannot get a pkg for: %s\n" % pkg_file)
57             continue
58         cb(pkg)
59
60
61 def show(pkg):
62     print 'Package:  ', pkg['package_name']
63     print 'Program:  ', pkg['name']
64     if pkg.has_key('version'):
65         print 'Version:  ', pkg['version']
66     print 'Homepage: ', pkg['homepage']
67     print
68
69
70 def download_file(src_url, dest_dir):
71     try:
72         hdr = {
73             'User-Agent': 'Wget/1.13.4 (linux-gnu)',
74         }
75         request = urllib2.Request(src_url, headers=hdr)
76         response = urllib2.urlopen(request)
77     except Exception, e:
78         print 'Downloading from', src_url, 'failed.', e
79         return
80
81     # get the final URL after possible redirect have been followed
82     url = response.geturl()
83
84     filename = ""
85
86     # From http://paste.pound-python.org/show/9545/
87     # TODO: use a proper module to parse HTTP headers
88     if 'Content-Disposition' in response.info() and len(response.info()['Content-Disposition'].split('filename=')) > 1:
89         # If the response has Content-Disposition, we take file name from it
90         filename = response.info()['Content-Disposition'].split('filename=')[1].decode('utf-8')
91         if filename[0] == '"' or filename[0] == "'":
92             filename = urllib2.unquote(filename.split('"')[1])
93     else:
94         filename = urllib2.unquote(url.split('/')[-1].decode('utf_8'))
95
96     if filename == "":
97         sys.stderr.write("Debug (%s): filename: %s url: %s\n" % (pkg['package_name'], filename, url))
98         return
99
100     # TODO: Add some integrity verification of downloaded files (md5, sha256?)
101
102     destfile = os.path.join(dest_dir, filename)
103     if os.path.exists(destfile):
104         # TODO: check if the file is a full download from previous run,
105         # if not download again discarding the existing file?
106         sys.stderr.write("Warning: %s exists!\n" % destfile)
107         return
108
109     if 'Content-Length' not in response.info():
110         sys.stderr.write("Cannot get the size of the file at %s\n" % src_url)
111         return
112
113     total_size = response.info().getheader('Content-Length').strip()
114     total_size = int(total_size)
115
116     #widgets = [pkg['name'], ' ', Percentage(), ' ', Bar(marker='=', left='[', right=']'),
117     widgets = [filename, ' ', Percentage(), ' ', Bar(marker='=', left='[', right=']'),
118                ' ', ETA(), ' ', FileTransferSpeed()]
119     pbar = ProgressBar(widgets=widgets, maxval=total_size).start()
120
121     outfile = open(destfile, mode='w')
122
123     bytes_so_far = 0
124     while 1:
125         chunk = response.read(CHUNK_SIZE)
126         if not chunk:
127             break
128
129         bytes_so_far += len(chunk)
130         outfile.write(chunk)
131         pbar.update(bytes_so_far)
132     pbar.finish()
133
134     outfile.close()
135
136
137 def download(pkg):
138     try:
139         pkg_url = pkg['url_' + ARCHITECTURE]
140     except KeyError:
141         pkg_url = pkg['url']
142     download_file(pkg_url, OUTPUT_DIR)
143
144
145 def show_all():
146     process_all(PKG_DIR, show)
147
148
149 def download_all():
150     if os.path.exists(OUTPUT_DIR) == False:
151         os.mkdir(OUTPUT_DIR, 0755)
152
153     process_all(PKG_DIR, download)
154
155
156 def usage():
157     usage = "winfreed - download a selection of Free Software for MS Windows.\n\n"
158     usage += "usage: %s <COMMAND>\n\n" % sys.argv[0]
159     usage += "COMMANDS:\n"
160     usage += "\tshow        Show info about all the available packages\n"
161     usage += "\tdownload    Download all the packages\n"
162     print usage
163
164 if __name__ == "__main__":
165
166     if len(sys.argv) < 2:
167         usage()
168         sys.exit(1)
169
170     if sys.argv[1] == 'download':
171         if len(sys.argv) > 2:
172             pkg = get_pkg(sys.argv[2])
173             download(pkg)
174         else:
175             download_all()
176     elif sys.argv[1] == 'show':
177         show_all()
178     else:
179         usage()
180         sys.exit(1)
181
182     sys.exit(0)