-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader_server.py
More file actions
237 lines (200 loc) · 9.49 KB
/
reader_server.py
File metadata and controls
237 lines (200 loc) · 9.49 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import os
import json
import base64
from urllib.parse import urlparse, parse_qs
from http.server import BaseHTTPRequestHandler
import templates
host = ('0.0.0.0', 60003)
json_path = "/var/www/HanMan/books.json"
imgs_path = "/var/www/HanMan/images"
class RequestHandler(BaseHTTPRequestHandler):
def log_message(self, format: str, *args) -> None:
return
def do_GET(self):
html = ""
route_path = self.path
if '?' in route_path:
route_path = self.path.split('?',1)[0]
if route_path.startswith("/comic"):
route_path = route_path[6:]
match route_path:
case '/' : html = self.get_booklist()
case '/booklist.html' : html = self.get_booklist()
case '/chapterlist.html' : html = self.get_chapterlist()
case '/imglist.html' : html = self.get_imglist()
case '/switchend':
self.switchend()
html = self.get_booklist()
case '/move':
self.move()
html = self.get_booklist()
case _:
if route_path.endswith(".html"):
full_path = os.getcwd() + route_path
if os.path.isfile(full_path):
with open(full_path, 'rb') as reader:
html = reader.read().decode()
else:
html="not file :" + full_path
else:
html=self.path
self.send_content(html)
def get_booklist(self):
with open(json_path, "r") as f:
books = json.load(f)
book_link_htmls=""
for bookitem in books:
maxchapter=""
chapter_folder = os.path.join(imgs_path, bookitem['name'])
if os.path.exists(chapter_folder) and os.path.isdir(chapter_folder):
chapters = os.listdir(chapter_folder)
maxchapter = 0
if len(chapters) > 0:
maxchapter = max(chapters, key=lambda chapter: int(os.path.basename(chapter)[0:3]))[0:3]
values = {
'url' : f"chapterlist.html?bookname={base64.urlsafe_b64encode(bookitem['name'].encode()).decode()}",
'status' : "已完结" if bookitem['end'] else "连载中",
'set_status' : f"switchend?bookid={bookitem['id']}",
'name' : bookitem['name'],
'font_color' : "#e6e6e6" if bookitem['readAt'] in ["000","001",maxchapter] else "#faf572",
'read_at' : bookitem['readAt'],
'total' : maxchapter,
'moveup' : f"move?type=up&bookid={bookitem['id']}",
'movedown' : f"move?type=down&bookid={bookitem['id']}"
}
book_link_htmls += templates.TEMPLATE_BOOK_LINK.format(**values)
return templates.TEMPLATE_BOOKS.replace(" <li_here />",book_link_htmls)
def get_chapterlist(self):
query = parse_qs(urlparse(self.path).query)
bookname = str(base64.urlsafe_b64decode(query.get('bookname', [''])[0]), encoding='utf-8')
chapter_folder = os.path.join(imgs_path, bookname)
if not os.path.exists(chapter_folder) or not os.path.isdir(chapter_folder):
return f"bookname:{bookname} not found"
chapter_link_htmls = ""
chapters = os.listdir(chapter_folder)
if len(chapters) == 0:
chapter_link_htmls = " <li>无章节</li> \n"
else:
readAt = 0
with open(json_path, "r+") as f:
books = json.load(f)
for bookitem in books:
if bookitem["name"] == bookname:
readAt = int(bookitem["readAt"])
break
chapters.sort(key=lambda chapter: int(os.path.basename(chapter)[0:3]), reverse = len(chapters)/2 < readAt)
for chapter in chapters:
values = {
'url' : f"imglist.html?bookname={encodeURLSafe(bookname)}&chapter={encodeURLSafe(os.path.basename(chapter))}",
'chapter_name' : os.path.basename(replaceURLSafe(chapter)),
'font_color' : "gray" if readAt != int(os.path.basename(chapter)[0:3]) else "#faf572",
}
chapter_link_htmls += templates.TEMPLATE_CHAPTER_LINK.format(**values)
return templates.TEMPLATE_BOOK_CHAPTERS.replace(" <li_here />",chapter_link_htmls).replace("{title}", bookname)
def get_imglist(self):
query = parse_qs(urlparse(self.path).query)
bookname = decodeURLSafe(query.get('bookname', [''])[0])
chapter = decodeURLSafe(query.get('chapter', [''])[0])
img_folder = os.path.join(imgs_path, bookname, chapter)
if not os.path.exists(img_folder) or not os.path.isdir(img_folder):
return f"bookname:{bookname} chapter:{chapter} not found"
last = ""
next = ""
chapter_folder = os.path.join(imgs_path, bookname)
chapters = os.listdir(chapter_folder)
if len(chapters) != 0:
chapters.sort(key=lambda _chapter: int(os.path.basename(_chapter)[0:3]))
try:
index = chapters.index(chapter)
if index == 0:
next = chapters[1]
elif index == len(chapters) - 1:
last = chapters[index - 1]
else:
last = chapters[index - 1]
next = chapters[index + 1]
except BaseException:
print("chapters.index(chapter) error")
imgs = os.listdir(img_folder)
img_link_htmls = ""
if len(imgs) == 0:
img_link_htmls = " <li>无图片</li> \n"
else:
imgs.sort(key=lambda img: int(os.path.basename(img)[0:3]))
for img in imgs:
img_link_htmls += f" <img src=\"/hanman/images/{replaceURLSafe(bookname)}/{replaceURLSafe(chapter)}/{img}\" /> \n"
with open(json_path, "r+") as f:
books = json.load(f)
for index,bookitem in enumerate(books):
if bookitem["name"] == bookname:
bookitem["readAt"] = chapter[0:3]
if next == '' and bookitem["end"]:
books.append(books[index])
books.remove(books[index])
break
self.write_json(books,f)
return templates.TEMPLATE_CHAPTER_IMGS\
.replace(" <img_here />", img_link_htmls)\
.replace("{chapter}", chapter)\
.replace("{chapter_list}", f"chapterlist.html?bookname={encodeURLSafe(bookname)}")\
.replace("{last}", "" if "" == last else f"imglist.html?bookname={encodeURLSafe(bookname)}&chapter={encodeURLSafe(last)}")\
.replace("{next}", "" if "" == next else f"imglist.html?bookname={encodeURLSafe(bookname)}&chapter={encodeURLSafe(next)}")
def switchend(self):
query = parse_qs(urlparse(self.path).query)
bookid = query.get('bookid', [''])[0]
with open(json_path, "r+") as f:
books = json.load(f)
for bookitem in books:
if bookitem["id"] == bookid:
bookitem["end"] = not bookitem["end"]
break
self.write_json(books,f)
def move(self):
query = parse_qs(urlparse(self.path).query)
type = query.get('type', [''])[0]
bookid = query.get('bookid', [''])[0]
with open(json_path, "r+") as f:
books = json.load(f)
target_index = -1
for index,bookitem in enumerate(books):
if bookitem["id"] == bookid:
target_index = index
break
if target_index == -1 :
print("cannot move 1")
else:
if target_index == 0 and "up" == type:
print("cannot move 2")
elif target_index == len(books)-1 and "down" == type:
print("cannot move 3")
else:
if "up" == type:
books[target_index-1], books[target_index] = books[target_index], books[target_index-1]
elif "down" == type:
books[target_index], books[target_index+1] = books[target_index+1], books[target_index]
self.write_json(books,f)
def send_content(self, page):
# page = page.encode()
# print(type(page))
b_page = bytes(page, encoding='utf-8')
self.send_response(200)
self.send_header("Content-type","text/html")
self.send_header("Content-Length", str(len(b_page)))
self.end_headers()
self.wfile.write(b_page)
def write_json(self, books, f):
jsonstr = json.dumps(books, ensure_ascii=False)
jsonstr = jsonstr.replace("}, {","}, \n {")\
.replace("[{","[\n {")\
.replace("}]","} \n]")\
.replace("true, \"","true, \"")\
.replace('"spiderby": "", "','"spiderby": "", "')
f.seek(0)
f.truncate()
f.write(jsonstr)
def encodeURLSafe(_str):
return base64.urlsafe_b64encode(_str.encode()).decode()
def decodeURLSafe(_str):
return str(base64.urlsafe_b64decode(_str), encoding='utf-8')
def replaceURLSafe(_str):
return _str.replace("&", "&").replace("?", "%3F")