示例#1
0
    def convert(self, oeb_book, output, input_plugin, opts, log):
        if input_plugin.name != "Kindle Comics Input":
            log.prints(INFO, "Executing default mobi plugin.")
            from calibre.ebooks.conversion.plugins.mobi_output import MOBIOutput
            plugin_path = os.path.join(
                sys.modules[MOBIOutput.__module__].__file__)
            mobi_output_plugin = MOBIOutput(plugin_path)
            mobi_output_plugin.convert(oeb_book, output, input_plugin, opts,
                                       log)
        else:
            log.prints(INFO, "Executing Kindle Comic Output plugin.")
            from calibre_plugins.kindle_comics_output.build_file \
                import build_meta_inf, make_zip, make_mobi, write_metadata_to_opf

            # convert oebbook to epub
            metadata = oeb_book.metadata
            path = os.path.join(oeb_book.container.rootdir, "..")
            write_metadata_to_opf(os.path.join(path, "OEBPS", "content.opf"),
                                  metadata)

            build_meta_inf(path)
            log.prints(INFO, "Make epub file...")
            zip_path = os.path.join(PersistentTemporaryDirectory("_epub"),
                                    "comic")
            zip_path = make_zip(zip_path, path)

            # convert epub to mobi with kindlegen
            mobi_output = make_mobi(zip_path)
            mobi_path = mobi_output[2]
            log.prints(INFO, "Created mobi.")

            # move mobi file to destination
            # todo what if output is directory
            move(mobi_path, output)
示例#2
0
def get_work_folder(comic_file):
    from calibre.ebooks.comic.input import extract_comic
    target_dir = extract_comic(comic_file)
    _log.prints(INFO, "Extracted images into " + target_dir)

    # move file structure up
    subdirectories = os.listdir(target_dir)

    # delete all not-images
    for file in os.listdir(target_dir):
        if os.path.isdir(os.path.join(target_dir, file)) \
                or file.lower().endswith('.png') \
                or file.lower().endswith('.jpg') \
                or file.lower().endswith('.jpeg') \
                or file.lower().endswith('.tif') \
                or file.lower().endswith('.tiff'):
            continue
        os.remove(os.path.join(target_dir, file))

    if len(subdirectories) == 1 and os.path.isdir(
            os.path.join(target_dir, subdirectories[0])):
        for f in os.listdir(os.path.join(target_dir, subdirectories[0])):
            move(os.path.join(target_dir, subdirectories[0], f), target_dir)
        os.rmdir(os.path.join(target_dir, subdirectories[0]))

    new_path = PersistentTemporaryDirectory(suffix='_oebps')
    copytree(target_dir, os.path.join(new_path, 'OEBPS', 'Images'))
    rmtree(target_dir)
    _log.prints(INFO, "Moved images to structure in " + new_path)

    return new_path
示例#3
0
    def run(self, yvesfile):
        from calibre.ebooks.html.to_zip import HTML2ZIP
        html2zip = HTML2ZIP(None)
        yves_temp_directory = PersistentTemporaryDirectory('yves_input')
        bibleName = yvesDir2HTML(yvesfile,yves_temp_directory)

        return html2zip.run(os.path.join( yves_temp_directory, bibleName ))
示例#4
0
    def unpack(self, book_id, fmt):
        '''
        Unpack the book in a temporary directory
        :param book_id: The book identifier
        :param fmt: The format to unpack
        '''
        from calibre.constants import DEBUG
        from calibre.ptempfile import PersistentTemporaryDirectory
        from calibre.ebooks.tweak import get_tools
        from calibre.ebooks.oeb.base import OEBBook
        from calibre.ebooks.oeb.reader import OEBReader
        from calibre.utils.logging import default_log
        from calibre_plugins.prince_pdf.dummy_preprocessor import dummy_preprocessor

        book_file = self.db.format(book_id,
                                   fmt,
                                   index_is_id=True,
                                   as_path=True)
        if DEBUG: print(_('Unpacking book...'))
        tdir = PersistentTemporaryDirectory('_unpack')
        exploder = get_tools(fmt)[0]
        if (exploder == None): return (None, None)
        opf = exploder(book_file, tdir)
        html_preprocessor = dummy_preprocessor()
        css_preprocessor = dummy_preprocessor()
        oeb = OEBBook(default_log, html_preprocessor, css_preprocessor)
        OEBReader()(oeb, opf)
        return (opf, oeb)
示例#5
0
 def __init__(self, *args):
     QNetworkAccessManager.__init__(self, *args)
     self.cache = QNetworkDiskCache(self)
     self.setCache(self.cache)
     self.cache.setCacheDirectory(
         PersistentTemporaryDirectory(prefix='disk_cache_'))
     self.cache.setMaximumCacheSize(0)
示例#6
0
    def __init__(self, pdfpath, parent=None):
        QDialog.__init__(self, parent)
        self.pdfpath = pdfpath
        self.stack = WaitLayout(_('Rendering PDF pages, please wait...'), parent=self)
        self.container = self.stack.after

        self.container.l = l = QVBoxLayout(self.container)
        self.la = la = QLabel(_('Choose a cover from the list of PDF pages below'))
        l.addWidget(la)
        self.covers = c = QListWidget(self)
        l.addWidget(c)
        self.item_delegate = CoverDelegate(self)
        c.setItemDelegate(self.item_delegate)
        c.setIconSize(QSize(120, 160))
        c.setSelectionMode(c.SingleSelection)
        c.setViewMode(c.IconMode)
        c.setUniformItemSizes(True)
        c.setResizeMode(c.Adjust)
        c.itemDoubleClicked.connect(self.accept, type=Qt.ConnectionType.QueuedConnection)

        self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        self.more_pages = b = bb.addButton(_('&More pages'), QDialogButtonBox.ButtonRole.ActionRole)
        b.clicked.connect(self.start_rendering)
        l.addWidget(bb)
        self.rendering_done.connect(self.show_pages, type=Qt.ConnectionType.QueuedConnection)
        self.first = 1
        self.setWindowTitle(_('Choose cover from PDF'))
        self.setWindowIcon(file_icon_provider().icon_from_ext('pdf'))
        self.resize(QSize(800, 600))
        self.tdir = PersistentTemporaryDirectory('_pdf_covers')
        self.start_rendering()
示例#7
0
 def get_comics_from_collection(self, stream):
     from calibre.libunzip import extract as zipextract
     tdir = PersistentTemporaryDirectory('_comic_collection')
     zipextract(stream, tdir)
     comics = []
     with CurrentDir(tdir):
         if not os.path.exists('comics.txt'):
             raise ValueError(
                 ('%s is not a valid comic collection'
                  ' no comics.txt was found in the file') % stream.name)
         with open('comics.txt', 'rb') as f:
             raw = f.read()
         if raw.startswith(codecs.BOM_UTF16_BE):
             raw = raw.decode('utf-16-be')[1:]
         elif raw.startswith(codecs.BOM_UTF16_LE):
             raw = raw.decode('utf-16-le')[1:]
         elif raw.startswith(codecs.BOM_UTF8):
             raw = raw.decode('utf-8')[1:]
         else:
             raw = raw.decode('utf-8')
         for line in raw.splitlines():
             line = line.strip()
             if not line:
                 continue
             fname, title = line.partition(':')[0], line.partition(':')[-1]
             fname = fname.replace('#', '_')
             fname = os.path.join(tdir, *fname.split('/'))
             if not title:
                 title = os.path.basename(fname).rpartition('.')[0]
             if os.access(fname, os.R_OK):
                 comics.append([title, fname])
     if not comics:
         raise ValueError('%s has no comics' % stream.name)
     return comics
示例#8
0
    def __init__(self, pdfpath, parent=None):
        QDialog.__init__(self, parent)
        self.pdfpath = pdfpath
        self.l = l = QGridLayout()
        self.setLayout(l)

        self.la = la = QLabel(_('Choose a cover from the list of PDF pages below'))
        l.addWidget(la)
        self.loading = la = QLabel('<b>'+_('Rendering PDF pages, please wait...'))
        l.addWidget(la)

        self.covers = c = QListWidget(self)
        l.addWidget(c)
        self.item_delegate = CoverDelegate(self)
        c.setItemDelegate(self.item_delegate)
        c.setIconSize(QSize(120, 160))
        c.setSelectionMode(c.SingleSelection)
        c.setViewMode(c.IconMode)
        c.setUniformItemSizes(True)
        c.setResizeMode(c.Adjust)
        c.itemDoubleClicked.connect(self.accept)

        self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        l.addWidget(bb)
        self.rendering_done.connect(self.show_pages, type=Qt.QueuedConnection)
        self.tdir = PersistentTemporaryDirectory('_pdf_covers')
        self.thread = Thread(target=self.render)
        self.thread.daemon = True
        self.thread.start()
        self.setWindowTitle(_('Choose cover from PDF'))
        self.setWindowIcon(file_icon_provider().icon_from_ext('pdf'))
        self.resize(QSize(800, 600))
示例#9
0
 def setUp(self):
     self.tdir = PersistentTemporaryDirectory('_calibre_dbtest')
     self.db = LibraryDatabase2(self.tdir)
     f = open(os.path.join(self.tdir, 'test.txt'), 'w+b')
     f.write('test')
     paths = list(repeat(f, 3))
     formats = list(repeat('txt', 3))
     m1 = MetaInformation('Test Ebook 1', ['Test Author 1'])
     m1.tags = ['tag1', 'tag2']
     m1.publisher = 'Test Publisher 1'
     m1.rating = 2
     m1.series = 'Test Series 1'
     m1.series_index = 3
     m1.author_sort = 'as1'
     m1.isbn = 'isbn1'
     m1.cover_data = ('jpg', self.img)
     m2 = MetaInformation('Test Ebook 2', ['Test Author 2'])
     m2.tags = ['tag3', 'tag4']
     m2.publisher = 'Test Publisher 2'
     m2.rating = 3
     m2.series = 'Test Series 2'
     m2.series_index = 1
     m2.author_sort = 'as1'
     m2.isbn = 'isbn1'
     self.db.add_books(paths, formats, [m1, m2, m2], add_duplicates=True)
     self.m1, self.m2 = m1, m2
示例#10
0
    def _start_webserver(self):
        '''
        setup bibi and start web server
        '''

        self.htmlroot = PersistentTemporaryDirectory()
        print(self.htmlroot)

        zipfile = os.path.join(self.htmlroot, 'bibi.zip')
        with open(zipfile, 'wb') as f:
            f.write(
                self.load_resources(['bibi-0.999.9-r7.zip'
                                     ]).itervalues().next())
        extract(zipfile, self.htmlroot)

        handler = RootedHTTPRequestHandler
        self.htmlroot = self.htmlroot + '/bibi-0.999.9-r7/bib'
        handler.base_path = self.htmlroot

        self.httpd = ThreadedTCPServer(('localhost', 0), handler)
        self.ip, self.port = self.httpd.server_address

        print('server started at: ', self.ip, str(self.port))

        # Start a thread with the server -- that thread will then start one
        # more thread for each request
        server_thread = threading.Thread(target=self.httpd.serve_forever)
        # Exit the server thread when the main thread terminates
        server_thread.daemon = True
        server_thread.start()
        print("Server loop running in thread: ", server_thread.name)
示例#11
0
    def getTemporaryFile(self):
        if (self.getfilenameprefs['file_name'] == "") or (not (os.path.exists(
                self.getfilenameprefs['file_name']))):
            aux = PersistentTemporaryDirectory("GetFileName")
            self.getfilenameprefs['file_name'] = os.path.join(aux, 'Dict.txt')

        return self.getfilenameprefs['file_name']
示例#12
0
    def plugin_button(self):
        self.t = time.time()

        if len(self.gui.library_view.get_selected_ids()) < 2:
            d = error_dialog(self.gui,
                             _('Cannot Merge Epubs'),
                             _('Less than 2 books selected.'),
                             show_copy_button=False)
            d.exec_()
        else:
            db=self.gui.current_db

            logger.debug("1:%s"%(time.time()-self.t))
            self.t = time.time()

            book_list = [ self._convert_id_to_book(x, good=False) for x in self.gui.library_view.get_selected_ids() ]
            # book_ids = self.gui.library_view.get_selected_ids()

            # put all temp epubs in a temp dir for convenience of
            # deleting and not needing to keep track of temp input
            # epubs vs using library epub.
            tdir = PersistentTemporaryDirectory(prefix='epubmerge_')
            LoopProgressDialog(self.gui,
                               book_list,
                               partial(self._populate_book_from_calibre_id, db=self.gui.current_db, tdir=tdir),
                               partial(self._start_merge,tdir=tdir),
                               init_label=_("Collecting EPUBs for merger..."),
                               win_title=_("Get EPUBs for merge"),
                               status_prefix=_("EPUBs collected"))
示例#13
0
文件: input.py 项目: Coi-l/calibre
def extract_comic(path_to_comic_file):
    '''
    Un-archive the comic file.
    '''
    tdir = PersistentTemporaryDirectory(suffix='_comic_extract')
    if not isinstance(tdir, unicode):
        # Needed in case the zip file has wrongly encoded unicode file/dir
        # names
        tdir = tdir.decode(filesystem_encoding)
    extract(path_to_comic_file, tdir)
    for x in walk(tdir):
        bn = os.path.basename(x)
        nbn = bn.replace('#', '_')
        if nbn != bn:
            os.rename(x, os.path.join(os.path.dirname(x), nbn))
    return tdir
示例#14
0
    def _download(self, cookie_file, url, filename, save_loc, add_to_lib):
        dfilename = ''

        if not url:
            raise Exception(_('No file specified to download.'))
        if not save_loc and not add_to_lib:
            # Nothing to do.
            return dfilename

        if not filename:
            filename = get_download_filename(url, cookie_file)
            filename, ext = os.path.splitext(filename)
            filename = filename[:60] + ext
            filename = ascii_filename(filename)

        br = browser()
        if cookie_file:
            cj = MozillaCookieJar()
            cj.load(cookie_file)
            br.set_cookiejar(cj)
        with closing(br.open(url)) as r:
            temp_path = os.path.join(PersistentTemporaryDirectory(), filename)
            tf = open(temp_path, 'w+b')
            tf.write(r.read())
            dfilename = tf.name

        return dfilename
示例#15
0
def extract_comic(path_to_comic_file):
    '''
    Un-archive the comic file.
    '''
    tdir = PersistentTemporaryDirectory(suffix='_comic_extract')
    if not isinstance(tdir, unicode):
        # Needed in case the zip file has wrongly encoded unicode file/dir
        # names
        tdir = tdir.decode(filesystem_encoding)
    extract(path_to_comic_file, tdir)
    for x in walk(tdir):
        bn = os.path.basename(x)
        nbn = bn.replace('#', '_')
        if nbn != bn:
            os.rename(x, os.path.join(os.path.dirname(x), nbn))
    return tdir
示例#16
0
 def setUp(self):
     tdir = PersistentTemporaryDirectory()
     path_to_dictionary.cache_dir = tdir
     dictionary_name_for_locale.cache_clear()
     dictionary_for_locale.cache_clear()
     get_cache_path.cache_clear()
     is_cache_up_to_date.updated = False
示例#17
0
    def __init__(self, book_ids, db, opts, root, parent=None, pool=None):
        QObject.__init__(self, parent)
        self.db = db.new_api
        self.plugboards = self.db.pref('plugboards', {})
        self.template_functions = self.db.pref('user_template_functions', [])
        load_user_template_functions('', self.template_functions)
        self.collected_data = {}
        self.errors = defaultdict(list)
        self._book_id_data = {}
        self.all_book_ids = frozenset(book_ids)
        self.pd = ProgressDialog(_('Saving %d books...') %
                                 len(self.all_book_ids),
                                 _('Collecting metadata...'),
                                 min=0,
                                 max=0,
                                 parent=parent,
                                 icon='save.png')
        self.do_one_signal.connect(self.tick, type=Qt.QueuedConnection)
        self.do_one = self.do_one_collect
        self.ids_to_collect = iter(self.all_book_ids)
        self.tdir = PersistentTemporaryDirectory('_save_to_disk')
        self.pool = pool

        self.pd.show()
        self.root, self.opts, self.path_length = sanitize_args(root, opts)
        self.do_one_signal.emit()
        if DEBUG:
            self.start_time = time.time()
示例#18
0
    def initialize(self):
        '''
        If plugin is not a built-in, copy the plugin's .ui and .py files from
        the ZIP file to $TMPDIR.
        Tab will be dynamically generated and added to the Catalog Options dialog in
        calibre.gui2.dialogs.catalog.py:Catalog
        '''
        from calibre.customize.builtins import plugins as builtin_plugins
        from calibre.customize.ui import config
        from calibre.ptempfile import PersistentTemporaryDirectory

        if not type(self) in builtin_plugins and self.name not in config[
                'disabled_plugins']:
            files_to_copy = [
                f"{self.name.lower()}.{ext}" for ext in ["ui", "py"]
            ]
            resources = zipfile.ZipFile(self.plugin_path, 'r')

            if self.resources_path is None:
                self.resources_path = PersistentTemporaryDirectory(
                    '_plugin_resources', prefix='')

            for file in files_to_copy:
                try:
                    resources.extract(file, self.resources_path)
                except:
                    print(
                        f" customize:__init__.initialize(): {file} not found in {os.path.basename(self.plugin_path)}"
                    )
                    continue
            resources.close()
示例#19
0
    def __init__(self, opts, log, cover_data=None, toc=None):
        from calibre.gui2 import must_use_qt
        from calibre.utils.podofo import get_podofo
        must_use_qt()
        QObject.__init__(self)

        self.logger = self.log = log
        self.podofo = get_podofo()
        self.doc = self.podofo.PDFDoc()

        self.loop = QEventLoop()
        self.view = QWebView()
        self.page = Page(opts, self.log)
        self.view.setPage(self.page)
        self.view.setRenderHints(QPainter.Antialiasing
                                 | QPainter.TextAntialiasing
                                 | QPainter.SmoothPixmapTransform)
        self.view.loadFinished.connect(self._render_html,
                                       type=Qt.QueuedConnection)
        for x in (Qt.Horizontal, Qt.Vertical):
            self.view.page().mainFrame().setScrollBarPolicy(
                x, Qt.ScrollBarAlwaysOff)
        self.render_queue = []
        self.combine_queue = []
        self.tmp_path = PersistentTemporaryDirectory(u'_pdf_output_parts')

        self.opts = opts
        self.cover_data = cover_data
        self.paged_js = None
        self.toc = toc
示例#20
0
    def __init__(self, opts, log, cover_data=None):
        from calibre.gui2 import is_ok_to_use_qt
        if not is_ok_to_use_qt():
            raise Exception('Not OK to use Qt')
        QObject.__init__(self)

        self.logger = log

        self.loop = QEventLoop()
        self.view = QWebView()
        self.view.setRenderHints(QPainter.Antialiasing
                                 | QPainter.TextAntialiasing
                                 | QPainter.SmoothPixmapTransform)
        self.view.loadFinished.connect(self._render_html,
                                       type=Qt.QueuedConnection)
        for x in (Qt.Horizontal, Qt.Vertical):
            self.view.page().mainFrame().setScrollBarPolicy(
                x, Qt.ScrollBarAlwaysOff)
        self.render_queue = []
        self.combine_queue = []
        self.tmp_path = PersistentTemporaryDirectory(u'_pdf_output_parts')

        self.opts = opts
        self.cover_data = cover_data
        self.paged_js = None
示例#21
0
文件: add.py 项目: wynick27/calibre
    def __init__(self, source, single_book_per_directory=True, db=None, parent=None, callback=None, pool=None, list_of_archives=False):
        if not validate_source(source, parent):
            return
        QObject.__init__(self, parent)
        self.single_book_per_directory = single_book_per_directory
        self.ignore_opf = False
        self.list_of_archives = list_of_archives
        self.callback = callback
        self.add_formats_to_existing = prefs['add_formats_to_existing']
        self.do_one_signal.connect(self.tick, type=Qt.QueuedConnection)
        self.pool = pool
        self.pd = ProgressDialog(_('Adding books...'), _('Scanning for files...'), min=0, max=0, parent=parent, icon='add_book.png')
        self.db = getattr(db, 'new_api', None)
        if self.db is not None:
            self.dbref = weakref.ref(db)
        self.source = source
        self.tdir = PersistentTemporaryDirectory('_add_books')
        self.scan_error = None
        self.file_groups = OrderedDict()
        self.abort_scan = False
        self.duplicates = []
        self.report = []
        self.items = []
        self.added_book_ids = set()
        self.merged_books = set()
        self.added_duplicate_info = set()
        self.pd.show()

        self.scan_thread = Thread(target=self.scan, name='ScanBooks')
        self.scan_thread.daemon = True
        self.scan_thread.start()
        self.do_one = self.monitor_scan
        self.do_one_signal.emit()
        if DEBUG:
            self.start_time = time.time()
示例#22
0
 def __init__(self,
              max_downloaded: int,
              db,
              reporter: Callable = None) -> None:
     self._max_downloaded = max_downloaded
     self._dir = PersistentTemporaryDirectory()
     self._db = db
     self._reporter = reporter
示例#23
0
 def __init__(self, tasks, result_queue, spare_server=None):
     self.tasks, self.result_queue = tasks, result_queue
     self.spare_server = spare_server
     self.canceled = False
     Thread.__init__(self)
     self.daemon = True
     self.failure_details = {}
     self.tdir = PersistentTemporaryDirectory('_rm_worker')
示例#24
0
    def __init__(self, pathtoazw3, log, clone_data=None, tdir=None):
        if clone_data is not None:
            super(AZW3Container, self).__init__(None,
                                                None,
                                                log,
                                                clone_data=clone_data)
            for x in ('pathtoazw3', 'obfuscated_fonts'):
                setattr(self, x, clone_data[x])
            return

        self.pathtoazw3 = pathtoazw3
        if tdir is None:
            tdir = PersistentTemporaryDirectory('_azw3_container')
        tdir = os.path.abspath(os.path.realpath(tdir))
        self.root = tdir
        with open(pathtoazw3, 'rb') as stream:
            raw = stream.read(3)
            if raw == b'TPZ':
                raise InvalidMobi(
                    _('This is not a MOBI file. It is a Topaz file.'))

            try:
                header = MetadataHeader(stream, default_log)
            except MobiError:
                raise InvalidMobi(_('This is not a MOBI file.'))

            if header.encryption_type != 0:
                raise DRMError()

            kf8_type = header.kf8_type

            if kf8_type is None:
                raise InvalidMobi(
                    _('This MOBI file does not contain a KF8 format '
                      'book. KF8 is the new format from Amazon. calibre can '
                      'only edit MOBI files that contain KF8 books. Older '
                      'MOBI files without KF8 are not editable.'))

            if kf8_type == 'joint':
                raise InvalidMobi(
                    _('This MOBI file contains both KF8 and '
                      'older Mobi6 data. calibre can only edit MOBI files '
                      'that contain only KF8 data.'))

        try:
            opf_path, obfuscated_fonts = fork_job(
                'calibre.ebooks.oeb.polish.container',
                'do_explode',
                args=(pathtoazw3, tdir),
                no_output=True)['result']
        except WorkerError as e:
            log(e.orig_tb)
            raise InvalidMobi('Failed to explode MOBI')
        super(AZW3Container, self).__init__(tdir, opf_path, log)
        self.obfuscated_fonts = {
            x.replace(os.sep, '/')
            for x in obfuscated_fonts
        }
示例#25
0
    def __init__(self, path):
        tmpdir = PersistentTemporaryDirectory("_kobo-driver-extended")
        zf = zipfile.ZipFile(path)
        zf.extractall(tmpdir)

        self.root = os.path.abspath(tmpdir)
        self.log = logging.Log(level=logging.DEBUG if DEBUG else logging.WARN)
        self.dirtied = set([])
        self.cache = {}
        self.mime_map = {}

        print("Container:__init__:Got container path {0}".format(self.root))

        if os.path.exists(os.path.join(self.root, 'mimetype')):
            os.remove(os.path.join(self.root, 'mimetype'))

        container_path = os.path.join(self.root, 'META-INF', 'container.xml')
        if not os.path.exists(container_path):
            raise InvalidEpub('No META-INF/container.xml in epub')
        self.container = etree.fromstring(open(container_path, 'rb').read())
        opf_files = self.container.xpath((
            r'child::ocf:rootfiles/ocf:rootfile[@media-type="{0}" and @full-path]'
            .format(guess_type('a.opf')[0])),
                                         namespaces=self.namespaces)
        if not opf_files:
            raise InvalidEpub(
                'META-INF/container.xml contains no link to OPF file')
        opf_path = os.path.join(self.root,
                                *opf_files[0].get('full-path').split('/'))
        if not os.path.exists(opf_path):
            raise InvalidEpub(
                'OPF file does not exist at location pointed to by META-INF/container.xml'
            )

        # Map of relative paths with / separators to absolute
        # paths on filesystem with os separators
        self.name_map = {}
        for dirpath, dirnames, filenames in os.walk(self.root):
            for f in filenames:
                path = os.path.join(dirpath, f)
                name = os.path.relpath(path, self.root).replace(os.sep, '/')
                self.name_map[name] = path
                self.mime_map[name] = guess_type(f)[0]
                if path == opf_path:
                    self.opf_name = name
                    self.mime_map[name] = guess_type('a.opf')[0]

        opf = self.opf
        for item in opf.xpath('//opf:manifest/opf:item[@href and @media-type]',
                              namespaces=self.namespaces):
            href = unquote(item.get('href'))
            item.set("href", href)
            self.mime_map[self.href_to_name(
                href,
                os.path.dirname(self.opf_name).replace(
                    os.sep, '/'))] = item.get('media-type')
        self.set(self.opf_name, opf)
示例#26
0
文件: boss.py 项目: kmshi/calibre
    def open_book(self, path=None, edit_file=None, clear_notify_data=True):
        if self.gui.action_save.isEnabled():
            if not question_dialog(
                    self.gui, _('Unsaved changes'),
                    _('The current book has unsaved changes. If you open a new book, they will be lost'
                      ' are you sure you want to proceed?')):
                return
        if self.save_manager.has_tasks:
            return info_dialog(
                self.gui,
                _('Cannot open'),
                _('The current book is being saved, you cannot open a new book until'
                  ' the saving is completed'),
                show=True)

        if not hasattr(path, 'rpartition'):
            path = choose_files(self.gui,
                                'open-book-for-tweaking',
                                _('Choose book'),
                                [(_('Books'), [x.lower() for x in SUPPORTED])],
                                all_files=False,
                                select_only_single_file=True)
            if not path:
                return
            path = path[0]

        ext = path.rpartition('.')[-1].upper()
        if ext not in SUPPORTED:
            return error_dialog(
                self.gui,
                _('Unsupported format'),
                _('Tweaking is only supported for books in the %s formats.'
                  ' Convert your book to one of these formats first.') %
                _(' and ').join(sorted(SUPPORTED)),
                show=True)
        if not os.path.exists(path):
            return error_dialog(self.gui,
                                _('File not found'),
                                _('The file %s does not exist.') % path,
                                show=True)

        for name in tuple(editors):
            self.close_editor(name)
        self.gui.preview.clear()
        self.container_count = -1
        if self.tdir:
            shutil.rmtree(self.tdir, ignore_errors=True)
        self.tdir = PersistentTemporaryDirectory()
        self._edit_file_on_open = edit_file
        self._clear_notify_data = clear_notify_data
        self.gui.blocking_job('open_book',
                              _('Opening book, please wait...'),
                              self.book_opened,
                              get_container,
                              path,
                              tdir=self.mkdtemp())
示例#27
0
    def __init__(self, pathtoepub, log, clone_data=None, tdir=None):
        if clone_data is not None:
            super(EpubContainer, self).__init__(None,
                                                None,
                                                log,
                                                clone_data=clone_data)
            for x in ('pathtoepub', 'obfuscated_fonts'):
                setattr(self, x, clone_data[x])
            return

        self.pathtoepub = pathtoepub
        if tdir is None:
            tdir = PersistentTemporaryDirectory('_epub_container')
        tdir = os.path.abspath(os.path.realpath(tdir))
        self.root = tdir
        with open(self.pathtoepub, 'rb') as stream:
            try:
                zf = ZipFile(stream)
                zf.extractall(tdir)
            except:
                log.exception('EPUB appears to be invalid ZIP file, trying a'
                              ' more forgiving ZIP parser')
                from calibre.utils.localunzip import extractall
                stream.seek(0)
                extractall(stream)
        try:
            os.remove(join(tdir, 'mimetype'))
        except EnvironmentError:
            pass

        container_path = join(self.root, 'META-INF', 'container.xml')
        if not exists(container_path):
            raise InvalidEpub('No META-INF/container.xml in epub')
        container = etree.fromstring(open(container_path, 'rb').read())
        opf_files = container.xpath(
            (r'child::ocf:rootfiles/ocf:rootfile'
             '[@media-type="%s" and @full-path]' % guess_type('a.opf')),
            namespaces={'ocf': OCF_NS})
        if not opf_files:
            raise InvalidEpub(
                'META-INF/container.xml contains no link to OPF file')
        opf_path = os.path.join(
            self.root, *(urlunquote(opf_files[0].get('full-path')).split('/')))
        if not exists(opf_path):
            raise InvalidEpub('OPF file does not exist at location pointed to'
                              ' by META-INF/container.xml')

        super(EpubContainer, self).__init__(tdir, opf_path, log)

        self.obfuscated_fonts = {}
        if 'META-INF/encryption.xml' in self.name_path_map:
            self.process_encryption()
        self.parsed_cache['META-INF/container.xml'] = container
示例#28
0
 def run(self):
     self.tdir = PersistentTemporaryDirectory('_auto_adder')
     while self.keep_running:
         self.wake_up.wait()
         self.wake_up.clear()
         if not self.keep_running:
             break
         try:
             self.auto_add()
         except:
             import traceback
             traceback.print_exc()
示例#29
0
 def queue_files(self):
     self.tdir = PersistentTemporaryDirectory('_queue_polish')
     self.jobs = []
     if len(self.book_id_map) <= 5:
         for i, (book_id, formats) in enumerate(self.book_id_map.iteritems()):
             self.do_book(i+1, book_id, formats)
     else:
         self.queue = [(i+1, id_) for i, id_ in enumerate(self.book_id_map)]
         self.pd = ProgressDialog(_('Queueing books for polishing'),
                                  max=len(self.queue), parent=self)
         QTimer.singleShot(0, self.do_one)
         self.pd.exec_()
示例#30
0
 def download_requested(self, download_item):
     path = download_item.path()
     fname = os.path.basename(path)
     download_id = download_item.id()
     tdir = PersistentTemporaryDirectory()
     self.download_data[download_id] = download_item
     path = os.path.join(tdir, fname)
     download_item.setPath(path)
     connect_lambda(download_item.downloadProgress, self, lambda self, done, total: self.download_progress(download_id, done, total))
     connect_lambda(download_item.finished, self, lambda self: self.download_finished(download_id))
     download_item.accept()
     self.central.download_progress.add_item(download_id, fname)
示例#31
0
def get_kindlegen():
    # copy kindlegen to destination
    plugin_path = os.path.join(__file__, "..")
    plugin_zip = ZipFile(plugin_path)
    kindlegen_path = PersistentTemporaryDirectory("_kindlegen")

    if os.name == 'nt':  # Windows
        kindlegen_filename = 'kindlegen.exe'
    else:  # Linux or macOS
        kindlegen_filename = 'kindlegen'

    plugin_zip.extract(kindlegen_filename, kindlegen_path)
    return os.path.join(kindlegen_path, kindlegen_filename)