Code:
from collections import defaultdict
from calibre.ebooks.metadata import (
authors_to_string, authors_to_sort_string, check_isbn, string_to_authors, title_sort
)
from calibre_plugins.action_chains.actions.base import ChainAction
class SwapTitleAuthors(ChainAction):
name = 'Swap title and author'
support_scopes = True
def __init__(self, plugin_action):
ChainAction.__init__(self, plugin_action)
self.gui = plugin_action.gui
self.db = self.gui.current_db
def author_sort_from_authors(self, authors):
return self.db.new_api.author_sort_from_authors(authors, key_func=lambda x: x)
def book_lang(self, book_id):
try:
book_lang = self.db.new_api.field_for('languages', book_id)[0]
except:
book_lang = None
return book_lang
def swap_title_author(self, book_ids):
id_fields_maps = defaultdict(dict)
for book_id in book_ids:
old_title = self.db.new_api.field_for('title', book_id)
old_authors = self.db.new_api.field_for('authors', book_id)
new_authors = string_to_authors(old_title)
id_fields_maps['authors'][book_id] = new_authors
id_fields_maps['author_sort'][book_id] = self.author_sort_from_authors(new_authors)
new_title = authors_to_string(old_authors)
id_fields_maps['title'][book_id] = new_title
id_fields_maps['sort'][book_id] = title_sort(new_title, lang=self.book_lang(book_id))
for field, id_val_map in id_fields_maps.items():
self.db.new_api.set_field(field, id_val_map)
def run(self, gui, settings, chain):
book_ids = chain.scope().get_book_ids()
self.swap_title_author(book_ids)