From 87ca3b84847e5bd1f2418d61fc7fe4cd41fd95eb Mon Sep 17 00:00:00 2001 From: David Date: Mon, 29 Oct 2018 22:18:16 +1100 Subject: [PATCH] Use metadata source and identifier rules to generate identifiers Extend identifier from URL parsing to use metadata source plugins and the identifier rules. Each plugin needs to override the id_from_url method. --- src/calibre/ebooks/metadata/sources/base.py | 10 +++++ src/calibre/gui2/metadata/basic_widgets.py | 48 +++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/src/calibre/ebooks/metadata/sources/base.py b/src/calibre/ebooks/metadata/sources/base.py index 43413e89cd..f3ef0a7bc7 100644 --- a/src/calibre/ebooks/metadata/sources/base.py +++ b/src/calibre/ebooks/metadata/sources/base.py @@ -495,6 +495,16 @@ class Source(Plugin): that could result in a generic cover image or a not found error. ''' return None + + def id_from_url(self, url): + ''' + Parse a URL and return a tuple of the form: + (identifier_type, identifier_value). + If the URL does not match the pattern for the metadata source, + return None. + ''' + return None + def identify_results_keygen(self, title=None, authors=None, identifiers={}): diff --git a/src/calibre/gui2/metadata/basic_widgets.py b/src/calibre/gui2/metadata/basic_widgets.py index 2076e4d65e..79a996eb21 100644 --- a/src/calibre/gui2/metadata/basic_widgets.py +++ b/src/calibre/gui2/metadata/basic_widgets.py @@ -1625,6 +1625,9 @@ class IdentifiersEdit(QLineEdit, ToMetadataMixin): self.setStyleSheet(INDICATOR_SHEET % col) def paste_identifier(self): + identifier_found = self.parse_clipboard_for_identifier() + if identifier_found: + return try: prefix = gprefs['paste_isbn_prefixes'][0] except IndexError: @@ -1656,6 +1659,51 @@ class IdentifiersEdit(QLineEdit, ToMetadataMixin): vals['isbn'] = text self.current_val = vals + if not text: + return + + def parse_clipboard_for_identifier(self): + from calibre.ebooks.metadata.sources.prefs import msprefs + from calibre.utils.formatter import EvalFormatter + text = unicode(QApplication.clipboard().text()).strip() + if not text: + return False + + rules = msprefs['id_link_rules'] + if rules: + formatter = EvalFormatter() + vals = {'id' : '(?P[^/]+)'} + for key in rules.keys(): + rule = rules[key] + for name, template in rule: + try: + url_pattern = formatter.safe_format(template, vals, '', vals) + new_id = re.compile(url_pattern) + new_id = new_id.search(text).group('new_id') + if new_id: + vals = self.current_val + vals[key] = new_id + self.current_val = vals + return True + except Exception: + import traceback + traceback.format_exc() + continue + + from calibre.customize.ui import all_metadata_plugins + + for plugin in all_metadata_plugins(): + try: + identifier = plugin.id_from_url(text) + if identifier: + vals = self.current_val + vals[identifier[0]] = identifier[1] + self.current_val = vals + return True + except Exception: + pass + + return False # }}}