public
Last active

Modification to the standard Kindle device interface plug-in for Calibre which takes care of updating the *.mbp metadata for newly generated *.mobi files in case an earlier version existed. Only needed for Kindle devices before the Touch generation.

  • Download Gist
gistfile1.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
import os
import struct
 
from calibre.devices.kindle.driver import KINDLE2
from calibre.ebooks.metadata.mobi import get_metadata
 
 
class KINDLE2(KINDLE2):
name = '%s MBP Update Mod' % KINDLE2.name.replace('/', ', ')
author = '%s, cryzed' % KINDLE2.author
description = '%s If *.mbp files are available they will be updated to match possibly changed *.mobi files.' % KINDLE2.description
 
def upload_books(self, files, names, on_card=None, end_session=True, metadata=None):
device_path = self._sanity_check(on_card, files)
original = []
 
# Collect original UIDs for *.mobi files with an associated *.mbp file
for name, metadatum in zip(names, metadata):
path = self.normalize_path(self.create_upload_path(device_path, metadatum, name))
mbp_path = '%s.mbp' % os.path.splitext(path)[0]
 
# No *.mbp file is associated with the *.mobi file, ignore this item
if not os.path.exists(mbp_path):
continue
 
with open(path, 'rb') as file:
metadata_ = get_metadata(file)
original.append((path, mbp_path, metadata_.uid))
 
# Replace old *.mobi files with new *.mobi files. The UIDs might have
# changed at this point.
result = super(KINDLE2, self).upload_books(files, names, on_card, end_session, metadata)
 
# Update the UIDs within the *.mbp files to match the new *.mobi files'
for path, mbp_path, uid in original:
with open(path, 'rb') as file:
# Retrieve the metadata from the updated *.mobi file
metadata = get_metadata(file)
 
with open(mbp_path, 'rb') as file:
content = file.read()
 
# Replace the old UID with the new one
uid = struct.pack('>I', uid)
new_uid = struct.pack('>I', metadata.uid)
content = content.replace(uid, new_uid)
with open(mbp_path, 'wb') as file:
file.write(content)
 
return result

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.