1
0
mirror of https://github.com/ciromattia/kcc synced 2025-12-13 09:46:25 +00:00

Use python-magic (https://github.com/ahupp/python-magic) to get mimetype from files (extension does not matter anymore)

This commit is contained in:
Ciro Mattia Gonano
2013-03-07 11:54:37 +01:00
parent c9d558a353
commit 640b5117f9
2 changed files with 29 additions and 18 deletions

View File

@@ -19,16 +19,22 @@ __copyright__ = '2012-2013, Ciro Mattia Gonano <ciromattia@gmail.com>'
__docformat__ = 'restructuredtext en'
import os
import magic
class CBxArchive:
def __init__(self, origFileName):
self.cbxexts = ['.zip', '.cbz', '.rar', '.cbr']
self.origFileName = origFileName
self.filename = os.path.splitext(origFileName)
mime = magic.from_buffer(open(origFileName).read(1024), mime=True)
if mime == 'application/x-rar':
self.compressor = 'rar'
elif mime == 'application/zip':
self.compressor = 'zip'
else:
self.compressor = None
def isCbxFile(self):
return self.filename[1].lower() in self.cbxexts
return self.compressor is not None
def extractCBZ(self, targetdir):
try:
@@ -59,16 +65,16 @@ class CBxArchive:
pass # skip MacOS special files
elif f.endswith('/'):
try:
os.makedirs(os.path.join(targetdir,f))
os.makedirs(os.path.join(targetdir, f))
except:
pass # the dir exists so we are going to extract the images only.
else:
cbrFile.extract(f, targetdir)
def extract(self, targetdir):
if '.cbr' == self.filename[1].lower() or '.rar' == self.filename[1].lower():
if self.compressor == 'rar':
self.extractCBR(targetdir)
elif '.cbz' == self.filename[1].lower() or '.zip' == self.filename[1].lower():
elif self.compressor == 'zip':
self.extractCBZ(targetdir)
adir = os.listdir(targetdir)
if len(adir) == 1 and os.path.isdir(os.path.join(targetdir, adir[0])):

View File

@@ -384,7 +384,6 @@ def genEpubStruct(path):
def getWorkFolder(afile):
workdir = tempfile.mkdtemp()
fname = os.path.splitext(afile)
if os.path.isdir(afile):
try:
import shutil
@@ -393,19 +392,25 @@ def getWorkFolder(afile):
path = workdir
except OSError:
raise
elif fname[1].lower() == '.pdf':
else:
import magic
mime = magic.from_buffer(open(afile).read(1024), mime=True)
if mime == 'application/pdf':
pdf = pdfjpgextract.PdfJpgExtract(afile)
path = pdf.extract()
else:
elif mime == 'application/x-rar' or mime == 'application/zip':
cbx = cbxarchive.CBxArchive(afile)
if cbx.isCbxFile():
try:
path = cbx.extract(workdir)
except OSError:
print 'Unrar not found, please download from http://www.rarlab.com/download.htm and put into your PATH.'
print 'Unrar not found, please download from ' + \
'http://www.rarlab.com/download.htm and put into your PATH.'
sys.exit(21)
else:
raise TypeError
else:
raise TypeError
move(path, path + "_temp")
move(path + "_temp", os.path.join(path, 'OEBPS', 'Images'))
return path