forked from yongkangc/llmreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1408 lines (1129 loc) · 45.3 KB
/
Copy pathserver.py
File metadata and controls
1408 lines (1129 loc) · 45.3 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
# Load .env file before any other imports that might use env vars
from dotenv import load_dotenv
load_dotenv()
import pickle
import shutil
import json
import uuid
import secrets
import time
from functools import lru_cache
from typing import Optional, Dict, List, Any
from datetime import datetime
from pathlib import Path
from fastapi import FastAPI, Request, HTTPException, UploadFile, File, Form
from fastapi.responses import HTMLResponse, FileResponse, Response, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
from reader3 import (
Book,
BookMetadata,
ChapterContent,
TOCEntry,
process_epub,
process_pdf,
rebuild_flattened_pdf_book,
save_to_pickle,
)
# --- Authentication Configuration ---
AUTH_PASSWORD = os.environ.get("LLMREADER_PASSWORD")
SECRET_KEY = os.environ.get("LLMREADER_SECRET_KEY", secrets.token_hex(32))
COOKIE_NAME = "llmreader_auth"
SESSION_DURATION = 30 * 24 * 60 * 60 # 30 days in seconds
# Rate limiting for failed login attempts
LOGIN_ATTEMPTS: Dict[str, List[float]] = {} # IP -> list of timestamps
MAX_ATTEMPTS = 5
RATE_LIMIT_WINDOW = 15 * 60 # 15 minutes
if not AUTH_PASSWORD:
raise RuntimeError(
"LLMREADER_PASSWORD environment variable is required. "
"Set it to a password to protect your library."
)
# Cookie serializer
cookie_serializer = URLSafeTimedSerializer(SECRET_KEY)
def create_auth_cookie() -> str:
"""Create a signed auth cookie with current timestamp."""
return cookie_serializer.dumps({"authenticated": True, "timestamp": time.time()})
def verify_cookie(cookie: Optional[str]) -> bool:
"""Verify auth cookie signature and check expiration."""
if not cookie:
return False
try:
data = cookie_serializer.loads(cookie, max_age=SESSION_DURATION)
return data.get("authenticated", False)
except (BadSignature, SignatureExpired):
return False
def check_rate_limit(ip: str) -> bool:
"""Check if IP is under rate limit. Returns True if allowed."""
now = time.time()
attempts = LOGIN_ATTEMPTS.get(ip, [])
# Remove attempts older than the window
attempts = [t for t in attempts if now - t < RATE_LIMIT_WINDOW]
LOGIN_ATTEMPTS[ip] = attempts
return len(attempts) < MAX_ATTEMPTS
def record_failed_attempt(ip: str) -> None:
"""Record a failed login attempt for rate limiting."""
now = time.time()
if ip not in LOGIN_ATTEMPTS:
LOGIN_ATTEMPTS[ip] = []
LOGIN_ATTEMPTS[ip].append(now)
def get_client_ip(request: Request) -> str:
"""Get client IP, accounting for proxies like Cloudflare."""
# Check for Cloudflare header first
cf_ip = request.headers.get("CF-Connecting-IP")
if cf_ip:
return cf_ip
# Check X-Forwarded-For
xff = request.headers.get("X-Forwarded-For")
if xff:
return xff.split(",")[0].strip()
# Fall back to direct client
return request.client.host if request.client else "unknown"
def _hash_password(password: str) -> str:
"""Create a keyed hash of the password using HMAC-SHA256."""
import hashlib
import hmac
return hmac.new(
SECRET_KEY.encode("utf-8"),
password.encode("utf-8"),
hashlib.sha256
).hexdigest()
def verify_password(input_password: str) -> bool:
"""Verify password using HMAC hashes and constant-time comparison."""
# Hash both passwords with the secret key, then compare hashes
input_hash = _hash_password(input_password)
stored_hash = _hash_password(AUTH_PASSWORD)
return secrets.compare_digest(input_hash, stored_hash)
def is_https(request: Request) -> bool:
"""Check if request is over HTTPS (directly or via proxy)."""
# Check X-Forwarded-Proto (set by reverse proxies like Cloudflare)
proto = request.headers.get("X-Forwarded-Proto", "")
if proto.lower() == "https":
return True
# Check the URL scheme directly
return request.url.scheme == "https"
app = FastAPI(root_path="/reader")
templates = Jinja2Templates(directory="templates")
# Mount static files directory
app.mount("/static", StaticFiles(directory="static"), name="static")
# Add root_path to all templates
templates.env.globals['root_path'] = "/reader"
# --- Service Worker Route (needs special scope header) ---
@app.get("/sw.js")
async def serve_service_worker():
"""Serve the Service Worker from root with proper scope header."""
sw_path = os.path.join("static", "sw.js")
if not os.path.exists(sw_path):
raise HTTPException(status_code=404, detail="Service Worker not found")
with open(sw_path, 'r') as f:
content = f.read()
return Response(
content=content,
media_type="application/javascript",
headers={"Service-Worker-Allowed": "/reader/"}
)
@app.get("/manifest.json")
async def serve_manifest():
"""Serve the PWA manifest."""
manifest_path = os.path.join("static", "manifest.json")
if not os.path.exists(manifest_path):
raise HTTPException(status_code=404, detail="Manifest not found")
return FileResponse(manifest_path, media_type="application/manifest+json")
@app.get("/favicon.ico")
async def serve_favicon():
"""Serve the app icon as a browser favicon."""
icon_path = os.path.join("static", "icons", "icon-192.png")
if not os.path.exists(icon_path):
raise HTTPException(status_code=404, detail="Favicon not found")
return FileResponse(icon_path, media_type="image/png")
# --- Authentication Middleware ---
@app.middleware("http")
async def auth_middleware(request: Request, call_next):
"""Protect all routes except /login and /static."""
path = request.url.path
# Allow login route (both GET and POST)
if path == "/login" or path == "/reader/login":
return await call_next(request)
# Allow static files (CSS, JS, etc.)
if path.startswith("/static/") or path.startswith("/reader/static/"):
return await call_next(request)
# Allow Service Worker and manifest
if path == "/sw.js" or path == "/reader/sw.js":
return await call_next(request)
if path == "/manifest.json" or path == "/reader/manifest.json":
return await call_next(request)
if path == "/favicon.ico" or path == "/reader/favicon.ico":
return await call_next(request)
# Allow book images (served from /read/{book_id}/images/ or /reader/read/{book_id}/images/)
if "/images/" in path and ("/read/" in path):
return await call_next(request)
# Check auth cookie
cookie = request.cookies.get(COOKIE_NAME)
if not verify_cookie(cookie):
# Redirect to login with the original URL as 'next' parameter
next_url = request.url.path
if request.url.query:
next_url += "?" + request.url.query
return RedirectResponse(
url=f"/reader/login?next={next_url}",
status_code=302
)
return await call_next(request)
# Where are the book folders located?
BOOKS_DIR = "."
# Highlights storage
HIGHLIGHTS_FILE = "highlights.json"
# Reading progress storage
PROGRESS_FILE = "reading_progress.json"
# Highlight tag limits
MAX_HIGHLIGHT_TAGS = 12
MAX_HIGHLIGHT_TAG_LENGTH = 30
def _sanitize_filename(filename: str, fallback_ext: str) -> str:
"""Return a filesystem-safe filename, ensuring an extension exists."""
base = os.path.basename(filename or "")
safe = "".join([c for c in base if c.isalnum() or c in ("-", "_", ".")]).strip(".")
if not safe:
safe = f"upload{fallback_ext}"
if not os.path.splitext(safe)[1]:
safe = safe + fallback_ext
return safe
# --- Highlights Storage Functions ---
def load_highlights() -> Dict[str, Any]:
"""Load highlights from JSON file."""
if not os.path.exists(HIGHLIGHTS_FILE):
return {}
try:
with open(HIGHLIGHTS_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
print(f"Error loading highlights: {e}")
return {}
def save_highlights(highlights: Dict[str, Any]) -> None:
"""Save highlights to JSON file atomically."""
try:
# Write to temp file first, then rename (atomic)
temp_file = HIGHLIGHTS_FILE + '.tmp'
with open(temp_file, 'w', encoding='utf-8') as f:
json.dump(highlights, f, indent=2, ensure_ascii=False)
os.replace(temp_file, HIGHLIGHTS_FILE)
except Exception as e:
print(f"Error saving highlights: {e}")
raise HTTPException(status_code=500, detail=f"Failed to save highlights: {e}")
# --- Reading Progress Storage Functions ---
def load_progress() -> Dict[str, Any]:
"""Load reading progress from JSON file."""
if not os.path.exists(PROGRESS_FILE):
return {}
try:
with open(PROGRESS_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
print(f"Error loading progress: {e}")
return {}
def save_progress(progress: Dict[str, Any]) -> None:
"""Save reading progress to JSON file atomically."""
try:
temp_file = PROGRESS_FILE + '.tmp'
with open(temp_file, 'w', encoding='utf-8') as f:
json.dump(progress, f, indent=2, ensure_ascii=False)
os.replace(temp_file, PROGRESS_FILE)
except Exception as e:
print(f"Error saving progress: {e}")
raise HTTPException(status_code=500, detail=f"Failed to save progress: {e}")
def normalize_highlight_tags(tags_input: Any) -> List[str]:
"""Normalize tags for highlights: lowercase, trimmed, unique, capped."""
if tags_input is None:
return []
if isinstance(tags_input, str):
raw_tags = tags_input.split(',')
elif isinstance(tags_input, list):
raw_tags = tags_input
else:
raw_tags = [tags_input]
normalized: List[str] = []
seen = set()
for raw_tag in raw_tags:
tag = str(raw_tag).strip().lower()
if not tag:
continue
if len(tag) > MAX_HIGHLIGHT_TAG_LENGTH:
continue
if tag in seen:
continue
normalized.append(tag)
seen.add(tag)
if len(normalized) >= MAX_HIGHLIGHT_TAGS:
break
return normalized
def hydrate_highlight_record(highlight: Dict[str, Any]) -> Dict[str, Any]:
"""Ensure highlight records include backward-compatible defaults."""
hydrated = dict(highlight)
hydrated["note"] = hydrated.get("note", "")
hydrated["color"] = hydrated.get("color", "yellow")
hydrated["tags"] = normalize_highlight_tags(hydrated.get("tags", []))
return hydrated
def hydrate_highlights_collection(highlights: Dict[str, Any]) -> Dict[str, Any]:
"""Normalize highlight records in an entire highlights payload."""
hydrated: Dict[str, Any] = {}
for book_id, book_data in highlights.items():
book_payload = dict(book_data)
book_payload["highlights"] = [
hydrate_highlight_record(highlight)
for highlight in book_data.get("highlights", [])
]
hydrated[book_id] = book_payload
return hydrated
def parse_highlight_ids(ids_input: Any) -> List[str]:
"""Normalize a highlight id list from request payloads."""
if not isinstance(ids_input, list):
return []
ids: List[str] = []
seen = set()
for raw_id in ids_input:
highlight_id = str(raw_id).strip()
if not highlight_id:
continue
if highlight_id in seen:
continue
ids.append(highlight_id)
seen.add(highlight_id)
return ids
def get_highlight_by_id(highlight_id: str) -> tuple[Optional[str], Optional[Dict], Optional[int]]:
"""
Find a highlight by ID across all books.
Returns (book_id, highlight_dict, index) or (None, None, None) if not found.
"""
highlights = load_highlights()
for book_id, book_data in highlights.items():
for idx, highlight in enumerate(book_data.get('highlights', [])):
if highlight.get('id') == highlight_id:
return book_id, highlight, idx
return None, None, None
def export_to_obsidian_markdown(filter_book_id: str = "") -> str:
"""
Export highlights to Obsidian-compatible markdown format.
If filter_book_id is provided, only export that book's highlights.
Returns markdown string.
"""
highlights = load_highlights()
if not highlights:
return "# Reading Highlights\n\nNo highlights yet."
lines = ["# Reading Highlights\n"]
book_ids = [filter_book_id] if filter_book_id and filter_book_id in highlights else sorted(highlights.keys())
for book_id in book_ids:
book_data = highlights[book_id]
book_highlights = [
hydrate_highlight_record(hl)
for hl in book_data.get('highlights', [])
]
if not book_highlights:
continue
# Load book to get title
book = load_book_cached(book_id)
book_title = book.metadata.title if book else book_id
lines.append(f"\n## [[{book_title}]]\n")
# Group by chapter
by_chapter: Dict[int, List[Dict]] = {}
for hl in book_highlights:
ch_idx = hl.get('chapter_index', 0)
if ch_idx not in by_chapter:
by_chapter[ch_idx] = []
by_chapter[ch_idx].append(hl)
for ch_idx in sorted(by_chapter.keys()):
chapter_highlights = by_chapter[ch_idx]
# Get chapter title
if book and ch_idx < len(book.spine):
chapter_title = book.spine[ch_idx].title
else:
chapter_title = f"Chapter {ch_idx + 1}"
lines.append(f"\n### {chapter_title}\n")
for hl in chapter_highlights:
# Add highlight text as blockquote
text = hl.get('text', '').strip()
lines.append(f"> {text}\n")
# Add block reference
hl_id = hl.get('id', 'unknown')
lines.append(f"^{hl_id}\n")
# Add note if present
note = hl.get('note', '').strip()
if note:
lines.append(f"Note: {note}\n")
tags = hl.get('tags', [])
if tags:
tag_line = " ".join(f"#{tag}" for tag in tags)
lines.append(f"Tags: {tag_line}\n")
# Add timestamp
timestamp = hl.get('timestamp', '')
if timestamp:
try:
dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
formatted_date = dt.strftime('%Y-%m-%d')
lines.append(f"Created: {formatted_date}\n")
except:
pass
lines.append("\n---\n")
return "\n".join(lines)
@lru_cache(maxsize=32)
def load_book_cached(folder_name: str) -> Optional[Book]:
"""
Loads the book from the pickle file.
Cached so we don't re-read the disk on every click.
"""
file_path = os.path.join(BOOKS_DIR, folder_name, "book.pkl")
if not os.path.exists(file_path):
return None
try:
with open(file_path, "rb") as f:
book = pickle.load(f)
# Migration: Add tags field for old books (version 3.0)
if not hasattr(book.metadata, 'tags'):
book.metadata.tags = []
rebuilt_book = rebuild_flattened_pdf_book(book)
if rebuilt_book is not None:
book = rebuilt_book
save_to_pickle(book, os.path.join(BOOKS_DIR, folder_name))
return book
except Exception as e:
print(f"Error loading book {folder_name}: {e}")
return None
# --- Authentication Routes ---
@app.get("/login", response_class=HTMLResponse)
async def login_page(request: Request, next: str = "/", error: Optional[str] = None):
"""Render the login page."""
return templates.TemplateResponse(request, "login.html", {
"next": next,
"error": error
})
@app.post("/login")
async def login_submit(
request: Request,
password: str = Form(...),
next: str = Form("/")
):
"""Handle login form submission."""
client_ip = get_client_ip(request)
# Check rate limit
if not check_rate_limit(client_ip):
return templates.TemplateResponse(request, "login.html", {
"next": next,
"error": "Too many login attempts. Please try again in 15 minutes."
}, status_code=429)
# Verify password using constant-time comparison
if not verify_password(password):
record_failed_attempt(client_ip)
return templates.TemplateResponse(request, "login.html", {
"next": next,
"error": "Invalid password"
}, status_code=401)
# Create response with redirect
# Ensure next URL is safe (relative path only)
safe_next = next if next.startswith("/") else "/"
response = RedirectResponse(url=safe_next, status_code=302)
# Set secure cookie
response.set_cookie(
key=COOKIE_NAME,
value=create_auth_cookie(),
max_age=SESSION_DURATION,
httponly=True, # Prevent JavaScript access (XSS protection)
samesite="lax", # CSRF protection
secure=is_https(request), # Only send over HTTPS when applicable
)
return response
@app.get("/logout")
async def logout(request: Request):
"""Log out by clearing the auth cookie."""
response = RedirectResponse(url="/reader/login", status_code=302)
response.delete_cookie(key=COOKIE_NAME)
return response
def find_cover_image(book, book_id: str) -> str | None:
"""Find cover image path for a book, returns URL path or None."""
# Look for common cover image patterns in the book's images dict
cover_patterns = ['cover.jpeg', 'cover.jpg', 'cover.png', 'Cover.jpeg', 'Cover.jpg', 'Cover.png']
for pattern in cover_patterns:
if pattern in book.images:
return f"/read/{book_id}/images/{book.images[pattern]}"
# Also check for keys containing 'cover'
for key, value in book.images.items():
if 'cover' in key.lower():
return f"/read/{book_id}/images/{value}"
return None
@app.get("/", response_class=HTMLResponse)
async def library_view(request: Request):
"""Lists all available processed books."""
books = []
all_tags = set()
progress_data = load_progress()
# Scan directory for folders ending in '_data' that have a book.pkl
if os.path.exists(BOOKS_DIR):
for item in os.listdir(BOOKS_DIR):
item_path = os.path.join(BOOKS_DIR, item)
if item.endswith("_data") and os.path.isdir(item_path):
# Try to load it to get the title
book = load_book_cached(item)
if book:
tags = getattr(book.metadata, 'tags', [])
all_tags.update(tags)
cover_image = find_cover_image(book, item)
book_progress = progress_data.get(item, {})
books.append({
"id": item,
"title": book.metadata.title,
"author": ", ".join(book.metadata.authors),
"chapters": len(book.spine),
"tags": tags,
"cover_image": cover_image,
"processed_at": getattr(book, 'processed_at', '2000-01-01'),
"progress": book_progress.get("percent_complete", 0),
"last_chapter": book_progress.get("chapter_index", 0),
"completed": book_progress.get("completed", False)
})
# Sort books by processed_at descending (newest first)
books.sort(key=lambda b: b['processed_at'], reverse=True)
return templates.TemplateResponse(request, "library.html", {
"books": books,
"all_tags": sorted(all_tags)
})
@app.get("/read/{book_id}", response_class=HTMLResponse)
async def redirect_to_first_chapter(book_id: str):
"""Helper to just go to chapter 0."""
return RedirectResponse(url=f"/read/{book_id}/0", status_code=302)
@app.get("/read/{book_id}/images/{image_name:path}")
async def serve_image(book_id: str, image_name: str):
"""
Serves images specifically for a book.
The HTML contains <img src="images/pic.jpg">.
The browser resolves this to /read/{book_id}/images/pic.jpg.
Must be defined BEFORE the chapter route to take precedence.
"""
safe_book_id = os.path.basename(book_id)
safe_image_name = os.path.basename(image_name)
img_path = os.path.join(BOOKS_DIR, safe_book_id, "images", safe_image_name)
if not os.path.exists(img_path):
raise HTTPException(status_code=404, detail="Image not found")
return FileResponse(img_path)
@app.get("/read/{book_id}/{chapter_ref:path}", response_class=HTMLResponse)
async def read_chapter(request: Request, book_id: str, chapter_ref: str):
"""
The main reader interface.
chapter_ref can be either:
- An integer index (e.g., "5")
- A chapter filename (e.g., "part0006.html" or "text/part0006.html")
"""
book = load_book_cached(book_id)
if not book:
raise HTTPException(status_code=404, detail="Book not found")
# Try to parse as integer first
if chapter_ref.isdigit():
chapter_index = int(chapter_ref)
else:
# It's a filename - find the matching chapter index
# Handle anchors (e.g., "part0006.html#section1")
clean_file = chapter_ref.split('#')[0]
anchor = chapter_ref.split('#')[1] if '#' in chapter_ref else None
basename = os.path.basename(clean_file)
chapter_index = None
for idx, chapter in enumerate(book.spine):
chapter_basename = os.path.basename(chapter.href)
if chapter.href == clean_file or chapter_basename == basename or chapter.href == basename:
chapter_index = idx
break
if chapter_index is None:
raise HTTPException(status_code=404, detail=f"Chapter '{chapter_ref}' not found")
# Redirect to canonical URL with index (preserving anchor if present)
redirect_url = f"/read/{book_id}/{chapter_index}"
if anchor:
redirect_url += f"#{anchor}"
return RedirectResponse(url=redirect_url, status_code=302)
if chapter_index < 0 or chapter_index >= len(book.spine):
raise HTTPException(status_code=404, detail="Chapter not found")
current_chapter = book.spine[chapter_index]
# Calculate Prev/Next links
prev_idx = chapter_index - 1 if chapter_index > 0 else None
next_idx = chapter_index + 1 if chapter_index < len(book.spine) - 1 else None
return templates.TemplateResponse(request, "reader.html", {
"book": book,
"current_chapter": current_chapter,
"chapter_index": chapter_index,
"book_id": book_id,
"prev_idx": prev_idx,
"next_idx": next_idx
})
@app.post("/upload")
async def upload_epub(file: UploadFile = File(...)):
"""
Accepts an EPUB or PDF upload, processes it into a *_data folder and returns basic info.
"""
if not file.filename:
raise HTTPException(status_code=400, detail="No file provided")
ext = os.path.splitext(file.filename)[1].lower()
if ext not in {".epub", ".pdf"}:
raise HTTPException(status_code=400, detail="Only .epub or .pdf files are supported")
safe_name = _sanitize_filename(file.filename, fallback_ext=ext)
base_name = os.path.splitext(safe_name)[0]
out_dir = os.path.join(BOOKS_DIR, f"{base_name}_data")
if os.path.exists(out_dir):
raise HTTPException(status_code=409, detail="Book already exists in library")
temp_path = os.path.join(BOOKS_DIR, safe_name)
try:
with open(temp_path, "wb") as buffer:
while True:
chunk = await file.read(1024 * 1024)
if not chunk:
break
buffer.write(chunk)
if ext == ".pdf":
book_obj = process_pdf(temp_path, out_dir)
else:
book_obj = process_epub(temp_path, out_dir)
save_to_pickle(book_obj, out_dir)
# Clear cache so subsequent requests pick up the new book list immediately.
load_book_cached.cache_clear()
except Exception as e:
# Best-effort cleanup
if os.path.exists(out_dir):
shutil.rmtree(out_dir, ignore_errors=True)
raise HTTPException(status_code=500, detail=f"Failed to process upload: {e}")
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
return {
"book_id": os.path.basename(out_dir),
"title": book_obj.metadata.title,
"chapters": len(book_obj.spine),
}
# --- Tag Management API ---
@app.get("/api/tags")
async def get_all_tags():
"""
Returns a list of all unique tags across all books in the library.
"""
tags = set()
if os.path.exists(BOOKS_DIR):
for item in os.listdir(BOOKS_DIR):
item_path = os.path.join(BOOKS_DIR, item)
if item.endswith("_data") and os.path.isdir(item_path):
book = load_book_cached(item)
if book and hasattr(book.metadata, 'tags'):
tags.update(book.metadata.tags)
return {"tags": sorted(tags)}
@app.get("/api/books/{book_id}/tags")
async def get_book_tags(book_id: str):
"""
Returns the tags for a specific book.
"""
book = load_book_cached(book_id)
if not book:
raise HTTPException(status_code=404, detail="Book not found")
tags = getattr(book.metadata, 'tags', [])
return {"tags": tags}
@app.put("/api/books/{book_id}/tags")
async def update_book_tags(book_id: str, request: Request):
"""
Updates the tags for a specific book.
Expects JSON body: {"tags": ["tag1", "tag2", ...]}
"""
book = load_book_cached(book_id)
if not book:
raise HTTPException(status_code=404, detail="Book not found")
try:
body = await request.json()
tags_input = body.get("tags", [])
# Clean and validate tags: strip whitespace, lowercase, remove empty
tags = []
for tag in tags_input:
tag_clean = str(tag).strip().lower()
if tag_clean and len(tag_clean) <= 30: # Max 30 chars per tag
tags.append(tag_clean)
# Remove duplicates while preserving order
seen = set()
unique_tags = []
for tag in tags:
if tag not in seen:
seen.add(tag)
unique_tags.append(tag)
# Update book metadata
book.metadata.tags = unique_tags
# Save updated book to pickle
book_path = os.path.join(BOOKS_DIR, book_id)
save_to_pickle(book, book_path)
# Clear cache to reload updated book
load_book_cached.cache_clear()
return {"tags": unique_tags}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to update tags: {e}")
# --- Reading Progress API ---
@app.get("/api/progress")
async def get_all_progress():
"""Get reading progress for all books."""
return load_progress()
@app.get("/api/books/{book_id}/progress")
async def get_book_progress(book_id: str):
"""Get reading progress for a specific book."""
progress = load_progress()
return progress.get(book_id, {"chapter_index": 0, "scroll_percent": 0, "percent_complete": 0})
@app.put("/api/books/{book_id}/progress")
async def update_book_progress(book_id: str, request: Request):
"""
Update reading progress for a specific book.
Expects JSON body: {"chapter_index": 0, "scroll_percent": 0.5, "total_chapters": 10}
"""
try:
body = await request.json()
chapter_index = body.get("chapter_index", 0)
scroll_percent = body.get("scroll_percent", 0)
total_chapters = body.get("total_chapters", 1)
# Calculate overall progress: (chapter + scroll within chapter) / total chapters
percent_complete = ((chapter_index + scroll_percent) / total_chapters) * 100
percent_complete = min(100, max(0, percent_complete))
progress = load_progress()
existing = progress.get(book_id, {})
# Auto-mark as completed when reaching 100%
completed = existing.get("completed", False)
if percent_complete >= 100:
completed = True
progress[book_id] = {
"chapter_index": chapter_index,
"scroll_percent": round(scroll_percent, 4),
"percent_complete": round(percent_complete, 1),
"completed": completed,
"updated_at": datetime.now().isoformat()
}
save_progress(progress)
return progress[book_id]
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to update progress: {e}")
@app.put("/api/books/{book_id}/completed")
async def toggle_book_completed(book_id: str, request: Request):
"""
Toggle or set the completed status of a book.
Expects JSON body: {"completed": true/false}
"""
try:
body = await request.json()
completed = body.get("completed", False)
progress = load_progress()
if book_id not in progress:
progress[book_id] = {
"chapter_index": 0,
"scroll_percent": 0,
"percent_complete": 0,
"completed": completed,
"updated_at": datetime.now().isoformat()
}
else:
progress[book_id]["completed"] = completed
progress[book_id]["updated_at"] = datetime.now().isoformat()
save_progress(progress)
return {"completed": completed}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to update completed status: {e}")
@app.delete("/api/books/{book_id}")
async def delete_book(book_id: str):
"""
Delete a book and all associated data.
Removes: book folder, highlights, reading progress.
"""
# Sanitize book_id to prevent directory traversal
safe_book_id = os.path.basename(book_id)
book_path = os.path.join(BOOKS_DIR, safe_book_id)
# Verify book exists
if not os.path.isdir(book_path) or not safe_book_id.endswith("_data"):
raise HTTPException(status_code=404, detail="Book not found")
try:
# Delete book folder (book.pkl + images/)
shutil.rmtree(book_path)
# Clean up highlights.json
highlights = load_highlights()
if safe_book_id in highlights:
del highlights[safe_book_id]
save_highlights(highlights)
# Clean up reading_progress.json
progress = load_progress()
if safe_book_id in progress:
del progress[safe_book_id]
save_progress(progress)
# Clear book cache
load_book_cached.cache_clear()
return {"success": True, "message": "Book deleted successfully"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to delete book: {e}")
# --- Highlights API ---
@app.get("/api/books/{book_id}/offline-package")
async def get_offline_package(book_id: str):
"""
Returns everything needed to download a book for offline reading.
Includes metadata, TOC, all chapters, and image manifest.
"""
book = load_book_cached(book_id)
if not book:
raise HTTPException(status_code=404, detail="Book not found")
# Build chapters array
chapters = []
for idx, chapter in enumerate(book.spine):
chapters.append({
"index": idx,
"href": chapter.href,
"title": chapter.title,
"html": chapter.content,
})
# Build image manifest (paths for client to fetch)
images = []
for original_path, local_filename in book.images.items():
images.append({
"path": f"/reader/read/{book_id}/images/{local_filename}",
"original": original_path,
})
# Convert TOC to serializable format
def toc_to_dict(entries):
result = []
for entry in entries:
result.append({
"title": entry.title,
"href": entry.href,
"file_href": entry.file_href,
"anchor": entry.anchor,
"children": toc_to_dict(entry.children) if entry.children else []
})
return result
return {
"book_id": book_id,
"metadata": {
"title": book.metadata.title,
"authors": book.metadata.authors,
"language": book.metadata.language,
},
"toc": toc_to_dict(book.toc),
"spine": [{"index": idx, "href": ch.href, "title": ch.title} for idx, ch in enumerate(book.spine)],