예제 #1
0
파일: wrapper.py 프로젝트: f0829/Sigil
 def copy_book_contents_to(self, destdir):
     destdir = unicode_str(destdir)
     if destdir is None or not unipath.isdir(destdir):
         raise WrapperException('destination directory does not exist')
     for id in self.id_to_filepath:
         rpath = self.id_to_filepath[id]
         in_manifest = id in self.id_to_mime
         data = self.readfile(id)
         filepath = os.path.join(destdir, rpath)
         base = os.path.dirname(filepath)
         if not unipath.exists(base):
             os.makedirs(base)
         if isinstance(data, text_type):
             data = utf8_str(data)
         with open(pathof(filepath), 'wb') as fp:
             fp.write(data)
     for id in self.book_href_to_filepath:
         rpath = self.book_href_to_filepath[id]
         data = self.readotherfile(id)
         filepath = os.path.join(destdir, rpath)
         base = os.path.dirname(filepath)
         if not unipath.exists(base):
             os.makedirs(base)
         if isinstance(data, text_type):
             data = utf8_str(data)
         with open(pathof(filepath), 'wb') as fp:
             fp.write(data)
예제 #2
0
 def copy_book_contents_to(self, destdir):
     destdir = unicode_str(destdir)
     if destdir is None or not unipath.isdir(destdir):
         raise WrapperException('destination directory does not exist')
     for id in self.id_to_filepath:
         rpath = self.id_to_filepath[id]
         in_manifest = id in self.id_to_mime
         data = self.readfile(id)
         filepath = os.path.join(destdir,rpath)
         base = os.path.dirname(filepath)
         if not unipath.exists(base):
             os.makedirs(base)
         if isinstance(data,text_type):
             data = utf8_str(data)
         with open(pathof(filepath),'wb') as fp:
             fp.write(data)
     for id in self.book_href_to_filepath:
         rpath = self.book_href_to_filepath[id]
         data = self.readotherfile(id)
         filepath = os.path.join(destdir,rpath)
         base = os.path.dirname(filepath)
         if not unipath.exists(base):
             os.makedirs(base)
         if isinstance(data,text_type):
             data = utf8_str(data)
         with open(pathof(filepath),'wb') as fp:
             fp.write(data)
예제 #3
0
    def makeImages(self, fname, cover_offset):
        bname = os.path.normpath(os.path.join(self.outdir, '..', fname))
        #bname = os.path.join(bname, "Images")

        if not unipath.exists(bname):
            unipath.makedirs(bname)

        # ready to build images
        if unipath.exists(self.k8images):
            distutils.dir_util.copy_tree(self.k8images, bname)
        else:
            distutils.dir_util.copy_tree(self.imgdir, bname)

        # HDイメージ差し替え
        replaceHDimages(self.HDimages, bname, cover_offset)
예제 #4
0
def replaceHDimages(src_dir, dest_dir, cover_offset):
    # HDイメージ差し替え
    if unipath.exists(src_dir):
        distutils.dir_util.copy_tree(src_dir, dest_dir)

        # HDカバー画像をリネーム
        if cover_offset is not None:
            imgtype = 'jpg'
            imgname = "image%05d.%s" % (cover_offset + 1, imgtype)
            imgpath = os.path.join(dest_dir, imgname)
            cvrname = "cover%05d.%s" % (cover_offset + 1, imgtype)
            cvrpath = os.path.join(dest_dir, cvrname)
            if unipath.exists(imgpath):
                if unipath.exists(cvrpath):
                    os.remove(cvrpath)
                os.rename(imgpath, cvrpath)
예제 #5
0
파일: wrapper.py 프로젝트: f0829/Sigil
 def readotherfile(self, book_href):
     id = unicode_str(book_href)
     id = unquoteurl(id)
     if id is None:
         raise WrapperException('None is not a valid book href')
     if id not in self.other and id in self.id_to_href:
         raise WrapperException(
             'Incorrect interface routine - use readfile')
     # handle special case of trying to read the opf after it has been modified
     if id == "OEBPS/content.opf":
         if id in self.modified:
             return self.build_opf()
     filepath = self.book_href_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('Book href does not exist')
     basedir = self.ebook_root
     if id in self.added or id in self.modified:
         basedir = self.outdir
     filepath = os.path.join(basedir, filepath)
     if not unipath.exists(filepath):
         raise WrapperException('File Does Not Exist')
     basename = os.path.basename(filepath)
     ext = os.path.splitext(basename)[1]
     ext = ext.lower()
     mime = ext_mime_map.get(ext, "")
     data = b''
     with open(filepath, 'rb') as fp:
         data = fp.read()
     if mime in TEXT_MIMETYPES:
         data = unicode_str(data)
     return data
예제 #6
0
파일: wrapper.py 프로젝트: pwr/Sigil
 def deletefile(self, id):
     id = unicode_str(id)
     filepath = self.id_to_filepath.get(id, None)
     if id is None:
         raise WrapperException('id does not exist in manifest')
     add_to_deleted = True
     # if file was added or modified, delete file from outdir
     if id in self.added or id in self.modified:
         filepath = os.path.join(self.outdir,filepath)
         if unipath.exists(filepath) and unipath.isfile(filepath):
             os.remove(pathof(filepath))
         if id in self.added:
             self.added.remove(id)
             add_to_deleted = False
         if id in self.modified:
             del self.modified[id]
     # remove from manifest
     href = self.id_to_href[id]
     del self.id_to_href[id]
     del self.id_to_mime[id]
     del self.href_to_id[href]
     # remove from spine
     new_spine = []
     was_modified = False
     for sid, linear in self.spine:
         if sid != id:
             new_spine.append((sid, linear))
         else:
             was_modified = True
     if was_modified:
         setspine(new_spine)
     if add_to_deleted:
         self.deleted.append(id)
         self.modified['OEBPS/content.opf'] = 'file'
     del self.id_to_filepath[id]
예제 #7
0
 def deletefile(self, id):
     id = unicode_str(id)
     filepath = self.id_to_filepath.get(id, None)
     if id is None:
         raise WrapperException('id does not exist in manifest')
     add_to_deleted = True
     # if file was added or modified, delete file from outdir
     if id in self.added or id in self.modified:
         filepath = os.path.join(self.outdir, filepath)
         if unipath.exists(filepath) and unipath.isfile(filepath):
             os.remove(pathof(filepath))
         if id in self.added:
             self.added.remove(id)
             add_to_deleted = False
         if id in self.modified:
             del self.modified[id]
     # remove from manifest
     href = self.id_to_href[id]
     del self.id_to_href[id]
     del self.id_to_mime[id]
     del self.href_to_id[href]
     # remove from spine
     new_spine = []
     was_modified = False
     for sid, linear in self.spine:
         if sid != id:
             new_spine.append((sid, linear))
         else:
             was_modified = True
     if was_modified:
         setspine(new_spine)
     if add_to_deleted:
         self.deleted.append(id)
         self.modified['OEBPS/content.opf'] = 'file'
     del self.id_to_filepath[id]
예제 #8
0
파일: wrapper.py 프로젝트: f0829/Sigil
 def deleteotherfile(self, book_href):
     id = unicode_str(book_href)
     id = unquoteurl(id)
     if id is None:
         raise WrapperException('None is not a valid book hrefbook href')
     if id not in self.other and id in self.id_to_href:
         raise WrapperException(
             'Incorrect interface routine - use deletefile')
     filepath = self.book_href_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('Book href does not exist')
     if id in PROTECTED_FILES:
         raise WrapperException('attempt to delete protected file')
     add_to_deleted = True
     # if file was added or modified delete file from outdir
     if id in self.added or id in self.modified:
         filepath = os.path.join(self.outdir, filepath)
         if unipath.exists(filepath) and unipath.isfile(filepath):
             os.remove(filepath)
         if id in self.added:
             self.added.remove(id)
             add_to_deleted = False
         if id in self.other:
             self.other.remove(id)
         if id in self.modified:
             del self.modified[id]
     if add_to_deleted:
         self.deleted.append(('other', id, book_href))
     del self.book_href_to_filepath[id]
예제 #9
0
파일: wrapper.py 프로젝트: JksnFst/Sigil
 def deleteotherfile(self, book_href):
     id = unicode_str(book_href)
     if id in self.id_to_href:
         raise WrapperException('Incorrect interface routine - use deletefile')
     filepath = self.id_to_filepath.get(id, None)
     if id is None:
         raise WrapperException('book href does not exist')
     if id in PROTECTED_FILES:
         raise WrapperException('attempt to delete protected file')
     add_to_deleted = True
     # if file was added or modified delete file from outdir
     if id in self.added or id in self.modified:
         filepath = os.path.join(self.outdir,filepath)
         if unipath.exists(filepath) and unipath.isfile(filepath):
             os.remove(filepath)
         if id in self.added:
             self.added.remove(id)
             add_to_deleted = False
         if id in self.other:
             self.other.remove(id)
         if id in self.modified:
             del self.modified[id]
     if add_to_deleted:
         self.deleted.append(('other', id, book_href))
     del self.id_to_filepath[id]
예제 #10
0
파일: wrapper.py 프로젝트: JksnFst/Sigil
 def readotherfile(self, book_href):
     id = unicode_str(book_href)
     if id in self.id_to_href:
         raise WrapperException('Incorrect interface routine - use readfile')
     # handle special case of trying to read the opf
     if id is not None and id == "OEBPS/content.opf":
         return self.build_opf()
     filepath = self.id_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('book href does not exist')
     basedir = self.ebook_root
     if id in self.added or id in self.modified:
         basedir = self.outdir
     filepath = os.path.join(basedir, filepath)
     if not unipath.exists(filepath):
         raise WrapperException('File Does Not Exist')
     basename = os.path.basename(filepath)
     ext = os.path.splitext(basename)[1]
     ext = ext.lower()
     mime = ext_mime_map.get(ext,'')
     data = b''
     with open(filepath,'rb') as fp:
         data = fp.read()
     if mime.endswith('+xml'):
         data = unicode_str(data)
     return data
예제 #11
0
 def __init__(self, infile, outdir):
     self.infile = infile
     self.outdir = outdir
     if not unipath.exists(self.outdir):
         unipath.mkdir(self.outdir)
     self.mobi7dir = os.path.join(self.outdir, 'mobi7')
     if not unipath.exists(self.mobi7dir):
         unipath.mkdir(self.mobi7dir)
     self.imgdir = os.path.join(self.mobi7dir, 'Images')
     if not unipath.exists(self.imgdir):
         unipath.mkdir(self.imgdir)
     self.hdimgdir = os.path.join(self.outdir, 'HDImages')
     if not unipath.exists(self.hdimgdir):
         unipath.mkdir(self.hdimgdir)
     self.outbase = os.path.join(
         self.outdir,
         os.path.splitext(os.path.split(infile)[1])[0])
예제 #12
0
 def makeZipStruct(self):
     self.k8dir = os.path.join(self.outdir, 'mobi8')
     self.k8oebps = os.path.join(self.k8dir, 'OEBPS')
     self.k8images = os.path.join(self.k8oebps, 'Images')
     self.HDimages = os.path.join(self.outdir, 'azw6_images')
     self.zipdir = os.path.join(self.outdir, 'zip')
     if not unipath.exists(self.zipdir):
         unipath.mkdir(self.zipdir)
예제 #13
0
파일: wrapper.py 프로젝트: JksnFst/Sigil
 def write_opf(self):
     if self.op is not None:
         filepath = pathof(os.path.join(self.outdir, 'OEBPS', self.opfname))
         base = os.path.dirname(filepath)
         if not unipath.exists(base):
             os.makedirs(base)
         with open(filepath,'wb') as fp:
             data = utf8_str(self.build_opf())
             fp.write(data)
예제 #14
0
파일: wrapper.py 프로젝트: f0829/Sigil
 def write_opf(self):
     if self.op is not None:
         filepath = pathof(os.path.join(self.outdir, 'OEBPS', self.opfname))
         base = os.path.dirname(filepath)
         if not unipath.exists(base):
             os.makedirs(base)
         with open(filepath, 'wb') as fp:
             data = utf8_str(self.build_opf())
             fp.write(data)
예제 #15
0
 def write_opf(self):
     if self.op is not None:
         platpath = self.opfbookpath.replace('/', os.sep)
         filepath = pathof(os.path.join(self.outdir, platpath))
         base = os.path.dirname(filepath)
         if not unipath.exists(base):
             os.makedirs(base)
         with open(filepath, 'wb') as fp:
             data = utf8_str(self.build_opf())
             fp.write(data)
예제 #16
0
 def addfile(self,
             uniqueid,
             basename,
             data,
             mime=None,
             properties=None,
             fallback=None,
             overlay=None):
     uniqueid = unicode_str(uniqueid)
     if uniqueid in self.id_to_href:
         raise WrapperException('Manifest Id is not unique')
     basename = unicode_str(basename)
     mime = unicode_str(mime)
     if mime is None:
         ext = os.path.splitext(basename)[1]
         ext = ext.lower()
         mime = ext_mime_map.get(ext, None)
     if mime is None:
         raise WrapperException("Mime Type Missing")
     if mime == "application/x-dtbncx+xml" and self.epub_version.startswith(
             "2"):
         raise WrapperException('Can not add or remove an ncx under epub2')
     group = mime_group_map.get(mime, "Misc")
     default_path = self.group_paths[group][0]
     bookpath = basename
     if default_path != "":
         bookpath = default_path + "/" + basename
     href = buildRelativePath(self.opfbookpath, bookpath)
     if href in self.href_to_id:
         raise WrapperException('Basename already exists')
     # now actually write out the new file
     filepath = bookpath.replace("/", os.sep)
     self.id_to_filepath[uniqueid] = filepath
     filepath = os.path.join(self.outdir, filepath)
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(base)
     if mime in TEXT_MIMETYPES or isinstance(data, text_type):
         data = utf8_str(data)
     with open(filepath, 'wb') as fp:
         fp.write(data)
     self.id_to_href[uniqueid] = href
     self.id_to_mime[uniqueid] = mime
     self.id_to_props[uniqueid] = properties
     self.id_to_fall[uniqueid] = fallback
     self.id_to_over[uniqueid] = overlay
     self.id_to_bookpath[uniqueid] = bookpath
     self.href_to_id[href] = uniqueid
     self.bookpath_to_id[bookpath] = uniqueid
     self.added.append(uniqueid)
     self.modified[self.opfbookpath] = 'file'
     return uniqueid
예제 #17
0
    def makeZip(self, fname, cover_offset, zip_compress=False):
        bname = os.path.normpath(
            os.path.join(self.outdir, '..', fname + '.zip'))
        if not unipath.exists(os.path.dirname(bname)):
            unipath.makedirs(os.path.dirname(bname))

        # ready to build zip
        self.outzip = zipfile.ZipFile(pathof(bname), 'w')

        if unipath.exists(self.k8images):
            distutils.dir_util.copy_tree(self.k8images, self.zipdir)
        else:
            distutils.dir_util.copy_tree(self.imgdir, self.zipdir)

        # HDイメージ差し替え
        replaceHDimages(self.HDimages, self.zipdir, cover_offset)

        # zip作成
        if zip_compress:
            self.zipUpDir(self.outzip, self.zipdir, '')
        else:
            self.zipUpDir(self.outzip, self.zipdir, '', zipfile.ZIP_STORED)
        self.outzip.close()
예제 #18
0
파일: wrapper.py 프로젝트: f0829/Sigil
 def addfile(self,
             uniqueid,
             basename,
             data,
             mime=None,
             properties=None,
             fallback=None,
             overlay=None):
     uniqueid = unicode_str(uniqueid)
     basename = unicode_str(basename)
     mime = unicode_str(mime)
     if mime is None:
         ext = os.path.splitext(basename)[1]
         ext = ext.lower()
         mime = ext_mime_map.get(ext, None)
     if mime is None:
         raise WrapperException("Mime Type Missing")
     if mime.startswith("audio"):
         base = 'Audio'
     elif mime.startswith("video"):
         base = "Video"
     else:
         base = mime_base_map.get(mime, 'Misc')
     href = base + "/" + basename
     if uniqueid in self.id_to_href:
         raise WrapperException('Manifest Id is not unique')
     if href in self.href_to_id:
         raise WrapperException('Basename is not unique')
     # now actually write out the new file
     filepath = href.replace("/", os.sep)
     filepath = os.path.join('OEBPS', filepath)
     self.id_to_filepath[uniqueid] = filepath
     filepath = os.path.join(self.outdir, filepath)
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(base)
     if mime in TEXT_MIMETYPES or isinstance(data, text_type):
         data = utf8_str(data)
     with open(filepath, 'wb') as fp:
         fp.write(data)
     self.id_to_href[uniqueid] = href
     self.id_to_mime[uniqueid] = mime
     self.id_to_props[uniqueid] = properties
     self.id_to_fall[uniqueid] = fallback
     self.id_to_over[uniqueid] = overlay
     self.href_to_id[href] = uniqueid
     self.added.append(uniqueid)
     self.modified['OEBPS/content.opf'] = 'file'
     return uniqueid
예제 #19
0
 def writefile(self, id, data):
     id = unicode_str(id)
     filepath = self.id_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('Id does not exist in manifest')
     mime = self.id_to_mime.get(id, '')
     filepath = os.path.join(self.outdir, filepath)
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(pathof(base))
     if mime.endswith('+xml') or isinstance(data, text_type):
         data = utf8_str(data)
     with open(filepath, 'wb') as fp:
         fp.write(data)
     self.modified[id] = 'file'
예제 #20
0
파일: wrapper.py 프로젝트: pwr/Sigil
 def writefile(self, id, data):
     id = unicode_str(id)
     filepath = self.id_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('Id does not exist in manifest')
     mime = self.id_to_mime.get(id,'')
     filepath = os.path.join(self.outdir, filepath)
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(pathof(base))
     if mime.endswith('+xml') or isinstance(data, text_type):
         data = utf8_str(data)
     with open(filepath,'wb') as fp:
         fp.write(data)
     self.modified[id] = 'file'
예제 #21
0
 def writeotherfile(self, book_href, data):
     id = unicode_str(book_href)
     filepath = self.id_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('book href does not exist')
     if id in PROTECTED_FILES:
         raise WrapperException('Attempt to modify protected file')
     filepath = os.path.join(self.outdir, filepath)
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(base)
     if isinstance(data, text_type):
         data = utf8_str(data)
     with open(filepath, 'wb') as fp:
         fp.write(data)
     self.modified[id] = 'file'
예제 #22
0
파일: wrapper.py 프로젝트: pwr/Sigil
 def writeotherfile(self, book_href, data):
     id = unicode_str(book_href)
     filepath = self.id_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('book href does not exist')
     if id in PROTECTED_FILES:
         raise WrapperException('Attempt to modify protected file')
     filepath = os.path.join(self.outdir, filepath)
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(base)
     if isinstance(data, text_type):
         data = utf8_str(data)
     with open(filepath,'wb') as fp:
         fp.write(data)
     self.modified[id] = 'file'
예제 #23
0
 def deletefile(self, id):
     id = unicode_str(id)
     if id not in self.id_to_href:
         raise WrapperException('Id does not exist in manifest')
     filepath = self.id_to_filepath.get(id, None)
     if id is None:
         raise WrapperException('Id does not exist in manifest')
     if self.epub_version.startswith("2") and id == self.gettocid():
         raise WrapperException('Can not add or remove an ncx under epub2')
     add_to_deleted = True
     # if file was added or modified, delete file from outdir
     if id in self.added or id in self.modified:
         filepath = os.path.join(self.outdir, filepath)
         if unipath.exists(filepath) and unipath.isfile(filepath):
             os.remove(pathof(filepath))
         if id in self.added:
             self.added.remove(id)
             add_to_deleted = False
         if id in self.modified:
             del self.modified[id]
     # remove from manifest
     href = self.id_to_href[id]
     mime = self.id_to_mime[id]
     bookpath = self.id_to_bookpath[id]
     del self.id_to_href[id]
     del self.id_to_mime[id]
     del self.id_to_props[id]
     del self.id_to_fall[id]
     del self.id_to_over[id]
     del self.id_to_bookpath[id]
     del self.href_to_id[href]
     del self.bookpath_to_id[bookpath]
     # remove from spine
     new_spine = []
     was_modified = False
     for sid, linear, properties in self.spine:
         if sid != id:
             new_spine.append((sid, linear, properties))
         else:
             was_modified = True
     if was_modified:
         self.setspine_epub3(new_spine)
     if add_to_deleted:
         self.deleted.append(('manifest', id, bookpath))
         self.modified[self.opfbookpath] = 'file'
     del self.id_to_filepath[id]
예제 #24
0
파일: wrapper.py 프로젝트: apys/Sigil
 def writeotherfile(self, book_href, data):
     id = unicode_str(book_href)
     if id in self.id_to_href:
         raise WrapperException("Incorrect interface routine - use writefile")
     filepath = self.id_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException("book href does not exist")
     if id in PROTECTED_FILES:
         raise WrapperException("Attempt to modify protected file")
     filepath = os.path.join(self.outdir, filepath)
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(base)
     if isinstance(data, text_type):
         data = utf8_str(data)
     with open(filepath, "wb") as fp:
         fp.write(data)
     self.modified[id] = "file"
예제 #25
0
 def addotherfile(self, book_href, data) :
     id = unicode_str(book_href)
     if id in self.other:
         raise WrapperException('book href must be unquie')
     desired_path = id.replace("/",os.sep)
     filepath = os.path.join(self.outdir,desired_path)
     if unipath.isfile(filepath):
         raise WrapperException('desired path already exists')
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(pathof(base))
     if isinstance(data, text_type):
         data = utf8_str(data)
     with open(pathof(filepath),'wb')as fp:
         fp.write(data)
     self.other.append(id)
     self.added.append(id)
     self.id_to_filepath[id] = desired_path
예제 #26
0
파일: wrapper.py 프로젝트: JksnFst/Sigil
 def addotherfile(self, book_href, data) :
     id = unicode_str(book_href)
     if id in self.other:
         raise WrapperException('book href must be unquie')
     desired_path = id.replace("/",os.sep)
     filepath = os.path.join(self.outdir,desired_path)
     if unipath.isfile(filepath):
         raise WrapperException('desired path already exists')
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(pathof(base))
     if isinstance(data, text_type):
         data = utf8_str(data)
     with open(pathof(filepath),'wb')as fp:
         fp.write(data)
     self.other.append(id)
     self.added.append(id)
     self.id_to_filepath[id] = desired_path
예제 #27
0
파일: wrapper.py 프로젝트: pwr/Sigil
 def readfile(self, id):
     id = unicode_str(id)
     filepath = self.id_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('Id does not exist in manifest')
     # already added or modified it will be in outdir
     basedir = self.ebook_root
     if id in self.added or id in self.modified:
         basedir = self.outdir
     filepath = os.path.join(basedir, filepath)
     if not unipath.exists(filepath):
         raise WrapperException('File Does Not Exist')
     data = ''
     with open(filepath,'rb') as fp:
         data = fp.read()
     mime = self.id_to_mime.get(id,'')
     if mime.endswith('+xml'):
         data = unicode_str(data)
     return data
예제 #28
0
 def readfile(self, id):
     id = unicode_str(id)
     filepath = self.id_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('Id does not exist in manifest')
     # already added or modified it will be in outdir
     basedir = self.ebook_root
     if id in self.added or id in self.modified:
         basedir = self.outdir
     filepath = os.path.join(basedir, filepath)
     if not unipath.exists(filepath):
         raise WrapperException('File Does Not Exist')
     data = ''
     with open(filepath, 'rb') as fp:
         data = fp.read()
     mime = self.id_to_mime.get(id, '')
     if mime.endswith('+xml'):
         data = unicode_str(data)
     return data
예제 #29
0
파일: wrapper.py 프로젝트: JksnFst/Sigil
 def addfile(self, uniqueid, basename, data, mime=None, properties=None, fallback=None, overlay=None):
     uniqueid = unicode_str(uniqueid)
     basename = unicode_str(basename)
     mime = unicode_str(mime)
     if mime is None:
         ext = os.path.splitext(basename)[1]
         ext = ext.lower()
         mime = ext_mime_map.get(ext, None)
     if mime is None:
         raise WrapperException("Mime Type Missing")
     if mime.startswith("audio"):
         base = 'Audio'
     elif mime.startswith("video"):
         base = "Video"
     else:
         base = mime_base_map.get(mime,'Misc')
     href = base + "/" + basename
     if uniqueid in self.id_to_href:
         raise WrapperException('Manifest Id is not unique')
     if href in self.href_to_id:
         raise WrapperException('Basename is not unique')
     # now actually write out the new file
     filepath = href.replace("/",os.sep)
     filepath = os.path.join('OEBPS', filepath)
     self.id_to_filepath[uniqueid] = filepath
     filepath = os.path.join(self.outdir,filepath)
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(base)
     if mime.endswith('+xml') or isinstance(data, text_type):
         data = utf8_str(data)
     with open(filepath,'wb') as fp:
         fp.write(data)
     self.id_to_href[uniqueid] = href
     self.id_to_mime[uniqueid] = mime
     self.id_to_props[uniqueid] = properties
     self.id_to_fall[uniqueid] = fallback
     self.id_to_over[uniqueid] = overlay
     self.href_to_id[href] = uniqueid
     self.added.append(uniqueid)
     self.modified['OEBPS/content.opf'] = 'file'
     return uniqueid
예제 #30
0
 def writeotherfile(self, book_href, data):
     id = unicode_str(book_href)
     id = unquoteurl(id)
     if id is None:
         raise WrapperException('None is not a valid book href')
     if id not in self.other and id in self.id_to_href:
         raise WrapperException('Incorrect interface routine - use writefile')
     filepath = self.book_href_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('Book href does not exist')
     if id in PROTECTED_FILES:
         raise WrapperException('Attempt to modify protected file')
     filepath = os.path.join(self.outdir, filepath)
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(base)
     if isinstance(data, text_type):
         data = utf8_str(data)
     with open(filepath,'wb') as fp:
         fp.write(data)
     self.modified[id] = 'file'
예제 #31
0
 def writeotherfile(self, book_href, data):
     id = unicode_str(book_href)
     id = unquoteurl(id)
     if id is None:
         raise WrapperException('None is not a valid book href')
     if id not in self.other and id in self.id_to_href:
         raise WrapperException('Incorrect interface routine - use writefile')
     filepath = self.book_href_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('Book href does not exist')
     if id in PROTECTED_FILES:
         raise WrapperException('Attempt to modify protected file')
     filepath = os.path.join(self.outdir, filepath)
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(base)
     if isinstance(data, text_type):
         data = utf8_str(data)
     with open(filepath,'wb') as fp:
         fp.write(data)
     self.modified[id] = 'file'
예제 #32
0
파일: wrapper.py 프로젝트: apys/Sigil
 def addfile(self, uniqueid, basename, data, mime=None):
     uniqueid = unicode_str(uniqueid)
     basename = unicode_str(basename)
     mime = unicode_str(mime)
     if mime is None:
         ext = os.path.splitext(basename)[1]
         ext = ext.lower()
         mime = ext_mime_map.get(ext, None)
     if mime is None:
         raise WrapperException("Mime Type Missing")
     if mime.startswith("audio"):
         base = "Audio"
     elif mime.startswith("video"):
         base = "Video"
     else:
         base = mime_base_map.get(mime, "Misc")
     href = base + "/" + basename
     if uniqueid in self.id_to_href:
         raise WrapperException("Manifest Id is not unique")
     if href in self.href_to_id:
         raise WrapperException("Basename is not unique")
     # now actually write out the new file
     filepath = href.replace("/", os.sep)
     filepath = os.path.join("OEBPS", filepath)
     self.id_to_filepath[uniqueid] = filepath
     filepath = os.path.join(self.outdir, filepath)
     base = os.path.dirname(filepath)
     if not unipath.exists(base):
         os.makedirs(base)
     if mime.endswith("+xml") or isinstance(data, text_type):
         data = utf8_str(data)
     with open(filepath, "wb") as fp:
         fp.write(data)
     self.id_to_href[uniqueid] = href
     self.id_to_mime[uniqueid] = mime
     self.href_to_id[href] = uniqueid
     self.added.append(uniqueid)
     self.modified["OEBPS/content.opf"] = "file"
     return uniqueid
    def cmdDo(self):
        global CRITERIA

        if self.dashBox.current() == 0:
            dash_settings = ''
        elif self.dashBox.current() == 1:
            dash_settings = 'd'
        elif self.dashBox.current() == 2:
            dash_settings = 'i'
        else:
            dash_settings = 'D'

        if self.use_file.get():
            self.cust_file_path.config(state="normal")
            if len(self.cust_file_path.get()):
                apos_exception_file = self.cust_file_path.get()
                if not unipath.exists(utf8_str(apos_exception_file)):
                    print('Apostrophe exception file %s does not exist!' %
                          apos_exception_file)
                    apos_exception_file = None
            else:
                apos_exception_file = None
            self.cust_file_path.config(state="readonly")
        else:
            apos_exception_file = None
        CRITERIA['apos_exception_file'] = apos_exception_file

        smarty_attr = self.edu_quotes.get(
        ) + dash_settings + self.edu_ellipses.get()
        if smarty_attr == '':
            smarty_attr = '0'
        CRITERIA['smarty_attr'] = smarty_attr

        CRITERIA['use_unicode'] = self.unicodevar.get()

        indices = self.filelist.curselection()
        CRITERIA['files'] = [self.filelist.get(index) for index in indices]

        self.quitApp()
예제 #34
0
 def deleteotherfile(self, book_href):
     id = unicode_str(book_href)
     filepath = self.id_to_filepath.get(id, None)
     if id is None:
         raise WrapperException('book href does not exist')
     if id in PROTECTED_FILES:
         raise WrapperException('attempt to delete protected file')
     add_to_deleted = True
     # if file was added or modified delete file from outdir
     if id in self.added or id in self.modified:
         filepath = os.path.join(self.outdir, filepath)
         if unipath.exists(filepath) and unipath.isfile(filepath):
             os.remove(filepath)
         if id in self.added:
             self.added.remove(id)
             add_to_deleted = False
         if id in self.other:
             self.other.remove(id)
         if id in self.modified:
             del self.modified[id]
     if add_to_deleted:
         self.deleted.append(id)
     del self.id_to_filepath[id]
    def cmdDo(self):
        global CRITERIA

        if self.dashBox.current() == 0:
            dash_settings = ''
        elif self.dashBox.current() == 1:
            dash_settings = 'd'
        elif self.dashBox.current() == 2:
            dash_settings = 'i'
        else:
            dash_settings = 'D'

        if self.use_file.get():
            self.cust_file_path.config(state="normal")
            if len(self.cust_file_path.get()):
                apos_exception_file = self.cust_file_path.get()
                if not unipath.exists(utf8_str(apos_exception_file)):
                    print ('Apostrophe exception file %s does not exist!' % apos_exception_file)
                    apos_exception_file = None
            else:
                apos_exception_file = None
            self.cust_file_path.config(state="readonly")
        else:
            apos_exception_file = None
        CRITERIA['apos_exception_file'] = apos_exception_file

        smarty_attr = self.edu_quotes.get() + dash_settings + self.edu_ellipses.get()
        if smarty_attr == '':
            smarty_attr = '0'
        CRITERIA['smarty_attr'] = smarty_attr

        CRITERIA['use_unicode'] = self.unicodevar.get()

        indices = self.filelist.curselection()
        CRITERIA['files'] = [self.filelist.get(index) for index in indices]

        self.quitApp()
예제 #36
0
 def readotherfile(self, book_href):
     id = unicode_str(book_href)
     # handle special case of trying to read the opf
     if id is not None and id == "OEBPS/content.opf":
         return self.build_opf()
     filepath = self.id_to_filepath.get(id, None)
     if filepath is None:
         raise WrapperException('book href does not exist')
     basedir = self.ebook_root
     if id in self.added or id in self.modified:
         basedir = self.outdir
     filepath = os.path.join(basedir, filepath)
     if not unipath.exists(filepath):
         raise WrapperException('File Does Not Exist')
     basename = os.path.basename(filepath)
     ext = os.path.splitext(basename)[1]
     ext = ext.lower()
     mime = ext_mime_map.get(ext, '')
     data = b''
     with open(filepath, 'rb') as fp:
         data = fp.read()
     if mime.endswith('+xml'):
         data = unicode_str(data)
     return data
예제 #37
0
 def makeK8Struct(self):
     self.k8dir = os.path.join(self.outdir, 'mobi8')
     if not unipath.exists(self.k8dir):
         unipath.mkdir(self.k8dir)
     self.k8metainf = os.path.join(self.k8dir, 'META-INF')
     if not unipath.exists(self.k8metainf):
         unipath.mkdir(self.k8metainf)
     self.k8oebps = os.path.join(self.k8dir, 'OEBPS')
     if not unipath.exists(self.k8oebps):
         unipath.mkdir(self.k8oebps)
     self.k8images = os.path.join(self.k8oebps, 'Images')
     if not unipath.exists(self.k8images):
         unipath.mkdir(self.k8images)
     self.HDimages = os.path.join(self.outdir, 'azw6_images')
     self.k8fonts = os.path.join(self.k8oebps, 'Fonts')
     if not unipath.exists(self.k8fonts):
         unipath.mkdir(self.k8fonts)
     self.k8styles = os.path.join(self.k8oebps, 'Styles')
     if not unipath.exists(self.k8styles):
         unipath.mkdir(self.k8styles)
     self.k8text = os.path.join(self.k8oebps, 'Text')
     if not unipath.exists(self.k8text):
         unipath.mkdir(self.k8text)
예제 #38
0
    def makeEPUB(self, usedmap, obfuscate_data, uid, output_epub, fname,
                 cover_offset):
        bname = os.path.normpath(
            os.path.join(self.outdir, '..', fname + '.epub'))
        if output_epub and not unipath.exists(os.path.dirname(bname)):
            unipath.makedirs(os.path.dirname(bname))

        # Create an encryption key for Adobe font obfuscation
        # based on the epub's uid
        if isinstance(uid, text_type):
            uid = uid.encode('ascii')
        if obfuscate_data:
            key = re.sub(br'[^a-fA-F0-9]', b'', uid)
            key = binascii.unhexlify((key + key)[:32])

        # copy over all images and fonts that are actually used in the ebook
        # and remove all font files from mobi7 since not supported
        imgnames = unipath.listdir(self.imgdir)
        for name in imgnames:
            if usedmap.get(name, 'not used') == 'used':
                filein = os.path.join(self.imgdir, name)
                if name.endswith(".ttf"):
                    fileout = os.path.join(self.k8fonts, name)
                elif name.endswith(".otf"):
                    fileout = os.path.join(self.k8fonts, name)
                elif name.endswith(".failed"):
                    fileout = os.path.join(self.k8fonts, name)
                else:
                    fileout = os.path.join(self.k8images, name)
                data = b''
                with open(pathof(filein), 'rb') as f:
                    data = f.read()
                if obfuscate_data:
                    if name in obfuscate_data:
                        data = mangle_fonts(key, data)
                open(pathof(fileout), 'wb').write(data)
                if name.endswith(".ttf") or name.endswith(".otf"):
                    os.remove(pathof(filein))

        # opf file name hard coded to "content.opf"
        container = '<?xml version="1.0" encoding="UTF-8"?>\n'
        container += '<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">\n'
        container += '    <rootfiles>\n'
        container += '<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>'
        container += '    </rootfiles>\n</container>\n'
        fileout = os.path.join(self.k8metainf, 'container.xml')
        with open(pathof(fileout), 'wb') as f:
            f.write(container.encode('utf-8'))

        if obfuscate_data:
            encryption = '<encryption xmlns="urn:oasis:names:tc:opendocument:xmlns:container" \
xmlns:enc="http://www.w3.org/2001/04/xmlenc#" xmlns:deenc="http://ns.adobe.com/digitaleditions/enc">\n'

            for font in obfuscate_data:
                encryption += '  <enc:EncryptedData>\n'
                encryption += '    <enc:EncryptionMethod Algorithm="http://ns.adobe.com/pdf/enc#RC"/>\n'
                encryption += '    <enc:CipherData>\n'
                encryption += '      <enc:CipherReference URI="OEBPS/Fonts/' + font + '"/>\n'
                encryption += '    </enc:CipherData>\n'
                encryption += '  </enc:EncryptedData>\n'
            encryption += '</encryption>\n'
            fileout = os.path.join(self.k8metainf, 'encryption.xml')
            with open(pathof(fileout), 'wb') as f:
                f.write(encryption.encode('utf-8'))

        if not output_epub:
            return

        # ready to build epub
        self.outzip = zipfile.ZipFile(pathof(bname), 'w')

        # HDイメージ差し替え
        replaceHDimages(self.HDimages, self.k8images, cover_offset)

        # add the mimetype file uncompressed
        mimetype = b'application/epub+zip'
        fileout = os.path.join(self.k8dir, 'mimetype')
        with open(pathof(fileout), 'wb') as f:
            f.write(mimetype)
        nzinfo = ZipInfo('mimetype', compress_type=zipfile.ZIP_STORED)
        #TTTTsstrwxrwxrwx0000000000ADVSHR
        #^^^^____________________________ file type as explained above
        #    ^^^_________________________ setuid, setgid, sticky
        #       ^^^^^^^^^________________ permissions
        #                ^^^^^^^^________ This is the "lower-middle byte" your post mentions
        #                        ^^^^^^^^ DOS attribute bits
        #    ‭0001100000000000000000000000‬
        nzinfo.external_attr = 0o600 << 16  # make this a normal file
        #    ‭0000000000000000000000100000‬
        nzinfo.external_attr |= 0x020
        self.outzip.writestr(nzinfo, mimetype)
        self.zipUpDir(self.outzip, self.k8dir, 'META-INF')
        self.zipUpDir(self.outzip, self.k8dir, 'OEBPS')
        self.outzip.close()
예제 #39
0
def main(argv=unicode_argv()):

    if len(argv) != 5:
        failed(
            None,
            msg="Launcher: improper number of arguments passed to launcher.py")
        return -1

    ebook_root = argv[1]
    outdir = argv[2]
    script_type = argv[3]
    target_file = argv[4]
    script_home = os.path.dirname(target_file)
    plugin_name = os.path.split(script_home)[-1]
    plugin_dir = os.path.dirname(script_home)
    script_module = os.path.splitext(os.path.basename(target_file))[0]

    # do basic sanity checking anyway
    if script_type not in SUPPORTED_SCRIPT_TYPES:
        failed(None,
               msg="Launcher: script type %s is not supported" % script_type)
        return -1

    ok = unipath.exists(ebook_root) and unipath.isdir(ebook_root)
    ok = ok and unipath.exists(outdir) and unipath.isdir(outdir)
    ok = ok and unipath.exists(script_home) and unipath.isdir(script_home)
    ok = ok and unipath.exists(target_file) and unipath.isfile(target_file)
    if not ok:
        failed(None, msg="Launcher: missing or incorrect paths passed in")
        return -1

    # update sys with path to target module home directory
    sys.path.append(script_home)

    # load and parse opf if present
    op = None
    opf_path = os.path.join(ebook_root, 'OEBPS', 'content.opf')
    if unipath.exists(opf_path) and unipath.isfile(opf_path):
        op = Opf_Parser(opf_path)

    # create a wrapper for record keeping and safety
    rk = Wrapper(ebook_root, outdir, op, plugin_dir, plugin_name)

    # get the correct container
    if script_type == 'edit':
        bc = BookContainer(rk)
    elif script_type == 'input':
        bc = InputContainer(rk)
    elif script_type == 'validation':
        bc = ValidationContainer(rk)
    else:
        bc = OutputContainer(rk)

    # start the target script
    ps = ProcessScript(script_type, script_module, bc)
    ps.launch()

    # get standard error and standard out from the target script
    successmsg = ''
    for data in ps.stdouttext:
        successmsg += unicode_str(data)
    successmsg = escapeit(successmsg)
    errorlog = ''
    for data in ps.stderrtext:
        errorlog += unicode_str(data)
    errorlog = escapeit(errorlog)

    # get the target's script wrapper xml
    resultxml = "".join(ps.wrapout)
    resultxml += "<msg>\n"
    if ps.exitcode == 0:
        resultxml += successmsg
        if _DEBUG:
            resultxml += errorlog
    else:
        if _DEBUG:
            resultxml += successmsg
        resultxml += errorlog
    resultxml += '</msg>\n</wrapper>\n'

    # write it to stdout and exit
    if PY3:
        sys.stdout.buffer.write(utf8_str(resultxml))
    else:
        sys.stdout.write(utf8_str(resultxml))
    return 0
예제 #40
0
파일: launcher.py 프로젝트: pwr/Sigil
def main(argv=unicode_argv()):

    if len(argv) != 5:
        failed(None, msg="Launcher: improper number of arguments passed to launcher.py")
        return -1

    ebook_root = argv[1]
    outdir = argv[2]
    script_type = argv[3]
    target_file = argv[4]
    script_home = os.path.dirname(target_file)
    script_module = os.path.splitext(os.path.basename(target_file))[0]

    # do basic sanity checking anyway
    if script_type not in SUPPORTED_SCRIPT_TYPES:
        failed(None, msg="Launcher: script type %s is not supported" % script_type)
        return -1

    ok = unipath.exists(ebook_root) and unipath.isdir(ebook_root)
    ok = ok and unipath.exists(outdir) and unipath.isdir(outdir)
    ok = ok and unipath.exists(script_home) and unipath.isdir(script_home)
    ok = ok and unipath.exists(target_file) and unipath.isfile(target_file)
    if not ok:
        failed(None, msg="Launcher: missing or incorrect paths passed in")
        return -1

    # update sys with path to target module home directory
    if script_home not in sys.path:
        sys.path.append(script_home)

    # load and parse opf if present
    op = None
    opf_path = os.path.join(ebook_root, "OEBPS", "content.opf")
    if unipath.exists(opf_path) and unipath.isfile(opf_path):
        op = Opf_Parser(opf_path)

    # create a wrapper for record keeping and safety
    rk = Wrapper(ebook_root, outdir, op)

    # get the correct container
    if script_type == "edit":
        bc = BookContainer(rk)
    elif script_type == "input":
        bc = InputContainer(rk)
    else:
        bc = OutputContainer(rk)

    # start the target script
    ps = ProcessScript(script_type, script_module, bc)
    ps.launch()

    # get standard error and standard out from the target script
    successmsg = ""
    for data in ps.stdouttext:
        successmsg += unicode_str(data)
    successmsg = escapeit(successmsg)
    errorlog = ""
    for data in ps.stderrtext:
        errorlog += unicode_str(data)
    errorlog = escapeit(errorlog)

    # get the target's script wrapper xml
    resultxml = "".join(ps.wrapout)
    resultxml += "<msg>\n"
    if ps.exitcode == 0:
        resultxml += successmsg
        if _DEBUG:
            resultxml += errorlog
    else:
        if _DEBUG:
            resultxml += successmsg
        resultxml += errorlog
    resultxml += "</msg>\n</wrapper>\n"

    # write it to stdout and exit
    if PY3:
        sys.stdout.buffer.write(utf8_str(resultxml))
    else:
        sys.stdout.write(utf8_str(resultxml))
    return 0
예제 #41
0
파일: azw2zip.py 프로젝트: junk2ool/azw2zip
def main(argv=unicode_argv()):
    progname = os.path.splitext(os.path.basename(argv[0]))[0]
    azw2zip_dir = os.path.dirname(os.path.abspath(argv[0]))

    print(u"{0:} v.{1:s}\nCopyright (C) 2020 junk2ool".format(
        progname, __version__))
    print(u"")

    try:
        opts, args = getopt.getopt(argv[1:], "zefptscomd")
    except getopt.GetoptError as err:
        print(str(err))
        usage(progname)
        sys.exit(2)

    if len(args) < 1:
        usage(progname)
        sys.exit(2)

    cfg = azw2zipConfig()
    cfg.load(os.path.join(azw2zip_dir, 'azw2zip.json'))

    updated_title = cfg.isUpdatedTitle()
    authors_sort = cfg.isAuthorsSort()
    compress_zip = cfg.isCompressZip()
    over_write = cfg.isOverWrite()
    output_thumb = cfg.isOutputThumb()
    output_zip = cfg.isOutputZip()
    output_epub = cfg.isOutputEpub()
    output_images = cfg.isOutputImages()
    output_pdf = cfg.isOutputPdf()
    debug_mode = cfg.isDebugMode()

    # オプション解析
    for o, a in opts:
        if o == "-t":
            updated_title = True
        if o == "-s":
            authors_sort = True
        if o == "-c":
            compress_zip = True
        if o == "-o":
            over_write = True
        if o == "-m":
            output_thumb = True
        if o == "-z":
            output_zip = True
        if o == "-e":
            output_epub = True
        if o == "-f":
            output_images = True
        if o == "-p":
            output_pdf = True
        if o == "-d":
            debug_mode = True
    if not output_zip and not output_epub and not output_images and not output_pdf:
        output_zip = True
    cfg.setOptions(updated_title, authors_sort, compress_zip, over_write,
                   output_thumb, debug_mode)
    cfg.setOutputFormats(output_zip, output_epub, output_images, output_pdf)

    # k4i ディレクトリはスクリプトのディレクトリ
    k4i_dir = cfg.getk4iDirectory()
    if not k4i_dir:
        k4i_dir = azw2zip_dir
    print(u"k4iディレクトリ: {}".format(k4i_dir))
    cfg.setk4iDirectory(k4i_dir)
    k4i_files = glob.glob(os.path.join(k4i_dir, '*.k4i'))
    if not len(k4i_files):
        # k4iがなければ作成
        if not sys.platform.startswith('win') and not sys.platform.startswith(
                'darwin'):
            # k4iはWindowsかMacでしか作成できない
            print(u"エラー : k4iファイルが見つかりません: {}".format(k4i_dir))
            exit(1)

        print(u"k4i作成: 開始: {}".format(k4i_dir))
        if debug_mode:
            kindlekey.getkey(k4i_dir)
        else:
            with redirect_stdout(open(os.devnull, 'w')):
                kindlekey.getkey(k4i_dir)
        k4i_files = glob.glob(os.path.join(k4i_dir, '*.k4i'))
        print(u"k4i作成: 完了: {}".format(k4i_files[0]))
    else:
        for k4i_fpath in k4i_files:
            print(u"k4i: {}".format(k4i_fpath))

    # 変換ディレクトリ
    in_dir = args[0]
    if not os.path.isabs(in_dir):
        in_dir = os.path.abspath(in_dir)
    if not in_dir:
        in_dir = os.getcwd()
    in_dir = os.path.realpath(os.path.normpath(in_dir))
    if (os.path.isfile(in_dir)):
        in_dir = os.path.dirname(in_dir)
    print(u"変換ディレクトリ: {}".format(in_dir))

    # 出力ディレクトリ作成
    out_dir = cfg.getOutputDirectory()
    if len(args) > 1:
        out_dir = args[1]
        if not os.path.isabs(out_dir):
            out_dir = os.path.abspath(out_dir)
    if not out_dir:
        out_dir = azw2zip_dir  #os.getcwd()
    out_dir = os.path.realpath(os.path.normpath(out_dir))
    cfg.setOutputDirectory(out_dir)

    print(u"出力ディレクトリ: {}".format(out_dir))
    if not unipath.exists(out_dir):
        unipath.mkdir(out_dir)
        print(u"出力ディレクトリ: 作成: {}".format(out_dir))

    output_zip_org = output_zip
    output_epub_org = output_epub
    output_images_org = output_images
    output_pdf_org = output_pdf

    # 処理ディレクトリのファイルを再帰走査
    for azw_fpath in find_all_files(in_dir):
        # ファイルでなければスキップ
        if not os.path.isfile(azw_fpath):
            continue
        # .azwファイルでなければスキップ
        fext = os.path.splitext(azw_fpath)[1].upper()
        if fext not in ['.AZW', '.AZW3']:
            continue

        output_zip = output_zip_org
        output_epub = output_epub_org
        output_images = output_images_org
        output_pdf = output_pdf_org

        output_format = [
            [output_zip, u"zip", u".zip"],
            [output_epub, u"epub", u".epub"],
            [output_images, u"Images", u""],
            [output_pdf, u"pdf", u".*.pdf"],
        ]

        print("")
        azw_dir = os.path.dirname(azw_fpath)
        print(u"変換開始: {}".format(azw_dir))

        # 上書きチェック
        a2z = azw2zip()
        over_write_flag = over_write
        try:
            if a2z.load(azw_fpath, '', debug_mode) != 0:
                over_write_flag = True
        except azw2zipException as e:
            print(str(e))
            over_write_flag = True

        cfg.setPrintReplica(a2z.is_print_replica())

        if not over_write_flag:
            fname_txt = cfg.makeOutputFileName(a2z.get_meta_data())
            for format in output_format:
                if format[0]:
                    output_fpath = os.path.join(out_dir, fname_txt + format[2])
                    output_files = glob.glob(output_fpath.replace('[', '[[]'))
                    if (len(output_files)):
                        format[0] = False
                        try:
                            print(u" {}変換: パス: {}".format(
                                format[1], output_files[0]))
                        except UnicodeEncodeError:
                            print(u" {}変換: パス: {}".format(
                                format[1], output_files[0].encode(
                                    'cp932', 'replace').decode('cp932')))
                    else:
                        over_write_flag = True

        if not over_write_flag:
            # すべてパス
            print(u"変換完了: {}".format(azw_dir))
            continue

        cfg.setOutputFormats(output_zip, output_epub, output_images,
                             output_pdf)

        # 作業ディレクトリ作成
        # ランダムな8文字のディレクトリ名
        source = string.ascii_letters + string.digits
        random_str = ''.join([random.choice(source) for _ in range(8)])
        temp_dir = os.path.join(out_dir, "Temp_" + random_str)
        book_fname = os.path.basename(os.path.dirname(azw_fpath))
        #temp_dir = os.path.join(out_dir, book_fname)
        print(u" 作業ディレクトリ: 作成: {}".format(temp_dir))
        if not unipath.exists(temp_dir):
            unipath.mkdir(temp_dir)

        cfg.setTempDirectory(temp_dir)

        # HD画像(resファイル)があれば展開
        res_files = glob.glob(os.path.join(os.path.dirname(azw_fpath),
                                           '*.res'))
        for res_fpath in res_files:
            print(u"  HD画像展開: 開始: {}".format(res_fpath))

            if debug_mode:
                DumpAZW6_v01.DumpAZW6(res_fpath, temp_dir)
            else:
                with redirect_stdout(open(os.devnull, 'w')):
                    DumpAZW6_v01.DumpAZW6(res_fpath, temp_dir)

            print(u"  HD画像展開: 完了: {}".format(
                os.path.join(temp_dir, 'azw6_images')))

        # azwならDRM解除
        DeDRM_path = ""
        if fext in ['.AZW']:
            print(u"  DRM解除: 開始: {}".format(azw_fpath))

            if debug_mode:
                decryptk4mobi(azw_fpath, temp_dir, k4i_dir)
            else:
                with redirect_stdout(open(os.devnull, 'w')):
                    decryptk4mobi(azw_fpath, temp_dir, k4i_dir)

            DeDRM_files = glob.glob(
                os.path.join(temp_dir, book_fname + '*.azw?'))
            if len(DeDRM_files) > 0:
                DeDRM_path = DeDRM_files[0]
                print(u"  DRM解除: 完了: {}".format(DeDRM_path))
            else:
                print(u"  DRM解除: 失敗:")
        elif fext in ['.AZW3']:
            DeDRM_path = azw_fpath

        if DeDRM_path and unipath.exists(DeDRM_path):
            # 書籍変換
            print(u"  書籍変換: 開始: {}".format(DeDRM_path))

            #unpack_dir = os.path.join(temp_dir, os.path.splitext(os.path.basename(DeDRM_path))[0])
            unpack_dir = temp_dir
            if debug_mode:
                kindleunpack.kindleunpack(DeDRM_path, unpack_dir, cfg)
            else:
                with redirect_stdout(open(os.devnull, 'w')):
                    kindleunpack.kindleunpack(DeDRM_path, unpack_dir, cfg)

            # 作成したファイル名を取得
            fname_path = os.path.join(temp_dir, "fname.txt")
            if unipath.exists(fname_path):
                fname_file = codecs.open(fname_path, 'r', 'utf-8')
                fname_txt = fname_file.readline().rstrip()
                fname_file.close()

                for format in output_format:
                    if format[0]:
                        output_fpath = os.path.join(out_dir,
                                                    fname_txt + format[2])
                        output_files = glob.glob(
                            output_fpath.replace('[', '[[]'))
                        if (len(output_files)):
                            try:
                                print(u"  {}変換: 完了: {}".format(
                                    format[1], output_files[0]))
                            except UnicodeEncodeError:
                                print(u"  {}変換: 完了: {}".format(
                                    format[1], output_files[0].encode(
                                        'cp932', 'replace').decode('cp932')))
            else:
                print(u"  書籍変換: 失敗:")
        else:
            print(u"  DRM解除: 失敗:")

        if not debug_mode:
            shutil.rmtree(temp_dir)
            print(u" 作業ディレクトリ: 削除: {}".format(temp_dir))

        print(u"変換完了: {}".format(azw_dir))

    return 0