1
0
mirror of https://github.com/ciromattia/kcc synced 2026-01-07 22:09:32 +00:00

Improved error handling

This commit is contained in:
Paweł Jastrzębski
2015-09-04 18:40:02 +02:00
parent 0988601842
commit c8698f6d99
3 changed files with 40 additions and 33 deletions

View File

@@ -430,16 +430,20 @@ class WorkerThread(QtCore.QThread):
GUI.progress.content = ''
self.errors = True
MW.addMessage.emit(str(warn), 'warning', False)
MW.addMessage.emit('Failed to create output file!', 'error', False)
MW.addTrayMessage.emit('Failed to create output file!', 'Critical')
MW.addMessage.emit('Error during conversion! Please consult '
'<a href="https://github.com/ciromattia/kcc/wiki/Error-messages">wiki</a> '
'for more details.', 'error', False)
MW.addTrayMessage.emit('Error during conversion!', 'Critical')
except Exception as err:
GUI.progress.content = ''
self.errors = True
_, _, traceback = sys.exc_info()
MW.showDialog.emit("Error during conversion %s:\n\n%s\n\nTraceback:\n%s"
% (jobargv[-1], str(err), sanitizeTrace(traceback)), 'error')
MW.addMessage.emit('Failed to create EPUB!', 'error', False)
MW.addTrayMessage.emit('Failed to create EPUB!', 'Critical')
MW.addMessage.emit('Error during conversion! Please consult '
'<a href="https://github.com/ciromattia/kcc/wiki/Error-messages">wiki</a> '
'for more details.', 'error', False)
MW.addTrayMessage.emit('Error during conversion!', 'Critical')
if not self.conversionAlive:
for item in outputPath:
if os.path.exists(item):
@@ -493,7 +497,7 @@ class WorkerThread(QtCore.QThread):
GUI.progress.content = ''
mobiPath = item.replace('.epub', '.mobi')
os.remove(mobiPath + '_toclean')
if GUI.targetDirectory and GUI.targetDirectory != os.path.split(mobiPath)[0]:
if GUI.targetDirectory and GUI.targetDirectory != os.path.dirname(mobiPath):
try:
move(mobiPath, GUI.targetDirectory)
mobiPath = os.path.join(GUI.targetDirectory, os.path.basename(mobiPath))
@@ -529,7 +533,7 @@ class WorkerThread(QtCore.QThread):
False)
else:
for item in outputPath:
if GUI.targetDirectory and GUI.targetDirectory != os.path.split(item)[0]:
if GUI.targetDirectory and GUI.targetDirectory != os.path.dirname(item):
try:
move(item, GUI.targetDirectory)
item = os.path.join(GUI.targetDirectory, os.path.basename(item))
@@ -540,8 +544,9 @@ class WorkerThread(QtCore.QThread):
GUI.progress.stop()
MW.hideProgressBar.emit()
GUI.needClean = True
MW.addMessage.emit('<b>All jobs completed.</b>', 'info', False)
MW.addTrayMessage.emit('All jobs completed.', 'Information')
if not self.errors:
MW.addMessage.emit('<b>All jobs completed.</b>', 'info', False)
MW.addTrayMessage.emit('All jobs completed.', 'Information')
MW.modeConvert.emit(1)

View File

@@ -647,44 +647,38 @@ def imgFileProcessing(work):
def getWorkFolder(afile):
if len(afile) > 240:
raise UserWarning("Path is too long.")
if os.path.isdir(afile):
workdir = mkdtemp('', 'KCC-')
try:
os.rmdir(workdir)
fullPath = os.path.join(workdir, 'OEBPS', 'Images')
if len(fullPath) > 240:
raise UserWarning("Path is too long.")
copytree(afile, fullPath)
sanitizePermissions(fullPath)
return workdir
except OSError:
except:
rmtree(workdir, True)
raise
raise UserWarning("Failed to prepare a workspace.")
elif afile.lower().endswith('.pdf'):
pdf = pdfjpgextract.PdfJpgExtract(afile)
path, njpg = pdf.extract()
if njpg == 0:
rmtree(path, True)
raise UserWarning("Failed to extract images.")
raise UserWarning("Failed to extract images from PDF file.")
else:
workdir = mkdtemp('', 'KCC-')
cbx = cbxarchive.CBxArchive(afile)
if cbx.isCbxFile():
try:
path = cbx.extract(workdir)
except OSError:
except:
rmtree(workdir, True)
raise UserWarning("Failed to extract file.")
raise UserWarning("Failed to extract archive.")
else:
rmtree(workdir, True)
raise TypeError("Failed to detect archive format.")
if len(os.path.join(path, 'OEBPS', 'Images')) > 240:
raise UserWarning("Path is too long.")
move(path, path + "_temp")
move(path + "_temp", os.path.join(path, 'OEBPS', 'Images'))
return path
raise UserWarning("Failed to detect archive format.")
newpath = mkdtemp('', 'KCC-')
move(path, os.path.join(newpath, 'OEBPS', 'Images'))
return newpath
def getOutputFilename(srcpath, wantedname, ext, tomeNumber):
@@ -841,13 +835,6 @@ def sanitizePermissions(filetree):
os.chmod(os.path.join(root, name), S_IWRITE | S_IREAD | S_IEXEC)
def sanitizeTemp():
for root, dirs, _ in walkLevel(gettempdir(), 0):
for tempdir in dirs:
if tempdir.startswith('KCC-'):
rmtree(os.path.join(root, tempdir), True)
# noinspection PyUnboundLocalVariable
def splitDirectory(path):
# Detect directory stucture
@@ -1046,7 +1033,7 @@ def createNewTome():
def slugify(value):
value = slugifyExt(value)
value = sub(r'0*([0-9]{4,})', r'\1', sub(r'([0-9]+)', r'0000\1', value))
value = sub(r'0*([0-9]{4,})', r'\1', sub(r'([0-9]+)', r'0000\1', value, count=2))
return value
@@ -1215,6 +1202,21 @@ def checkTools(source):
exit(1)
def checkPre(source):
# Make sure that all temporary files are gone
for root, dirs, _ in walkLevel(gettempdir(), 0):
for tempdir in dirs:
if tempdir.startswith('KCC-'):
rmtree(os.path.join(root, tempdir), True)
# Make sure that target directory is writable
if os.path.isdir(source):
writable = os.access(os.path.abspath(os.path.join(source, '..')), os.W_OK)
else:
writable = os.access(os.path.dirname(source), os.W_OK)
if not writable:
raise UserWarning("Target directory is not writable.")
def makeBook(source, qtGUI=None):
"""Generates MOBI/EPUB/CBZ comic ebook from a bunch of images."""
global GUI
@@ -1223,7 +1225,7 @@ def makeBook(source, qtGUI=None):
GUI.progressBarTick.emit('1')
else:
checkTools(source)
sanitizeTemp()
checkPre(source)
path = getWorkFolder(source)
print("\nChecking images...")
getComicInfo(os.path.join(path, "OEBPS", "Images"), source)

View File

@@ -509,4 +509,4 @@ class Cover:
try:
self.image.save(self.target, "JPEG", optimize=1, quality=80)
except IOError:
raise RuntimeError('Failed to save cover')
raise RuntimeError('Failed to process downloaded cover.')