Skip to content

Commit 6ded698

Browse files
committed
feat: shutdown & multi thread per book
1 parent 1b70c07 commit 6ded698

3 files changed

Lines changed: 62 additions & 40 deletions

File tree

epub_browser/main.py

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -101,33 +101,30 @@ def add_book_thread(filename, pbar):
101101
return
102102

103103
# 是否需要监控
104+
watcher = EPUBWatcher(args.filename, library)
104105
def watch_changes():
105-
watcher = EPUBWatcher(args.filename, library)
106-
watcher.watch()
107-
106+
try:
107+
watcher.watch()
108+
except Exception as e:
109+
print(f"Error occurred: {e}")
110+
108111
if args.watch:
109112
watchdog_thread = threading.Thread(
110113
target=watch_changes, name="WatchdogThread"
111114
)
112115
watchdog_thread.daemon = True # 设置为守护线程(可选,这样主程序退出时线程会自动结束)
113116
watchdog_thread.start()
114-
117+
115118
# 创建服务器
119+
server_instance = EPUBServer(library, args.log)
116120
def start_serve():
117-
server_instance = EPUBServer(library, args.log)
118121
try:
119122
server_instance.start_server(
120123
port=args.port,
121124
no_browser=args.no_browser,
122125
)
123-
except KeyboardInterrupt:
124-
print("\n\nShutting down server...")
125126
except Exception as e:
126-
print(f"Error occurred: {e}")
127-
finally:
128-
server_instance.stop_server()
129-
if not args.keep_files:
130-
library.cleanup()
127+
print(f"Error occurred: {e}")
131128

132129
server_thread = threading.Thread(
133130
target=start_serve, name="ServerThread"
@@ -142,11 +139,17 @@ def start_serve():
142139
if not server_thread.is_alive():
143140
print("Server down")
144141
break
145-
if not watchdog_thread.is_alive():
146-
print("Watchdog down")
147-
break
142+
if args.watch and watchdog_thread:
143+
if not watchdog_thread.is_alive():
144+
print("Watchdog down")
145+
break
148146
except KeyboardInterrupt:
149147
print("\nShutting down...")
148+
except Exception as e:
149+
print(f"Error occurred: {e}")
150+
finally:
151+
if not args.keep_files:
152+
library.cleanup()
150153

151154

152155
if __name__ == '__main__':

epub_browser/processor.py

Lines changed: 37 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
import hashlib
88
import json
99
import minify_html
10+
import threading
11+
12+
from concurrent.futures import ThreadPoolExecutor
1013
from datetime import datetime
1114

1215
class EPUBProcessor:
@@ -566,26 +569,41 @@ def create_index_page(self):
566569

567570
def create_chapter_pages(self):
568571
"""创建章节页面"""
569-
for i, chapter in enumerate(self.chapters):
570-
chapter_path = os.path.join(self.extract_dir, chapter['path'])
571-
572-
if os.path.exists(chapter_path):
573-
try:
574-
# 读取章节内容
575-
with open(chapter_path, 'r', encoding='utf-8') as f:
576-
content = f.read()
577-
578-
# 处理HTML内容,修复资源链接并提取样式
579-
body_content, style_links = self.process_html_content(content, chapter['path'])
580-
581-
# 创建章节页面
582-
chapter_html = self.create_chapter_template(body_content, style_links, i, chapter['title'])
572+
def create_chapter_page(chapter_path, chapter, i):
573+
try:
574+
# 读取章节内容
575+
with open(chapter_path, 'r', encoding='utf-8') as f:
576+
content = f.read()
577+
578+
# 处理HTML内容,修复资源链接并提取样式
579+
body_content, style_links = self.process_html_content(content, chapter['path'])
580+
581+
# 创建章节页面
582+
chapter_html = self.create_chapter_template(body_content, style_links, i, chapter['title'])
583+
584+
with open(os.path.join(self.web_dir, f'chapter_{i}.html'), 'w', encoding='utf-8') as f:
585+
f.write(chapter_html)
583586

584-
with open(os.path.join(self.web_dir, f'chapter_{i}.html'), 'w', encoding='utf-8') as f:
585-
f.write(chapter_html)
586-
587-
except Exception as e:
588-
print(f"Failed to process chapter {chapter['path']}: {e}")
587+
except Exception as e:
588+
print(f"Failed to process chapter {chapter['path']}: {e}")
589+
590+
# 创建并启动线程
591+
threads = []
592+
with ThreadPoolExecutor(max_workers=10) as executor: # 限制最大10个并发线程
593+
for i, chapter in enumerate(self.chapters):
594+
chapter_path = os.path.join(self.extract_dir, chapter['path'])
595+
if os.path.exists(chapter_path):
596+
thread = threading.Thread(
597+
target=create_chapter_page,
598+
args=(chapter_path, chapter, i)
599+
)
600+
threads.append(thread)
601+
thread.start()
602+
603+
# 等待所有线程完成
604+
for thread in threads:
605+
thread.join()
606+
589607

590608
def process_html_content(self, content, chapter_path):
591609
"""处理HTML内容,修复资源链接并提取样式"""

epub_browser/watch.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def on_created(self, event):
3838
book_hash = book_info['hash']
3939
self.library.move_book(book_hash)
4040
self.library.create_library_home()
41-
print(f"[Added] book: {book_info['title']}")
41+
print(f"Added book: {book_info['title']}")
4242

4343
def on_modified(self, event):
4444
if not event.is_directory and event.src_path.endswith('.epub'):
@@ -55,7 +55,7 @@ def on_modified(self, event):
5555
book_hash = book_info['hash']
5656
self.library.move_book(book_hash)
5757
self.library.create_library_home()
58-
print(f"[Updated] book: {book_info['title']}")
58+
print(f"Updated book: {book_info['title']}")
5959

6060
def on_deleted(self, event):
6161
if not event.is_directory and event.src_path.endswith('.epub'):
@@ -72,11 +72,11 @@ def on_deleted(self, event):
7272
book_info = self.library.books[book_hash]
7373
self.library.remove_book(book_hash)
7474
self.library.create_library_home()
75-
print(f"[Deleted] book: {book_info['title']}")
75+
print(f"Deleted book: {book_info['title']}")
7676

7777
def on_moved(self, event):
7878
if not event.is_directory and event.src_path.endswith('.epub'):
79-
title = event.src_path
79+
title = os.path.basename(event.src_path)
8080
if event.src_path in self.library.file2hash:
8181
book_hash = self.library.file2hash[event.src_path]
8282
book_info = self.library.books[book_hash]
@@ -87,15 +87,16 @@ def on_moved(self, event):
8787
book_info = self.library.books[book_hash]
8888
self.library.remove_book(book_hash)
8989
self.library.create_library_home()
90-
print(f"[Deleted] book: {book_info['title']}")
90+
print(f"Deleted book: {book_info['title']}")
9191
if event.dest_path.endswith('.epub'):
92+
print(f"Waiting to add book...")
9293
if (not os.path.basename(event.dest_path).startswith(".")) and (not self.has_hidden_component(event.dest_path)):
9394
ok, book_info = self.library.add_book(event.dest_path)
9495
if ok:
9596
book_hash = book_info['hash']
9697
self.library.move_book(book_hash)
9798
self.library.create_library_home()
98-
print(f"[Added] book: {book_info['title']}")
99+
print(f"Added book: {book_info['title']}")
99100

100101
class EPUBWatcher:
101102
def __init__(self, paths, library):

0 commit comments

Comments
 (0)