API-Dokumentation für Erweiterungen

Definiert diverse abstrakte Basisklassen, die als Unterklassen verwendet werden können, um mächtige Erweiterungen zu erstellen. Die nützlichen Klassen sind:

Erweiterung

class calibre.customize.Plugin(plugin_path)[Quellcode]

Eine Calibre-Erweiterung. Hilfreiche Attribute sind unter anderem:

  • self.installation_type: Stores how the plugin was installed.

  • self.plugin_path: Stores path to the ZIP file that contains

    Erweiterung enthält, oder None, falls es eine integrierte Erweiterung ist

  • self.site_customization: Speichert eine eingegebene Anpassungszeichenkette

    eingegeben wurde.

Methoden die in Unterklassen überschrieben werden sollten:

Nützliche Verfahren:

supported_platforms = []

Liste von Plattformen auf denen diese Erweiterung funktioniert. Zum Beispiel: ['windows', 'osx', 'linux']

name = 'Trivial Plugin'

Der Name dieser Erweiterung. Sie müssen etwas anderes festlegen als Trivial-Erweiterung, damit es funktioniert.

version = (1, 0, 0)

Die Version dieser Erweiterung als 3-Tupel (major, minor, revision)

description = 'Macht rein gar nichts'

Eine kurze Beschreibung, was diese Erweiterung macht.

author = 'Unbekannt'

Der Autor dieser Erweiterung

priority = 1

When more than one plugin exists for a filetype, the plugins are run in order of decreasing priority. Plugins with higher priority will be run first. The highest possible priority is sys.maxsize. Default priority is 1.

minimum_calibre_version = (0, 4, 118)

Die älteste Version von Calibre, die diese Erweiterung erfordert

installation_type = None

The way this plugin is installed

can_be_disabled = True

Falls False, wird der Benutzer keine Möglichkeit haben, die Erweiterung zu deaktivieren. Bitte mit Vorsicht verwenden.

type = 'Basis'

Der Typ dieser Erweiterung. Wird benutzt, um Erweiterungen in der GUI zu kategorisieren

initialize()[Quellcode]

Called once when calibre plugins are initialized. Plugins are re-initialized every time a new plugin is added. Also note that if the plugin is run in a worker process, such as for adding books, then the plugin will be initialized for every new worker process.

Perform any plugin specific initialization here, such as extracting resources from the plugin ZIP file. The path to the ZIP file is available as self.plugin_path.

Beachten Sie, dass self.site_customization an diesem Punkt nicht verfügbar ist.

config_widget()[Quellcode]

Implement this method and save_settings() in your plugin to use a custom configuration dialog, rather then relying on the simple string based default customization.

This method, if implemented, must return a QWidget. The widget can have an optional method validate() that takes no arguments and is called immediately after the user clicks OK. Changes are applied if and only if the method returns True.

If for some reason you cannot perform the configuration at this time, return a tuple of two strings (message, details), these will be displayed as a warning dialog to the user and the process will be aborted.

save_settings(config_widget)[Quellcode]

Save the settings specified by the user with config_widget.

Parameter:

config_widget – The widget returned by config_widget().

do_user_config(parent=None)[Quellcode]

This method shows a configuration dialog for this plugin. It returns True if the user clicks OK, False otherwise. The changes are automatically applied.

load_resources(names)[Quellcode]

If this plugin comes in a ZIP file (user added plugin), this method will allow you to load resources from the ZIP file.

Zum Beispiel, um ein Bild zu laden:

pixmap = QPixmap()
pixmap.loadFromData(self.load_resources(['images/icon.png'])['images/icon.png'])
icon = QIcon(pixmap)
Parameter:

names – List of paths to resources in the ZIP file using / as separator

Rückgabe:

A dictionary of the form {name: file_contents}. Any names that were not found in the ZIP file will not be present in the dictionary.

customization_help(gui=False)[Quellcode]

Return a string giving help on how to customize this plugin. By default raise a NotImplementedError, which indicates that the plugin does not require customization.

If you re-implement this method in your subclass, the user will be asked to enter a string as customization for this plugin. The customization string will be available as self.site_customization.

Site customization could be anything, for example, the path to a needed binary on the user’s computer.

Parameter:

gui – Liefert HTML-Hilfe falls Tue, gibt ansonsten Hilfe als einfachen Text zurück.

temporary_file(suffix)[Quellcode]

Return a file-like object that is a temporary file on the file system. This file will remain available even after being closed and will only be removed on interpreter shutdown. Use the name member of the returned object to access the full path to the created temporary file.

Parameter:

suffix – Das Suffix der temporären Datei.

cli_main(args)[Quellcode]

This method is the main entry point for your plugins command line interface. It is called when the user does: calibre-debug -r „Plugin Name“. Any arguments passed are present in the args variable.

Dateityp-Erweiterungen

class calibre.customize.FileTypePlugin(plugin_path)[Quellcode]

Bases: Plugin

Eine Erweiterung, die einem bestimmten Satz von Dateitypen zugeordnet ist.

file_types = {}

Set of file types for which this plugin should be run. Use ‚*‘ for all file types. For example: {'lit', 'mobi', 'prc'}

on_import = False

Falls True, wird diese Erweiterung immer dann ausgeführt, wenn Bücher zur Datenbank hinzugefügt werden

on_postimport = False

If True, this plugin is run after books are added to the database. In this case the postimport and postadd methods of the plugin are called.

on_postconvert = False

If True, this plugin is run after a book is converted. In this case the postconvert method of the plugin is called.

on_postdelete = False

If True, this plugin is run after a book file is deleted from the database. In this case the postdelete method of the plugin is called.

on_preprocess = False

If True, this plugin is run just before a conversion

on_postprocess = False

If True, this plugin is run after conversion on the final file produced by the conversion output plugin.

type = 'Dateityp'

Der Typ dieser Erweiterung. Wird benutzt, um Erweiterungen in der GUI zu kategorisieren

run(path_to_ebook)[Quellcode]

Run the plugin. Must be implemented in subclasses. It should perform whatever modifications are required on the e-book and return the absolute path to the modified e-book. If no modifications are needed, it should return the path to the original e-book. If an error is encountered it should raise an Exception. The default implementation simply return the path to the original e-book. Note that the path to the original file (before any file type plugins are run, is available as self.original_path_to_file).

The modified e-book file should be created with the temporary_file() method.

Parameter:

path_to_ebook – Absoluter Pfad des eBooks.

Rückgabe:

Absoluter Pfad des geänderten eBooks.

postimport(book_id, book_format, db)[Quellcode]

Called post import, i.e., after the book file has been added to the database. Note that this is different from postadd() which is called when the book record is created for the first time. This method is called whenever a new file is added to a book record. It is useful for modifying the book record based on the contents of the newly added file.

Parameter:
  • book_id – Datenbankkennung des hinzugefügten Buches.

  • book_format – Der Dateityp des Buchs das hinzugefügt wurde.

  • db – Bibliotheksdatenbank.

postconvert(book_id, book_format, db)[Quellcode]

Called post conversion, i.e., after the conversion output book file has been added to the database. Note that it is run after a conversion only, not after a book is added. It is useful for modifying the book record based on the contents of the newly added file.

Parameter:
  • book_id – Datenbankkennung des hinzugefügten Buches.

  • book_format – Der Dateityp des Buchs das hinzugefügt wurde.

  • db – Bibliotheksdatenbank.

postdelete(book_id, book_format, db)[Quellcode]

Called post deletion, i.e., after the book file has been deleted from the database. Note that it is not run when a book record is deleted, only when one or more formats from the book are deleted. It is useful for modifying the book record based on the format of the deleted file.

Parameter:
  • book_id – Datenbankkennung des hinzugefügten Buches.

  • book_format – Der Dateityp des Buchs das hinzugefügt wurde.

  • db – Bibliotheksdatenbank.

postadd(book_id, fmt_map, db)[Quellcode]

Called post add, i.e. after a book has been added to the db. Note that this is different from postimport(), which is called after a single book file has been added to a book. postadd() is called only when an entire book record with possibly more than one book file has been created for the first time. This is useful if you wish to modify the book record in the database when the book is first added to calibre.

Parameter:
  • book_id – Datenbankkennung des hinzugefügten Buches.

  • fmt_map – Map of file format to path from which the file format was added. Note that this might or might not point to an actual existing file, as sometimes files are added as streams. In which case it might be a dummy value or a non-existent path.

  • db – Bibliotheksdatenbank

Metadaten-Erweiterungen

class calibre.customize.MetadataReaderPlugin(*args, **kwargs)[Quellcode]

Bases: Plugin

A plugin that implements reading metadata from a set of file types.

file_types = {}

Set of file types for which this plugin should be run. For example: set(['lit', 'mobi', 'prc'])

supported_platforms = ['windows', 'osx', 'linux']

Liste von Plattformen auf denen diese Erweiterung funktioniert. Zum Beispiel: ['windows', 'osx', 'linux']

version = (7, 21, 100)

Die Version dieser Erweiterung als 3-Tupel (major, minor, revision)

author = 'Kovid Goyal'

Der Autor dieser Erweiterung

type = 'Metadatenleser'

Der Typ dieser Erweiterung. Wird benutzt, um Erweiterungen in der GUI zu kategorisieren

get_metadata(stream, type)[Quellcode]

Return metadata for the file represented by stream (a file like object that supports reading). Raise an exception when there is an error with the input data.

Parameter:

type – The type of file. Guaranteed to be one of the entries in file_types.

Rückgabe:

A calibre.ebooks.metadata.book.Metadata object

class calibre.customize.MetadataWriterPlugin(*args, **kwargs)[Quellcode]

Bases: Plugin

A plugin that implements reading metadata from a set of file types.

file_types = {}

Set of file types for which this plugin should be run. For example: set(['lit', 'mobi', 'prc'])

supported_platforms = ['windows', 'osx', 'linux']

Liste von Plattformen auf denen diese Erweiterung funktioniert. Zum Beispiel: ['windows', 'osx', 'linux']

version = (7, 21, 100)

Die Version dieser Erweiterung als 3-Tupel (major, minor, revision)

author = 'Kovid Goyal'

Der Autor dieser Erweiterung

type = 'Metadatenschreiber'

Der Typ dieser Erweiterung. Wird benutzt, um Erweiterungen in der GUI zu kategorisieren

set_metadata(stream, mi, type)[Quellcode]

Set metadata for the file represented by stream (a file like object that supports reading). Raise an exception when there is an error with the input data.

Parameter:
  • type – The type of file. Guaranteed to be one of the entries in file_types.

  • mi – A calibre.ebooks.metadata.book.Metadata object

Katalog-Erweiterungen

class calibre.customize.CatalogPlugin(plugin_path)[Quellcode]

Bases: Plugin

Eine Erweiterung, die einen Kataloggenerator implementiert.

file_types = {}

Output file type for which this plugin should be run. For example: ‚epub‘ or ‚xml‘

type = 'Katalogerzeugung'

Der Typ dieser Erweiterung. Wird benutzt, um Erweiterungen in der GUI zu kategorisieren

cli_options = []

CLI parser options specific to this plugin, declared as namedtuple Option:

from collections import namedtuple Option = namedtuple(‚Option‘, ‚option, default, dest, help‘) cli_options = [Option(‘–catalog-title‘, default = ‚My Catalog‘, dest = ‚catalog_title‘, help = (_(‚Title of generated catalog. nDefault:‘) + „ ‚“ + ‚%default‘ + „‘“))] cli_options parsed in calibre.db.cli.cmd_catalog:option_parser()

initialize()[Quellcode]

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

run(path_to_output, opts, db, ids, notification=None)[Quellcode]

Run the plugin. Must be implemented in subclasses. It should generate the catalog in the format specified in file_types, returning the absolute path to the generated catalog file. If an error is encountered it should raise an Exception.

The generated catalog file should be created with the temporary_file() method.

Parameter:
  • path_to_output – Absoluter Pfad zur generierten Katalogdatei.

  • opts – A dictionary of keyword arguments

  • db – Ein LibraryDatabase2-Objekt

Metadata download plugins

class calibre.ebooks.metadata.sources.base.Source(*args, **kwargs)[Quellcode]

Bases: Plugin

type = 'Metadatenquelle'

Der Typ dieser Erweiterung. Wird benutzt, um Erweiterungen in der GUI zu kategorisieren

author = 'Kovid Goyal'

Der Autor dieser Erweiterung

supported_platforms = ['windows', 'osx', 'linux']

Liste von Plattformen auf denen diese Erweiterung funktioniert. Zum Beispiel: ['windows', 'osx', 'linux']

capabilities = frozenset({})

Set of capabilities supported by this plugin. Useful capabilities are: ‚identify‘, ‚cover‘

touched_fields = frozenset({})

List of metadata fields that can potentially be download by this plugin during the identify phase

has_html_comments = False

Set this to True if your plugin returns HTML formatted comments

supports_gzip_transfer_encoding = False

Setting this to True means that the browser object will indicate that it supports gzip transfer encoding. This can speedup downloads but make sure that the source actually supports gzip transfer encoding correctly first

ignore_ssl_errors = False

Set this to True to ignore HTTPS certificate errors when connecting to this source.

cached_cover_url_is_reliable = True

Cached cover URLs can sometimes be unreliable (i.e. the download could fail or the returned image could be bogus). If that is often the case with this source, set to False

options = ()

A list of Option objects. They will be used to automatically construct the configuration widget for this plugin

config_help_message = None

A string that is displayed at the top of the config widget for this plugin

can_get_multiple_covers = False

If True this source can return multiple covers for a given query

auto_trim_covers = False

If set to True covers downloaded by this plugin are automatically trimmed.

prefer_results_with_isbn = True

If set to True, and this source returns multiple results for a query, some of which have ISBNs and some of which do not, the results without ISBNs will be ignored

is_configured()[Quellcode]

Return False if your plugin needs to be configured before it can be used. For example, it might need a username/password/API key.

customization_help()[Quellcode]

Return a string giving help on how to customize this plugin. By default raise a NotImplementedError, which indicates that the plugin does not require customization.

If you re-implement this method in your subclass, the user will be asked to enter a string as customization for this plugin. The customization string will be available as self.site_customization.

Site customization could be anything, for example, the path to a needed binary on the user’s computer.

Parameter:

gui – Liefert HTML-Hilfe falls Tue, gibt ansonsten Hilfe als einfachen Text zurück.

config_widget()[Quellcode]

Implement this method and save_settings() in your plugin to use a custom configuration dialog, rather then relying on the simple string based default customization.

This method, if implemented, must return a QWidget. The widget can have an optional method validate() that takes no arguments and is called immediately after the user clicks OK. Changes are applied if and only if the method returns True.

If for some reason you cannot perform the configuration at this time, return a tuple of two strings (message, details), these will be displayed as a warning dialog to the user and the process will be aborted.

save_settings(config_widget)[Quellcode]

Save the settings specified by the user with config_widget.

Parameter:

config_widget – The widget returned by config_widget().

get_author_tokens(authors, only_first_author=True)[Quellcode]

Take a list of authors and return a list of tokens useful for an AND search query. This function tries to return tokens in first name middle names last name order, by assuming that if a comma is in the author name, the name is in lastname, other names form.

get_title_tokens(title, strip_joiners=True, strip_subtitle=False)[Quellcode]

Take a title and return a list of tokens useful for an AND search query. Excludes connectives(optionally) and punctuation.

split_jobs(jobs, num)[Quellcode]

Split a list of jobs into at most num groups, as evenly as possible

test_fields(mi)[Quellcode]

Return the first field from self.touched_fields that is null on the mi object

clean_downloaded_metadata(mi)[Quellcode]

Call this method in your plugin’s identify method to normalize metadata before putting the Metadata object into result_queue. You can of course, use a custom algorithm suited to your metadata source.

get_book_url(identifiers)[Quellcode]

Return a 3-tuple or None. The 3-tuple is of the form: (identifier_type, identifier_value, URL). The URL is the URL for the book identified by identifiers at this source. identifier_type, identifier_value specify the identifier corresponding to the URL. This URL must be browsable to by a human using a browser. It is meant to provide a clickable link for the user to easily visit the books page at this source. If no URL is found, return None. This method must be quick, and consistent, so only implement it if it is possible to construct the URL from a known scheme given identifiers.

get_book_url_name(idtype, idval, url)[Quellcode]

Return a human readable name from the return value of get_book_url().

get_book_urls(identifiers)[Quellcode]

Override this method if you would like to return multiple URLs for this book. Return a list of 3-tuples. By default this method simply calls get_book_url().

get_cached_cover_url(identifiers)[Quellcode]

Return cached cover URL for the book identified by the identifiers dictionary or None if no such URL exists.

Note that this method must only return validated URLs, i.e. not URLS that could result in a generic cover image or a not found error.

id_from_url(url)[Quellcode]

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.

identify_results_keygen(title=None, authors=None, identifiers={})[Quellcode]

Return a function that is used to generate a key that can sort Metadata objects by their relevance given a search query (title, authors, identifiers).

These keys are used to sort the results of a call to identify().

For details on the default algorithm see InternalMetadataCompareKeyGen. Re-implement this function in your plugin if the default algorithm is not suitable.

identify(log, result_queue, abort, title=None, authors=None, identifiers={}, timeout=30)[Quellcode]

Identify a book by its Title/Author/ISBN/etc.

If identifiers(s) are specified and no match is found and this metadata source does not store all related identifiers (for example, all ISBNs of a book), this method should retry with just the title and author (assuming they were specified).

If this metadata source also provides covers, the URL to the cover should be cached so that a subsequent call to the get covers API with the same ISBN/special identifier does not need to get the cover URL again. Use the caching API for this.

Every Metadata object put into result_queue by this method must have a source_relevance attribute that is an integer indicating the order in which the results were returned by the metadata source for this query. This integer will be used by compare_identify_results(). If the order is unimportant, set it to zero for every result.

Make sure that any cover/ISBN mapping information is cached before the Metadata object is put into result_queue.

Parameter:
  • log – A log object, use it to output debugging information/errors

  • result_queue – A result Queue, results should be put into it. Each result is a Metadata object

  • abort – If abort.is_set() returns True, abort further processing and return as soon as possible

  • title – Der Titel dieses Buchs, kann auch None sein

  • authors – Eine Liste von Autoren dieses Buchs, kann auch None sein

  • identifiers – A dictionary of other identifiers, most commonly {‚isbn‘:‘1234…‘}

  • timeout – Timeout in seconds, no network request should hang for longer than timeout.

Rückgabe:

None falls keine Fehler aufgetreten sind, andernfalls eine Unicode-Darstellung des Fehlers die dem Benutzer angezeigt werden kann

download_cover(log, result_queue, abort, title=None, authors=None, identifiers={}, timeout=30, get_best_cover=False)[Quellcode]

Download a cover and put it into result_queue. The parameters all have the same meaning as for identify(). Put (self, cover_data) into result_queue.

This method should use cached cover URLs for efficiency whenever possible. When cached data is not present, most plugins simply call identify and use its results.

If the parameter get_best_cover is True and this plugin can get multiple covers, it should only get the „best“ one.

class calibre.ebooks.metadata.sources.base.InternalMetadataCompareKeyGen(mi, source_plugin, title, authors, identifiers)[Quellcode]

Generate a sort key for comparison of the relevance of Metadata objects, given a search query. This is used only to compare results from the same metadata source, not across different sources.

The sort key ensures that an ascending order sort is a sort by order of decreasing relevance.

Der Algorithmus ist:

  • Prefer results that have at least one identifier the same as for the query

  • Prefer results with a cached cover URL

  • Prefer results with all available fields filled in

  • Prefer results with the same language as the current user interface language

  • Prefer results that are an exact title match to the query

  • Prefer results with longer comments (greater than 10% longer)

  • Use the relevance of the result as reported by the metadata source’s search

    engine

Conversion plugins

class calibre.customize.conversion.InputFormatPlugin(*args)[Quellcode]

Bases: Plugin

InputFormatPlugins are responsible for converting a document into HTML+OPF+CSS+etc. The results of the conversion must be encoded in UTF-8. The main action happens in convert().

type = 'Konvertierungseingabe'

Der Typ dieser Erweiterung. Wird benutzt, um Erweiterungen in der GUI zu kategorisieren

can_be_disabled = False

Falls False, wird der Benutzer keine Möglichkeit haben, die Erweiterung zu deaktivieren. Bitte mit Vorsicht verwenden.

supported_platforms = ['windows', 'osx', 'linux']

Liste von Plattformen auf denen diese Erweiterung funktioniert. Zum Beispiel: ['windows', 'osx', 'linux']

file_types = {}

Set of file types for which this plugin should be run For example: set(['azw', 'mobi', 'prc'])

is_image_collection = False

If True, this input plugin generates a collection of images, one per HTML file. This can be set dynamically, in the convert method if the input files can be both image collections and non-image collections. If you set this to True, you must implement the get_images() method that returns a list of images.

core_usage = 1

Number of CPU cores used by this plugin. A value of -1 means that it uses all available cores

for_viewer = False

If set to True, the input plugin will perform special processing to make its output suitable for viewing

output_encoding = 'utf-8'

The encoding that this input plugin creates files in. A value of None means that the encoding is undefined and must be detected individually

common_options = {<calibre.customize.conversion.OptionRecommendation object>}

Options shared by all Input format plugins. Do not override in sub-classes. Use options instead. Every option must be an instance of OptionRecommendation.

options = {}

Options to customize the behavior of this plugin. Every option must be an instance of OptionRecommendation.

recommendations = {}

A set of 3-tuples of the form (option_name, recommended_value, recommendation_level)

get_images()[Quellcode]

Return a list of absolute paths to the images, if this input plugin represents an image collection. The list of images is in the same order as the spine and the TOC.

convert(stream, options, file_ext, log, accelerators)[Quellcode]

This method must be implemented in sub-classes. It must return the path to the created OPF file or an OEBBook instance. All output should be contained in the current folder. If this plugin creates files outside the current folder they must be deleted/marked for deletion before this method returns.

Parameter:
  • stream – A file like object that contains the input file.

  • options – Options to customize the conversion process. Guaranteed to have attributes corresponding to all the options declared by this plugin. In addition, it will have a verbose attribute that takes integral values from zero upwards. Higher numbers mean be more verbose. Another useful attribute is input_profile that is an instance of calibre.customize.profiles.InputProfile.

  • file_ext – The extension (without the .) of the input file. It is guaranteed to be one of the file_types supported by this plugin.

  • log – A calibre.utils.logging.Log object. All output should use this object.

  • accelerators – A dictionary of various information that the input plugin can get easily that would speed up the subsequent stages of the conversion.

postprocess_book(oeb, opts, log)[Quellcode]

Called to allow the input plugin to perform postprocessing after the book has been parsed.

specialize(oeb, opts, log, output_fmt)[Quellcode]

Called to allow the input plugin to specialize the parsed book for a particular output format. Called after postprocess_book and before any transforms are performed on the parsed book.

gui_configuration_widget(parent, get_option_by_name, get_option_help, db, book_id=None)[Quellcode]

Called to create the widget used for configuring this plugin in the calibre GUI. The widget must be an instance of the PluginWidget class. See the builtin input plugins for examples.

class calibre.customize.conversion.OutputFormatPlugin(*args)[Quellcode]

Bases: Plugin

OutputFormatPlugins are responsible for converting an OEB document (OPF+HTML) into an output e-book.

The OEB document can be assumed to be encoded in UTF-8. The main action happens in convert().

type = 'Konvertierungsausgabe'

Der Typ dieser Erweiterung. Wird benutzt, um Erweiterungen in der GUI zu kategorisieren

can_be_disabled = False

Falls False, wird der Benutzer keine Möglichkeit haben, die Erweiterung zu deaktivieren. Bitte mit Vorsicht verwenden.

supported_platforms = ['windows', 'osx', 'linux']

Liste von Plattformen auf denen diese Erweiterung funktioniert. Zum Beispiel: ['windows', 'osx', 'linux']

file_type = None

Der Dateityp (Dateierweiterung ohne führenden Punkt), den diese Erweiterung ausgibt

common_options = {<calibre.customize.conversion.OptionRecommendation object>}

Options shared by all Input format plugins. Do not override in sub-classes. Use options instead. Every option must be an instance of OptionRecommendation.

options = {}

Options to customize the behavior of this plugin. Every option must be an instance of OptionRecommendation.

recommendations = {}

A set of 3-tuples of the form (option_name, recommended_value, recommendation_level)

property description

str(object=‘‘) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‚strict‘.

convert(oeb_book, output, input_plugin, opts, log)[Quellcode]

Render the contents of oeb_book (which is an instance of calibre.ebooks.oeb.OEBBook) to the file specified by output.

Parameter:
  • output – Either a file like object or a string. If it is a string it is the path to a folder that may or may not exist. The output plugin should write its output into that folder. If it is a file like object, the output plugin should write its output into the file.

  • input_plugin – The input plugin that was used at the beginning of the conversion pipeline.

  • opts – Conversion options. Guaranteed to have attributes corresponding to the OptionRecommendations of this plugin.

  • log – The logger. Print debug/info messages etc. using this.

specialize_options(log, opts, input_fmt)[Quellcode]

Can be used to change the values of conversion options, as used by the conversion pipeline.

specialize_css_for_output(log, opts, item, stylizer)[Quellcode]

Can be used to make changes to the CSS during the CSS flattening process.

Parameter:
  • item – The item (HTML file) being processed

  • stylizer – A Stylizer object containing the flattened styles for item. You can get the style for any element by stylizer.style(element).

gui_configuration_widget(parent, get_option_by_name, get_option_help, db, book_id=None)[Quellcode]

Called to create the widget used for configuring this plugin in the calibre GUI. The widget must be an instance of the PluginWidget class. See the builtin output plugins for examples.

Gerätetreiber

The base class for all device drivers is DevicePlugin. However, if your device exposes itself as a USBMS drive to the operating system, you should use the USBMS class instead as it implements all the logic needed to support these kinds of devices.

class calibre.devices.interface.DevicePlugin(plugin_path)[Quellcode]

Bases: Plugin

Defines the interface that should be implemented by backends that communicate with an e-book reader.

type = 'Geräteschnittstelle'

Der Typ dieser Erweiterung. Wird benutzt, um Erweiterungen in der GUI zu kategorisieren

FORMATS = ['lrf', 'rtf', 'pdf', 'txt']

Geordnete Liste unterstützter Formate

VENDOR_ID = 0

VENDOR_ID can be either an integer, a list of integers or a dictionary If it is a dictionary, it must be a dictionary of dictionaries, of the form:

{
 integer_vendor_id : { product_id : [list of BCDs], ... },
 ...
}
PRODUCT_ID = 0

An integer or a list of integers

BCD = None

BCD can be either None to not distinguish between devices based on BCD, or it can be a list of the BCD numbers of all devices supported by this driver.

THUMBNAIL_HEIGHT = 68

Höhe der Vorschaubilder auf dem Gerät

THUMBNAIL_COMPRESSION_QUALITY = 75

Compression quality for thumbnails. Set this closer to 100 to have better quality thumbnails with fewer compression artifacts. Of course, the thumbnails get larger as well.

WANTS_UPDATED_THUMBNAILS = False

Set this to True if the device supports updating cover thumbnails during sync_booklists. Setting it to true will ask device.py to refresh the cover thumbnails during book matching

CAN_SET_METADATA = ['title', 'authors', 'collections']

Whether the metadata on books can be set via the GUI.

CAN_DO_DEVICE_DB_PLUGBOARD = False

Whether the device can handle device_db metadata plugboards

path_sep = '/'

Path separator for paths to books on device

icon = 'reader.png'

Symbol für dieses Gerät

UserAnnotation

alias of Annotation

OPEN_FEEDBACK_MESSAGE = None

GUI displays this as a message if not None in the status bar. Useful if opening can take a long time

VIRTUAL_BOOK_EXTENSIONS = frozenset({})

Set of extensions that are „virtual books“ on the device and therefore cannot be viewed/saved/added to library. For example: frozenset(['kobo'])

VIRTUAL_BOOK_EXTENSION_MESSAGE = None

Message to display to user for virtual book extensions.

NUKE_COMMENTS = None

Whether to nuke comments in the copy of the book sent to the device. If not None this should be short string that the comments will be replaced by.

MANAGES_DEVICE_PRESENCE = False

If True indicates that this driver completely manages device detection, ejecting and so forth. If you set this to True, you must implement the detect_managed_devices and debug_managed_device_detection methods. A driver with this set to true is responsible for detection of devices, managing a blacklist of devices, a list of ejected devices and so forth. calibre will periodically call the detect_managed_devices() method and if it returns a detected device, calibre will call open(). open() will be called every time a device is returned even if previous calls to open() failed, therefore the driver must maintain its own blacklist of failed devices. Similarly, when ejecting, calibre will call eject() and then assuming the next call to detect_managed_devices() returns None, it will call post_yank_cleanup().

SLOW_DRIVEINFO = False

If set the True, calibre will call the get_driveinfo() method after the books lists have been loaded to get the driveinfo.

ASK_TO_ALLOW_CONNECT = False

If set to True, calibre will ask the user if they want to manage the device with calibre, the first time it is detected. If you set this to True you must implement get_device_uid() and ignore_connected_device() and get_user_blacklisted_devices() and set_user_blacklisted_devices()

user_feedback_after_callback = None

Set this to a dictionary of the form {‚title‘:title, ‚msg‘:msg, ‚det_msg‘:detailed_msg} to have calibre popup a message to the user after some callbacks are run (currently only upload_books). Be careful to not spam the user with too many messages. This variable is checked after every callback, so only set it when you really need to.

classmethod get_open_popup_message()[Quellcode]

GUI displays this as a non-modal popup. Should be an instance of OpenPopupMessage

is_usb_connected(devices_on_system, debug=False, only_presence=False)[Quellcode]

Return True, device_info if a device handled by this plugin is currently connected.

Parameter:

devices_on_system – Liste der derzeit verbundenen Geräte

detect_managed_devices(devices_on_system, force_refresh=False)[Quellcode]

Wird nur aufgerufen falls MANAGES_DEVICE_PRESENCE True ist.

Scan for devices that this driver can handle. Should return a device object if a device is found. This object will be passed to the open() method as the connected_device. If no device is found, return None. The returned object can be anything, calibre does not use it, it is only passed to open().

This method is called periodically by the GUI, so make sure it is not too resource intensive. Use a cache to avoid repeatedly scanning the system.

Parameter:
  • devices_on_system – Set of USB devices found on the system.

  • force_refresh – If True and the driver uses a cache to prevent repeated scanning, the cache must be flushed.

debug_managed_device_detection(devices_on_system, output)[Quellcode]

Wird nur aufgerufen falls MANAGES_DEVICE_PRESENCE True ist.

Should write information about the devices detected on the system to output, which is a file like object.

Gibt wahr wieder, wenn ein Gerät gefunden und erfolgreich geöffnet wurde, sonst falsch.

reset(key='-1', log_packets=False, report_progress=None, detected_device=None)[Quellcode]
Parameter:
  • key – Der Schlüssel zum Entsperren des Geräts

  • log_packets – If true the packet stream to/from the device is logged

  • report_progress – Function that is called with a % progress (number between 0 and 100) for various tasks. If it is called with -1 that means that the task does not have any progress information

  • detected_device – Device information from the device scanner

can_handle_windows(usbdevice, debug=False)[Quellcode]

Optional method to perform further checks on a device to see if this driver is capable of handling it. If it is not it should return False. This method is only called after the vendor, product ids and the bcd have matched, so it can do some relatively time intensive checks. The default implementation returns True. This method is called only on Windows. See also can_handle().

Note that for devices based on USBMS this method by default delegates to can_handle(). So you only need to override can_handle() in your subclass of USBMS.

Parameter:

usbdevice – A usbdevice as returned by calibre.devices.winusb.scan_usb_devices()

can_handle(device_info, debug=False)[Quellcode]

Unix-Version von can_handle_windows().

Parameter:

device_info – Is a tuple of (vid, pid, bcd, manufacturer, product, serial number)

open(connected_device, library_uuid)[Quellcode]

Perform any device specific initialization. Called after the device is detected but before any other functions that communicate with the device. For example: For devices that present themselves as USB Mass storage devices, this method would be responsible for mounting the device or if the device has been automounted, for finding out where it has been mounted. The method calibre.devices.usbms.device.Device.open() has an implementation of this function that should serve as a good example for USB Mass storage devices.

This method can raise an OpenFeedback exception to display a message to the user.

Parameter:
  • connected_device – The device that we are trying to open. It is a tuple of (vendor id, product id, bcd, manufacturer name, product name, device serial number). However, some devices have no serial number and on Windows only the first three fields are present, the rest are None.

  • library_uuid – The UUID of the current calibre library. Can be None if there is no library (for example when used from the command line).

eject()[Quellcode]

Un-mount / eject the device from the OS. This does not check if there are pending GUI jobs that need to communicate with the device.

NOTE: That this method may not be called on the same thread as the rest of the device methods.

post_yank_cleanup()[Quellcode]

Called if the user yanks the device without ejecting it first.

set_progress_reporter(report_progress)[Quellcode]

Set a function to report progress information.

Parameter:

report_progress – Function that is called with a % progress (number between 0 and 100) for various tasks. If it is called with -1 that means that the task does not have any progress information

get_device_information(end_session=True)[Quellcode]

Ask device for device information. See L{DeviceInfoQuery}.

Rückgabe:

(device name, device version, software version on device, MIME type) The tuple can optionally have a fifth element, which is a drive information dictionary. See usbms.driver for an example.

get_driveinfo()[Quellcode]

Return the driveinfo dictionary. Usually called from get_device_information(), but if loading the driveinfo is slow for this driver, then it should set SLOW_DRIVEINFO. In this case, this method will be called by calibre after the book lists have been loaded. Note that it is not called on the device thread, so the driver should cache the drive info in the books() method and this function should return the cached data.

card_prefix(end_session=True)[Quellcode]

Return a 2 element list of the prefix to paths on the cards. If no card is present None is set for the card’s prefix. E.G. (‚/place‘, ‚/place2‘) (None, ‚place2‘) (‚place‘, None) (None, None)

total_space(end_session=True)[Quellcode]
Gibt den kompletten Speicherplatz der auf den folgenden Einhängepunkten verfügbar ist zurück:
  1. Hauptspeicher

  2. Speicherkarte A

  3. Speicherkarte B

Rückgabe:

A 3 element list with total space in bytes of (1, 2, 3). If a particular device doesn’t have any of these locations it should return 0.

free_space(end_session=True)[Quellcode]
Gibt den freien Speicherplatz der auf den folgenden Einhängepunkten verfügbar ist zurück:
  1. Hauptspeicher

  2. Karte A

  3. Karte B

Rückgabe:

A 3 element list with free space in bytes of (1, 2, 3). If a particular device doesn’t have any of these locations it should return -1.

books(oncard=None, end_session=True)[Quellcode]

Return a list of e-books on the device.

Parameter:

oncard – If ‚carda‘ or ‚cardb‘ return a list of e-books on the specific storage card, otherwise return list of e-books in main memory of device. If a card is specified and no books are on the card return empty list.

Rückgabe:

Eine BuchListe.

upload_books(files, names, on_card=None, end_session=True, metadata=None)[Quellcode]

Upload a list of books to the device. If a file already exists on the device, it should be replaced. This method should raise a FreeSpaceError if there is not enough free space on the device. The text of the FreeSpaceError must contain the word „card“ if on_card is not None otherwise it must contain the word „memory“.

Parameter:
  • files – Eine Liste mit Pfaden

  • names – A list of file names that the books should have once uploaded to the device. len(names) == len(files)

  • metadata – If not None, it is a list of Metadata objects. The idea is to use the metadata to determine where on the device to put the book. len(metadata) == len(files). Apart from the regular cover (path to cover), there may also be a thumbnail attribute, which should be used in preference. The thumbnail attribute is of the form (width, height, cover_data as jpeg).

Rückgabe:

A list of 3-element tuples. The list is meant to be passed to add_books_to_metadata().

classmethod add_books_to_metadata(locations, metadata, booklists)[Quellcode]

Add locations to the booklists. This function must not communicate with the device.

Parameter:
  • locations – Ergebnis eines Aufrufs von L{upload_books}

  • metadata – List of Metadata objects, same as for upload_books().

  • booklists – A tuple containing the result of calls to (books(oncard=None)(), books(oncard='carda')(), :meth`books(oncard=‘cardb‘)`).

delete_books(paths, end_session=True)[Quellcode]

Bücher unter Pfaden vom Gerät löschen.

classmethod remove_books_from_metadata(paths, booklists)[Quellcode]

Remove books from the metadata list. This function must not communicate with the device.

Parameter:
  • paths – Pfade zu Büchern auf dem Gerät.

  • booklists – A tuple containing the result of calls to (books(oncard=None)(), books(oncard='carda')(), :meth`books(oncard=‘cardb‘)`).

sync_booklists(booklists, end_session=True)[Quellcode]

Metadaten auf dem Gerät aktualisieren.

Parameter:

booklists – A tuple containing the result of calls to (books(oncard=None)(), books(oncard='carda')(), :meth`books(oncard=‘cardb‘)`).

get_file(path, outfile, end_session=True)[Quellcode]

Read the file at path on the device and write it to outfile.

Parameter:

outfile – file object like sys.stdout or the result of an open() call.

classmethod config_widget()[Quellcode]

Should return a QWidget. The QWidget contains the settings for the device interface

classmethod save_settings(settings_widget)[Quellcode]

Should save settings to disk. Takes the widget created in config_widget() and saves all settings to disk.

classmethod settings()[Quellcode]

Should return an opts object. The opts object should have at least one attribute format_map which is an ordered list of formats for the device.

set_plugboards(plugboards, pb_func)[Quellcode]

provide the driver the current set of plugboards and a function to select a specific plugboard. This method is called immediately before add_books and sync_booklists.

pb_func is a callable with the following signature::

def pb_func(device_name, format, plugboards)

You give it the current device name (either the class name or DEVICE_PLUGBOARD_NAME), the format you are interested in (a ‚real‘ format or ‚device_db‘), and the plugboards (you were given those by set_plugboards, the same place you got this method).

Rückgabe:

None or a single plugboard instance.

set_driveinfo_name(location_code, name)[Quellcode]

Set the device name in the driveinfo file to ‚name‘. This setting will persist until the file is re-created or the name is changed again.

Non-disk devices should implement this method based on the location codes returned by the get_device_information() method.

prepare_addable_books(paths)[Quellcode]

Given a list of paths, returns another list of paths. These paths point to addable versions of the books.

If there is an error preparing a book, then instead of a path, the position in the returned list for that book should be a three tuple: (original_path, the exception instance, traceback)

startup()[Quellcode]

Called when calibre is starting the device. Do any initialization required. Note that multiple instances of the class can be instantiated, and thus __init__ can be called multiple times, but only one instance will have this method called. This method is called on the device thread, not the GUI thread.

shutdown()[Quellcode]

Called when calibre is shutting down, either for good or in preparation to restart. Do any cleanup required. This method is called on the device thread, not the GUI thread.

get_device_uid()[Quellcode]

Must return a unique id for the currently connected device (this is called immediately after a successful call to open()). You must implement this method if you set ASK_TO_ALLOW_CONNECT = True

ignore_connected_device(uid)[Quellcode]

Should ignore the device identified by uid (the result of a call to get_device_uid()) in the future. You must implement this method if you set ASK_TO_ALLOW_CONNECT = True. Note that this function is called immediately after open(), so if open() caches some state, the driver should reset that state.

get_user_blacklisted_devices()[Quellcode]

Return map of device uid to friendly name for all devices that the user has asked to be ignored.

set_user_blacklisted_devices(devices)[Quellcode]

Set the list of device uids that should be ignored by this driver.

specialize_global_preferences(device_prefs)[Quellcode]

Implement this method if your device wants to override a particular preference. You must ensure that all call sites that want a preference that can be overridden use device_prefs[‚something‘] instead of prefs[‚something‘]. Your method should call device_prefs.set_overrides(pref=val, pref=val, …). Currently used for: metadata management (prefs[‚manage_device_metadata‘])

set_library_info(library_name, library_uuid, field_metadata)[Quellcode]

Implement this method if you want information about the current calibre library. This method is called at startup and when the calibre library changes while connected.

is_dynamically_controllable()[Quellcode]

Called by the device manager when starting plugins. If this method returns a string, then a) it supports the device manager’s dynamic control interface, and b) that name is to be used when talking to the plugin.

This method can be called on the GUI thread. A driver that implements this method must be thread safe.

start_plugin()[Quellcode]

This method is called to start the plugin. The plugin should begin to accept device connections however it does that. If the plugin is already accepting connections, then do nothing.

This method can be called on the GUI thread. A driver that implements this method must be thread safe.

stop_plugin()[Quellcode]

This method is called to stop the plugin. The plugin should no longer accept connections, and should cleanup behind itself. It is likely that this method should call shutdown. If the plugin is already not accepting connections, then do nothing.

This method can be called on the GUI thread. A driver that implements this method must be thread safe.

get_option(opt_string, default=None)[Quellcode]

Return the value of the option indicated by opt_string. This method can be called when the plugin is not started. Return None if the option does not exist.

This method can be called on the GUI thread. A driver that implements this method must be thread safe.

set_option(opt_string, opt_value)[Quellcode]

Set the value of the option indicated by opt_string. This method can be called when the plugin is not started.

This method can be called on the GUI thread. A driver that implements this method must be thread safe.

is_running()[Quellcode]

Return True if the plugin is started, otherwise false

This method can be called on the GUI thread. A driver that implements this method must be thread safe.

synchronize_with_db(db, book_id, book_metadata, first_call)[Quellcode]

Called during book matching when a book on the device is matched with a book in calibre’s db. The method is responsible for synchronizing data from the device to calibre’s db (if needed).

The method must return a two-value tuple. The first value is a set of calibre book ids changed if calibre’s database was changed or None if the database was not changed. If the first value is an empty set then the metadata for the book on the device is updated with calibre’s metadata and given back to the device, but no GUI refresh of that book is done. This is useful when the calibre data is correct but must be sent to the device.

The second value is itself a 2-value tuple. The first value in the tuple specifies whether a book format should be sent to the device. The intent is to permit verifying that the book on the device is the same as the book in calibre. This value must be None if no book is to be sent, otherwise return the base file name on the device (a string like foobar.epub). Be sure to include the extension in the name. The device subsystem will construct a send_books job for all books with not- None returned values. Note: other than to later retrieve the extension, the name is ignored in cases where the device uses a template to generate the file name, which most do. The second value in the returned tuple indicated whether the format is future-dated. Return True if it is, otherwise return False. calibre will display a dialog to the user listing all future dated books.

Extremely important: this method is called on the GUI thread. It must be threadsafe with respect to the device manager’s thread.

book_id: the calibre id for the book in the database. book_metadata: the Metadata object for the book coming from the device. first_call: True if this is the first call during a sync, False otherwise

class calibre.devices.interface.BookList(oncard, prefix, settings)[Quellcode]

Bases: list

A list of books. Each Book object must have the fields

  1. Titel

  2. Autoren

  3. Größe (Dateigröße des Buches)

  4. datetime (a UTC time tuple)

  5. path (path on the device to the book)

  6. thumbnail (can be None) thumbnail is either a str/bytes object with the image data or it should have an attribute image_path that stores an absolute (platform native) path to the image

  7. tags (a list of strings, can be empty).

supports_collections()[Quellcode]

Return True if the device supports collections for this book list.

add_book(book, replace_metadata)[Quellcode]

Add the book to the booklist. Intent is to maintain any device-internal metadata. Return True if booklists must be sync’ed

remove_book(book)[Quellcode]

Remove a book from the booklist. Correct any device metadata at the same time

get_collections(collection_attributes)[Quellcode]

Return a dictionary of collections created from collection_attributes. Each entry in the dictionary is of the form collection name:[list of books]

The list of books is sorted by book title, except for collections created from series, in which case series_index is used.

Parameter:

collection_attributes – Eine Liste der Attribute des Buchobjektes

USB-Massenspeicher-basierte Geräte

The base class for such devices is calibre.devices.usbms.driver.USBMS. This class in turn inherits some of its functionality from its bases, documented below. A typical basic USBMS based driver looks like this:

from calibre.devices.usbms.driver import USBMS

class PDNOVEL(USBMS):
    name = 'Pandigital Novel device interface'
    gui_name = 'PD Novel'
    description = _('Communicate with the Pandigital Novel')
    author = 'Kovid Goyal'
    supported_platforms = ['windows', 'linux', 'osx']
    FORMATS = ['epub', 'pdf']

    VENDOR_ID   = [0x18d1]
    PRODUCT_ID  = [0xb004]
    BCD         = [0x224]

    THUMBNAIL_HEIGHT = 144

    EBOOK_DIR_MAIN = 'eBooks'
    SUPPORTS_SUB_DIRS = False

    def upload_cover(self, path, filename, metadata):
        coverdata = getattr(metadata, 'thumbnail', None)
        if coverdata and coverdata[2]:
            with open('%s.jpg' % os.path.join(path, filename), 'wb') as coverfile:
                coverfile.write(coverdata[2])
class calibre.devices.usbms.device.Device(plugin_path)[Quellcode]

Bases: DeviceConfig, DevicePlugin

This class provides logic common to all drivers for devices that export themselves as USB Mass Storage devices. Provides implementations for mounting/ejecting of USBMS devices on all platforms.

VENDOR_ID = 0

VENDOR_ID can be either an integer, a list of integers or a dictionary If it is a dictionary, it must be a dictionary of dictionaries, of the form:

{
 integer_vendor_id : { product_id : [list of BCDs], ... },
 ...
}
PRODUCT_ID = 0

An integer or a list of integers

BCD = None

BCD can be either None to not distinguish between devices based on BCD, or it can be a list of the BCD numbers of all devices supported by this driver.

WINDOWS_MAIN_MEM = None

String identifying the main memory of the device in the Windows PnP id strings This can be None, string, list of strings or compiled regex

WINDOWS_CARD_A_MEM = None

String identifying the first card of the device in the Windows PnP id strings This can be None, string, list of strings or compiled regex

WINDOWS_CARD_B_MEM = None

String identifying the second card of the device in the Windows PnP id strings This can be None, string, list of strings or compiled regex

OSX_MAIN_MEM_VOL_PAT = None

Used by the new driver detection to disambiguate main memory from storage cards. Should be a regular expression that matches the main memory mount point assigned by macOS

BACKLOADING_ERROR_MESSAGE = None
MAX_PATH_LEN = 250

The maximum length of paths created on the device

NEWS_IN_FOLDER = True

Put news in its own folder

reset(key='-1', log_packets=False, report_progress=None, detected_device=None)[Quellcode]
Parameter:
  • key – Der Schlüssel zum Entsperren des Geräts

  • log_packets – If true the packet stream to/from the device is logged

  • report_progress – Function that is called with a % progress (number between 0 and 100) for various tasks. If it is called with -1 that means that the task does not have any progress information

  • detected_device – Device information from the device scanner

set_progress_reporter(report_progress)[Quellcode]

Set a function to report progress information.

Parameter:

report_progress – Function that is called with a % progress (number between 0 and 100) for various tasks. If it is called with -1 that means that the task does not have any progress information

card_prefix(end_session=True)[Quellcode]

Return a 2 element list of the prefix to paths on the cards. If no card is present None is set for the card’s prefix. E.G. (‚/place‘, ‚/place2‘) (None, ‚place2‘) (‚place‘, None) (None, None)

total_space(end_session=True)[Quellcode]
Gibt den kompletten Speicherplatz der auf den folgenden Einhängepunkten verfügbar ist zurück:
  1. Hauptspeicher

  2. Speicherkarte A

  3. Speicherkarte B

Rückgabe:

A 3 element list with total space in bytes of (1, 2, 3). If a particular device doesn’t have any of these locations it should return 0.

free_space(end_session=True)[Quellcode]
Gibt den freien Speicherplatz der auf den folgenden Einhängepunkten verfügbar ist zurück:
  1. Hauptspeicher

  2. Karte A

  3. Karte B

Rückgabe:

A 3 element list with free space in bytes of (1, 2, 3). If a particular device doesn’t have any of these locations it should return -1.

windows_sort_drives(drives)[Quellcode]

Called to disambiguate main memory and storage card for devices that do not distinguish between them on the basis of WINDOWS_CARD_NAME. For example: The EB600

can_handle_windows(usbdevice, debug=False)[Quellcode]

Optional method to perform further checks on a device to see if this driver is capable of handling it. If it is not it should return False. This method is only called after the vendor, product ids and the bcd have matched, so it can do some relatively time intensive checks. The default implementation returns True. This method is called only on Windows. See also can_handle().

Note that for devices based on USBMS this method by default delegates to can_handle(). So you only need to override can_handle() in your subclass of USBMS.

Parameter:

usbdevice – A usbdevice as returned by calibre.devices.winusb.scan_usb_devices()

open(connected_device, library_uuid)[Quellcode]

Perform any device specific initialization. Called after the device is detected but before any other functions that communicate with the device. For example: For devices that present themselves as USB Mass storage devices, this method would be responsible for mounting the device or if the device has been automounted, for finding out where it has been mounted. The method calibre.devices.usbms.device.Device.open() has an implementation of this function that should serve as a good example for USB Mass storage devices.

This method can raise an OpenFeedback exception to display a message to the user.

Parameter:
  • connected_device – The device that we are trying to open. It is a tuple of (vendor id, product id, bcd, manufacturer name, product name, device serial number). However, some devices have no serial number and on Windows only the first three fields are present, the rest are None.

  • library_uuid – The UUID of the current calibre library. Can be None if there is no library (for example when used from the command line).

eject()[Quellcode]

Un-mount / eject the device from the OS. This does not check if there are pending GUI jobs that need to communicate with the device.

NOTE: That this method may not be called on the same thread as the rest of the device methods.

post_yank_cleanup()[Quellcode]

Called if the user yanks the device without ejecting it first.

sanitize_callback(path)[Quellcode]

Callback to allow individual device drivers to override the path sanitization used by create_upload_path().

filename_callback(default, mi)[Quellcode]

Callback to allow drivers to change the default file name set by create_upload_path().

sanitize_path_components(components)[Quellcode]

Perform any device specific sanitization on the path components for files to be uploaded to the device

get_annotations(path_map)[Quellcode]

Resolve path_map to annotation_map of files found on the device

add_annotation_to_library(db, db_id, annotation)[Quellcode]

Add an annotation to the calibre library

class calibre.devices.usbms.cli.CLI[Quellcode]
class calibre.devices.usbms.driver.USBMS(plugin_path)[Quellcode]

Bases: CLI, Device

The base class for all USBMS devices. Implements the logic for sending/getting/updating metadata/caching metadata/etc.

description = 'Kommunikation mit einem eBook-Reader.'

Eine kurze Beschreibung, was diese Erweiterung macht.

author = 'John Schember'

Der Autor dieser Erweiterung

supported_platforms = ['windows', 'osx', 'linux']

Liste von Plattformen auf denen diese Erweiterung funktioniert. Zum Beispiel: ['windows', 'osx', 'linux']

booklist_class

alias of BookList

book_class

alias of Book

FORMATS = []

Geordnete Liste unterstützter Formate

CAN_SET_METADATA = []

Whether the metadata on books can be set via the GUI.

get_device_information(end_session=True)[Quellcode]

Ask device for device information. See L{DeviceInfoQuery}.

Rückgabe:

(device name, device version, software version on device, MIME type) The tuple can optionally have a fifth element, which is a drive information dictionary. See usbms.driver for an example.

set_driveinfo_name(location_code, name)[Quellcode]

Set the device name in the driveinfo file to ‚name‘. This setting will persist until the file is re-created or the name is changed again.

Non-disk devices should implement this method based on the location codes returned by the get_device_information() method.

books(oncard=None, end_session=True)[Quellcode]

Return a list of e-books on the device.

Parameter:

oncard – If ‚carda‘ or ‚cardb‘ return a list of e-books on the specific storage card, otherwise return list of e-books in main memory of device. If a card is specified and no books are on the card return empty list.

Rückgabe:

Eine BuchListe.

upload_books(files, names, on_card=None, end_session=True, metadata=None)[Quellcode]

Upload a list of books to the device. If a file already exists on the device, it should be replaced. This method should raise a FreeSpaceError if there is not enough free space on the device. The text of the FreeSpaceError must contain the word „card“ if on_card is not None otherwise it must contain the word „memory“.

Parameter:
  • files – Eine Liste mit Pfaden

  • names – A list of file names that the books should have once uploaded to the device. len(names) == len(files)

  • metadata – If not None, it is a list of Metadata objects. The idea is to use the metadata to determine where on the device to put the book. len(metadata) == len(files). Apart from the regular cover (path to cover), there may also be a thumbnail attribute, which should be used in preference. The thumbnail attribute is of the form (width, height, cover_data as jpeg).

Rückgabe:

A list of 3-element tuples. The list is meant to be passed to add_books_to_metadata().

upload_cover(path, filename, metadata, filepath)[Quellcode]

Upload book cover to the device. Default implementation does nothing.

Parameter:
  • path – The full path to the folder where the associated book is located.

  • filename – Der Name der Buchdatei ohne die Endung.

  • metadata – metadata belonging to the book. Use metadata.thumbnail for cover

  • filepath – Der vollständige Pfad zur eBook-Datei

add_books_to_metadata(locations, metadata, booklists)[Quellcode]

Add locations to the booklists. This function must not communicate with the device.

Parameter:
  • locations – Ergebnis eines Aufrufs von L{upload_books}

  • metadata – List of Metadata objects, same as for upload_books().

  • booklists – A tuple containing the result of calls to (books(oncard=None)(), books(oncard='carda')(), :meth`books(oncard=‘cardb‘)`).

delete_books(paths, end_session=True)[Quellcode]

Bücher unter Pfaden vom Gerät löschen.

remove_books_from_metadata(paths, booklists)[Quellcode]

Remove books from the metadata list. This function must not communicate with the device.

Parameter:
  • paths – Pfade zu Büchern auf dem Gerät.

  • booklists – A tuple containing the result of calls to (books(oncard=None)(), books(oncard='carda')(), :meth`books(oncard=‘cardb‘)`).

sync_booklists(booklists, end_session=True)[Quellcode]

Metadaten auf dem Gerät aktualisieren.

Parameter:

booklists – A tuple containing the result of calls to (books(oncard=None)(), books(oncard='carda')(), :meth`books(oncard=‘cardb‘)`).

classmethod normalize_path(path)[Quellcode]

Return path with platform native path separators

User interface actions

If you are adding your own plugin in a ZIP file, you should subclass both InterfaceActionBase and InterfaceAction. The load_actual_plugin() method of your InterfaceActionBase subclass must return an instantiated object of your InterfaceBase subclass.

class calibre.gui2.actions.InterfaceAction(parent, site_customization)[Quellcode]

Bases: QObject

A plugin representing an „action“ that can be taken in the graphical user interface. All the items in the toolbar and context menus are implemented by these plugins.

Note that this class is the base class for these plugins, however, to integrate the plugin with calibre’s plugin system, you have to make a wrapper class that references the actual plugin. See the calibre.customize.builtins module for examples.

If two InterfaceAction objects have the same name, the one with higher priority takes precedence.

Sub-classes should implement the genesis(), library_changed(), location_selected(), shutting_down(), initialization_complete() and tag_browser_context_action() methods.

Once initialized, this plugin has access to the main calibre GUI via the gui member. You can access other plugins by name, for example:

self.gui.iactions['Save To Disk']

To access the actual plugin, use the interface_action_base_plugin attribute, this attribute only becomes available after the plugin has been initialized. Useful if you want to use methods from the plugin class like do_user_config().

The QAction specified by action_spec is automatically create and made available as self.qaction.

name = 'Implement me'

The plugin name. If two plugins with the same name are present, the one with higher priority takes precedence.

priority = 1

The plugin priority. If two plugins with the same name are present, the one with higher priority takes precedence.

popup_type = 1

The menu popup type for when this plugin is added to a toolbar

auto_repeat = False

Whether this action should be auto repeated when its shortcut key is held down.

action_spec = ('text', 'icon', None, None)

Of the form: (text, icon_path, tooltip, keyboard shortcut). icon, tooltip and keyboard shortcut can be None. keyboard shortcut must be either a string, None or tuple of shortcuts. If None, a keyboard shortcut corresponding to the action is not registered. If you pass an empty tuple, then the shortcut is registered with no default key binding.

action_shortcut_name = None

If not None, used for the name displayed to the user when customizing the keyboard shortcuts for the above action spec instead of action_spec[0]

action_add_menu = False

If True, a menu is automatically created and added to self.qaction

action_menu_clone_qaction = False

If True, a clone of self.qaction is added to the menu of self.qaction If you want the text of this action to be different from that of self.qaction, set this variable to the new text

dont_add_to = frozenset({})

Set of locations to which this action must not be added. See all_locations for a list of possible locations

dont_remove_from = frozenset({})

Set of locations from which this action must not be removed. See all_locations for a list of possible locations

action_type = 'global'

Type of action ‚current‘ means acts on the current view ‚global‘ means an action that does not act on the current view, but rather on calibre as a whole

accepts_drops = False

If True, then this InterfaceAction will have the opportunity to interact with drag and drop events. See the methods, accept_enter_event(), :meth`:accept_drag_move_event`, drop_event() for details.

accept_enter_event(event, mime_data)[Quellcode]

This method should return True iff this interface action is capable of handling the drag event. Do not call accept/ignore on the event, that will be taken care of by the calibre UI.

accept_drag_move_event(event, mime_data)[Quellcode]

This method should return True iff this interface action is capable of handling the drag event. Do not call accept/ignore on the event, that will be taken care of by the calibre UI.

drop_event(event, mime_data)[Quellcode]

This method should perform some useful action and return True iff this interface action is capable of handling the drop event. Do not call accept/ignore on the event, that will be taken care of by the calibre UI. You should not perform blocking/long operations in this function. Instead emit a signal or use QTimer.singleShot and return quickly. See the builtin actions for examples.

create_menu_action(menu, unique_name, text, icon=None, shortcut=None, description=None, triggered=None, shortcut_name=None, persist_shortcut=False)[Quellcode]

Convenience method to easily add actions to a QMenu. Returns the created QAction. This action has one extra attribute calibre_shortcut_unique_name which if not None refers to the unique name under which this action is registered with the keyboard manager.

Parameter:
  • menu – The QMenu the newly created action will be added to

  • unique_name – A unique name for this action, this must be globally unique, so make it as descriptive as possible. If in doubt, add an UUID to it.

  • text – Der Text der Aktion.

  • icon – Either a QIcon or a file name. The file name is passed to the QIcon.ic() builtin, so you do not need to pass the full path to the images folder.

  • shortcut – A string, a list of strings, None or False. If False, no keyboard shortcut is registered for this action. If None, a keyboard shortcut with no default keybinding is registered. String and list of strings register a shortcut with default keybinding as specified.

  • description – A description for this action. Used to set tooltips.

  • triggered – A callable which is connected to the triggered signal of the created action.

  • shortcut_name – The text displayed to the user when customizing the keyboard shortcuts for this action. By default it is set to the value of text.

  • persist_shortcut – Shortcuts for actions that don’t always appear, or are library dependent, may disappear when other keyboard shortcuts are edited unless `persist_shortcut` is set True.

load_resources(names)[Quellcode]

If this plugin comes in a ZIP file (user added plugin), this method will allow you to load resources from the ZIP file.

Zum Beispiel, um ein Bild zu laden:

pixmap = QPixmap()
pixmap.loadFromData(tuple(self.load_resources(['images/icon.png']).values())[0])
icon = QIcon(pixmap)
Parameter:

names – List of paths to resources in the ZIP file using / as separator

Rückgabe:

A dictionary of the form {name : file_contents}. Any names that were not found in the ZIP file will not be present in the dictionary.

genesis()[Quellcode]

Setup this plugin. Only called once during initialization. self.gui is available. The action specified by action_spec is available as self.qaction.

location_selected(loc)[Quellcode]

Called whenever the book list being displayed in calibre changes. Currently values for loc are: library, main, card and cardb.

This method should enable/disable this action and its sub actions as appropriate for the location.

library_about_to_change(olddb, db)[Quellcode]

Called whenever the current library is changed.

Parameter:
  • olddb – The LibraryDatabase corresponding to the previous library.

  • db – The LibraryDatabase corresponding to the new library.

library_changed(db)[Quellcode]

Called whenever the current library is changed.

Parameter:

db – The LibraryDatabase corresponding to the current library.

gui_layout_complete()[Quellcode]

Called once per action when the layout of the main GUI is completed. If your action needs to make changes to the layout, they should be done here, rather than in initialization_complete().

initialization_complete()[Quellcode]

Called once per action when the initialization of the main GUI is completed.

tag_browser_context_action(index)[Quellcode]

Called when displaying the context menu in the Tag browser. index is the QModelIndex that points to the Tag browser item that was right clicked. Test it for validity with index.valid() and get the underlying TagTreeItem object with index.data(Qt.ItemDataRole.UserRole). Any action objects yielded by this method will be added to the context menu.

shutting_down()[Quellcode]

Called once per plugin when the main GUI is in the process of shutting down. Release any used resources, but try not to block the shutdown for long periods of time.

class calibre.customize.InterfaceActionBase(*args, **kwargs)[Quellcode]

Bases: Plugin

supported_platforms = ['windows', 'osx', 'linux']

Liste von Plattformen auf denen diese Erweiterung funktioniert. Zum Beispiel: ['windows', 'osx', 'linux']

author = 'Kovid Goyal'

Der Autor dieser Erweiterung

type = 'Benutzeroberfläche'

Der Typ dieser Erweiterung. Wird benutzt, um Erweiterungen in der GUI zu kategorisieren

can_be_disabled = False

Falls False, wird der Benutzer keine Möglichkeit haben, die Erweiterung zu deaktivieren. Bitte mit Vorsicht verwenden.

load_actual_plugin(gui)[Quellcode]

This method must return the actual interface action plugin object.

Preferences plugins

class calibre.customize.PreferencesPlugin(plugin_path)[Quellcode]

Bases: Plugin

A plugin representing a widget displayed in the Preferences dialog.

This plugin has only one important method create_widget(). The various fields of the plugin control how it is categorized in the UI.

supported_platforms = ['windows', 'osx', 'linux']

Liste von Plattformen auf denen diese Erweiterung funktioniert. Zum Beispiel: ['windows', 'osx', 'linux']

author = 'Kovid Goyal'

Der Autor dieser Erweiterung

type = 'Einstellungen'

Der Typ dieser Erweiterung. Wird benutzt, um Erweiterungen in der GUI zu kategorisieren

can_be_disabled = False

Falls False, wird der Benutzer keine Möglichkeit haben, die Erweiterung zu deaktivieren. Bitte mit Vorsicht verwenden.

config_widget = None

Import path to module that contains a class named ConfigWidget which implements the ConfigWidgetInterface. Used by create_widget().

category_order = 100

Where in the list of categories the category of this plugin should be.

name_order = 100

Where in the list of names in a category, the gui_name of this plugin should be

category = None

Die Kategorie, in der diese Erweiterung enthalten sein soll

gui_category = None

Der Name der Kategorie, welcher dem Benutzer zu dieser Erweiterung angezeigt wird

gui_name = None

Der Name, welcher dem Benutzer zu dieser Erweiterung angezeigt wird

icon = None

The icon for this plugin, should be an absolute path

description = None

The description used for tooltips and the like

create_widget(parent=None)[Quellcode]

Create and return the actual Qt widget used for setting this group of preferences. The widget must implement the calibre.gui2.preferences.ConfigWidgetInterface.

The default implementation uses config_widget to instantiate the widget.

class calibre.gui2.preferences.ConfigWidgetInterface[Quellcode]

This class defines the interface that all widgets displayed in the Preferences dialog must implement. See ConfigWidgetBase for a base class that implements this interface and defines various convenience methods as well.

changed_signal = None

This signal must be emitted whenever the user changes a value in this widget

supports_restoring_to_defaults = True

Set to True iff the restore_to_defaults() method is implemented.

restore_defaults_desc = 'Einstellungen auf Standardwerte zurücksetzen. Zum tatsächlichen Speichern der Standardeinstellungen muss auf "Anwenden" geklickt werden.'

The tooltip for the „Restore defaults“ button

restart_critical = False

If True the Preferences dialog will not allow the user to set any more preferences. Only has effect if commit() returns True.

genesis(gui)[Quellcode]

Called once before the widget is displayed, should perform any necessary setup.

Parameter:

gui – The main calibre graphical user interface

initialize()[Quellcode]

Should set all config values to their initial values (the values stored in the config files). A „return“ statement is optional. Return False if the dialog is not to be shown.

restore_defaults()[Quellcode]

Should set all config values to their defaults.

commit()[Quellcode]

Save any changed settings. Return True if the changes require a restart, False otherwise. Raise an AbortCommit exception to indicate that an error occurred. You are responsible for giving the user feedback about what the error is and how to correct it.

refresh_gui(gui)[Quellcode]

Called once after this widget is committed. Responsible for causing the gui to reread any changed settings. Note that by default the GUI re-initializes various elements anyway, so most widgets won’t need to use this method.

initial_tab_changed()[Quellcode]

Called if the initially displayed tab is changed before the widget is shown, but after it is initialized.

class calibre.gui2.preferences.ConfigWidgetBase(parent=None)[Quellcode]

Base class that contains code to easily add standard config widgets like checkboxes, combo boxes, text fields and so on. See the register() method.

This class automatically handles change notification, resetting to default, translation between gui objects and config objects, etc. for registered settings.

If your config widget inherits from this class but includes setting that are not registered, you should override the ConfigWidgetInterface methods and call the base class methods inside the overrides.

changed_signal

This signal must be emitted whenever the user changes a value in this widget

supports_restoring_to_defaults = True

Set to True iff the restore_to_defaults() method is implemented.

restart_critical = False

If True the Preferences dialog will not allow the user to set any more preferences. Only has effect if commit() returns True.

register(name, config_obj, gui_name=None, choices=None, restart_required=False, empty_string_is_None=True, setting=<class 'calibre.gui2.preferences.Setting'>)[Quellcode]

Register a setting.

Parameter:
  • name – Der Einstellungsname

  • config_obj – The config object that reads/writes the setting

  • gui_name – The name of the GUI object that presents an interface to change the setting. By default it is assumed to be 'opt_' + name.

  • choices – If this setting is a multiple choice (combobox) based setting, the list of choices. The list is a list of two element tuples of the form: [(gui name, value), ...]

  • setting – The class responsible for managing this setting. The default class handles almost all cases, so this param is rarely used.

initialize()[Quellcode]

Should set all config values to their initial values (the values stored in the config files). A „return“ statement is optional. Return False if the dialog is not to be shown.

commit(*args)[Quellcode]

Save any changed settings. Return True if the changes require a restart, False otherwise. Raise an AbortCommit exception to indicate that an error occurred. You are responsible for giving the user feedback about what the error is and how to correct it.

restore_defaults(*args)[Quellcode]

Should set all config values to their defaults.