home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyc (Python 2.6)
-
- from __future__ import with_statement
- __license__ = 'GPL 3'
- __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
- __docformat__ = 'restructuredtext en'
- import os
- import uuid
- from itertools import cycle
- from lxml import etree
- from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation
-
- class EPUBInput(InputFormatPlugin):
- name = 'EPUB Input'
- author = 'Kovid Goyal'
- description = 'Convert EPUB files (.epub) to HTML'
- file_types = set([
- 'epub'])
- recommendations = set([
- ('page_breaks_before', '/', OptionRecommendation.MED)])
-
- def decrypt_font(self, key, path):
- raw = open(path, 'rb').read()
- crypt = raw[:1024]
- key = cycle(iter(key))
- decrypt = []([ chr(ord(x) ^ key.next()) for x in crypt ])
-
- try:
- f = _[2]
- f.write(decrypt)
- f.write(raw[1024:])
- finally:
- pass
-
-
-
- def process_encryption(self, encfile, opf, log):
- key = None
- for item in opf.identifier_iter():
- scheme = None
- for xkey in item.attrib.keys():
- if xkey.endswith('scheme'):
- scheme = item.get(xkey)
- continue
-
- if (scheme or scheme.lower() == 'uuid' or item.text) and item.text.startswith('urn:uuid:'):
-
- try:
- key = str(item.text).rpartition(':')[-1]
- key = list(map(ord, uuid.UUID(key).bytes))
- import traceback
- traceback.print_exc()
- key = None
-
- continue
-
-
- try:
- root = etree.parse(encfile)
- for em in root.xpath('descendant::*[contains(name(), "EncryptionMethod")]'):
- algorithm = em.get('Algorithm', '')
- if algorithm != 'http://ns.adobe.com/pdf/enc#RC':
- return False
- cr = em.getparent().xpath('descendant::*[contains(name(), "CipherReference")]')[0]
- uri = cr.get('URI')
- path = os.path.abspath(os.path.join(os.path.dirname(encfile), '..', *uri.split('/')))
- if key is not None and os.path.exists(path):
- self._encrypted_font_uris.append(uri)
- self.decrypt_font(key, path)
- continue
- algorithm != 'http://ns.adobe.com/pdf/enc#RC'
-
- return True
- except:
- import traceback
- traceback.print_exc()
-
- return False
-
-
- def rationalize_cover(self, opf, log):
- (guide_cover, guide_elem) = (None, None)
- for guide_elem in opf.iterguide():
- if guide_elem.get('type', '').lower() == 'cover':
- guide_cover = guide_elem.get('href', '')
- break
- continue
-
- if not guide_cover:
- return None
- spine = list(opf.iterspine())
- if not spine:
- return None
- idref = spine[0].get('idref', '')
- manifest = list(opf.itermanifest())
- if not manifest:
- return None
- elem = _[1]
- if not elem or elem[0].get('href', None) != guide_cover:
- return None
- log('Found HTML cover', guide_cover)
- guide_elem.set('href', 'calibre_raster_cover.jpg')
- OPF = OPF
- import calibre.ebooks.oeb.base
- t = etree.SubElement(elem[0].getparent(), OPF('item'), href = guide_elem.get('href'), id = 'calibre_raster_cover')
- t.set('media-type', 'image/jpeg')
- for elem in list(opf.iterguide()):
- if elem.get('type', '').lower() == 'titlepage':
- elem.getparent().remove(elem)
- continue
- [] if not self.for_viewer else []
-
- t = etree.SubElement(guide_elem.getparent(), OPF('reference'))
- t.set('type', 'titlepage')
- t.set('href', guide_cover)
- t.set('title', 'Title Page')
- render_html_svg_workaround = render_html_svg_workaround
- import calibre.ebooks
- renderer = render_html_svg_workaround(guide_cover, log)
-
-
- def convert(self, stream, options, file_ext, log, accelerators):
- ZipFile = ZipFile
- import calibre.utils.zipfile
- walk = walk
- import calibre
- DRMError = DRMError
- import calibre.ebooks
- OPF = OPF
- import calibre.ebooks.metadata.opf2
- zf = ZipFile(stream)
- zf.extractall(os.getcwd())
- encfile = os.path.abspath(os.path.join('META-INF', 'encryption.xml'))
- opf = None
- for f in walk(u'.'):
- if f.lower().endswith('.opf') and '__MACOSX' not in f:
- opf = os.path.abspath(f)
- break
- continue
-
- path = getattr(stream, 'name', 'stream')
- if opf is None:
- raise ValueError('%s is not a valid EPUB file' % path)
- opf is None
- opf = os.path.relpath(opf, os.getcwdu())
- parts = os.path.split(opf)
- opf = OPF(opf, os.path.dirname(os.path.abspath(opf)))
- self._encrypted_font_uris = []
- if os.path.exists(encfile):
- if not self.process_encryption(encfile, opf, log):
- raise DRMError(os.path.basename(path))
- self.process_encryption(encfile, opf, log)
-
- self.encrypted_fonts = self._encrypted_font_uris
- if len(parts) > 1 and parts[0]:
- delta = '/'.join(parts[:-1]) + '/'
- for elem in opf.itermanifest():
- elem.set('href', delta + elem.get('href'))
-
- for elem in opf.iterguide():
- elem.set('href', delta + elem.get('href'))
-
-
- self.rationalize_cover(opf, log)
- self.optimize_opf_parsing = opf
- for x in opf.itermanifest():
- if x.get('media-type', '') == 'application/x-dtbook+xml':
- raise ValueError('EPUB files with DTBook markup are not supported')
- x.get('media-type', '') == 'application/x-dtbook+xml'
-
-
- try:
- nopf = _[1]
- nopf.write(opf.render())
- finally:
- pass
-
- return os.path.abspath('content.opf')
-
-
-