-
Notifications
You must be signed in to change notification settings - Fork 0
/
epub.py
93 lines (77 loc) · 2.32 KB
/
epub.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import zipfile
import sys
import shutil
import xml.dom.minidom as dom
import webbrowser
import socket
import threading
class OpenBookT (threading.Thread):
url = ''
def __init__(self, id, name, delay, url):
threading.Thread.__init__(self)
self.threadID = id
self.name = name
self.delay = delay
self.url = url
def run(self):
webbrowser.open(self.url)
def toMetaPath(dirPath):
with open(os.path.join(dirPath, 'META-INF', 'container.xml'), 'r') as f:
data = f.read()
xr = dom.parseString(data).documentElement
return '/' + xr.getElementsByTagName("rootfile")[0].getAttribute('full-path')
def openBook(url):
time.sleep(1)
webbrowser.open(url)
def main():
if len(sys.argv) < 2:
sys.stderr.write('Error: too less arguments. Need file path')
exit(-1)
args = sys.argv.copy()
args.pop(0)
path = ' '.join(args)
print('Open', path)
port = 8123
maxloop = 256
while maxloop > 0:
try:
socket.socket(socket.AF_INET).connect(('127.0.0.1', port))
port += 1
maxloop -= 1
except Exception as err:
maxloop = -5
if maxloop == 0:
sys.stderr.write('Max port count!')
exit(-1)
tmpdir = os.path.join('.', r'tmp' + str(port))
if os.path.exists(tmpdir):
shutil.rmtree(tmpdir)
metajs = '''
var meta = {
'''
try:
f = zipfile.ZipFile(path)
for file in f.namelist():
f.extract(file, tmpdir)
metajs += '"metaPath": "%s"' % (toMetaPath(tmpdir))
metajs += '\n}'
with open('meta.js', 'w') as wf:
wf.write(metajs)
shutil.copy('index.html', os.path.join(tmpdir, 'index.html'))
shutil.copy('meta.js', os.path.join(tmpdir, 'meta.js'))
url = 'http://127.0.0.1:' + str(port) + '/index.html'
print(url)
t = OpenBookT(1, 'Book', 1, url)
t.start()
os.system(' '.join(['python', '-m', 'http.server',
'--directory', tmpdir,
str(port)]))
exit(0)
except Exception as err:
sys.stderr.write(str(err))
if __name__ == '__main__':
main()