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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from __future__ import with_statement
  5. __license__ = 'GPL 3'
  6. __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
  7. __docformat__ = 'restructuredtext en'
  8. import os
  9. import uuid
  10. from itertools import cycle
  11. from lxml import etree
  12. from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation
  13.  
  14. class EPUBInput(InputFormatPlugin):
  15.     name = 'EPUB Input'
  16.     author = 'Kovid Goyal'
  17.     description = 'Convert EPUB files (.epub) to HTML'
  18.     file_types = set([
  19.         'epub'])
  20.     output_encoding = None
  21.     recommendations = set([
  22.         ('page_breaks_before', '/', OptionRecommendation.MED)])
  23.     
  24.     def decrypt_font(self, key, path):
  25.         raw = open(path, 'rb').read()
  26.         crypt = raw[:1024]
  27.         key = cycle(iter(key))
  28.         decrypt = []([ chr(ord(x) ^ key.next()) for x in crypt ])
  29.         
  30.         try:
  31.             f = _[2]
  32.             f.write(decrypt)
  33.             f.write(raw[1024:])
  34.         finally:
  35.             pass
  36.  
  37.  
  38.     
  39.     def process_encryption(self, encfile, opf, log):
  40.         key = None
  41.         for item in opf.identifier_iter():
  42.             scheme = None
  43.             for xkey in item.attrib.keys():
  44.                 if xkey.endswith('scheme'):
  45.                     scheme = item.get(xkey)
  46.                     continue
  47.             
  48.             if (scheme or scheme.lower() == 'uuid' or item.text) and item.text.startswith('urn:uuid:'):
  49.                 
  50.                 try:
  51.                     key = str(item.text).rpartition(':')[-1]
  52.                     key = list(map(ord, uuid.UUID(key).bytes))
  53.                 import traceback
  54.                 traceback.print_exc()
  55.                 key = None
  56.  
  57.                 continue
  58.         
  59.         
  60.         try:
  61.             root = etree.parse(encfile)
  62.             for em in root.xpath('descendant::*[contains(name(), "EncryptionMethod")]'):
  63.                 algorithm = em.get('Algorithm', '')
  64.                 if algorithm != 'http://ns.adobe.com/pdf/enc#RC':
  65.                     return False
  66.                 cr = em.getparent().xpath('descendant::*[contains(name(), "CipherReference")]')[0]
  67.                 uri = cr.get('URI')
  68.                 path = os.path.abspath(os.path.join(os.path.dirname(encfile), '..', *uri.split('/')))
  69.                 if key is not None and os.path.exists(path):
  70.                     self._encrypted_font_uris.append(uri)
  71.                     self.decrypt_font(key, path)
  72.                     continue
  73.                 algorithm != 'http://ns.adobe.com/pdf/enc#RC'
  74.             
  75.             return True
  76.         except:
  77.             import traceback
  78.             traceback.print_exc()
  79.  
  80.         return False
  81.  
  82.     
  83.     def rationalize_cover(self, opf, log):
  84.         (guide_cover, guide_elem) = (None, None)
  85.         for guide_elem in opf.iterguide():
  86.             if guide_elem.get('type', '').lower() == 'cover':
  87.                 guide_cover = guide_elem.get('href', '')
  88.                 break
  89.                 continue
  90.         
  91.         if not guide_cover:
  92.             return None
  93.         spine = list(opf.iterspine())
  94.         if not spine:
  95.             return None
  96.         idref = spine[0].get('idref', '')
  97.         manifest = list(opf.itermanifest())
  98.         if not manifest:
  99.             return None
  100.         elem = _[1]
  101.         if not elem or elem[0].get('href', None) != guide_cover:
  102.             return None
  103.         log('Found HTML cover', guide_cover)
  104.         guide_elem.set('href', 'calibre_raster_cover.jpg')
  105.         OPF = OPF
  106.         import calibre.ebooks.oeb.base
  107.         t = etree.SubElement(elem[0].getparent(), OPF('item'), href = guide_elem.get('href'), id = 'calibre_raster_cover')
  108.         t.set('media-type', 'image/jpeg')
  109.         for elem in list(opf.iterguide()):
  110.             if elem.get('type', '').lower() == 'titlepage':
  111.                 elem.getparent().remove(elem)
  112.                 continue
  113.             [] if not self.for_viewer else []
  114.         
  115.         t = etree.SubElement(guide_elem.getparent(), OPF('reference'))
  116.         t.set('type', 'titlepage')
  117.         t.set('href', guide_cover)
  118.         t.set('title', 'Title Page')
  119.         render_html_svg_workaround = render_html_svg_workaround
  120.         import calibre.ebooks
  121.         renderer = render_html_svg_workaround(guide_cover, log)
  122.  
  123.     
  124.     def find_opf(self):
  125.         
  126.         def attr(n, attr):
  127.             for k, v in n.attrib.items():
  128.                 if k.endswith(attr):
  129.                     return v
  130.             
  131.  
  132.         
  133.         try:
  134.             
  135.             try:
  136.                 f = _[1]
  137.                 root = etree.fromstring(f.read())
  138.                 for r in root.xpath('//*[local-name()="rootfile"]'):
  139.                     path = attr(r, 'full-path')
  140.                     if not path:
  141.                         continue
  142.                     
  143.                     path = os.path.join(os.getcwdu(), *path.split('/'))
  144.                     if os.path.exists(path):
  145.                         return path
  146.             finally:
  147.                 pass
  148.  
  149.         except:
  150.             import traceback
  151.             traceback.print_exc()
  152.  
  153.  
  154.     
  155.     def convert(self, stream, options, file_ext, log, accelerators):
  156.         ZipFile = ZipFile
  157.         import calibre.utils.zipfile
  158.         walk = walk
  159.         import calibre
  160.         DRMError = DRMError
  161.         import calibre.ebooks
  162.         OPF = OPF
  163.         import calibre.ebooks.metadata.opf2
  164.         zf = ZipFile(stream)
  165.         zf.extractall(os.getcwd())
  166.         encfile = os.path.abspath(os.path.join('META-INF', 'encryption.xml'))
  167.         opf = self.find_opf()
  168.         if opf is None:
  169.             for f in walk(u'.'):
  170.                 if f.lower().endswith('.opf') and '__MACOSX' not in f and not os.path.basename(f).startswith('.'):
  171.                     opf = os.path.abspath(f)
  172.                     break
  173.                     continue
  174.             
  175.         
  176.         path = getattr(stream, 'name', 'stream')
  177.         if opf is None:
  178.             raise ValueError('%s is not a valid EPUB file' % path)
  179.         opf is None
  180.         opf = os.path.relpath(opf, os.getcwdu())
  181.         parts = os.path.split(opf)
  182.         opf = OPF(opf, os.path.dirname(os.path.abspath(opf)))
  183.         self._encrypted_font_uris = []
  184.         if os.path.exists(encfile):
  185.             if not self.process_encryption(encfile, opf, log):
  186.                 raise DRMError(os.path.basename(path))
  187.             self.process_encryption(encfile, opf, log)
  188.         
  189.         self.encrypted_fonts = self._encrypted_font_uris
  190.         if len(parts) > 1 and parts[0]:
  191.             delta = '/'.join(parts[:-1]) + '/'
  192.             for elem in opf.itermanifest():
  193.                 elem.set('href', delta + elem.get('href'))
  194.             
  195.             for elem in opf.iterguide():
  196.                 elem.set('href', delta + elem.get('href'))
  197.             
  198.         
  199.         self.rationalize_cover(opf, log)
  200.         self.optimize_opf_parsing = opf
  201.         for x in opf.itermanifest():
  202.             if x.get('media-type', '') == 'application/x-dtbook+xml':
  203.                 raise ValueError('EPUB files with DTBook markup are not supported')
  204.             x.get('media-type', '') == 'application/x-dtbook+xml'
  205.         
  206.         
  207.         try:
  208.             nopf = _[1]
  209.             nopf.write(opf.render())
  210.         finally:
  211.             pass
  212.  
  213.         return os.path.abspath('content.opf')
  214.  
  215.  
  216.