13b75804e95eee25020a538daae6d08aa4ae286b
[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(pkg):
67     # the "%s" in URLs are meant to be replaced with LANGCODE
68     try:
69         url = pkg['URL'] % LANGCODE
70     except:
71         url = pkg['URL']
72         pass
73
74     response = urllib2.urlopen(url)
75
76     filename = ""
77     if 'Content-Disposition' in  response.info():
78         # Use the filename the server tells us if any,
79         # re pattern from http://stackoverflow.com/questions/8035900
80         content_disposition = response.info().getheader('Content-Disposition').strip()
81         filename = re.findall("filename=(\S+)", content_disposition)[0]
82
83     if filename == "":
84         filename = urllib2.unquote(os.path.basename(response.geturl()))
85
86     if filename == "":
87         sys.stderr.write("Debug (%s): filename: %s url: %s\n" %(pkg['package_name'], filename, response.geturl()))
88         return
89
90     destfile = os.path.join(OUTPUT_DIR, filename)
91     if os.path.exists(destfile):
92         sys.stderr.write("Warning (%s): %s exists!\n" % (pkg['package_name'], destfile))
93         return
94
95     outfile = open(destfile, mode='w')
96
97     total_size = response.info().getheader('Content-Length').strip()
98     total_size = int(total_size)
99
100     widgets = [pkg['name'], ' ', Percentage(), ' ', Bar(marker='=', left='[', right=']'),
101                ' ', ETA(), ' ', FileTransferSpeed()]
102     pbar = ProgressBar(widgets=widgets, maxval=total_size).start()
103
104     bytes_so_far = 0
105     while 1:
106         chunk = response.read(CHUNK_SIZE)
107         if not chunk:
108             break
109
110         bytes_so_far += len(chunk)
111         outfile.write(chunk)
112         pbar.update(bytes_so_far)
113     pbar.finish()
114
115
116 def show_all():
117     process_all(PKG_DIR, show)
118
119
120 def download_all():
121     if os.path.exists(OUTPUT_DIR) == False:
122         os.mkdir(OUTPUT_DIR, 0755)
123
124     process_all(PKG_DIR, download)
125
126
127 def usage():
128     usage = "winfreed - download a selection of Free Software for MS Windows.\n\n"
129     usage += "usage: %s <COMMAND>\n\n" % sys.argv[0]
130     usage += "COMMANDS:\n"
131     usage += "\tshow        Show info about all the available packages\n"
132     usage += "\tdownload    Download all the packages\n"
133     print usage
134
135 if __name__ == "__main__":
136
137     if len(sys.argv) < 2:
138         usage()
139         sys.exit(1)
140
141     if sys.argv[1] == 'download':
142         download_all()
143     elif sys.argv[1] == 'show':
144         show_all()
145     else:
146         usage()
147         sys.exit(1)
148
149     sys.exit(0)