home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_885 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  6.2 KB  |  182 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.     recommendations = set([
  21.         ('page_breaks_before', '/', OptionRecommendation.MED)])
  22.     
  23.     def decrypt_font(self, key, path):
  24.         raw = open(path, 'rb').read()
  25.         crypt = raw[:1024]
  26.         key = cycle(iter(key))
  27.         decrypt = []([ chr(ord(x) ^ key.next()) for x in crypt ])
  28.         
  29.         try:
  30.             f = _[2]
  31.             f.write(decrypt)
  32.             f.write(raw[1024:])
  33.         finally:
  34.             pass
  35.  
  36.  
  37.     
  38.     def process_encryption(self, encfile, opf, log):
  39.         key = None
  40.         for item in opf.identifier_iter():
  41.             scheme = None
  42.             for xkey in item.attrib.keys():
  43.                 if xkey.endswith('scheme'):
  44.                     scheme = item.get(xkey)
  45.                     continue
  46.             
  47.             if (scheme or scheme.lower() == 'uuid' or item.text) and item.text.startswith('urn:uuid:'):
  48.                 
  49.                 try:
  50.                     key = str(item.text).rpartition(':')[-1]
  51.                     key = list(map(ord, uuid.UUID(key).bytes))
  52.                 import traceback
  53.                 traceback.print_exc()
  54.                 key = None
  55.  
  56.                 continue
  57.         
  58.         
  59.         try:
  60.             root = etree.parse(encfile)
  61.             for em in root.xpath('descendant::*[contains(name(), "EncryptionMethod")]'):
  62.                 algorithm = em.get('Algorithm', '')
  63.                 if algorithm != 'http://ns.adobe.com/pdf/enc#RC':
  64.                     return False
  65.                 cr = em.getparent().xpath('descendant::*[contains(name(), "CipherReference")]')[0]
  66.                 uri = cr.get('URI')
  67.                 path = os.path.abspath(os.path.join(os.path.dirname(encfile), '..', *uri.split('/')))
  68.                 if key is not None and os.path.exists(path):
  69.                     self._encrypted_font_uris.append(uri)
  70.                     self.decrypt_font(key, path)
  71.                     continue
  72.                 algorithm != 'http://ns.adobe.com/pdf/enc#RC'
  73.             
  74.             return True
  75.         except:
  76.             import traceback
  77.             traceback.print_exc()
  78.  
  79.         return False
  80.  
  81.     
  82.     def rationalize_cover(self, opf, log):
  83.         (guide_cover, guide_elem) = (None, None)
  84.         for guide_elem in opf.iterguide():
  85.             if guide_elem.get('type', '').lower() == 'cover':
  86.                 guide_cover = guide_elem.get('href', '')
  87.                 break
  88.                 continue
  89.         
  90.         if not guide_cover:
  91.             return None
  92.         spine = list(opf.iterspine())
  93.         if not spine:
  94.             return None
  95.         idref = spine[0].get('idref', '')
  96.         manifest = list(opf.itermanifest())
  97.         if not manifest:
  98.             return None
  99.         elem = _[1]
  100.         if not elem or elem[0].get('href', None) != guide_cover:
  101.             return None
  102.         log('Found HTML cover', guide_cover)
  103.         guide_elem.set('href', 'calibre_raster_cover.jpg')
  104.         OPF = OPF
  105.         import calibre.ebooks.oeb.base
  106.         t = etree.SubElement(elem[0].getparent(), OPF('item'), href = guide_elem.get('href'), id = 'calibre_raster_cover')
  107.         t.set('media-type', 'image/jpeg')
  108.         for elem in list(opf.iterguide()):
  109.             if elem.get('type', '').lower() == 'titlepage':
  110.                 elem.getparent().remove(elem)
  111.                 continue
  112.             [] if not self.for_viewer else []
  113.         
  114.         t = etree.SubElement(guide_elem.getparent(), OPF('reference'))
  115.         t.set('type', 'titlepage')
  116.         t.set('href', guide_cover)
  117.         t.set('title', 'Title Page')
  118.         render_html_svg_workaround = render_html_svg_workaround
  119.         import calibre.ebooks
  120.         renderer = render_html_svg_workaround(guide_cover, log)
  121.  
  122.     
  123.     def convert(self, stream, options, file_ext, log, accelerators):
  124.         ZipFile = ZipFile
  125.         import calibre.utils.zipfile
  126.         walk = walk
  127.         import calibre
  128.         DRMError = DRMError
  129.         import calibre.ebooks
  130.         OPF = OPF
  131.         import calibre.ebooks.metadata.opf2
  132.         zf = ZipFile(stream)
  133.         zf.extractall(os.getcwd())
  134.         encfile = os.path.abspath(os.path.join('META-INF', 'encryption.xml'))
  135.         opf = None
  136.         for f in walk(u'.'):
  137.             if f.lower().endswith('.opf') and '__MACOSX' not in f:
  138.                 opf = os.path.abspath(f)
  139.                 break
  140.                 continue
  141.         
  142.         path = getattr(stream, 'name', 'stream')
  143.         if opf is None:
  144.             raise ValueError('%s is not a valid EPUB file' % path)
  145.         opf is None
  146.         opf = os.path.relpath(opf, os.getcwdu())
  147.         parts = os.path.split(opf)
  148.         opf = OPF(opf, os.path.dirname(os.path.abspath(opf)))
  149.         self._encrypted_font_uris = []
  150.         if os.path.exists(encfile):
  151.             if not self.process_encryption(encfile, opf, log):
  152.                 raise DRMError(os.path.basename(path))
  153.             self.process_encryption(encfile, opf, log)
  154.         
  155.         self.encrypted_fonts = self._encrypted_font_uris
  156.         if len(parts) > 1 and parts[0]:
  157.             delta = '/'.join(parts[:-1]) + '/'
  158.             for elem in opf.itermanifest():
  159.                 elem.set('href', delta + elem.get('href'))
  160.             
  161.             for elem in opf.iterguide():
  162.                 elem.set('href', delta + elem.get('href'))
  163.             
  164.         
  165.         self.rationalize_cover(opf, log)
  166.         self.optimize_opf_parsing = opf
  167.         for x in opf.itermanifest():
  168.             if x.get('media-type', '') == 'application/x-dtbook+xml':
  169.                 raise ValueError('EPUB files with DTBook markup are not supported')
  170.             x.get('media-type', '') == 'application/x-dtbook+xml'
  171.         
  172.         
  173.         try:
  174.             nopf = _[1]
  175.             nopf.write(opf.render())
  176.         finally:
  177.             pass
  178.  
  179.         return os.path.abspath('content.opf')
  180.  
  181.  
  182.