I'm trying to write a plugin which will zero the ratings on any books which are imported.
I thought this would be a simple job, but sadly it is proving a little more fiddly than I'd expect. Looking at the documentation I see that I need a FileTypePlugin, and there is the ability to call a method post-import, which sounds like it should do the right thing.
My code looks like this:
Code:
import os
from calibre.customize import FileTypePlugin
from calibre.ebooks.metadata.meta import get_metadata, set_metadata
class ZeroRatingsPlugin(FileTypePlugin):
name = 'Reset Rating Plugin'
description = 'When a book is imported set the rating to zero.'
supported_platforms = ['windows', 'osx', 'linux']
author = 'Mysql.'
version = (1, 0, 1)
file_types = set(['epub', 'mobi', 'lit', 'prc'])
on_import = True
on_postimport = True
minimum_calibre_version = (2,0,0)
def run(self, path_to_ebook):
'''
NOP
'''
print "ZeroRatings::run(%s)" % path_to_ebook
return path_to_ebook
def postimport( book_id, book_format, db):
'''
Find the path to the book, and zero the rating.
'''
print "ZeroRatings::postimport()"
if db is None:
from calibre.library import db
db = db() # initialize calibre library database
path_to_ebook = db.format_abspath(book_id, book_format, index_is_id=True)
print( "Path to book is %s" % path_to_ebook )
file = open(path_to_ebook, 'r+b')
print "Book is at " , path_to_ebook
ext = os.path.splitext(path_to_ebook)[-1][1:].lower()
mi = get_metadata(file, ext)
print "Current rating is:", mi.rating
mi.rating = 0
set_metadata(file, mi, ext)
(Obviously the last part of the code is work in progress, and I've been able to test it due to the problem I'm having)
When I import a book I see this
Code:
ZeroRatings::run(/home/skx/test/foo.epub)
(I'm testing via "calibre-debug -s; calibre-customize -b $(pwd); calibre-debug -g", from my plugin-directory.)
That suggests that my Plugins run method is called but NOT the postimport method.
I get the feeling I'm missing something obvious, but I'm not sure what that might be.