From 39032f5b5efcb4ddfc2f489a89952941d2c17b46 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Fri, 13 Apr 2018 09:27:48 +0530 Subject: [PATCH] Start work on tool to upgrade EPUB 2 to 3 automatically --- src/calibre/ebooks/metadata/opf_2_to_3.py | 6 ++-- src/calibre/ebooks/oeb/polish/upgrade.py | 35 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 src/calibre/ebooks/oeb/polish/upgrade.py diff --git a/src/calibre/ebooks/metadata/opf_2_to_3.py b/src/calibre/ebooks/metadata/opf_2_to_3.py index a98c231cfb..c87a5c753c 100644 --- a/src/calibre/ebooks/metadata/opf_2_to_3.py +++ b/src/calibre/ebooks/metadata/opf_2_to_3.py @@ -9,7 +9,8 @@ from lxml import etree from calibre.ebooks.metadata.opf3 import ( DC, OPF, XPath, create_rating, create_series, create_timestamp, encode_is_multiple, ensure_id, parse_date, read_prefixes, read_refines, - read_user_metadata2, refdef, remove_element, set_refines, set_user_metadata3 + read_user_metadata2, refdef, remove_element, set_last_modified, set_refines, + set_user_metadata3 ) from calibre.ebooks.metadata.utils import parse_opf, pretty_print_opf @@ -97,7 +98,7 @@ def upgrade_timestamp(root, data): except Exception: pass else: - create_timestamp(m, val) + create_timestamp(root, data.prefixes, m, val) def upgrade_date(root, data): @@ -186,6 +187,7 @@ def upgrade_metadata(root): upgrade_meta(root, data) remove_invalid_attrs_in_dc_metadata(root, data) + set_last_modified(root, data.prefixes, data.refines) pretty_print_opf(root) diff --git a/src/calibre/ebooks/oeb/polish/upgrade.py b/src/calibre/ebooks/oeb/polish/upgrade.py new file mode 100644 index 0000000000..76fa409d96 --- /dev/null +++ b/src/calibre/ebooks/oeb/polish/upgrade.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python2 +# vim:fileencoding=utf-8 +# License: GPLv3 Copyright: 2018, Kovid Goyal + +from __future__ import (absolute_import, division, print_function, + unicode_literals) + +from calibre.ebooks.metadata.opf_2_to_3 import upgrade_metadata + + +def epub_2_to_3(container, report): + upgrade_metadata(container.opf) + container.dirty(container.opf_name) + container.opf.set('version', '3.0') + + +def upgrade_book(container, report): + if container.book_type != 'epub' or container.opf_version_parsed.major >= 3: + report(_('No upgrade needed')) + return False + epub_2_to_3(container, report) + report(_('Updated EPUB from version 2 to 3')) + return True + + +if __name__ == '__main__': + from calibre.ebooks.oeb.polish.container import get_container + from calibre.utils.logging import default_log + default_log.filter_level = default_log.DEBUG + inbook = sys.argv[-1] + ebook = get_container(inbook, default_log) + if upgrade_book(ebook, print): + outbook = inbook.rpartition('.')[0] + '-upgraded.' + inbook.rpartition('.')[-1] + ebook.commit(outbook) + print('Upgraded book written to:', outbook)