a59d78e39a11e4f9d7abf832b6c60b8614170fe4
[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  Antonio Ospite <ospite@studenti.unina.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 re
21 import os
22 import sys
23 import glob
24 import json
25 import urllib2
26 from progressbar import Bar, ETA, FileTransferSpeed, Percentage, ProgressBar
27
28 # TODO make OUTPUT_DIR and LANGCODE configurable from command line
29 OUTPUT_DIR = 'downloads'
30 LANGCODE = 'en-US'
31
32 # TODO PKG_DIR in $(datadir) or something like that for python projects
33 PKG_DIR = 'pkgs'
34 CHUNK_SIZE = 8192
35
36
37 def get_pkg(json_file):
38     with open(json_file, mode='r') as f:
39         pkg = json.load(f)
40         basename = os.path.basename(json_file)
41         package_name = os.path.splitext(basename)[0]
42         pkg['package_name'] = package_name
43         f.close()
44         return pkg
45
46     return None
47
48
49 def process_all(path, cb):
50     listing = glob.glob(os.path.join(path, '*.json'))
51     for json_file in listing:
52         pkg = get_pkg(json_file)
53         if not pkg:
54             sys.stderr.write("Error: cannot get a pkg for: %s\n" % json_file)
55             continue
56         cb(pkg)
57
58
59 def show(pkg):
60     print 'Package:  ', pkg['package_name']
61     print 'Program:  ', pkg['name']
62     print 'Homepage: ', pkg['homepage']
63     print
64
65
66 def download_file(src_url, dest_dir):
67     try:
68         response = urllib2.urlopen(src_url)
69     except Exception, e:
70         if hasattr(e, 'reason'):
71             print 'Download failed. Reason: ', e.reason
72         elif hasattr(e, 'code'):
73             print 'Download failed. Error code: ', e.code
74         return
75
76     # get the final URL after possible redirect have been followed
77     url = response.geturl()
78
79     filename = ""
80
81     # From http://paste.pound-python.org/show/9545/
82     # TODO: use a proper module to parse HTTP headers
83     if 'Content-Disposition' in response.info() and len(response.info()['Content-Disposition'].split('filename=')) > 1:
84         # If the response has Content-Disposition, we take file name from it
85         filename = response.info()['Content-Disposition'].split('filename=')[1].decode('utf-8')
86         if filename[0] == '"' or filename[0] == "'":
87             filename = urllib2.unquote(filename.split('"')[1])
88     else:
89         filename = urllib2.unquote(url.split('/')[-1].decode('utf_8'))
90
91     if filename == "":
92         sys.stderr.write("Debug (%s): filename: %s url: %s\n" % (pkg['package_name'], filename, url))
93         return
94
95     # TODO: Add some integrity verification of downloaded files (md5, sha256?)
96
97     destfile = os.path.join(dest_dir, filename)
98     if os.path.exists(destfile):
99         # TODO: check if the file is a full download from previous run,
100         # if not download again discarding the existing file?
101         sys.stderr.write("Warning: %s exists!\n" % destfile)
102         return
103
104     outfile = open(destfile, mode='w')
105
106     total_size = response.info().getheader('Content-Length').strip()
107     total_size = int(total_size)
108
109     #widgets = [pkg['name'], ' ', Percentage(), ' ', Bar(marker='=', left='[', right=']'),
110     widgets = [filename, ' ', Percentage(), ' ', Bar(marker='=', left='[', right=']'),
111                ' ', ETA(), ' ', FileTransferSpeed()]
112     pbar = ProgressBar(widgets=widgets, maxval=total_size).start()
113
114     bytes_so_far = 0
115     while 1:
116         chunk = response.read(CHUNK_SIZE)
117         if not chunk:
118             break
119
120         bytes_so_far += len(chunk)
121         outfile.write(chunk)
122         pbar.update(bytes_so_far)
123     pbar.finish()
124
125     outfile.close()
126
127
128 def download(pkg):
129     # the "%s" in URLs are meant to be replaced with LANGCODE
130     try:
131         pkg_url = pkg['URL'] % LANGCODE
132     except:
133         pkg_url = pkg['URL']
134         pass
135
136     download_file(pkg_url, OUTPUT_DIR)
137
138
139 def show_all():
140     process_all(PKG_DIR, show)
141
142
143 def download_all():
144     if os.path.exists(OUTPUT_DIR) == False:
145         os.mkdir(OUTPUT_DIR, 0755)
146
147     process_all(PKG_DIR, download)
148
149
150 def usage():
151     usage = "winfreed - download a selection of Free Software for MS Windows.\n\n"
152     usage += "usage: %s <COMMAND>\n\n" % sys.argv[0]
153     usage += "COMMANDS:\n"
154     usage += "\tshow        Show info about all the available packages\n"
155     usage += "\tdownload    Download all the packages\n"
156     print usage
157
158 if __name__ == "__main__":
159
160     if len(sys.argv) < 2:
161         usage()
162         sys.exit(1)
163
164     if sys.argv[1] == 'download':
165         download_all()
166     elif sys.argv[1] == 'show':
167         show_all()
168     else:
169         usage()
170         sys.exit(1)
171
172     sys.exit(0)