From 07078bd55c7e986eb3d1f213e6e2c408d327b043 Mon Sep 17 00:00:00 2001
From: Dmitry Shelepnev <mitshel@mail.ru>
Date: Sun, 26 Feb 2017 15:35:19 +0300
Subject: [PATCH] Add extract_cover_memory for mobi books

---
 book_tools/format/__init__.py |  1 -
 book_tools/format/epub.py     |  1 +
 book_tools/format/mobi.py     | 10 ++++++++++
 book_tools/pymobi/mobi.py     |  9 +++++++++
 opds_catalog/dl.py            |  3 ++-
 opds_catalog/sopdscan.py      |  2 ++
 6 files changed, 24 insertions(+), 2 deletions(-)

diff --git a/book_tools/format/__init__.py b/book_tools/format/__init__.py
index b3228ee..b458c1b 100644
--- a/book_tools/format/__init__.py
+++ b/book_tools/format/__init__.py
@@ -77,7 +77,6 @@ def create_bookfile(file, original_filename):
     if isinstance(file, str):
         file = open(file, 'rb')
     mimetype = detect_mime(file)
-    file.seek(0,0)
     if mimetype == Mimetype.EPUB:
         return EPub(file, original_filename)
     elif mimetype == Mimetype.FB2:
diff --git a/book_tools/format/epub.py b/book_tools/format/epub.py
index 3331635..eb07f32 100644
--- a/book_tools/format/epub.py
+++ b/book_tools/format/epub.py
@@ -50,6 +50,7 @@ class EPub(BookFile):
         self.__initialize()
 
     def __initialize(self):
+        self.file.seek(0,0)
         self.__zip_file = zipfile.ZipFile(self.file)
         self.issues = []
         try:
diff --git a/book_tools/format/mobi.py b/book_tools/format/mobi.py
index a7e8c2c..9b43aaf 100644
--- a/book_tools/format/mobi.py
+++ b/book_tools/format/mobi.py
@@ -35,3 +35,13 @@ class Mobipocket(BookFile):
                 return (None, False)
         finally:
             shutil.rmtree(tmp_dir)
+
+    def extract_cover_memory(self):
+        try:
+            image = BookMobi(self.file).unpackMobiCover()
+        except Exception as err:
+            print(err)
+            image = None
+
+        return image
+
diff --git a/book_tools/pymobi/mobi.py b/book_tools/pymobi/mobi.py
index c91cc23..c0a713f 100644
--- a/book_tools/pymobi/mobi.py
+++ b/book_tools/pymobi/mobi.py
@@ -262,6 +262,7 @@ class BookMobi(object):
             f = file
         self.filename = f.name
         self.f = f
+        self.f.seek(0,0)
         # palm database header
         header = f.read(78)
         for key, u_fmt, offset in self.palmdb_format:
@@ -556,6 +557,14 @@ class BookMobi(object):
             self.saveRecordImage(cover_rn, '%s_cover' % basename)
         print('Unpack MOBI successfully')
 
+    def unpackMobiCover(self):
+        if 201 in self.mobi_exth:
+            cover_rn, = struct.unpack('>L', self.mobi_exth[201])
+            cover_rn += self.mobi['firstImageIndex']
+            rec = self.loadRecord(cover_rn)
+            return rec
+        return None
+
     def removeSrcs(self, outmobi, outsrcs=None):
         srcs_rn = self.mobi['srcsRecordNumber']
         srcs_rc = self.mobi['srcsRecordCount']
diff --git a/opds_catalog/dl.py b/opds_catalog/dl.py
index aa2b390..eb698f3 100644
--- a/opds_catalog/dl.py
+++ b/opds_catalog/dl.py
@@ -97,7 +97,7 @@ def Download(request, book_id, zip_flag):
 
     return response
 
-
+# Новая версия (0.42) процедуры извлечения обложек из файлов книг fb2, epub, mobi
 def Cover(request, book_id, thumbnail=False):
     """ Загрузка обложки """
     book = Book.objects.get(id=book_id)
@@ -153,6 +153,7 @@ def Cover(request, book_id, thumbnail=False):
 
     return response
 
+# Старая версия (до 0.41) процедуры извлечения обложек из файлов книг только fb2
 def Cover0(request, book_id, thumbnail = False):
     """ Загрузка обложки """
     book = Book.objects.get(id=book_id)
diff --git a/opds_catalog/sopdscan.py b/opds_catalog/sopdscan.py
index 8f6058b..bba06f2 100644
--- a/opds_catalog/sopdscan.py
+++ b/opds_catalog/sopdscan.py
@@ -195,6 +195,7 @@ class opdsScanner:
                 zip_process_error = 1
             self.bad_archives+=zip_process_error
 
+    # Новая версия (0.42) процедуры извлечения метаданных из файлов книг fb2, epub, mobi
     def processfile(self,name,full_path,file,cat,archive=0,file_size=0):
         (n, e) = os.path.splitext(name)
         if e.lower() in config.SOPDS_BOOK_EXTENSIONS.split():
@@ -246,6 +247,7 @@ class opdsScanner:
                 self.books_skipped+=1
                 self.logger.debug("Book "+rel_path+"/"+name+" Already in DB.")
 
+    # Старая версия (до 0.41) процедуры извлечения метаданных из файлов книг только fb2
     def processfile0(self,name,full_path,file,cat,archive=0,file_size=0):
         (n,e)=os.path.splitext(name)
         if e.lower() in config.SOPDS_BOOK_EXTENSIONS.split():
-- 
GitLab