about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPaweł Jastrzębski <pawelj@iosphe.re>2015-09-04 18:40:02 +0200
committerPaweł Jastrzębski <pawelj@iosphe.re>2015-09-04 18:40:02 +0200
commitc8698f6d99ce2f9c5a9d9970ccb4eb2d264c1866 (patch)
treefb2ac80653c3db23162a6b525637d26308ef5660
parentImplemented new method to detect color images (diff)
downloadkcc-c8698f6d99ce2f9c5a9d9970ccb4eb2d264c1866.tar.gz
kcc-c8698f6d99ce2f9c5a9d9970ccb4eb2d264c1866.tar.bz2
kcc-c8698f6d99ce2f9c5a9d9970ccb4eb2d264c1866.zip
Improved error handling
-rw-r--r--kcc/KCC_gui.py21
-rwxr-xr-xkcc/comic2ebook.py50
-rwxr-xr-xkcc/image.py2
3 files changed, 40 insertions, 33 deletions
diff --git a/kcc/KCC_gui.py b/kcc/KCC_gui.py
index 421d73b..45e5ba7 100644
--- a/kcc/KCC_gui.py
+++ b/kcc/KCC_gui.py
@@ -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)
 
 
diff --git a/kcc/comic2ebook.py b/kcc/comic2ebook.py
index a80fa50..4f27f68 100755
--- a/kcc/comic2ebook.py
+++ b/kcc/comic2ebook.py
@@ -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)
diff --git a/kcc/image.py b/kcc/image.py
index 0cf4ac7..b98bc2a 100755
--- a/kcc/image.py
+++ b/kcc/image.py
@@ -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.')