more logging, and fix terrible spelling
[objavi2.git] / espri.cgi
blob2749646c97b41ec81442784e795fb04c28e9b2bd
1 #!/usr/bin/python
3 # Part of Espri, an importer of e-books into Booki
5 # Copyright (C) 2009 Douglas Bagnall
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 2 of the License, or
10 # (at your option) any later version.
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.
17 # You should have received a copy of the GNU General Public License along
18 # with this program; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 import os, sys
22 import re
23 from urllib2 import urlopen, HTTPError
24 import traceback
26 from objavi import epub
27 from objavi.cgi_utils import shift_file, parse_args, optionise, print_template
28 from objavi.cgi_utils import output_blob_and_exit, log
29 from objavi import config
31 IA_EPUB_URL = "http://www.archive.org/download/%s/%s.epub"
33 def print_form(booklink):
34 print_template('templates/espri.html',
35 {'booklink': booklink,
39 def ia_espri(book_id):
40 epuburl = IA_EPUB_URL % (book_id, book_id)
41 log(epuburl)
42 zipurl = '%s/%s.zip' % (config.BOOKI_BOOK_DIR, book_id)
43 f = urlopen(epuburl)
44 s = f.read()
45 f.close()
46 e = epub.Epub()
47 e.load(s)
48 e.parse_meta()
49 e.parse_opf()
50 e.parse_ncx()
51 e.make_bookizip(zipurl)
52 return zipurl
54 def is_name(s):
55 if re.match(r'^[\w-]+$', s):
56 return s
58 ARG_VALIDATORS = {
59 "book": is_name,
60 'mode': ('zip', 'html').__contains__
63 if __name__ == '__main__':
64 args = parse_args(ARG_VALIDATORS)
65 if 'book' in args:
66 try:
67 url = ia_espri(args['book'])
68 book_link = '<p>Download <a href="%s">%s booki-zip</a>.</p>' % (url, args['book'])
69 except Exception, e:
70 traceback.print_exc()
71 log(e, args)
72 book_link = '<p>Error: <b>%s</b> when trying to get %s</p>' % (e, args['book'])
73 else:
74 book_link = ''
76 mode = args.get('mode', 'html')
77 if mode == 'zip':
78 f = open(url)
79 data = f.read()
80 f.close()
81 output_blob_and_exit(data, 'application/x-booki+zip', args['book'] + '.zip')
82 else:
83 print_form(book_link)