1
# -*- coding: utf-8 -*-
4
Read meta information from eReader pdb files.
8
__copyright__ = '2009, John Schember <john@nachtimwald.com>'
9
__docformat__ = 'restructuredtext en'
13
from calibre.ebooks.metadata import MetaInformation
14
from calibre.ebooks.metadata import authors_to_string
15
from calibre.ebooks.pdb.ereader.reader132 import HeaderRecord
16
from calibre.ebooks.pdb.header import PdbHeaderBuilder
17
from calibre.ebooks.pdb.header import PdbHeaderReader
19
def get_metadata(stream, extract_cover=True):
21
Return metadata as a L{MetaInfo} object
23
mi = MetaInformation(None, [_('Unknown')])
26
pheader = PdbHeaderReader(stream)
28
# Only Dropbook produced 132 byte record0 files are supported
29
if len(pheader.section_data(0)) == 132:
30
hr = HeaderRecord(pheader.section_data(0))
32
if hr.version in (2, 10) and hr.has_metadata == 1:
34
mdata = pheader.section_data(hr.metadata_offset)
36
mdata = mdata.split('\x00')
38
mi.authors = [mdata[1]]
39
mi.publisher = mdata[3]
45
mi.title = pheader.title if pheader.title else _('Unknown')
49
def set_metadata(stream, mi):
50
pheader = PdbHeaderReader(stream)
52
# Only Dropbook produced 132 byte record0 files are supported
53
if pheader.section_data(0) != 132:
56
sections = [pheader.section_data(x) for x in range(0, pheader.section_count())]
57
hr = HeaderRecord(sections[0])
59
if hr.version not in (2, 10):
62
# Create a metadata record for the file if one does not alreay exist
63
if not hr.has_metadata:
64
sections += ['', 'MeTaInFo\x00']
65
last_data = len(sections) - 1
67
for i in range(0, 132, 2):
68
val, = struct.unpack('>H', sections[0][i:i + 2])
69
if val >= hr.last_data_offset:
70
sections[0][i:i + 2] = struct.pack('>H', last_data)
72
sections[0][24:26] = struct.pack('>H', 1) # Set has metadata
73
sections[0][44:46] = struct.pack('>H', last_data - 1) # Set location of metadata
74
sections[0][52:54] = struct.pack('>H', last_data) # Ensure last data offset is updated
76
# Merge the metadata into the file
77
file_mi = get_metadata(stream, False)
78
file_mi.smart_update(mi)
79
sections[hr.metadata_offset] = '%s\x00%s\x00%s\x00%s\x00%s\x00' % \
80
(file_mi.title, authors_to_string(file_mi.authors), '', file_mi.publisher, file_mi.isbn)
82
# Rebuild the PDB wrapper because the offsets have changed due to the
84
pheader_builder = PdbHeaderBuilder(pheader.ident, pheader.title)
87
pheader_builder.build_header([len(x) for x in sections], stream)
89
# Write the data back to the file