/
ConvertFile.py
96 lines (72 loc) · 2.17 KB
/
ConvertFile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env python
import os, zipfile
import imghdr
import shutil
from book import Book
from convert import BookConvert
class convertFile():
def __init__(self):
pass
def convert(self, filePath, outDir, Device, verbose):
listDir = []
isDir = os.path.isdir(filePath)
if (isDir):
title = os.path.basename(filePath)
listDir = os.listdir(filePath)
else:
listDir.append(filePath)
title = 'Pictures'
outputBook = Book()
outputBook.DefaultDevice = Device
if (title == None or title == ""):
title = 'Pictures'
files = []
directories = []
compressedFiles = []
# Recursively loop through the filesystem
for filename in listDir:
if (isDir):
filename = os.path.join(filePath, filename)
if (os.path.isdir(str(filename))):
directories.append(filename)
else:
if (outputBook.isImageFile(filename)):
files.append(filename)
else:
imageExts = ['.cbz', '.zip']
if os.path.splitext(filename)[1].lower() in imageExts:
compressedFiles.append(filename)
if (len(files) > 0):
outputBook.addImageFiles(files)
outputBook.title = title
bookConvert = BookConvert(outputBook, os.path.abspath(outDir), verbose)
bookConvert.Export()
outDir = os.path.join(outDir, title)
for directory in directories:
self.convert(directory, outDir, Device, verbose)
for compressedFile in compressedFiles:
try:
z = zipfile.ZipFile(compressedFile, 'r')
except:
if (verbose):
print "Failed to convert %s. Check if it is a valid zipFile."
continue
if (isDir):
temp_dir = os.path.join(filePath, os.path.splitext(os.path.basename(compressedFile))[0])
else:
temp_dir = os.path.splitext(compressedFile)[0]
try:
os.mkdir(temp_dir)
except:
continue
for name in z.namelist():
tempName = os.path.join(temp_dir, name)
self.extract_from_zip(name, tempName, z)
z.close
self.convert(temp_dir, outDir, Device, verbose)
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
def extract_from_zip(self, name, dest_path, zip_file):
dest_file = open(dest_path, 'wb')
dest_file.write(zip_file.read(name))
dest_file.close()