home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 January / maximum-cd-2011-01.iso / DiscContents / calibre-0.7.26.msi / file_1425 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-10-31  |  8.3 KB  |  209 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __license__ = 'GPL v3'
  5. __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
  6. __docformat__ = 'restructuredtext en'
  7. import re
  8. import os
  9. import cherrypy
  10. from calibre import fit_image, guess_type
  11. from calibre.utils.date import fromtimestamp
  12. from calibre.library.caches import SortKeyGenerator
  13. from calibre.utils.magick.draw import save_cover_data_to, Image, thumbnail as generate_thumbnail
  14.  
  15. class CSSortKeyGenerator(SortKeyGenerator):
  16.     
  17.     def __init__(self, fields, fm):
  18.         SortKeyGenerator.__init__(self, fields, fm, None)
  19.  
  20.     
  21.     def __call__(self, record):
  22.         return self.itervals(record).next()
  23.  
  24.  
  25.  
  26. class ContentServer(object):
  27.     
  28.     def add_routes(self, connect):
  29.         connect('root', '/', self.index)
  30.         connect('old', '/old', self.old)
  31.         connect('get', '/get/{what}/{id}', self.get, conditions = dict(method = [
  32.             'GET',
  33.             'HEAD']))
  34.         connect('static', '/static/{name:.*?}', self.static, conditions = dict(method = [
  35.             'GET',
  36.             'HEAD']))
  37.  
  38.     
  39.     def last_modified(self, updated):
  40.         lm = updated.strftime('day, %d month %Y %H:%M:%S GMT')
  41.         day = {
  42.             0: 'Sun',
  43.             1: 'Mon',
  44.             2: 'Tue',
  45.             3: 'Wed',
  46.             4: 'Thu',
  47.             5: 'Fri',
  48.             6: 'Sat' }
  49.         lm = lm.replace('day', day[int(updated.strftime('%w'))])
  50.         month = {
  51.             1: 'Jan',
  52.             2: 'Feb',
  53.             3: 'Mar',
  54.             4: 'Apr',
  55.             5: 'May',
  56.             6: 'Jun',
  57.             7: 'Jul',
  58.             8: 'Aug',
  59.             9: 'Sep',
  60.             10: 'Oct',
  61.             11: 'Nov',
  62.             12: 'Dec' }
  63.         return lm.replace('month', month[updated.month])
  64.  
  65.     
  66.     def sort(self, items, field, order):
  67.         field = self.db.data.sanitize_sort_field_name(field)
  68.         if field not in self.db.field_metadata.sortable_field_keys():
  69.             raise cherrypy.HTTPError(400, '%s is not a valid sort field' % field)
  70.         field not in self.db.field_metadata.sortable_field_keys()
  71.         keyg = CSSortKeyGenerator([
  72.             (field, order)], self.db.field_metadata)
  73.         items.sort(key = keyg, reverse = not order)
  74.  
  75.     
  76.     def get(self, what, id):
  77.         
  78.         try:
  79.             id = int(id)
  80.         except ValueError:
  81.             id = id.rpartition('_')[-1].partition('.')[0]
  82.             match = re.search('\\d+', id)
  83.             if not match:
  84.                 raise cherrypy.HTTPError(404, 'id:%s not an integer' % id)
  85.             match
  86.             id = int(match.group())
  87.  
  88.         if not self.db.has_id(id):
  89.             raise cherrypy.HTTPError(404, 'id:%d does not exist in database' % id)
  90.         self.db.has_id(id)
  91.         if what == 'thumb' or what.startswith('thumb_'):
  92.             
  93.             try:
  94.                 (width, height) = map(int, what.split('_')[1:])
  95.             except:
  96.                 (width, height) = (60, 80)
  97.  
  98.             return self.get_cover(id, thumbnail = True, thumb_width = width, thumb_height = height)
  99.         if what == 'cover':
  100.             return self.get_cover(id)
  101.         return self.get_format(id, what)
  102.  
  103.     
  104.     def static(self, name):
  105.         name = name.lower()
  106.         cherrypy.response.headers['Content-Type'] = {
  107.             'js': 'text/javascript',
  108.             'css': 'text/css',
  109.             'png': 'image/png',
  110.             'gif': 'image/gif',
  111.             'html': 'text/html',
  112.             '': 'application/octet-stream' }[name.rpartition('.')[-1].lower()]
  113.         cherrypy.response.headers['Last-Modified'] = self.last_modified(self.build_time)
  114.         path = P('content_server/' + name)
  115.         if not os.path.exists(path):
  116.             raise cherrypy.HTTPError(404, '%s not found' % name)
  117.         os.path.exists(path)
  118.         if self.opts.develop:
  119.             lm = fromtimestamp(os.stat(path).st_mtime)
  120.             cherrypy.response.headers['Last-Modified'] = self.last_modified(lm)
  121.         
  122.         
  123.         try:
  124.             f = _[1]
  125.             ans = f.read()
  126.         finally:
  127.             pass
  128.  
  129.         return ans
  130.  
  131.     
  132.     def index(self, **kwargs):
  133.         ua = cherrypy.request.headers.get('User-Agent', '').strip()
  134.         if not cherrypy.request.headers.get('Stanza-Device-Name', 919) != 919 and cherrypy.request.headers.get('Want-OPDS-Catalog', 919) != 919:
  135.             pass
  136.         want_opds = ua.startswith('Stanza')
  137.         want_mobile = self.MOBILE_UA.search(ua) is not None
  138.         if self.opts.develop and not want_mobile:
  139.             cherrypy.log('User agent: ' + ua)
  140.         
  141.         if want_opds:
  142.             return self.opds(version = 0)
  143.         if want_mobile:
  144.             return self.mobile()
  145.         return self.browse_toplevel()
  146.  
  147.     
  148.     def old(self, **kwargs):
  149.         return self.static('index.html').replace('{prefix}', self.opts.url_prefix)
  150.  
  151.     
  152.     def get_cover(self, id, thumbnail = False, thumb_width = 60, thumb_height = 80):
  153.         
  154.         try:
  155.             cherrypy.response.headers['Content-Type'] = 'image/jpeg'
  156.             cherrypy.response.timeout = 3600
  157.             cover = self.db.cover(id, index_is_id = True, as_file = True)
  158.             cherrypy.response.headers['Last-Modified'] = self.last_modified(updated)
  159.             if thumbnail:
  160.                 return generate_thumbnail(cover, width = thumb_width, height = thumb_height)[-1]
  161.             img = Image()
  162.             img.load(cover)
  163.             (width, height) = img.size
  164.             (scaled, width, height) = cover if cover is None else cover.__exit__(thumbnail, fit_image, width, height if thumbnail else self.max_cover_width if thumbnail else self.max_cover_height)
  165.             if not scaled:
  166.                 return cover
  167.             return save_cover_data_to(img, 'img.jpg', return_data = True, resize_to = (width, height))
  168.         except Exception:
  169.             err = None
  170.             import traceback
  171.             cherrypy.log.error('Failed to generate cover:')
  172.             cherrypy.log.error(traceback.print_exc())
  173.             raise cherrypy.HTTPError(404, 'Failed to generate cover: %r' % err)
  174.  
  175.  
  176.     
  177.     def get_format(self, id, format):
  178.         format = format.upper()
  179.         fmt = self.db.format(id, format, index_is_id = True, as_file = True, mode = 'rb')
  180.         if fmt is None:
  181.             raise cherrypy.HTTPError(404, 'book: %d does not have format: %s' % (id, format))
  182.         fmt is None
  183.         if format == 'EPUB':
  184.             TemporaryFile = TemporaryFile
  185.             import tempfile
  186.             set_metadata = set_metadata
  187.             import calibre.ebooks.metadata.meta
  188.             raw = fmt.read()
  189.             fmt = TemporaryFile()
  190.             fmt.write(raw)
  191.             fmt.seek(0)
  192.             set_metadata(fmt, self.db.get_metadata(id, index_is_id = True, get_cover = True), 'epub')
  193.             fmt.seek(0)
  194.         
  195.         mt = guess_type('dummy.' + format.lower())[0]
  196.         if mt is None:
  197.             mt = 'application/octet-stream'
  198.         
  199.         cherrypy.response.headers['Content-Type'] = mt
  200.         cherrypy.response.timeout = 3600
  201.         path = getattr(fmt, 'name', None)
  202.         if path and os.path.exists(path):
  203.             updated = fromtimestamp(os.stat(path).st_mtime)
  204.             cherrypy.response.headers['Last-Modified'] = self.last_modified(updated)
  205.         
  206.         return fmt
  207.  
  208.  
  209.