Documentação de API para plug-ins¶
Define várias classes abstratas que podem ser subclassificadas para criar plugins poderosos. As classes úteis são:
Plugin¶
- class calibre.customize.Plugin(plugin_path)[código-fonte]¶
Um plugin calibre. Membros úteis incluem:
self.installation_type
: Stores how the plugin was installed.self.plugin_path
: Stores path to the ZIP file that containseste plugin ou nenhum se for um plugin integrado
self.site_customization
: Guarda um texto de personalização inseridopelo usuário.
Métodos que devem ser sobrescritos nas sub classes:
Métodos úteis:
__enter__()
- supported_platforms = []¶
Lista de plataformas em que este plugin funciona. Por exemplo : “ [’ 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 = 'Não faz absolutamente nada'¶
Uma curta descrição do que este plugin faz
- author = 'Desconhecido'¶
O autor deste plugin
- 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)¶
The earliest version of calibre this plugin requires
- installation_type = None¶
The way this plugin is installed
- can_be_disabled = True¶
Se falso, o usuário não será capaz de desativar este plugin. Use com cuidado.
- type = 'Base'¶
The type of this plugin. Used for categorizing plugins in the GUI
- initialize()[código-fonte]¶
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()[código-fonte]¶
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)[código-fonte]¶
Save the settings specified by the user with config_widget.
- Parâmetros:
config_widget – The widget returned by
config_widget()
.
- do_user_config(parent=None)[código-fonte]¶
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)[código-fonte]¶
If this plugin comes in a ZIP file (user added plugin), this method will allow you to load resources from the ZIP file.
Por exemplo, para carregar uma imagem
pixmap = QPixmap() pixmap.loadFromData(self.load_resources(['images/icon.png'])['images/icon.png']) icon = QIcon(pixmap)
- Parâmetros:
names – List of paths to resources in the ZIP file using / as separator
- Retorna:
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)[código-fonte]¶
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.
- Parâmetros:
gui – Se verdadeiro retorna ajuda em HTML, caso contrário retorna ajuda em texto simples.
- temporary_file(suffix)[código-fonte]¶
Devolve um objeto tipo ficheiro que é um ficheiro temporário no sistema de ficheiros. Este ficheiro permanecerá disponível mesmo depois de ser fechado e apenas será removido ao se desligar o interpretador. Use o membro
name
do objeto devolvido para aceder ao caminho completo do ficheiro temporário assim criado.- Parâmetros:
suffix – The suffix that the temporary file will have.
- cli_main(args)[código-fonte]¶
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)[código-fonte]¶
Base:
Plugin
Um plugin que está associado com um determinado conjunto de tipos de arquivo.
- 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¶
Se Verdadeiro, este plugin é executado quando os livros são adicionados ao banco de dados
- 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¶
Se Verdadeiro, este plugin é executado pouco antes de uma conversão
- on_postprocess = False¶
Se Verdadeiro, este plugin é executado após a conversão no arquivo final produzido pelo plugin de saída de conversão.
- type = 'Tipo de arquivo'¶
The type of this plugin. Used for categorizing plugins in the GUI
- run(path_to_ebook)[código-fonte]¶
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.- Parâmetros:
path_to_ebook – Caminho absoluto para o ebook.
- Retorna:
Caminho absoluto para o ebook editado
- postimport(book_id, book_format, db)[código-fonte]¶
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.- Parâmetros:
book_id – ID no banco de dados do livro adicionado.
book_format – O tipo de arquivo do livro que foi adicionado.
db – Library database.
- postconvert(book_id, book_format, db)[código-fonte]¶
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.
- Parâmetros:
book_id – ID no banco de dados do livro adicionado.
book_format – O tipo de arquivo do livro que foi adicionado.
db – Library database.
- postdelete(book_id, book_format, db)[código-fonte]¶
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.
- Parâmetros:
book_id – ID no banco de dados do livro adicionado.
book_format – O tipo de arquivo do livro que foi adicionado.
db – Library database.
- postadd(book_id, fmt_map, db)[código-fonte]¶
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.- Parâmetros:
book_id – ID no banco de dados do livro adicionado.
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 – Base de dados da biblioteca
Plugins de Metadados¶
- class calibre.customize.MetadataReaderPlugin(*args, **kwargs)[código-fonte]¶
Base:
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']¶
Lista de plataformas em que este plugin funciona. Por exemplo : “ [’ windows ‘, ‘ osx’ , ‘linux’ ]”
- version = (7, 21, 100)¶
The version of this plugin as a 3-tuple (major, minor, revision)
- author = 'Kovid Goyal'¶
O autor deste plugin
- type = 'Leitor de metadados'¶
The type of this plugin. Used for categorizing plugins in the GUI
- get_metadata(stream, type)[código-fonte]¶
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.
- Parâmetros:
type – The type of file. Guaranteed to be one of the entries in
file_types
.- Retorna:
Um objeto
calibre.ebooks.metadata.book.Metadata
- class calibre.customize.MetadataWriterPlugin(*args, **kwargs)[código-fonte]¶
Base:
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']¶
Lista de plataformas em que este plugin funciona. Por exemplo : “ [’ windows ‘, ‘ osx’ , ‘linux’ ]”
- version = (7, 21, 100)¶
The version of this plugin as a 3-tuple (major, minor, revision)
- author = 'Kovid Goyal'¶
O autor deste plugin
- type = 'Escritor de metadados'¶
The type of this plugin. Used for categorizing plugins in the GUI
- set_metadata(stream, mi, type)[código-fonte]¶
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.
- Parâmetros:
type – The type of file. Guaranteed to be one of the entries in
file_types
.mi – Um objeto
calibre.ebooks.metadata.book.Metadata
Plugins de Catálogo¶
- class calibre.customize.CatalogPlugin(plugin_path)[código-fonte]¶
Base:
Plugin
Um plugin que implementa um gerador de catálogos.
- file_types = {}¶
Output file type for which this plugin should be run. For example: ‘epub’ or ‘xml’
- type = 'Gerador de catálogo'¶
The type of this plugin. Used for categorizing plugins in the GUI
- 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()[código-fonte]¶
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)[código-fonte]¶
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.- Parâmetros:
path_to_output – Absolute path to the generated catalog file.
opts – A dictionary of keyword arguments
db – A LibraryDatabase2 object
Plug-ins de download de metadados¶
- class calibre.ebooks.metadata.sources.base.Source(*args, **kwargs)[código-fonte]¶
Base:
Plugin
- type = 'Fonte de metadados'¶
The type of this plugin. Used for categorizing plugins in the GUI
- author = 'Kovid Goyal'¶
O autor deste plugin
- supported_platforms = ['windows', 'osx', 'linux']¶
Lista de plataformas em que este plugin funciona. Por exemplo : “ [’ 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()[código-fonte]¶
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()[código-fonte]¶
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.
- Parâmetros:
gui – Se verdadeiro retorna ajuda em HTML, caso contrário retorna ajuda em texto simples.
- config_widget()[código-fonte]¶
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)[código-fonte]¶
Save the settings specified by the user with config_widget.
- Parâmetros:
config_widget – The widget returned by
config_widget()
.
- get_author_tokens(authors, only_first_author=True)[código-fonte]¶
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)[código-fonte]¶
Take a title and return a list of tokens useful for an AND search query. Excludes connectives(optionally) and punctuation.
- split_jobs(jobs, num)[código-fonte]¶
Split a list of jobs into at most num groups, as evenly as possible
- test_fields(mi)[código-fonte]¶
Return the first field from self.touched_fields that is null on the mi object
- clean_downloaded_metadata(mi)[código-fonte]¶
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)[código-fonte]¶
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)[código-fonte]¶
Return a human readable name from the return value of get_book_url().
- get_book_urls(identifiers)[código-fonte]¶
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)[código-fonte]¶
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)[código-fonte]¶
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={})[código-fonte]¶
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)[código-fonte]¶
Identificar um livro pelo seu título/autor/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.
Cada objeto de metadados colocado na result_queue por este método tem de ter um atributo de source_relevance que consiste num valor inteiro que indica a ordem pela qual os resultados foram devolvidos pela fonte de metadados para esta consulta. Este valor inteiro será usado por
compare_identify_results()
. Se a ordem for irrelevante, defina-o para zero em cada resultado.Verifique se todas as informações de mapeamento de capa/ISBN são armazenadas em cache antes que o objeto metadados seja colocado na fila de resultados (result_queue).
- Parâmetros:
log – Um objeto de registo de atividade. Use-o para produzir informação de depuração/erros
result_queue – Uma fila de resultados, onde os resultados devem ser colocados. Cada resultado é um objeto de metadados.
abort – If abort.is_set() returns True, abort further processing and return as soon as possible
title – O título do livro, que pode ser Nenhum
authors – Uma lista de autores do livro, que pode ser Nenhum
identifiers – Um dicionário de outros identificadores, sendo os mais comuns {‘isbn’:’1234…’}
timeout – Tempo de espera em segundos, nenhum pedido à rede deve ficar em espera por mais tempo de que o tempo de espera.
- Retorna:
Nenhum se não ocorrerem erros, caso contrário a representação em Unicode do erro adequada para mostrar ao utilizador.
- download_cover(log, result_queue, abort, title=None, authors=None, identifiers={}, timeout=30, get_best_cover=False)[código-fonte]¶
Descarregue uma capa e coloque-a na result_queue. Os parâmetros têm todos o mesmo significado que para
identify()
. Coloque (self, cover_data) na result_queue.Este método deve, sempre que possível e por motivos de eficiência, usar URL de capa que esteja em cache. Quando não estejam presentes dados em cache, a maioria dos plugins simplesmente invoca o método identify e usa os respetivos resultados.
Se o parâmetro get_best_cover for True e este plugin puder obter múltiplas capas, deve apenas obter a “melhor” delas.
- class calibre.ebooks.metadata.sources.base.InternalMetadataCompareKeyGen(mi, source_plugin, title, authors, identifiers)[código-fonte]¶
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.
O algoritmo é:
Prefere resultados que têm pelo menos um identificador o mesmo que para a consulta
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
motor
Plugins de Conversão¶
- class calibre.customize.conversion.InputFormatPlugin(*args)[código-fonte]¶
Base:
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 = 'Entrada de conversão'¶
The type of this plugin. Used for categorizing plugins in the GUI
- can_be_disabled = False¶
Se falso, o usuário não será capaz de desativar este plugin. Use com cuidado.
- supported_platforms = ['windows', 'osx', 'linux']¶
Lista de plataformas em que este plugin funciona. Por exemplo : “ [’ windows ‘, ‘ osx’ , ‘linux’ ]”
- file_types = {}¶
Conjunto de tipos de arquivos para os quais este plugin deve ser executado Por exemplo: “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¶
Se definido como Verdadeiro, o plug-in de entrada irá executar o processamento especial para fazer a sua saída adequado para visualização
- 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 ofOptionRecommendation
.
- 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()[código-fonte]¶
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)[código-fonte]¶
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.- Parâmetros:
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 ofcalibre.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 – Um objeto
calibre.utils.logging.Log
. Todas as saídas devem usar este objeto.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)[código-fonte]¶
Called to allow the input plugin to perform postprocessing after the book has been parsed.
- specialize(oeb, opts, log, output_fmt)[código-fonte]¶
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)[código-fonte]¶
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)[código-fonte]¶
Base:
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 = 'Saída de conversão'¶
The type of this plugin. Used for categorizing plugins in the GUI
- can_be_disabled = False¶
Se falso, o usuário não será capaz de desativar este plugin. Use com cuidado.
- supported_platforms = ['windows', 'osx', 'linux']¶
Lista de plataformas em que este plugin funciona. Por exemplo : “ [’ windows ‘, ‘ osx’ , ‘linux’ ]”
- file_type = None¶
The file type (extension without leading period) that this plugin outputs
- 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 ofOptionRecommendation
.
- 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
Crie um novo objeto string a partir do objeto fornecido. Se a codificação ou os erros forem especificados, o objeto deve expor um buffer de dados que será decodificado usando a codificação fornecida e o manipulador de erros. Caso contrário, retorna o resultado do
object.__str__()
(se definido) ourepr(object)
. O padrão de codificação ésys.getdefaultencoding()
. O padrão de erros é ‘strict’.
- convert(oeb_book, output, input_plugin, opts, log)[código-fonte]¶
Render the contents of oeb_book (which is an instance of
calibre.ebooks.oeb.OEBBook
) to the file specified by output.- Parâmetros:
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)[código-fonte]¶
Can be used to change the values of conversion options, as used by the conversion pipeline.
- specialize_css_for_output(log, opts, item, stylizer)[código-fonte]¶
Can be used to make changes to the CSS during the CSS flattening process.
- Parâmetros:
item – O item (ficheiro HTML) a ser processado
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)[código-fonte]¶
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.
Drivers de Dispositivo¶
A classe base para todos os drivers de dispositivo é DevicePlugin
. No entanto, se seu dispositivo se expõe como uma unidade USBMS para o sistema operacional, você deve usar a classe USBMS, pois ela implementa toda a lógica necessária para oferecer suporte a esses tipos de dispositivos.
- class calibre.devices.interface.DevicePlugin(plugin_path)[código-fonte]¶
Base:
Plugin
Defines the interface that should be implemented by backends that communicate with an e-book reader.
- type = 'Interface do dispositivo'¶
The type of this plugin. Used for categorizing plugins in the GUI
- FORMATS = ['lrf', 'rtf', 'pdf', 'txt']¶
Lista ordenada de formatos suportados
- 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¶
Um inteiro ou uma lista de inteiros
- 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¶
Altura das miniaturas no dispositivo
- 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'¶
Ícone para este dispositivo
- UserAnnotation¶
apelido de
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¶
Mensagem para mostrar ao usuário para extensões de livros virtuais.
- 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()
andignore_connected_device()
andget_user_blacklisted_devices()
andset_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()[código-fonte]¶
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)[código-fonte]¶
Return True, device_info if a device handled by this plugin is currently connected.
- Parâmetros:
devices_on_system – Lista dos dispositivos conectados atualmente
- detect_managed_devices(devices_on_system, force_refresh=False)[código-fonte]¶
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.
- Parâmetros:
devices_on_system – Conjunto de dispositivos USB que foram encontrados no sistema.
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)[código-fonte]¶
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)[código-fonte]¶
- Parâmetros:
key – A chave para desbloquear o dispositivo
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)[código-fonte]¶
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 overridecan_handle()
in your subclass of USBMS.- Parâmetros:
usbdevice – A usbdevice as returned by
calibre.devices.winusb.scan_usb_devices()
- can_handle(device_info, debug=False)[código-fonte]¶
Unix version of
can_handle_windows()
.- Parâmetros:
device_info – Is a tuple of (vid, pid, bcd, manufacturer, product, serial number)
- open(connected_device, library_uuid)[código-fonte]¶
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.
- Parâmetros:
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()[código-fonte]¶
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()[código-fonte]¶
Called if the user yanks the device without ejecting it first.
- set_progress_reporter(report_progress)[código-fonte]¶
Set a function to report progress information.
- Parâmetros:
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)[código-fonte]¶
Ask device for device information. See L{DeviceInfoQuery}.
- Retorna:
(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()[código-fonte]¶
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)[código-fonte]¶
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)[código-fonte]¶
- Get total space available on the mountpoints:
Memória principal
Cartão de memória A
Cartão de memória B
- Retorna:
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)[código-fonte]¶
- Get free space available on the mountpoints:
Memória principal
Cartão A
Cartão B
- Retorna:
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)[código-fonte]¶
Devolve a lista de livros no dispositivo.
- Parâmetros:
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.
- Retorna:
Uma lista de livros.
- upload_books(files, names, on_card=None, end_session=True, metadata=None)[código-fonte]¶
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” ifon_card
is not None otherwise it must contain the word “memory”.- Parâmetros:
files – Lista de caminhos
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).
- Retorna:
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)[código-fonte]¶
Add locations to the booklists. This function must not communicate with the device.
- Parâmetros:
locations – Result of a call to L{upload_books}
metadata – List of
Metadata
objects, same as forupload_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)[código-fonte]¶
Eliminar livros em caminhos no dispositivo
- classmethod remove_books_from_metadata(paths, booklists)[código-fonte]¶
Remove books from the metadata list. This function must not communicate with the device.
- Parâmetros:
paths – caminhos para livros o dispositivo.
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)[código-fonte]¶
Atualizar metadados no dispositivo.
- Parâmetros:
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)[código-fonte]¶
Read the file at
path
on the device and write it to outfile.- Parâmetros:
outfile – file object like
sys.stdout
or the result of anopen()
call.
- classmethod config_widget()[código-fonte]¶
Should return a QWidget. The QWidget contains the settings for the device interface
- classmethod save_settings(settings_widget)[código-fonte]¶
Should save settings to disk. Takes the widget created in
config_widget()
and saves all settings to disk.
- classmethod settings()[código-fonte]¶
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)[código-fonte]¶
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).
- Retorna:
Nenhum ou um quadro de conexões individual
- set_driveinfo_name(location_code, name)[código-fonte]¶
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)[código-fonte]¶
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()[código-fonte]¶
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()[código-fonte]¶
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()[código-fonte]¶
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)[código-fonte]¶
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()[código-fonte]¶
Return map of device uid to friendly name for all devices that the user has asked to be ignored.
- set_user_blacklisted_devices(devices)[código-fonte]¶
Set the list of device uids that should be ignored by this driver.
- specialize_global_preferences(device_prefs)[código-fonte]¶
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)[código-fonte]¶
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()[código-fonte]¶
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()[código-fonte]¶
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()[código-fonte]¶
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)[código-fonte]¶
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)[código-fonte]¶
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()[código-fonte]¶
Retorna verdadeiro se o plug-in foi iniciado, caso contrário falso
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)[código-fonte]¶
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)[código-fonte]¶
Base:
list
Uma lista de livros. Cada objeto de livro deve ter os campos
título
autores
tamanho (tamanho do arquivo do livro)
datetime (uma enupla de hora UTC)
path (caminho, no dispositivo, para o livro)
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
etiquetas (uma lista de entradas, pode estar vazia).
- supports_collections()[código-fonte]¶
Return True if the device supports collections for this book list.
- add_book(book, replace_metadata)[código-fonte]¶
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)[código-fonte]¶
Remove a book from the booklist. Correct any device metadata at the same time
- get_collections(collection_attributes)[código-fonte]¶
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.
- Parâmetros:
collection_attributes – A list of attributes of the Book object
Dispositivos baseados em armazenamento em massa USB¶
A classe base para tais dispositivos é calibre.devices.usbms.driver.USBMS
. Essa classe, por sua vez, herda algumas de suas funcionalidades de suas bases, documentadas a seguir. Um driver básico baseado em USBMS típico se parece com isto:
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)[código-fonte]¶
Base:
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¶
Um inteiro ou uma lista de inteiros
- 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¶
O comprimento máximo do caminhos criado no dispositivo
- NEWS_IN_FOLDER = True¶
Coloque notícias em sua própria pasta
- reset(key='-1', log_packets=False, report_progress=None, detected_device=None)[código-fonte]¶
- Parâmetros:
key – A chave para desbloquear o dispositivo
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)[código-fonte]¶
Set a function to report progress information.
- Parâmetros:
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)[código-fonte]¶
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)[código-fonte]¶
- Get total space available on the mountpoints:
Memória principal
Cartão de memória A
Cartão de memória B
- Retorna:
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)[código-fonte]¶
- Get free space available on the mountpoints:
Memória principal
Cartão A
Cartão B
- Retorna:
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)[código-fonte]¶
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)[código-fonte]¶
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 overridecan_handle()
in your subclass of USBMS.- Parâmetros:
usbdevice – A usbdevice as returned by
calibre.devices.winusb.scan_usb_devices()
- open(connected_device, library_uuid)[código-fonte]¶
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.
- Parâmetros:
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()[código-fonte]¶
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()[código-fonte]¶
Called if the user yanks the device without ejecting it first.
- sanitize_callback(path)[código-fonte]¶
Callback to allow individual device drivers to override the path sanitization used by
create_upload_path()
.
- filename_callback(default, mi)[código-fonte]¶
Callback to allow drivers to change the default file name set by
create_upload_path()
.
- sanitize_path_components(components)[código-fonte]¶
Perform any device specific sanitization on the path components for files to be uploaded to the device
- get_annotations(path_map)[código-fonte]¶
Resolve path_map to annotation_map of files found on the device
- add_annotation_to_library(db, db_id, annotation)[código-fonte]¶
Adicionar uma nota à biblioteca Calibre
- class calibre.devices.usbms.cli.CLI[código-fonte]¶
- class calibre.devices.usbms.driver.USBMS(plugin_path)[código-fonte]¶
-
The base class for all USBMS devices. Implements the logic for sending/getting/updating metadata/caching metadata/etc.
- description = 'Comunicar-se com um leitor de e-books.'¶
Uma curta descrição do que este plugin faz
- author = 'John Schember'¶
O autor deste plugin
- supported_platforms = ['windows', 'osx', 'linux']¶
Lista de plataformas em que este plugin funciona. Por exemplo : “ [’ windows ‘, ‘ osx’ , ‘linux’ ]”
- booklist_class¶
apelido de
BookList
- book_class¶
apelido de
Book
- FORMATS = []¶
Lista ordenada de formatos suportados
- CAN_SET_METADATA = []¶
Whether the metadata on books can be set via the GUI.
- get_device_information(end_session=True)[código-fonte]¶
Ask device for device information. See L{DeviceInfoQuery}.
- Retorna:
(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)[código-fonte]¶
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)[código-fonte]¶
Devolve a lista de livros no dispositivo.
- Parâmetros:
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.
- Retorna:
Uma lista de livros.
- upload_books(files, names, on_card=None, end_session=True, metadata=None)[código-fonte]¶
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” ifon_card
is not None otherwise it must contain the word “memory”.- Parâmetros:
files – Lista de caminhos
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).
- Retorna:
A list of 3-element tuples. The list is meant to be passed to
add_books_to_metadata()
.
- upload_cover(path, filename, metadata, filepath)[código-fonte]¶
Upload book cover to the device. Default implementation does nothing.
- Parâmetros:
path – The full path to the folder where the associated book is located.
filename – O nome do arquivo do livro sem a extensão.
metadata – metadata belonging to the book. Use metadata.thumbnail for cover
filepath – O caminho absoluto para o ficheiro de ebook
- add_books_to_metadata(locations, metadata, booklists)[código-fonte]¶
Add locations to the booklists. This function must not communicate with the device.
- Parâmetros:
locations – Result of a call to L{upload_books}
metadata – List of
Metadata
objects, same as forupload_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)[código-fonte]¶
Eliminar livros em caminhos no dispositivo
- remove_books_from_metadata(paths, booklists)[código-fonte]¶
Remove books from the metadata list. This function must not communicate with the device.
- Parâmetros:
paths – caminhos para livros o dispositivo.
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)[código-fonte]¶
Atualizar metadados no dispositivo.
- Parâmetros:
booklists – A tuple containing the result of calls to (
books(oncard=None)()
,books(oncard='carda')()
, :meth`books(oncard=’cardb’)`).
- classmethod normalize_path(path)[código-fonte]¶
Return path with platform native path separators
User interface actions¶
Se você estiver adicionando seu próprio plug-in em um arquivo ZIP, deve criar uma subclasse de InterfaceActionBase
e InterfaceAction
. O método load_actual_plugin()
de sua subclasse InterfaceActionBase
deve retornar um objeto instanciado de sua subclasse InterfaceBase
.
- class calibre.gui2.actions.InterfaceAction(parent, site_customization)[código-fonte]¶
Base:
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()
andtag_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 asself.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]
Se True, será criado um menu e adicionado automaticamente a self.qaction
Se True, um clone de self.qaction é adicionado ao menu de self.qaction. Se pretender que o texto desta ação seja diferente do de self.qaction, modifique esta variável para o novo texto
- dont_add_to = frozenset({})¶
Conjunto de locais aos quais esta ação não pode ser adicionada. Veja
all_locations
para uma lista de locais possíveis
- dont_remove_from = frozenset({})¶
Conjunto de locais dos quais esta ação não pode ser removida. Ver
all_locations
para uma lista de locais possíveis
- action_type = 'global'¶
Tipo de ação ‘corrente’ significa que ações na vista ‘global’ atual implicam uma ação que não se repercute na vista atual, mas sim no Calibre como um todo
- 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)[código-fonte]¶
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)[código-fonte]¶
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)[código-fonte]¶
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.
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.
- Parâmetros:
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 – O texto da ação.
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 descrição para esta ação. Usado para definir dicas de ferramentas.
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)[código-fonte]¶
If this plugin comes in a ZIP file (user added plugin), this method will allow you to load resources from the ZIP file.
Por exemplo, para carregar uma imagem
pixmap = QPixmap() pixmap.loadFromData(tuple(self.load_resources(['images/icon.png']).values())[0]) icon = QIcon(pixmap)
- Parâmetros:
names – List of paths to resources in the ZIP file using / as separator
- Retorna:
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()[código-fonte]¶
Setup this plugin. Only called once during initialization. self.gui is available. The action specified by
action_spec
is available asself.qaction
.
- location_selected(loc)[código-fonte]¶
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)[código-fonte]¶
Chamado toda vez que a biblioteca atual é alterada.
- Parâmetros:
olddb – The LibraryDatabase corresponding to the previous library.
db – The LibraryDatabase corresponding to the new library.
- library_changed(db)[código-fonte]¶
Chamado toda vez que a biblioteca atual é alterada.
- Parâmetros:
db – The LibraryDatabase corresponding to the current library.
- gui_layout_complete()[código-fonte]¶
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()[código-fonte]¶
Chamada uma vez por ação quando a inicialização do GUI principal é concluida.
- tag_browser_context_action(index)[código-fonte]¶
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()[código-fonte]¶
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)[código-fonte]¶
Base:
Plugin
- supported_platforms = ['windows', 'osx', 'linux']¶
Lista de plataformas em que este plugin funciona. Por exemplo : “ [’ windows ‘, ‘ osx’ , ‘linux’ ]”
- author = 'Kovid Goyal'¶
O autor deste plugin
- type = 'Ação da interface do usuário'¶
The type of this plugin. Used for categorizing plugins in the GUI
- can_be_disabled = False¶
Se falso, o usuário não será capaz de desativar este plugin. Use com cuidado.
- load_actual_plugin(gui)[código-fonte]¶
This method must return the actual interface action plugin object.
Plugins de Preferências¶
- class calibre.customize.PreferencesPlugin(plugin_path)[código-fonte]¶
Base:
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']¶
Lista de plataformas em que este plugin funciona. Por exemplo : “ [’ windows ‘, ‘ osx’ , ‘linux’ ]”
- author = 'Kovid Goyal'¶
O autor deste plugin
- type = 'Preferências'¶
The type of this plugin. Used for categorizing plugins in the GUI
- can_be_disabled = False¶
Se falso, o usuário não será capaz de desativar este plugin. Use com cuidado.
- config_widget = None¶
Import path to module that contains a class named ConfigWidget which implements the ConfigWidgetInterface. Used by
create_widget()
.
- 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)[código-fonte]¶
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[código-fonte]¶
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 = 'Restaurar configurações para valores padrão. Você tem que clicar em Aplicar para realmente salvar os configurações padrão.'¶
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)[código-fonte]¶
Called once before the widget is displayed, should perform any necessary setup.
- Parâmetros:
gui – The main calibre graphical user interface
- initialize()[código-fonte]¶
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()[código-fonte]¶
Should set all config values to their defaults.
- commit()[código-fonte]¶
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)[código-fonte]¶
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()[código-fonte]¶
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)[código-fonte]¶
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'>)[código-fonte]¶
Register a setting.
- Parâmetros:
name – The setting name
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()[código-fonte]¶
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)[código-fonte]¶
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)[código-fonte]¶
Should set all config values to their defaults.