about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPaweł Jastrzębski <[email protected]>2015-10-25 20:04:21 +0100
committerPaweł Jastrzębski <[email protected]>2015-10-25 20:04:21 +0100
commita93da2136b4d109c0b13e5211fcaa0ecef2b9018 (patch)
treec6369ce47636f6ca0d597759ece29e5abe7af551
parentEscape special characters in TOC (diff)
downloadkcc-a93da2136b4d109c0b13e5211fcaa0ecef2b9018.tar.gz
kcc-a93da2136b4d109c0b13e5211fcaa0ecef2b9018.tar.bz2
kcc-a93da2136b4d109c0b13e5211fcaa0ecef2b9018.zip
Added cover upload
-rwxr-xr-xkcc/comic2ebook.py22
-rwxr-xr-xkcc/image.py8
-rw-r--r--kcc/kindle.py42
3 files changed, 65 insertions, 7 deletions
diff --git a/kcc/comic2ebook.py b/kcc/comic2ebook.py
index 3a50e5c..adc3d0a 100755
--- a/kcc/comic2ebook.py
+++ b/kcc/comic2ebook.py
@@ -53,6 +53,7 @@ from . import cbxarchive
 from . import pdfjpgextract
 from . import dualmetafix
 from . import metadata
+from . import kindle
 from . import __version__
 
 
@@ -197,7 +198,6 @@ def buildHTML(path, imgfile, imgfilepath):
 
 
 def buildNCX(dstdir, title, chapters, chapterNames):
-    options.uuid = str(uuid4())
     ncxfile = os.path.join(dstdir, 'OEBPS', 'toc.ncx')
     f = open(ncxfile, "w", encoding='UTF-8')
     f.writelines(["<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
@@ -465,7 +465,8 @@ def buildEPUB(path, chapterNames, tomeNumber):
                 if cover is None:
                     cover = os.path.join(os.path.join(path, 'OEBPS', 'Images'),
                                          'cover' + getImageFileName(filelist[-1][1])[1])
-                    image.Cover(os.path.join(filelist[-1][0], filelist[-1][1]), cover, options, tomeNumber)
+                    options.covers.append((image.Cover(os.path.join(filelist[-1][0], filelist[-1][1]), cover, options,
+                                                       tomeNumber), options.uuid))
     # Overwrite chapternames if tree is flat and ComicInfo.xml has bookmarks
     if not chapterNames and options.chapters:
         chapterlist = []
@@ -678,7 +679,7 @@ def getCoversFromMCB(mangaID):
     try:
         jsonRaw = urlopen(Request('http://mcd.iosphe.re/api/v1/series/' + mangaID + '/',
                                   headers={'User-Agent': 'KindleComicConverter/' + __version__}))
-        jsonData = loads(jsonRaw.readall().decode('utf-8'))
+        jsonData = loads(jsonRaw.read().decode('utf-8'))
         for volume in jsonData['Covers']['a']:
             if volume['Side'] == 'front':
                 covers[int(volume['Volume'])] = volume['Raw']
@@ -1141,7 +1142,9 @@ def makeBook(source, qtGUI=None):
         GUI.progressBarTick.emit(str(len(tomes) + 1))
         GUI.progressBarTick.emit('tick')
     options.baseTitle = options.title
+    options.covers = []
     for tome in tomes:
+        options.uuid = str(uuid4())
         if len(tomes) > 9:
             tomeNumber += 1
             options.title = options.baseTitle + ' [' + str(tomeNumber).zfill(2) + '/' + str(len(tomes)).zfill(2) + ']'
@@ -1168,8 +1171,9 @@ def makeBook(source, qtGUI=None):
         if GUI:
             GUI.progressBarTick.emit('tick')
     if not GUI and options.format == 'MOBI':
-        print("Creating MOBI file...")
+        print("Creating MOBI files...")
         work = []
+        k = kindle.Kindle()
         for i in filepath:
             work.append([i])
         output = makeMOBI(work, GUI)
@@ -1178,22 +1182,26 @@ def makeBook(source, qtGUI=None):
                 print('Error: KindleGen failed to create MOBI!')
                 print(errors)
                 return filepath
+        if k.path and k.coverSupport:
+            print("Kindle detected. Uploading covers...")
         for i in filepath:
-            output = makeMOBIFix(i)
+            output = makeMOBIFix(i, options.covers[filepath.index(i)][1])
             if not output[0]:
                 print('Error: Failed to tweak KindleGen output!')
                 return filepath
             else:
                 os.remove(i.replace('.epub', '.mobi') + '_toclean')
+            if k.path and k.coverSupport:
+                options.covers[filepath.index(i)][0].saveToKindle(k, options.covers[filepath.index(i)][1])
     return filepath
 
 
-def makeMOBIFix(item):
+def makeMOBIFix(item, uuid):
     os.remove(item)
     mobiPath = item.replace('.epub', '.mobi')
     move(mobiPath, mobiPath + '_toclean')
     try:
-        dualmetafix.DualMobiMetaFix(mobiPath + '_toclean', mobiPath, bytes(options.uuid, 'UTF-8'))
+        dualmetafix.DualMobiMetaFix(mobiPath + '_toclean', mobiPath, bytes(uuid, 'UTF-8'))
         return [True]
     except Exception as err:
         return [False, format(err)]
diff --git a/kcc/image.py b/kcc/image.py
index dc6dbee..6dd4d98 100755
--- a/kcc/image.py
+++ b/kcc/image.py
@@ -453,3 +453,11 @@ class Cover:
             self.image.save(self.target, "JPEG", optimize=1, quality=80)
         except IOError:
             raise RuntimeError('Failed to process downloaded cover.')
+
+    def saveToKindle(self, kindle, asin):
+        self.image = self.image.resize((300, 470), Image.ANTIALIAS).convert('L')
+        try:
+            self.image.save(os.path.join(kindle.path.split('documents')[0], 'system', 'thumbnails',
+                                         'thumbnail_' + asin + '_EBOK_portrait.jpg'), 'JPEG')
+        except IOError:
+            raise RuntimeError('Failed to upload cover.')
diff --git a/kcc/kindle.py b/kcc/kindle.py
new file mode 100644
index 0000000..ddfe1d5
--- /dev/null
+++ b/kcc/kindle.py
@@ -0,0 +1,42 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2013-2015 Pawel Jastrzebski <[email protected]>
+#
+# Permission to use, copy, modify, and/or distribute this software for
+# any purpose with or without fee is hereby granted, provided that the
+# above copyright notice and this permission notice appear in all
+# copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
+# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
+# AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
+# DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
+# OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+# PERFORMANCE OF THIS SOFTWARE.
+
+import os.path
+import psutil
+
+
+class Kindle:
+    def __init__(self):
+        self.path = self.findDevice()
+        if self.path:
+            self.coverSupport = self.checkThumbnails()
+        else:
+            self.coverSupport = False
+
+    def findDevice(self):
+        for drive in psutil.disk_partitions(False):
+            if 'removable' in drive[3] or 'vfat' in drive[2] or 'msdos' in drive[2]:
+                if os.path.isdir(os.path.join(drive[1], 'system')) and \
+                        os.path.isdir(os.path.join(drive[1], 'documents')):
+                    return drive[1]
+        return False
+
+    def checkThumbnails(self):
+        if os.path.isdir(os.path.join(self.path, 'system', 'thumbnails')):
+            return True
+        return False