def migrate_previous_viewer_prefs(): new_prefs = vprefs if new_prefs['old_prefs_migrated']: return old_vprefs = JSONConfig('viewer') old_prefs = JSONConfig('viewer.py') with new_prefs: sd = new_prefs['session_data'] fs = sd.get('standalone_font_settings', {}) for k in ('serif', 'sans', 'mono'): defval = 'Liberation ' + k.capitalize() k += '_family' if old_prefs.get(k) and old_prefs[k] != defval: fs[k] = old_prefs[k] if old_prefs.get('standard_font') in ('serif', 'sans', 'mono'): fs['standard_font'] = old_prefs['standard_font'] if old_prefs.get('minimum_font_size' ) is not None and old_prefs['minimum_font_size'] != 8: fs['minimum_font_size'] = old_prefs['minimum_font_size'] sd['standalone_font_settings'] = fs ms = sd.get('standalone_misc_settings', {}) ms['remember_window_geometry'] = bool( old_prefs.get('remember_window_size', False)) ms['remember_last_read'] = bool( old_prefs.get('remember_current_page', True)) ms['save_annotations_in_ebook'] = bool( old_prefs.get('copy_bookmarks_to_file', True)) ms['singleinstance'] = bool(old_vprefs.get('singleinstance', False)) sd['standalone_misc_settings'] = ms for k in ('top', 'bottom'): v = old_prefs.get(k + '_margin') if v != 20 and v is not None: sd['margin_' + k] = v v = old_prefs.get('side_margin') if v is not None and v != 40: sd['margin_left'] = sd['margin_right'] = v // 2 if old_prefs.get('user_css'): sd['user_stylesheet'] = old_prefs['user_css'] cps = {'portrait': 0, 'landscape': 0} cp = old_prefs.get('cols_per_screen_portrait') if cp and cp > 1: cps['portrait'] = cp cl = old_prefs.get('cols_per_screen_landscape') if cl and cl > 1: cps['landscape'] = cp if cps['portrait'] or cps['landscape']: sd['columns_per_screen'] = cps if old_vprefs.get('in_paged_mode') is False: sd['read_mode'] = 'flow' new_prefs.set('session_data', sd) new_prefs.set('old_prefs_migrated', True)
def run(self): books_ids = self.get_books_ids() if books_ids: json_string = "" try: mode = zipfile.ZIP_DEFLATED except: mode = zipfile.ZIP_STORED with zipfile.ZipFile('library.json.zip', 'w', mode) as zif: with open('library.json', 'w') as file: prefs = JSONConfig('plugins/letssharebooks.conf') json_string += '{{"library_uuid": "{}",'.format(str(prefs['library_uuid'])) json_string += '"last_modified": "1383473174.624734", ' json_string += '"books" : [' for book in map(self.get_book_metadata, books_ids): json_string += "{},\n".format(book) json_string = json_string[:-2] + "]}" file.write(json_string) file.close() zif.write('library.json') zif.close() with open('library.json.zip', 'r') as file: r = requests.post("http://localhost:4321/upload_catalog", files={'uploaded_file': file}) self.debug_log.addItem(r.content) return
class MarvinManagerPlugin(InterfaceActionBase): name = 'Marvin XD' description = 'Extended Driver for Marvin' supported_platforms = ['linux', 'osx', 'windows'] author = 'Wulf C. Krueger' # #mark ~~~ plugin version ~~~ version = (1, 2, 4) # #mark ~~~ Minimum calibre version ~~~ minimum_calibre_version = (1, 29, 0) actual_plugin = 'calibre_plugins.marvin_manager.action:MarvinManagerAction' prefs = JSONConfig('plugins/Marvin XD') def is_customizable(self): return True def config_widget(self): ''' See devices.usbms.deviceconfig:DeviceConfig() ''' self.cw = None if self.actual_plugin_: from calibre_plugins.marvin_manager.config import ConfigWidget self.icon = getattr(self.actual_plugin, 'icon', None) self.opts = getattr(self.actual_plugin, 'opts', None) self.resources_path = getattr(self.actual_plugin, 'resources_path', None) self.verbose = self.prefs.get('debug_plugin', False) self.cw = ConfigWidget(self.actual_plugin_) return self.cw def save_settings(self, config_widget): config_widget.save_settings() if self.actual_plugin_: self.actual_plugin_.rebuild_menus()
def create_action(self, for_toolbar=True): self.plugin_prefs = JSONConfig( 'plugins/{0}_SpanDivEdit'.format(PLUGIN_SAFE_NAME)) self.plugin_prefs.defaults['parse_current'] = True # Create an action, this will be added to the plugins toolbar and # the plugins menu ac = QAction(get_icons('images/spandivedit_icon.png'), _('حذف تگ های اضافه'), self.gui) self.restore_prefs() if not for_toolbar: # Register a keyboard shortcut for this toolbar action. We only # register it for the action created for the menu, not the toolbar, # to avoid a double trigger self.register_shortcut(ac, 'edit-spans-divs', default_keys=('Ctrl+Shift+Alt+E', )) else: menu = QMenu() ac.setMenu(menu) checked_menu_item = menu.addAction(_('Edit current file only'), self.toggle_parse_current) checked_menu_item.setCheckable(True) checked_menu_item.setChecked(self.parse_current) menu.addSeparator() config_menu_item = menu.addAction(_('Customize'), self.show_configuration) ac.triggered.connect(self.dispatcher) return ac
def check_for_add_to_editor_toolbar(self, plugin, previously_installed): if not previously_installed: from calibre.utils.config import JSONConfig prefs = JSONConfig('newly-installed-editor-plugins') pl = set(prefs.get('newly_installed_plugins', ())) pl.add(plugin.name) prefs['newly_installed_plugins'] = sorted(pl)
def __init__(self): JSON_PATH = os.path.join( u"plugins", PLUGIN_NAME.strip().lower().replace(' ', '_') + '.json') self.dedrmprefs = JSONConfig(JSON_PATH) self.dedrmprefs.defaults['configured'] = False self.dedrmprefs.defaults['bandnkeys'] = {} self.dedrmprefs.defaults['adeptkeys'] = {} self.dedrmprefs.defaults['ereaderkeys'] = {} self.dedrmprefs.defaults['kindlekeys'] = {} self.dedrmprefs.defaults['androidkeys'] = {} self.dedrmprefs.defaults['pids'] = [] self.dedrmprefs.defaults['serials'] = [] self.dedrmprefs.defaults['adobewineprefix'] = "" self.dedrmprefs.defaults['kindlewineprefix'] = "" # initialise # we must actually set the prefs that are dictionaries and lists # to empty dictionaries and lists, otherwise we are unable to add to them # as then it just adds to the (memory only) dedrmprefs.defaults versions! if self.dedrmprefs['bandnkeys'] == {}: self.dedrmprefs['bandnkeys'] = {} if self.dedrmprefs['adeptkeys'] == {}: self.dedrmprefs['adeptkeys'] = {} if self.dedrmprefs['ereaderkeys'] == {}: self.dedrmprefs['ereaderkeys'] = {} if self.dedrmprefs['kindlekeys'] == {}: self.dedrmprefs['kindlekeys'] = {} if self.dedrmprefs['androidkeys'] == {}: self.dedrmprefs['androidkeys'] = {} if self.dedrmprefs['pids'] == []: self.dedrmprefs['pids'] = [] if self.dedrmprefs['serials'] == []: self.dedrmprefs['serials'] = []
def __init__(self, parent=None): self.loaded_ruleset = None QWidget.__init__(self, parent) self.PREFS_OBJECT = JSONConfig('style-transform-rules') l = QVBoxLayout(self) self.rules_widget = w = Rules(self) w.changed.connect(self.changed.emit) l.addWidget(w) self.h = h = QHBoxLayout() l.addLayout(h) self.export_button = b = QPushButton(_('E&xport'), self) b.setToolTip(_('Export these rules to a file')) b.clicked.connect(self.export_rules) h.addWidget(b) self.import_button = b = QPushButton(_('&Import'), self) b.setToolTip(_('Import previously exported rules')) b.clicked.connect(self.import_rules) h.addWidget(b) self.test_button = b = QPushButton(_('&Test rules'), self) b.clicked.connect(self.test_rules) h.addWidget(b) h.addStretch(10) self.save_button = b = QPushButton(_('&Save'), self) b.setToolTip(_('Save this ruleset for later re-use')) b.clicked.connect(self.save_ruleset) h.addWidget(b) self.export_button = b = QPushButton(_('&Load'), self) self.load_menu = QMenu(self) b.setMenu(self.load_menu) b.setToolTip(_('Load a previously saved ruleset')) b.clicked.connect(self.load_ruleset) h.addWidget(b) self.build_load_menu()
def add_routes(self, connect): base_href = '/browse' connect('browse', base_href, self.browse_catalog) connect('browse_catalog', base_href+'/category/{category}', self.browse_catalog) connect('browse_category_group', base_href+'/category_group/{category}/{group}', self.browse_category_group) connect('browse_matches', base_href+'/matches/{category}/{cid}', self.browse_matches) connect('browse_booklist_page', base_href+'/booklist_page', self.browse_booklist_page) connect('browse_search', base_href+'/search', self.browse_search) connect('browse_details', base_href+'/details/{id}', self.browse_details) connect('browse_book', base_href+'/book/{id}', self.browse_book) connect('browse_random', base_href+'/random', self.browse_random) connect('browse_category_icon', base_href+'/icon/{name}', self.browse_icon) self.icon_map = JSONConfig('gui').get('tags_browser_category_icons', {})
def __init__(self, *args, **kwargs): super(DJVUmaker, self).__init__(*args, **kwargs) self.prints = prints # Easer access because of Calibre load plugins instead of importing # Set default preferences for JSONConfig DEFAULT_STORE_VALUES = {} DEFAULT_STORE_VALUES['plugin_version'] = PLUGINVER DEFAULT_STORE_VALUES['postimport'] = False for item in self.REGISTERED_BACKENDS: DEFAULT_STORE_VALUES[item] = { 'flags': [], 'installed': False, 'version': None } if 'djvudigital' in self.REGISTERED_BACKENDS: DEFAULT_STORE_VALUES['use_backend'] = 'djvudigital' else: raise Exception('No djvudigital backend.') # JSONConfig is a dict-like object, # if coresponding .json file has not a specific key, it's got from .defaults self.plugin_prefs = JSONConfig(os.path.join('plugins', PLUGINNAME)) self.plugin_prefs.defaults = DEFAULT_STORE_VALUES # make sure to create plugins/djvumaker.json # self.plugin_prefs.values() doesn't use self.plugin_prefs.__getitem__() # and returns real json, not defaults if not self.plugin_prefs.values(): for key, val in DEFAULT_STORE_VALUES.iteritems(): self.plugin_prefs[key] = val
def export_config(self, base_dir, library_usage_stats): for key, relpath in self.metadata['config_dir']: f = self.start_file(key, relpath) path = os.path.join(base_dir, relpath.replace('/', os.sep)) try: with lopen(path, 'wb') as dest: shutil.copyfileobj(f, dest) except EnvironmentError: os.makedirs(os.path.dirname(path)) with lopen(path, 'wb') as dest: shutil.copyfileobj(f, dest) f.close() gpath = os.path.join(base_dir, 'global.py') try: with lopen(gpath, 'rb') as f: raw = f.read() except EnvironmentError: raw = b'' try: lpath = library_usage_stats.most_common(1)[0][0] except Exception: lpath = None c = create_global_prefs(StringConfig(raw, 'calibre wide preferences')) c.set('installation_uuid', str(uuid.uuid4())) c.set('library_path', lpath) raw = c.src if not isinstance(raw, bytes): raw = raw.encode('utf-8') with lopen(gpath, 'wb') as f: f.write(raw) gprefs = JSONConfig('gui', base_path=base_dir) gprefs['library_usage_stats'] = dict(library_usage_stats)
def __init__(self, parent=None, config_name='shortcuts/main'): QObject.__init__(self, parent) self.config = JSONConfig(config_name) self.shortcuts = OrderedDict() self.keys_map = {} self.groups = {}
def cache(self): if not hasattr(self, '_mr_cache'): from calibre.utils.config import JSONConfig self._mr_cache = JSONConfig('mobileread_get_books') self._mr_cache.file_path = os.path.join( cache_dir(), 'mobileread_get_books.json') self._mr_cache.refresh() return self._mr_cache
def __init__(self, gui, name, config=None, base_plugin=None): self.gui = gui self.name = name self.base_plugin = base_plugin if config is None: from calibre.utils.config import JSONConfig config = JSONConfig('store/stores/' + ascii_filename(self.name)) self.config = config
def reload_cache(self): if not hasattr(self, 'cache'): from calibre.utils.config import JSONConfig self.cache = JSONConfig('fonts/scanner_cache') else: self.cache.refresh() if self.cache.get('version', None) != self.CACHE_VERSION: self.cache.clear() self.cached_fonts = self.cache.get('fonts', {})
def __init__(self, database, book_id, connections): self._connections = connections book_path = database.field_for('path', book_id).replace('/', os.sep) self._prefs = JSONConfig(os.path.join(book_path, 'book_settings'), base_path=LIBRARY) self._prefs.setdefault('asin', '') self._prefs.setdefault('goodreads_url', '') self._prefs.setdefault('aliases', {}) self._prefs.setdefault('sample_xray', '') self._prefs.commit() self._title = database.field_for('title', book_id) self._author = ' & '.join(database.field_for('authors', book_id)) self._asin = self._prefs['asin'] if self._prefs['asin'] != '' else None self._goodreads_url = self._prefs['goodreads_url'] self._sample_xray = self._prefs['sample_xray'] if not self._asin: identifiers = database.field_for('identifiers', book_id) if 'mobi-asin' in identifiers.keys(): self._asin = database.field_for('identifiers', book_id)['mobi-asin'].decode('ascii') self._prefs['asin'] = self._asin else: self._asin = self.search_for_asin_on_amazon(self.title_and_author) if self._asin: metadata = database.get_metadata(book_id) identifiers = metadata.get_identifiers() identifiers['mobi-asin'] = self._asin metadata.set_identifiers(identifiers) database.set_metadata(book_id, metadata) self._prefs['asin'] = self._asin if self._goodreads_url == '': url = None if self._asin: url = self.search_for_goodreads_url(self._asin) if not url and self._title != 'Unknown' and self._author != 'Unknown': url = self.search_for_goodreads_url(self.title_and_author) if url: self._goodreads_url = url self._prefs['goodreads_url'] = self._goodreads_url if not self._asin: self._asin = self.search_for_asin_on_goodreads(self._goodreads_url) if self._asin: metadata = database.get_metadata(book_id) identifiers = metadata.get_identifiers() identifiers['mobi-asin'] = self._asin metadata.set_identifiers(identifiers) database.set_metadata(book_id, metadata) self._prefs['asin'] = self._asin self._aliases = self._prefs['aliases'] self.save()
def prefsPrep(self): from calibre.utils.config import JSONConfig plugin_prefs = JSONConfig('plugins/{0}_ChineseConversion_settings'.format(PLUGIN_SAFE_NAME)) plugin_prefs.defaults['use_html_file'] = True plugin_prefs.defaults['use_entire_book'] = True plugin_prefs.defaults['orientation'] = 0 plugin_prefs.defaults['no_optimization'] = True plugin_prefs.defaults['readium_optimization'] = False plugin_prefs.defaults['kindle_optimization'] = False return plugin_prefs
def install_new_plugins(): from calibre.utils.config import JSONConfig prefs = JSONConfig('newly-installed-editor-plugins') pl = prefs.get('newly_installed_plugins', ()) if pl: for name in pl: plugin = find_plugin(name) if plugin is not None: install_plugin(plugin) prefs['newly_installed_plugins'] = []
def prefsPrep(self): from calibre.utils.config import JSONConfig plugin_prefs = JSONConfig('plugins/{0}_SmarterPunct_settings'.format(PLUGIN_SAFE_NAME)) plugin_prefs.defaults['edu_quotes'] = True plugin_prefs.defaults['use_file'] = False plugin_prefs.defaults['file_path'] = '' plugin_prefs.defaults['dashes'] = 1 plugin_prefs.defaults['ellipses'] = True plugin_prefs.defaults['unicode'] = True return plugin_prefs
def icon_map(): global _icon_map with _icon_map_lock: if _icon_map is None: _icon_map = category_icon_map.copy() custom_icons = JSONConfig('gui').get('tags_browser_category_icons', {}) for k, v in custom_icons.iteritems(): if os.access(os.path.join(config_dir, 'tb_icons', v), os.R_OK): _icon_map[k] = '_' + quote(v) _icon_map['file_type_icons'] = { k:'mimetypes/%s.png' % v for k, v in EXT_MAP.iteritems() } return _icon_map
def prefs(self): if self._prefs is None: self._prefs = p = JSONConfig('mtp_devices') p.defaults['format_map'] = self.FORMATS p.defaults['send_to'] = ['Calibre_Companion', 'Books', 'eBooks/import', 'eBooks', 'wordplayer/calibretransfer', 'sdcard/ebooks', 'kindle'] p.defaults['send_template'] = '{title} - {authors}' p.defaults['blacklist'] = [] p.defaults['history'] = {} p.defaults['rules'] = [] p.defaults['ignored_folders'] = {} return self._prefs
def builtins_loaded(self): self.last_check_time = 0 self.version_map = {} self.cached_version_map = {} self.name_rmap = {} for key, val in self.iteritems(): prefix, name = val.__module__.rpartition('.')[0::2] if prefix == 'calibre.gui2.store.stores' and name.endswith('_plugin'): module = sys.modules[val.__module__] sv = getattr(module, 'store_version', None) if sv is not None: name = name.rpartition('_')[0] self.version_map[name] = sv self.name_rmap[name] = key self.cache_file = JSONConfig('store/plugin_cache') self.load_cache()
def __init__(self, json_path=None): if json_path is None: JSON_PATH = os.path.join( "plugins", PLUGIN_NAME.strip().lower().replace(' ', '_') + '.json') else: JSON_PATH = json_path self.dedrmprefs = JSONConfig(JSON_PATH) self.dedrmprefs.defaults['configured'] = False self.dedrmprefs.defaults['deobfuscate_fonts'] = True self.dedrmprefs.defaults['remove_watermarks'] = False self.dedrmprefs.defaults['bandnkeys'] = {} self.dedrmprefs.defaults['adeptkeys'] = {} self.dedrmprefs.defaults['ereaderkeys'] = {} self.dedrmprefs.defaults['kindlekeys'] = {} self.dedrmprefs.defaults['androidkeys'] = {} self.dedrmprefs.defaults['pids'] = [] self.dedrmprefs.defaults['serials'] = [] self.dedrmprefs.defaults['lcp_passphrases'] = [] self.dedrmprefs.defaults['adobe_pdf_passphrases'] = [] self.dedrmprefs.defaults['adobewineprefix'] = "" self.dedrmprefs.defaults['kindlewineprefix'] = "" # initialise # we must actually set the prefs that are dictionaries and lists # to empty dictionaries and lists, otherwise we are unable to add to them # as then it just adds to the (memory only) dedrmprefs.defaults versions! if self.dedrmprefs['bandnkeys'] == {}: self.dedrmprefs['bandnkeys'] = {} if self.dedrmprefs['adeptkeys'] == {}: self.dedrmprefs['adeptkeys'] = {} if self.dedrmprefs['ereaderkeys'] == {}: self.dedrmprefs['ereaderkeys'] = {} if self.dedrmprefs['kindlekeys'] == {}: self.dedrmprefs['kindlekeys'] = {} if self.dedrmprefs['androidkeys'] == {}: self.dedrmprefs['androidkeys'] = {} if self.dedrmprefs['pids'] == []: self.dedrmprefs['pids'] = [] if self.dedrmprefs['serials'] == []: self.dedrmprefs['serials'] = [] if self.dedrmprefs['lcp_passphrases'] == []: self.dedrmprefs['lcp_passphrases'] = [] if self.dedrmprefs['adobe_pdf_passphrases'] == []: self.dedrmprefs['adobe_pdf_passphrases'] = []
def startImport(self): from pprint import pprint plugin_prefs = JSONConfig('plugins/Mendeley') job = ThreadedJob('Mendeley_importer', 'Importing Mendeley Documents', func=do_work, args=(), kwargs={}, callback=self.importer_finished) self.gui.job_manager.run_threaded_job(job) self.startImportButton.setEnabled(False) self.helpl.setText( 'Importing documents. You can close the dialog. See the progress in the Calibre jobs (see the Status Bar).' )
def create_action(self, for_toolbar=True): self.plugin_prefs = JSONConfig('plugins/{0}_CSScm2em'.format(PLUGIN_SAFE_NAME)) self.plugin_prefs.defaults['parse_current'] = True # Create an action, this will be added to the plugins toolbar and # the plugins menu ac = QAction(get_icon('images/css_icon.png'), _('Convert CSS cm to em'), self.gui) self.restore_prefs() if not for_toolbar: # Register a keyboard shortcut for this toolbar action. We only # register it for the action created for the menu, not the toolbar, # to avoid a double trigger self.register_shortcut(ac, 'css-cms-to-ems', default_keys=('Ctrl+Shift+Alt+C',)) menu = QMenu() ac.setMenu(menu) checked_menu_item = menu.addAction(_('Convert current CSS file only'), self.toggle_parse_current) checked_menu_item.setCheckable(True) checked_menu_item.setChecked(self.parse_current) ac.triggered.connect(self.dispatcher) return ac
def __init__(self, current_library=""): import calibre_plugins.getfilename.config as cfg PLUGIN_NAME = u"GetFileName" JSON_PATH = os.path.join( u"plugins", PLUGIN_NAME.strip().lower().replace(' ', '_') + '.json') self.getfilenameprefs = JSONConfig(JSON_PATH) # print "Prefs: ", self.getfilenameprefs self.def_lib = {} self.def_lib['configured'] = False self.def_lib['nom_col'] = "" self.def_lib['ext_col'] = "" self.def_lib['path_col'] = "" self.def_lib['opc_name'] = "file" self.def_lib['date_col'] = "" self.def_lib[cfg.KEY_SCHEMA_VERSION] = "" self.current_library = current_library self.getfilenameprefs.defaults['nom_col'] = "" self.getfilenameprefs.defaults['ext_col'] = "" self.getfilenameprefs.defaults['path_col'] = "" self.getfilenameprefs.defaults['opc_name'] = "file" self.getfilenameprefs.defaults['date_col'] = "" self.getfilenameprefs.defaults[cfg.KEY_SCHEMA_VERSION] = "" self.getfilenameprefs.defaults['configured'] = False self.getfilenameprefs.defaults['pref_lib'] = {} self.getfilenameprefs.defaults['file_name'] = "" if 'pref_lib' not in self.getfilenameprefs: self.getfilenameprefs['pref_lib'] = {} try: del self.getfilenameprefs['procesados'] except KeyError: pass
def prefsPrep(self): from calibre.utils.config import JSONConfig plugin_prefs = JSONConfig( 'plugins/{0}_ChineseConversion_settings'.format(PLUGIN_SAFE_NAME)) plugin_prefs.defaults['input_format'] = 0 plugin_prefs.defaults['output_format'] = 0 plugin_prefs.defaults['no_conversion'] = True plugin_prefs.defaults['trad_to_simp'] = False plugin_prefs.defaults['use_html_file'] = True plugin_prefs.defaults['simp_to_trad'] = False plugin_prefs.defaults['trad_to_trad'] = False plugin_prefs.defaults['use_entire_book'] = True plugin_prefs.defaults['use_target_phrases'] = True plugin_prefs.defaults['quote_no_conversion'] = True plugin_prefs.defaults['quote_trad_to_simp'] = False plugin_prefs.defaults['quote_simp_to_trad'] = False plugin_prefs.defaults['use_smart_quotes'] = False plugin_prefs.defaults['orientation'] = 0 plugin_prefs.defaults['no_optimization'] = True plugin_prefs.defaults['readium_optimization'] = False plugin_prefs.defaults['kindle_optimization'] = False return plugin_prefs
def clean_downloaded_metadata(self, mi): """ Overridden from the calibre default so that we can stop this plugin messing with the tag casing coming from Goodreads """ series_in_title = r'\s*{0}\s*#?{1}\s*'.format(mi.series, mi.series_index) if mi.title: mi.title = re.sub(series_in_title + r'[:-]', r'', mi.title, flags=re.IGNORECASE).strip() mi.title = re.sub(r'(?:[^:-]+)[:-]' + series_in_title, r'', mi.title, flags=re.IGNORECASE).strip() mi.title = re.sub(r'\(.*?\)', r'', mi.title, flags=re.IGNORECASE).strip() mi.title = re.sub(r'\[.*?\]', r'', mi.title, flags=re.IGNORECASE).strip() mi.title = fixcase(mi.title) mi.title = mi.title.strip() if mi.authors: mi.authors = fixauthors(mi.authors) try: plugin_prefs = JSONConfig('plugins/Quality Check') from calibre_plugins.quality_check.config import STORE_OPTIONS, KEY_AUTHOR_INITIALS_MODE, AUTHOR_INITIALS_MODES initials_mode = plugin_prefs[STORE_OPTIONS].get( KEY_AUTHOR_INITIALS_MODE, u'A. B.') from calibre_plugins.quality_check.helpers import get_formatted_author_initials mi.authors = [ get_formatted_author_initials(initials_mode, author) for author in mi.authors ] except: pass
def __init__(self, gui, icon, do_user_config): QDialog.__init__(self, gui) self.gui = gui self.do_user_config = do_user_config self.db = gui.current_db self.layout = QVBoxLayout() self.setLayout(self.layout) self.setWindowTitle('Mendeley Plugin') self.setWindowIcon(icon) self.setMinimumWidth(500) self.resize(self.sizeHint()) self.startImportButton = QPushButton( 'Import documents from \'calibre\' Mendeley folder.') self.startImportButton.clicked.connect(self.startImport) self.layout.addWidget(self.startImportButton) self.helpl = QLabel('\n') self.helpl.setWordWrap(True) self.layout.addWidget(self.helpl) self.layout.setSizeConstraint(QLayout.SetFixedSize) plugin_prefs = JSONConfig('plugins/Mendeley') if not plugin_prefs.has_key('account') or not plugin_prefs.has_key( 'verification'): from calibre_plugins.mendeley_to_calibre import config as ConfigWidget dialog = ConfigWidget.ConfigWidget('plugin_option') dialog.add_ok_cancel_buttons() dialog.exec_() self.showErrorSignal.connect(self.show_dialog, type=Qt.QueuedConnection)
KEY_SORT: [], KEY_APPLY_VIRTLIB: False, KEY_VIRTLIB: '', KEY_APPLY_RESTRICTION: False, KEY_RESTRICTION: '', KEY_APPLY_SEARCH: False, KEY_SEARCH: '', KEY_APPLY_PIN_COLUMNS: False, KEY_PIN_COLUMNS: [], KEY_PIN_SPLITTER_STATE: None, KEY_JUMP_TO_TOP: False, } # This is where preferences for this plugin used to be stored prior to 1.3 plugin_prefs = JSONConfig('plugins/View Manager') def migrate_json_config_if_required(): # As of version 1.3 we no longer require a local json file as # all configuration is stored in the database json_path = plugin_prefs.file_path if not os.path.exists(json_path): return # We have to wait for all libraries to have been migrated into # the database. Once they have, we can nuke the json file if 'libraries' not in plugin_prefs: try: os.remove(json_path) except: pass
def run(self, path_to_output, opts, db, notification=DummyReporter()): from calibre.library.catalogs.epub_mobi_builder import CatalogBuilder from calibre.utils.logging import default_log as log # If preset specified from the cli, insert stored options from JSON file if hasattr(opts, 'preset') and opts.preset: available_presets = JSONConfig("catalog_presets") if not opts.preset in available_presets: if available_presets: print(_('Error: Preset "%s" not found.' % opts.preset)) print( _('Stored presets: %s' % ', '.join( [p for p in sorted(available_presets.keys())]))) else: print(_('Error: No stored presets.')) return 1 # Copy the relevant preset values to the opts object for item in available_presets[opts.preset]: if not item in [ 'exclusion_rules_tw', 'format', 'prefix_rules_tw' ]: setattr(opts, item, available_presets[opts.preset][item]) # Provide an unconnected device opts.connected_device = { 'is_device_connected': False, 'kind': None, 'name': None, 'save_template': None, 'serial': None, 'storage': None, } # Convert prefix_rules and exclusion_rules from JSON lists to tuples prs = [] for rule in opts.prefix_rules: prs.append(tuple(rule)) opts.prefix_rules = tuple(prs) ers = [] for rule in opts.exclusion_rules: ers.append(tuple(rule)) opts.exclusion_rules = tuple(ers) opts.log = log opts.fmt = self.fmt = path_to_output.rpartition('.')[2] # Add local options opts.creator = '%s, %s %s, %s' % (strftime('%A'), strftime('%B'), strftime('%d').lstrip('0'), strftime('%Y')) opts.creator_sort_as = '%s %s' % ('calibre', strftime('%Y-%m-%d')) opts.connected_kindle = False # Finalize output_profile op = opts.output_profile if op is None: op = 'default' if opts.connected_device['name'] and 'kindle' in opts.connected_device[ 'name'].lower(): opts.connected_kindle = True if opts.connected_device['serial'] and \ opts.connected_device['serial'][:4] in ['B004', 'B005']: op = "kindle_dx" else: op = "kindle" opts.description_clip = 380 if op.endswith( 'dx') or 'kindle' not in op else 100 opts.author_clip = 100 if op.endswith( 'dx') or 'kindle' not in op else 60 opts.output_profile = op opts.basename = "Catalog" opts.cli_environment = not hasattr(opts, 'sync') # Hard-wired to always sort descriptions by author, with series after non-series opts.sort_descriptions_by_author = True build_log = [] build_log.append( u"%s('%s'): Generating %s %sin %s environment, locale: '%s'" % (self.name, current_library_name(), self.fmt, 'for %s ' % opts.output_profile if opts.output_profile else '', 'CLI' if opts.cli_environment else 'GUI', calibre_langcode_to_name(canonicalize_lang(get_lang()), localize=False))) # If exclude_genre is blank, assume user wants all tags as genres if opts.exclude_genre.strip() == '': #opts.exclude_genre = '\[^.\]' #build_log.append(" converting empty exclude_genre to '\[^.\]'") opts.exclude_genre = 'a^' build_log.append(" converting empty exclude_genre to 'a^'") if opts.connected_device['is_device_connected'] and \ opts.connected_device['kind'] == 'device': if opts.connected_device['serial']: build_log.append(u" connected_device: '%s' #%s%s " % \ (opts.connected_device['name'], opts.connected_device['serial'][0:4], 'x' * (len(opts.connected_device['serial']) - 4))) for storage in opts.connected_device['storage']: if storage: build_log.append(u" mount point: %s" % storage) else: build_log.append(u" connected_device: '%s'" % opts.connected_device['name']) try: for storage in opts.connected_device['storage']: if storage: build_log.append(u" mount point: %s" % storage) except: build_log.append(u" (no mount points)") else: build_log.append(u" connected_device: '%s'" % opts.connected_device['name']) opts_dict = vars(opts) if opts_dict['ids']: build_log.append(" book count: %d" % len(opts_dict['ids'])) sections_list = [] if opts.generate_authors: sections_list.append('Authors') if opts.generate_titles: sections_list.append('Titles') if opts.generate_series: sections_list.append('Series') if opts.generate_genres: sections_list.append('Genres') if opts.generate_recently_added: sections_list.append('Recently Added') if opts.generate_descriptions: sections_list.append('Descriptions') if not sections_list: if opts.cli_environment: opts.log.warn( '*** No Section switches specified, enabling all Sections ***' ) opts.generate_authors = True opts.generate_titles = True opts.generate_series = True opts.generate_genres = True opts.generate_recently_added = True opts.generate_descriptions = True sections_list = [ 'Authors', 'Titles', 'Series', 'Genres', 'Recently Added', 'Descriptions' ] else: opts.log.warn( '\n*** No enabled Sections, terminating catalog generation ***' ) return [ "No Included Sections", "No enabled Sections.\nCheck E-book options tab\n'Included sections'\n" ] if opts.fmt == 'mobi' and sections_list == ['Descriptions']: warning = _( "\n*** Adding 'By Authors' Section required for MOBI output ***" ) opts.log.warn(warning) sections_list.insert(0, 'Authors') opts.generate_authors = True opts.log(u" Sections: %s" % ', '.join(sections_list)) opts.section_list = sections_list # Limit thumb_width to 1.0" - 2.0" try: if float(opts.thumb_width) < float(self.THUMB_SMALLEST): log.warning("coercing thumb_width from '%s' to '%s'" % (opts.thumb_width, self.THUMB_SMALLEST)) opts.thumb_width = self.THUMB_SMALLEST if float(opts.thumb_width) > float(self.THUMB_LARGEST): log.warning("coercing thumb_width from '%s' to '%s'" % (opts.thumb_width, self.THUMB_LARGEST)) opts.thumb_width = self.THUMB_LARGEST opts.thumb_width = "%.2f" % float(opts.thumb_width) except: log.error("coercing thumb_width from '%s' to '%s'" % (opts.thumb_width, self.THUMB_SMALLEST)) opts.thumb_width = "1.0" # eval prefix_rules if passed from command line if type(opts.prefix_rules) is not tuple: try: opts.prefix_rules = eval(opts.prefix_rules) except: log.error("malformed --prefix-rules: %s" % opts.prefix_rules) raise for rule in opts.prefix_rules: if len(rule) != 4: log.error( "incorrect number of args for --prefix-rules: %s" % repr(rule)) # eval exclusion_rules if passed from command line if type(opts.exclusion_rules) is not tuple: try: opts.exclusion_rules = eval(opts.exclusion_rules) except: log.error("malformed --exclusion-rules: %s" % opts.exclusion_rules) raise for rule in opts.exclusion_rules: if len(rule) != 3: log.error( "incorrect number of args for --exclusion-rules: %s" % repr(rule)) # Display opts keys = sorted(opts_dict.keys()) build_log.append(" opts:") for key in keys: if key in [ 'catalog_title', 'author_clip', 'connected_kindle', 'creator', 'cross_reference_authors', 'description_clip', 'exclude_book_marker', 'exclude_genre', 'exclude_tags', 'exclusion_rules', 'fmt', 'genre_source_field', 'header_note_source_field', 'merge_comments_rule', 'output_profile', 'prefix_rules', 'preset', 'read_book_marker', 'search_text', 'sort_by', 'sort_descriptions_by_author', 'sync', 'thumb_width', 'use_existing_cover', 'wishlist_tag' ]: build_log.append(" %s: %s" % (key, repr(opts_dict[key]))) if opts.verbose: log('\n'.join(line for line in build_log)) # Capture start_time opts.start_time = time.time() self.opts = opts if opts.verbose: log.info(" Begin catalog source generation (%s)" % str( datetime.timedelta(seconds=int(time.time() - opts.start_time)))) # Launch the Catalog builder catalog = CatalogBuilder(db, opts, self, report_progress=notification) try: catalog.build_sources() if opts.verbose: log.info(" Completed catalog source generation (%s)\n" % str( datetime.timedelta(seconds=int(time.time() - opts.start_time)))) except (AuthorSortMismatchException, EmptyCatalogException), e: log.error(" *** Terminated catalog generation: %s ***" % e)