Commit 5c5e746d authored by Dmitry Shelepnev's avatar Dmitry Shelepnev
Browse files

End of day commit

parent 0196135f
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
#    Simple OPDS - программа для каталогизации электронных книг и организации
#                  доступа к ним с использованием протокола OPDS.
#    Copyright (C)2014, Дмитрий Шелепнёв
#    Copyright (C)2017, Дмитрий Шелепнёв
#
#    Это программа является свободным программным обеспечением. Вы можете
#    распространять и/или модифицировать её согласно условиям Стандартной

book_tools/LICENSE

0 → 100644
+22 −0
Original line number Diff line number Diff line
The MIT License (MIT)

Copyright (c) 2014 FBReader.ORG Limited

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

book_tools/__init__.py

0 → 100644
+0 −0

Empty file added.

+111 −0
Original line number Diff line number Diff line
#import magic
import os
import zipfile
from xml import sax

from book_tools.format.mimetype import Mimetype

from book_tools.format.util import list_zip_file_infos
from book_tools.format.epub import EPub
from book_tools.format.fb2 import FB2, FB2Zip
#from fbreader.format.pdf import PDF
#from fbreader.format.msword import MSWord
from book_tools.format.mobi import Mobipocket
#from fbreader.format.rtf import RTF
#from fbreader.format.djvu import DjVu
#from fbreader.format.dummy import Dummy

#__detector = magic.open(magic.MAGIC_MIME_TYPE)
#__detector.load()

class __detector:
    @staticmethod
    def file(filename):
        (n, e) = os.path.splitext(filename)
        if e.lower() == '.fb2':
            return Mimetype.FB2
        elif e.lower()=='.epub' or e.lower()=='.zip':
            return Mimetype.ZIP
        elif e.lower()=='.pdf':
            return Mimetype.PDF
        elif e.lower()=='.doc' or e.lower()=='.docx':
            return Mimetype.MSWORD
        elif e.lower()=='.djvu':
            return Mimetype.DJVU
        elif e.lower()=='.txt':
            return Mimetype.TEXT
        elif e.lower()=='.rtf':
            return Mimetype.RTF
        else:
            return Mimetype.OCTET_STREAM

def detect_mime(file):
    FB2_ROOT = 'FictionBook'
    mime = __detector.file(file.name)

    try:
        if mime == Mimetype.XML or mime == Mimetype.FB2:
            if FB2_ROOT == __xml_root_tag(file):
                return Mimetype.FB2
        elif mime == Mimetype.ZIP:
            with zipfile.ZipFile(file) as zip_file:
                if not zip_file.testzip():
                    infolist = list_zip_file_infos(zip_file)
                    if len(infolist) == 1:
                        if FB2_ROOT == __xml_root_tag(zip_file.open(infolist[0])):
                            return Mimetype.FB2_ZIP
                    try:
                        with zip_file.open('mimetype') as mimetype_file:
                            if mimetype_file.read(30).decode().rstrip('\n\r') == Mimetype.EPUB:
                                return Mimetype.EPUB
                    except Exception as e:
                        pass
        elif mime == Mimetype.OCTET_STREAM:
            mobiflag =  file.read(68)
            if mobiflag.decode()[60:] == 'BOOKMOBI':
                return Mimetype.MOBI
    except:
        pass

    return mime

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:
        return FB2(file, original_filename)
    elif mimetype == Mimetype.FB2_ZIP:
        return FB2Zip(file, original_filename)
    elif mimetype == Mimetype.MOBI:
        return Mobipocket(file, original_filename)
#    elif mimetype == Mimetype.PDF:
#        return PDF(path, original_filename)
#    elif mimetype == Mimetype.MSWORD:
#        return MSWord(path, original_filename)
#    elif mimetype == Mimetype.RTF:
#        return RTF(path, original_filename)
#    elif mimetype == Mimetype.DJVU:
#        return DjVu(path, original_filename)
#    elif mimetype in [Mimetype.TEXT]:
#        return Dummy(path, original_filename, mimetype)
    else:
        raise Exception('File type \'%s\' is not supported, sorry' % mimetype)

def __xml_root_tag(file):
    class XMLRootFound(Exception):
        def __init__(self, name):
            self.name = name

    class RootTagFinder(sax.handler.ContentHandler):
        def startElement(self, name, attributes):
            raise XMLRootFound(name)

    try:
        sax.parse(file, RootTagFinder())
    except XMLRootFound as e:
        return e.name
    return None
+34 −0
Original line number Diff line number Diff line
import gzip, os
#from Crypto.Cipher import AES
from tempfile import mktemp

def encrypt(file_name, key, working_dir):
    '''
    file_name:     full path to file to encrypt
    key:           16 byte string
    working_dir:   directory to create temorary files
    '''
    # tmp_file_name = mktemp(dir=working_dir)
    # with open(file_name, 'rb') as istream:
    #     with gzip.open(tmp_file_name, 'wb') as ostream:
    #         ostream.writelines(istream)
    #
    # init_vector = os.urandom(16)
    #
    # mode = AES.MODE_CBC
    # encryptor = AES.new(key, mode, init_vector)
    #
    # with open(tmp_file_name, 'rb') as istream:
    #     with open(file_name, 'wb') as ostream:
    #         ostream.write(init_vector)
    #         while True:
    #             data = istream.read(8192)
    #             if len(data) == 8192:
    #                 ostream.write(encryptor.encrypt(data))
    #             else:
    #                 pad = 16 - len(data) % 16
    #                 ostream.write(encryptor.encrypt(data + pad * chr(pad)))
    #                 break
    #
    # os.remove(tmp_file_name)
    pass
Loading