API Documentation for plugins

Defines various abstract base classes that can be subclassed to create powerful plugins. The useful classes are:

Plugin

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

A calibre plugin. Useful members include:

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

    this plugin or None if it is a builtin plugin

  • self.site_customization: Stores a customization string entered

    by the user.

Methods that should be overridden in sub classes:

Useful methods:

supported_platforms = []

List of platforms this plugin works on. For example: ['windows', 'osx', 'linux']

name = 'Trivial Plugin'

The name of this plugin. You must set it something other than Trivial Plugin for it to work.

version = (1, 0, 0)

The version of this plugin as a 3-tuple (major, minor, revision)

description = u'Does absolutely nothing'

A short string describing what this plugin does

author = u'Unknown'

The author of this plugin

priority = 1

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

minimum_calibre_version = (0, 4, 118)

The earliest version of calibre this plugin requires

can_be_disabled = True

If False, the user will not be able to disable this plugin. Use with care.

type = u'Base'

The type of this plugin. Used for categorizing plugins in the GUI

initialize()[source]

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.

Note that self.site_customization is not available at this point.

config_widget()[source]

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)[source]

Save the settings specified by the user with config_widget.

Parameters:config_widget – The widget returned by config_widget().
do_user_config(parent=None)[source]

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)[source]

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

For example to load an image:

pixmap = QPixmap()
pixmap.loadFromData(self.load_resources(['images/icon.png']).itervalues().next())
icon = QIcon(pixmap)
Parameters:names – List of paths to resources in the zip file using / as separator
Returns: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)[source]

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.

Parameters:gui – If True return HTML help, otherwise return plain text help.
temporary_file(suffix)[source]

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.

Parameters:suffix – The suffix that the temporary file will have.
cli_main(args)[source]

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.

FileTypePlugin

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

Bases: calibre.customize.Plugin

A plugin that is associated with a particular set of file types.

file_types = set([])

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

on_import = False

If True, this plugin is run when books are added to the database

on_postimport = False

If True, this plugin is run after books are added to the database

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.

run(path_to_ebook)[source]

Run the plugin. Must be implemented in subclasses. It should perform whatever modifications are required on the ebook and return the absolute path to the modified ebook. If no modifications are needed, it should return the path to the original ebook. If an error is encountered it should raise an Exception. The default implementation simply return the path to the original ebook.

The modified ebook file should be created with the temporary_file() method.

Parameters:path_to_ebook – Absolute path to the ebook.
Returns:Absolute path to the modified ebook.
postimport(book_id, book_format, db)[source]

Called post import, i.e., after the book file has been added to the database.

Parameters:
  • book_id – Database id of the added book.
  • book_format – The file type of the book that was added.
  • db – Library database.

Metadata plugins

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

Bases: calibre.customize.Plugin

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

file_types = set([])

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

get_metadata(stream, type)[source]

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. :param type: The type of file. Guaranteed to be one of the entries in file_types. :return: A calibre.ebooks.metadata.book.Metadata object

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

Bases: calibre.customize.Plugin

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

file_types = set([])

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

set_metadata(stream, mi, type)[source]

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. :param type: The type of file. Guaranteed to be one of the entries in file_types. :param mi: A calibre.ebooks.metadata.book.Metadata object

Catalog plugins

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

Bases: calibre.customize.Plugin

A plugin that implements a catalog generator.

file_types = set([])

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

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 library.cli:catalog_option_parser()
initialize()[source]

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)[source]

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.

Parameters:
  • path_to_output – Absolute path to the generated catalog file.
  • opts – A dictionary of keyword arguments
  • db – A LibraryDatabase2 object

Metadata download plugins

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

Bases: calibre.customize.Plugin

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 add Accept-Encoding: gzip to all requests. This can speedup downloads but make sure that the source actually supports gzip transfer encoding correctly first

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()[source]

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

get_author_tokens(authors, only_first_author=True)[source]

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)[source]

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

split_jobs(jobs, num)[source]

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

test_fields(mi)[source]

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

clean_downloaded_metadata(mi)[source]

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)[source]

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 browseable 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)[source]

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

get_cached_cover_url(identifiers)[source]

Return cached cover URL for the book identified by the identifiers dict 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.

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

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)[source]

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.

Parameters:
  • 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 – The title of the book, can be None
  • authors – A list of authors of the book, can be None
  • identifiers – A dictionary of other identifiers, most commonly {‘isbn’:‘1234...’}
  • timeout – Timeout in seconds, no network request should hang for longer than timeout.
Returns:

None if no errors occurred, otherwise a unicode representation of the error suitable for showing to the user

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

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)[source]

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.

The algorithm is:

  • 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)[source]

Bases: calibre.customize.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().

file_types = set([])

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 = set([<calibre.customize.conversion.OptionRecommendation object at 0x7fb6bcc2f3d0>])

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 = set([])

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

recommendations = set([])

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

get_images()[source]

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)[source]

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 directory. If this plugin creates files outside the current directory they must be deleted/marked for deletion before this method returns.

Parameters:
  • 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.
  • accelarators – 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)[source]

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

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

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)[source]

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 builting input plugins for examples.

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

Bases: calibre.customize.Plugin

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

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

file_type = None

The file type (extension without leading period) that this plugin outputs

common_options = set([<calibre.customize.conversion.OptionRecommendation object at 0x7fb6bcc2f550>])

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 = set([])

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

recommendations = set([])

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

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

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

Parameters:
  • output – Either a file like object or a string. If it is a string it is the path to a directory that may or may not exist. The output plugin should write its output into that directory. 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_css_for_output(log, opts, item, stylizer)[source]

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

Parameters:
  • 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)[source]

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.

Device Drivers

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)[source]

Bases: calibre.customize.Plugin

Defines the interface that should be implemented by backends that communicate with an ebook reader.

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

Ordered list of supported formats

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

Height for thumbnails on the device

THUMBNAIL_COMPRESSION_QUALITY = 75

Width for thumbnails on the device. Setting this will force thumbnails to this size, not preserving aspect ratio. If it is not set, then the aspect ratio will be preserved and the thumbnail will be no higher than THUMBNAIL_HEIGHT 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 = '/home/kovid/work/calibre/resources/images/reader.png'

Icon for this device

UserAnnotation

alias of Annotation

OPEN_FEEDBACK_MESSAGE = None

GUI displays this as a message if not None. 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'])

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 is 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.

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

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

Parameters:devices_on_system – List of devices currently connected
detect_managed_devices(devices_on_system, force_refresh=False)[source]

Called only if MANAGES_DEVICE_PRESENCE is True.

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.

Parameters:
  • 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)[source]

Called only if MANAGES_DEVICE_PRESENCE is True.

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

Should return True if a device was detected and successfully opened, otherwise False.

reset(key='-1', log_packets=False, report_progress=None, detected_device=None)[source]
Parameters:
  • key – The key to unlock the device
  • 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(device_id, debug=False)[source]

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().

Parameters:device_info – On windows a device ID string. On Unix a tuple of (vendor_id, product_id, bcd).
can_handle(device_info, debug=False)[source]

Unix version of can_handle_windows()

Parameters:device_info – Is a tuple of (vid, pid, bcd, manufacturer, product, serial number)
open(connected_device, library_uuid)[source]

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.

Parameters:
  • 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()[source]

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()[source]

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

set_progress_reporter(report_progress)[source]

Set a function to report progress information.

Parameters: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)[source]

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

Returns:(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()[source]

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)[source]

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)[source]
Get total space available on the mountpoints:
  1. Main memory
  2. Memory Card A
  3. Memory Card B
Returns: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)[source]
Get free space available on the mountpoints:
  1. Main memory
  2. Card A
  3. Card B
Returns: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)[source]

Return a list of ebooks on the device.

Parameters:oncard – If ‘carda’ or ‘cardb’ return a list of ebooks on the specific storage card, otherwise return list of ebooks in main memory of device. If a card is specified and no books are on the card return empty list.
Returns:A BookList.
upload_books(files, names, on_card=None, end_session=True, metadata=None)[source]

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”.

Parameters:
  • files – A list of paths
  • 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).
Returns:

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)[source]

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

Parameters:
  • locations – Result of a call to 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)[source]

Delete books at paths on device.

classmethod remove_books_from_metadata(paths, booklists)[source]

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

Parameters:
  • paths – paths to books on the device.
  • 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)[source]

Update metadata on device.

Parameters: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)[source]

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

Parameters:outfile – file object like sys.stdout or the result of an open() call.
classmethod config_widget()[source]

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

classmethod save_settings(settings_widget)[source]

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

classmethod settings()[source]

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)[source]

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).

Returns:None or a single plugboard instance.
set_driveinfo_name(location_code, name)[source]

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)[source]

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()[source]

Called when calibre is 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()[source]

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()[source]

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)[source]

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()[source]

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

set_user_blacklisted_devices(devices)[source]

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

specialize_global_preferences(device_prefs)[source]

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)[source]

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()[source]

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()[source]

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()[source]

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)[source]

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)[source]

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()[source]

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)[source]

Called during book matching when a book on the device is matched with a book in calibre’s db. The method is responsible for syncronizing 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)[source]

Bases: list

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

  1. title
  2. authors
  3. size (file size of the book)
  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()[source]

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

add_book(book, replace_metadata)[source]

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)[source]

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

get_collections(collection_attributes)[source]

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.

Parameters:collection_attributes – A list of attributes of the Book object

USB Mass Storage based devices

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]

    VENDOR_NAME = 'ANDROID'
    WINDOWS_MAIN_MEM = WINDOWS_CARD_A_MEM = '__UMS_COMPOSITE'
    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)[source]

Bases: calibre.devices.usbms.deviceconfig.DeviceConfig, calibre.devices.interface.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.

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 OS X

MAX_PATH_LEN = 250

The maximum length of paths created on the device

NEWS_IN_FOLDER = True

Put news in its own folder

windows_sort_drives(drives)[source]

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

sanitize_callback(path)[source]

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

filename_callback(default, mi)[source]

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

sanitize_path_components(components)[source]

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

get_annotations(path_map)[source]

Resolve path_map to annotation_map of files found on the device

add_annotation_to_library(db, db_id, annotation)[source]

Add an annotation to the calibre library

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

Bases: calibre.devices.usbms.cli.CLI, calibre.devices.usbms.device.Device

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

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

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

Parameters:
  • path – The full path to the directory where the associated book is located.
  • filename – The name of the book file without the extension.
  • metadata – metadata belonging to the book. Use metadata.thumbnail for cover
  • filepath – The full path to the ebook file
classmethod normalize_path(path)[source]

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 you InterfaceActionBase subclass must return an instantiated object of your InterfaceBase subclass.

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

Bases: PyQt5.QtCore.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() and initialization_complete() 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 shortcut must be 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_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)[source]

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)[source]

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)[source]

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)[source]

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.

Parameters:
  • 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 a uuid to it.
  • text – The text of the action.
  • icon – Either a QIcon or a file name. The file name is passed to the I() builtin, so you do not need to pass the full path to the images directory.
  • 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 test displayed to the user when customizing the keyboard shortcuts for this action. By default it is set to the value of text.
load_resources(names)[source]

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

For example to load an image:

pixmap = QPixmap()
pixmap.loadFromData(self.load_resources(['images/icon.png']).itervalues().next())
icon = QIcon(pixmap)
Parameters:names – List of paths to resources in the zip file using / as separator
Returns: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()[source]

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)[source]

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_changed(db)[source]

Called whenever the current library is changed.

Parameters:db – The LibraryDatabase corresponding to the current library.
gui_layout_complete()[source]

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()[source]

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

shutting_down()[source]

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.

Returns:False to halt the shutdown. You are responsible for telling the user why the shutdown was halted.
class calibre.customize.InterfaceActionBase(*args, **kwargs)[source]

Bases: calibre.customize.Plugin

load_actual_plugin(gui)[source]

This method must return the actual interface action plugin object.

Preferences Plugins

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

Bases: calibre.customize.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.

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

The category this plugin should be in

gui_category = None

The category name displayed to the user for this plugin

gui_name = None

The name displayed to the user for this plugin

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)[source]

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[source]

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 = u'Restore settings to default values. You have to click Apply to actually save the default settings.'

The tooltip for the Restore to 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)[source]

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

Parameters:gui – The main calibre graphical user interface
initialize()[source]

Should set all config values to their initial values (the values stored in the config files).

restore_defaults()[source]

Should set all config values to their defaults.

commit()[source]

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)[source]

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.

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

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.

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

Register a setting.

Parameters:
  • name – The setting name
  • config – 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.

Viewer plugins

class calibre.customize.ViewerPlugin(plugin_path)[source]

Bases: calibre.customize.Plugin

type = u'Viewer'

These plugins are used to add functionality to the calibre viewer.

load_fonts()[source]

This method is called once at viewer startup. It should load any fonts it wants to make available. For example:

def load_fonts():
    from PyQt5.Qt import QFontDatabase
    font_data = get_resources(['myfont1.ttf', 'myfont2.ttf'])
    for raw in font_data.itervalues():
        QFontDatabase.addApplicationFontFromData(raw)
load_javascript(evaljs)[source]

This method is called every time a new HTML document is loaded in the viewer. Use it to load javascript libraries into the viewer. For example:

def load_javascript(self, evaljs):
    js = get_resources('myjavascript.js')
    evaljs(js)
run_javascript(evaljs)[source]

This method is called every time a document has finished loading. Use it in the same way as load_javascript().

customize_ui(ui)[source]

This method is called once when the viewer is created. Use it to make any customizations you want to the viewer’s user interface. For example, you can modify the toolbars via ui.tool_bar and ui.tool_bar2.

customize_context_menu(menu, event, hit_test_result)[source]

This method is called every time the context (right-click) menu is shown. You can use it to customize the context menu. event is the context menu event and hit_test_result is the QWebHitTestResult for this event in the currently loaded document.