epub: use metadata.cover if set

This commit is contained in:
j 2016-01-05 15:20:47 +05:30
parent 78c9c5443f
commit ca3888869b

View file

@ -26,16 +26,26 @@ def cover(path):
except zipfile.BadZipFile: except zipfile.BadZipFile:
logger.debug('invalid epub file %s', path) logger.debug('invalid epub file %s', path)
return data return data
def use(filename):
logger.debug('using %s', filename)
return z.read(filename)
for f in z.filelist: for f in z.filelist:
if 'cover' in f.filename.lower() and f.filename.split('.')[-1] in ('jpg', 'jpeg', 'png'): if 'cover' in f.filename.lower() and f.filename.split('.')[-1] in ('jpg', 'jpeg', 'png'):
logger.debug('using %s', f.filename) return use(f.filename)
data = z.read(f.filename)
break
if not data:
files = [f.filename for f in z.filelist] files = [f.filename for f in z.filelist]
opf = [f for f in files if f.endswith('opf')] opf = [f for f in files if f.endswith('opf')]
if opf: if opf:
#logger.debug('opf: %s', z.read(opf[0]).decode())
info = ET.fromstring(z.read(opf[0])) info = ET.fromstring(z.read(opf[0]))
metadata = info.findall('{http://www.idpf.org/2007/opf}metadata')[0]
for e in metadata.getchildren():
if e.tag == '{http://www.idpf.org/2007/opf}meta' and e.attrib['name'] == 'cover':
filename = e.attrib['content']
filename = [f for f in files if filename in f]
if filename:
return use(filename[0])
manifest = info.findall('{http://www.idpf.org/2007/opf}manifest')[0] manifest = info.findall('{http://www.idpf.org/2007/opf}manifest')[0]
images = [e for e in manifest.getchildren() if 'image' in e.attrib['media-type']] images = [e for e in manifest.getchildren() if 'image' in e.attrib['media-type']]
if images: if images:
@ -48,7 +58,8 @@ def cover(path):
if image_data: if image_data:
image_data.sort(key=lambda i: len(i[1])) image_data.sort(key=lambda i: len(i[1]))
data = image_data[-1][1] data = image_data[-1][1]
if not data: logger.debug('using %s', image_data[-1][0])
return data
for e in manifest.getchildren(): for e in manifest.getchildren():
if 'html' in e.attrib['media-type']: if 'html' in e.attrib['media-type']:
filename = unquote(e.attrib['href']) filename = unquote(e.attrib['href'])
@ -61,10 +72,8 @@ def cover(path):
img = unquote(img[0]) img = unquote(img[0])
img = os.path.normpath(os.path.join(os.path.dirname(filename), img)) img = os.path.normpath(os.path.join(os.path.dirname(filename), img))
if img in files: if img in files:
logger.debug('using %s', img) return use(img)
data = z.read(img) # fallback return black cover
break
if not data:
img = Image.new('RGB', (80, 128)) img = Image.new('RGB', (80, 128))
o = BytesIO() o = BytesIO()
img.save(o, format='jpeg') img.save(o, format='jpeg')