コード例 #1
0
    def _modify_epub(self, infile, metadata, container=None):
        if not infile.endswith(EPUB_EXT):
            if not infile.endswith(KEPUB_EXT):
                self.skip_renaming_files.add(metadata.uuid)
            else:
                log.info("KoboTouchExtended:_modify_epub:Skipping all "
                         "processing for calibre-converted KePub file "
                         "{0}".format(infile))
            return super(KOBOTOUCHEXTENDED,
                         self)._modify_epub(infile, metadata, container)

        log.info(
            "KoboTouchExtended:_modify_epub:Adding basic Kobo features to "
            "{0} by {1}".format(metadata.title,
                                " and ".join(metadata.authors)))

        opts = self.settings()
        skip_failed = self.skip_failed
        if skip_failed:
            log.info(
                "KoboTouchExtended:_modify_epub:Failed conversions will be skipped"
            )
        else:
            log.info(
                "KoboTouchExtended:_modify_epub:Failed conversions will raise "
                "exceptions")

        is_encumbered_book = False
        try:
            if container is None:
                container = KEPubContainer(infile, log)
            else:
                is_encumbered_book = container.is_drm_encumbered
        except DRMError:
            log.warning("KoboTouchExtended:_modify_epub:ERROR: ePub is "
                        "DRM-encumbered, not modifying")
            is_encumbered_book = True

        if is_encumbered_book:
            self.skip_renaming_files.add(metadata.uuid)
            if self.upload_encumbered:
                return super(KOBOTOUCHEXTENDED,
                             self)._modify_epub(infile, metadata, container)
            else:
                return False

        try:
            # Add the conversion info file
            calibre_details_file = self.normalize_path(
                os.path.join(self._main_prefix, "driveinfo.calibre"))
            log.debug("KoboTouchExtended:_modify_epub:Calibre details file :: "
                      "{0}".format(calibre_details_file))
            o = {}
            if os.path.isfile(calibre_details_file):
                with open(calibre_details_file, "rb") as f:
                    o = json.loads(f.read())
                for prop in (
                        "device_store_uuid",
                        "prefix",
                        "last_library_uuid",
                        "location_code",
                ):
                    del o[prop]
            else:
                log.warning(
                    "KoboTouchExtended:_modify_file:Calibre details file does "
                    "not exist!")
            o["kobotouchextended_version"] = ".".join(
                [str(n) for n in self.version])
            o["kobotouchextended_options"] = str(opts.extra_customization)
            o["kobotouchextended_currenttime"] = datetime.utcnow().ctime()
            kte_data_file = self.temporary_file("_KoboTouchExtendedDriverInfo")
            log.debug("KoboTouchExtended:_modify_epub:Driver data file :: {0}".
                      format(kte_data_file.name))
            kte_data_file.write(json.dumps(o).encode("UTF-8"))
            kte_data_file.close()
            container.copy_file_to_container(kte_data_file.name,
                                             name="driverinfo.kte",
                                             mt="application/json")

            modify_epub(
                container,
                infile,
                metadata=metadata,
                opts={
                    "clean_markup": self.clean_markup,
                    "hyphenate": self.hyphenate
                    and not self.disable_hyphenation,
                    "no-hyphens": self.disable_hyphenation,
                    "smarten_punctuation": self.smarten_punctuation,
                    "extended_kepub_features": self.extra_features,
                },
            )
        except Exception as e:
            log.exception("Failed to process {0} by {1}: {2}".format(
                metadata.title,
                " and ".join(metadata.authors),
                e.message,
            ))

            if not skip_failed:
                raise

            self.skip_renaming_files.add(metadata.uuid)
            return super(KOBOTOUCHEXTENDED,
                         self)._modify_epub(infile, metadata, container)

        if not self.extra_features:
            self.skip_renaming_files.add(metadata.uuid)

        dpath = self.file_copy_dir or ""
        if dpath != "":
            dpath = os.path.expanduser(dpath).strip()
            dpath = self.create_upload_path(dpath, metadata,
                                            metadata.kte_calibre_name)
            log.info(
                "KoboTouchExtended:_modify_epub:Generated KePub file copy "
                "path: {0}".format(dpath))
            shutil.copy(infile, dpath)

        retval = super(KOBOTOUCHEXTENDED,
                       self)._modify_epub(infile, metadata, container)
        if retval:
            container.commit(outpath=infile)
        return retval
コード例 #2
0
ファイル: driver.py プロジェクト: yakushi/calibre-kobo-driver
    def _modify_epub(self, infile, metadata, container=None):
        if not infile.endswith(EPUB_EXT):
            if not infile.endswith(KEPUB_EXT):
                self.skip_renaming_files.add(metadata.uuid)
            else:
                debug_print("KoboTouchExtended:_modify_epub:Skipping all processing for calibre-converted KePub file {0}".format(infile))
            return super(KOBOTOUCHEXTENDED, self)._modify_epub(infile, metadata, container)

        debug_print("KoboTouchExtended:_modify_epub:Adding basic Kobo features to {0} by {1}".format(metadata.title, ' and '.join(metadata.authors)))
        opts = self.settings()

        skip_failed = opts.extra_customization[self.OPT_SKIP_FAILED]
        if skip_failed:
            debug_print("KoboTouchExtended:_modify_epub:Failed conversions will be skipped")
        else:
            debug_print("KoboTouchExtended:_modify_epub:Failed conversions will raise exceptions")

        if container is None:
            container = KEPubContainer(infile, default_log)

        try:
            if container.is_drm_encumbered:
                debug_print("KoboTouchExtended:_modify_epub:ERROR: ePub is DRM-encumbered, not modifying")
                self.skip_renaming_files.add(metadata.uuid)
                if opts.extra_customization[self.OPT_UPLOAD_ENCUMBERED]:
                    return super(KOBOTOUCHEXTENDED, self)._modify_epub(infile, metadata, container)
                else:
                    return False

            # Add the conversion info file
            calibre_details_file = self.normalize_path(os.path.join(self._main_prefix, 'driveinfo.calibre'))
            debug_print("KoboTouchExtended:_modify_epub:Calibre details file :: {0}".format(calibre_details_file))
            o = {}
            if os.path.isfile:
                f = open(calibre_details_file, 'rb')
                o = json.loads(f.read())
                f.close()
                for prop in ('device_store_uuid', 'prefix', 'last_library_uuid', 'location_code'):
                    del(o[prop])
            else:
                debug_print("KoboTouchExtended:_modify_file:Calibre details file does not exist!")
            o['kobotouchextended_version'] = ".".join([str(n) for n in self.version])
            o['kobotouchextended_options'] = str(opts.extra_customization)
            o['kobotouchextended_currenttime'] = datetime.utcnow().ctime()
            kte_data_file = self.temporary_file('_KoboTouchExtendedDriverInfo')
            debug_print("KoboTouchExtended:_modify_epub:Driver data file :: {0}".format(kte_data_file.name))
            kte_data_file.write(json.dumps(o))
            kte_data_file.close()
            container.copy_file_to_container(kte_data_file.name, name='driverinfo.kte', mt='application/json')

            modify_epub(container, infile, metadata=metadata, opts={
                'clean_markup': opts.extra_customization[self.OPT_CLEAN_MARKUP],
                'hyphenate': opts.extra_customization[self.OPT_HYPHENATE],
                'replace_lang': opts.extra_customization[self.OPT_REPLACE_LANG],
                'smarten_punctuation': opts.extra_customization[self.OPT_SMARTEN_PUNCTUATION],
                'extended_kepub_features': opts.extra_customization[self.OPT_EXTRA_FEATURES]
            })
        except Exception as e:
            exc_tb = sys.exc_info()[2]
            while exc_tb.tb_next and 'kobotouch_extended' in exc_tb.tb_next.tb_frame.f_code.co_filename:
                exc_tb = exc_tb.tb_next
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            if not skip_failed:
                raise InvalidEPub(metadata.title, " and ".join(metadata.authors), e.message, fname=fname, lineno=exc_tb.tb_lineno)
            else:
                self.skip_renaming_files.add(metadata.uuid)
                debug_print("Failed to process {0} by {1} with error: {2} (file: {3}, lineno: {4})".format(metadata.title, " and ".join(metadata.authors), e.message, fname, exc_tb.tb_lineno))
                return super(KOBOTOUCHEXTENDED, self)._modify_epub(infile, metadata, container)

        if not opts.extra_customization[self.OPT_EXTRA_FEATURES]:
            self.skip_renaming_files.add(metadata.uuid)

        dpath = opts.extra_customization[self.OPT_FILE_COPY_DIR]
        dpath = os.path.expanduser(dpath).strip()
        if dpath != "":
            dpath = self.create_upload_path(dpath, metadata, metadata.kte_calibre_name)
            debug_print("KoboTouchExtended:_modify_epub:Generated KePub file copy path: {0}".format(dpath))
            shutil.copy(infile, dpath)

        return super(KOBOTOUCHEXTENDED, self)._modify_epub(infile, metadata, container)
コード例 #3
0
    def _modify_epub(self, infile, metadata, container=None):
        if not infile.endswith(EPUB_EXT):
            if not infile.endswith(KEPUB_EXT):
                self.skip_renaming_files.add(metadata.uuid)
            else:
                debug_print("KoboTouchExtended:_modify_epub:Skipping all "
                            "processing for calibre-converted KePub file "
                            "{0}".format(infile))
            return super(KOBOTOUCHEXTENDED,
                         self)._modify_epub(infile, metadata, container)

        debug_print("KoboTouchExtended:_modify_epub:Adding basic Kobo "
                    "features to {0} by {1}".format(
                        metadata.title, ' and '.join(metadata.authors)))

        opts = self.settings()
        skip_failed = self.skip_failed
        if skip_failed:
            debug_print("KoboTouchExtended:_modify_epub:Failed conversions "
                        "will be skipped")
        else:
            debug_print("KoboTouchExtended:_modify_epub:Failed conversions "
                        "will raise exceptions")

        if container is None:
            container = KEPubContainer(infile, default_log)

        try:
            if container.is_drm_encumbered:
                debug_print(
                    "KoboTouchExtended:_modify_epub:ERROR: ePub is DRM-encumbered, not modifying"
                )
                self.skip_renaming_files.add(metadata.uuid)
                if self.upload_encumbered:
                    return super(KOBOTOUCHEXTENDED,
                                 self)._modify_epub(infile, metadata,
                                                    container)
                else:
                    return False

            # Add the conversion info file
            calibre_details_file = self.normalize_path(
                os.path.join(self._main_prefix, 'driveinfo.calibre'))
            debug_print(
                "KoboTouchExtended:_modify_epub:Calibre details file :: {0}".
                format(calibre_details_file))
            o = {}
            if os.path.isfile(calibre_details_file):
                f = open(calibre_details_file, 'rb')
                o = json.loads(f.read())
                f.close()
                for prop in ('device_store_uuid', 'prefix',
                             'last_library_uuid', 'location_code'):
                    del (o[prop])
            else:
                debug_print(
                    "KoboTouchExtended:_modify_file:Calibre details file does not exist!"
                )
            o['kobotouchextended_version'] = ".".join(
                [str(n) for n in self.version])
            o['kobotouchextended_options'] = str(opts.extra_customization)
            o['kobotouchextended_currenttime'] = datetime.utcnow().ctime()
            kte_data_file = self.temporary_file('_KoboTouchExtendedDriverInfo')
            debug_print(
                "KoboTouchExtended:_modify_epub:Driver data file :: {0}".
                format(kte_data_file.name))
            kte_data_file.write(json.dumps(o))
            kte_data_file.close()
            container.copy_file_to_container(kte_data_file.name,
                                             name='driverinfo.kte',
                                             mt='application/json')

            modify_epub(container,
                        infile,
                        metadata=metadata,
                        opts={
                            'clean_markup': self.clean_markup,
                            'hyphenate': self.hyphenate
                            and not self.disable_hyphenation,
                            'no-hyphens': self.disable_hyphenation,
                            'replace_lang': self.replace_lang,
                            'smarten_punctuation': self.smarten_punctuation,
                            'extended_kepub_features': self.extra_features
                        })
        except Exception as e:
            exc_tb = sys.exc_info()[2]
            while exc_tb.tb_next and 'kobotouch_extended' in exc_tb.tb_next.tb_frame.f_code.co_filename:
                exc_tb = exc_tb.tb_next
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            if not skip_failed:
                raise InvalidEPub(metadata.title,
                                  " and ".join(metadata.authors),
                                  e.message,
                                  fname=fname,
                                  lineno=exc_tb.tb_lineno)
            else:
                self.skip_renaming_files.add(metadata.uuid)
                debug_print(
                    "Failed to process {0} by {1} with error: {2} (file: {3}, lineno: {4})"
                    .format(metadata.title, " and ".join(metadata.authors),
                            e.message, fname, exc_tb.tb_lineno))
                return super(KOBOTOUCHEXTENDED,
                             self)._modify_epub(infile, metadata, container)

        if not self.extra_features:
            self.skip_renaming_files.add(metadata.uuid)

        dpath = self.file_copy_dir
        dpath = os.path.expanduser(dpath).strip()
        if dpath != "":
            dpath = self.create_upload_path(dpath, metadata,
                                            metadata.kte_calibre_name)
            debug_print(
                "KoboTouchExtended:_modify_epub:Generated KePub file copy path: {0}"
                .format(dpath))
            shutil.copy(infile, dpath)

        retval = super(KOBOTOUCHEXTENDED,
                       self)._modify_epub(infile, metadata, container)
        if retval:
            container.commit(outpath=infile)
        return retval
コード例 #4
0
ファイル: driver.py プロジェクト: jgoguen/calibre-kobo-driver
    def _modify_epub(self, infile, metadata, container=None):
        if not infile.endswith(EPUB_EXT):
            if not infile.endswith(KEPUB_EXT):
                self.skip_renaming_files.add(metadata.uuid)
            else:
                default_log(
                    "KoboTouchExtended:_modify_epub:Skipping all "
                    "processing for calibre-converted KePub file "
                    "{0}".format(infile)
                )
            return super(KOBOTOUCHEXTENDED, self)._modify_epub(
                infile, metadata, container
            )

        default_log(
            "KoboTouchExtended:_modify_epub:Adding basic Kobo features to "
            "{0} by {1}".format(metadata.title, " and ".join(metadata.authors))
        )

        opts = self.settings()
        skip_failed = self.skip_failed
        if skip_failed:
            default_log(
                "KoboTouchExtended:_modify_epub:Failed conversions will be " "skipped"
            )
        else:
            default_log(
                "KoboTouchExtended:_modify_epub:Failed conversions will raise "
                "exceptions"
            )

        is_encumbered_book = False
        try:
            if container is None:
                container = KEPubContainer(infile, default_log)
            else:
                is_encumbered_book = container.is_drm_encumbered
        except DRMError:
            default_log(
                "KoboTouchExtended:_modify_epub:ERROR: ePub is "
                "DRM-encumbered, not modifying"
            )
            is_encumbered_book = True

        if is_encumbered_book:
            self.skip_renaming_files.add(metadata.uuid)
            if self.upload_encumbered:
                return super(KOBOTOUCHEXTENDED, self)._modify_epub(
                    infile, metadata, container
                )
            else:
                return False

        try:
            # Add the conversion info file
            calibre_details_file = self.normalize_path(
                os.path.join(self._main_prefix, "driveinfo.calibre")
            )
            default_log(
                "KoboTouchExtended:_modify_epub:Calibre details file :: "
                "{0}".format(calibre_details_file)
            )
            o = {}
            if os.path.isfile(calibre_details_file):
                with open(calibre_details_file, "rb") as f:
                    o = json.loads(f.read())
                for prop in (
                    "device_store_uuid",
                    "prefix",
                    "last_library_uuid",
                    "location_code",
                ):
                    del o[prop]
            else:
                default_log(
                    "KoboTouchExtended:_modify_file:Calibre details file does "
                    "not exist!"
                )
            o["kobotouchextended_version"] = ".".join([str(n) for n in self.version])
            o["kobotouchextended_options"] = str(opts.extra_customization)
            o["kobotouchextended_currenttime"] = datetime.utcnow().ctime()
            kte_data_file = self.temporary_file("_KoboTouchExtendedDriverInfo")
            default_log(
                "KoboTouchExtended:_modify_epub:Driver data file :: {0}".format(
                    kte_data_file.name
                )
            )
            kte_data_file.write(json.dumps(o))
            kte_data_file.close()
            container.copy_file_to_container(
                kte_data_file.name, name="driverinfo.kte", mt="application/json"
            )

            modify_epub(
                container,
                infile,
                metadata=metadata,
                opts={
                    "clean_markup": self.clean_markup,
                    "hyphenate": self.hyphenate and not self.disable_hyphenation,
                    "no-hyphens": self.disable_hyphenation,
                    "smarten_punctuation": self.smarten_punctuation,
                    "extended_kepub_features": self.extra_features,
                },
            )
        except Exception as e:
            exc_tb = sys.exc_info()[2]
            while (
                exc_tb.tb_next
                and "kobotouch_extended" in exc_tb.tb_next.tb_frame.f_code.co_filename
            ):
                exc_tb = exc_tb.tb_next
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            if not skip_failed:
                raise InvalidEPub(
                    metadata.title,
                    " and ".join(metadata.authors),
                    e.message,
                    fname=fname,
                    lineno=exc_tb.tb_lineno,
                )
            else:
                self.skip_renaming_files.add(metadata.uuid)
                default_log(
                    "Failed to process {0} by {1} with error: {2} (file: {3}, "
                    "lineno: {4})".format(
                        metadata.title,
                        " and ".join(metadata.authors),
                        e.message,
                        fname,
                        exc_tb.tb_lineno,
                    )
                )
                return super(KOBOTOUCHEXTENDED, self)._modify_epub(
                    infile, metadata, container
                )

        if not self.extra_features:
            self.skip_renaming_files.add(metadata.uuid)

        dpath = self.file_copy_dir
        dpath = os.path.expanduser(dpath).strip()
        if dpath != "":
            dpath = self.create_upload_path(dpath, metadata, metadata.kte_calibre_name)
            default_log(
                "KoboTouchExtended:_modify_epub:Generated KePub file copy "
                "path: {0}".format(dpath)
            )
            shutil.copy(infile, dpath)

        retval = super(KOBOTOUCHEXTENDED, self)._modify_epub(
            infile, metadata, container
        )
        if retval:
            container.commit(outpath=infile)
        return retval