View Single Post
Old 05-22-2025, 04:49 AM   #70
capink
Wizard
capink ought to be getting tired of karma fortunes by now.capink ought to be getting tired of karma fortunes by now.capink ought to be getting tired of karma fortunes by now.capink ought to be getting tired of karma fortunes by now.capink ought to be getting tired of karma fortunes by now.capink ought to be getting tired of karma fortunes by now.capink ought to be getting tired of karma fortunes by now.capink ought to be getting tired of karma fortunes by now.capink ought to be getting tired of karma fortunes by now.capink ought to be getting tired of karma fortunes by now.capink ought to be getting tired of karma fortunes by now.
 
Posts: 1,203
Karma: 1995558
Join Date: Aug 2015
Device: Kindle
Duplicate a book

Action to duplicate a book, originally written by bluefish2020

Code:
import os

from calibre_plugins.action_chains.actions.base import ChainAction

class DuplicateBookAction(ChainAction):
    name = 'Duplicate Book'
    support_scopes = True

    # code adapted from calibre/gui2/actions/add.py:add_empty()
    def run(self, gui, settings, chain):
        db = gui.current_db
        selected_books = chain.scope().get_book_ids()
        
        ids, orig_fmts = [], []
        for book_id in selected_books:
            metadata = db.get_metadata(book_id, index_is_id=True, get_cover=True, cover_as_data=True)
            orig_fmts = tuple(db.new_api.format(book_id, fmt, as_path=True) for fmt in db.new_api.formats(book_id))
            new_book_id = db.import_book(metadata, orig_fmts)
            ids.append(new_book_id)
            
        self.refresh_gui(gui, len(selected_books))
        # entirely optional: select and mark the copies
        if ids:
            ids.reverse()
            gui.library_view.select_rows(ids)
            db.set_marked_ids({id: 'duplicate' for id in ids})
        # clean up temp files created by new_api.format()
        for path in orig_fmts:
            os.remove(path)                        

    def refresh_gui(self, gui, num):
        gui.library_view.model().books_added(num)
        gui.refresh_cover_browser()
        gui.tags_view.recount()

Last edited by capink; 05-25-2025 at 09:01 PM.
capink is offline   Reply With Quote