forked from sweatyeggs69/Bookie
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1685 lines (1501 loc) · 66.8 KB
/
app.py
File metadata and controls
1685 lines (1501 loc) · 66.8 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
"""Bookie – Docker ebook manager with Material Design 3 UI."""
import io
import json
import math
import os
import re
import secrets
import logging
import stat
import time
import urllib.request
import urllib.error
import zipfile
import xml.etree.ElementTree as ET
from datetime import timedelta, date
from pathlib import Path
import crypto
DATA_DIR = Path(os.environ.get("DATA_DIR", "data"))
DEFAULT_DB_FILENAME = "bookie.db"
LEGACY_DB_FILENAME = "booker.db"
def _get_or_create_secret_key() -> str:
key_file = DATA_DIR / "secret_key"
key_file.parent.mkdir(parents=True, exist_ok=True)
if key_file.exists():
return key_file.read_text().strip()
key = secrets.token_hex(32)
key_file.write_text(key)
key_file.chmod(stat.S_IRUSR | stat.S_IWUSR)
return key
# ---------------------------------------------------------------------------
# Embedded metadata extraction
# ---------------------------------------------------------------------------
def extract_embedded_metadata(file_path: Path, ext: str) -> dict:
"""Extract title/author/etc. from embedded EPUB, PDF, or audio file metadata."""
if ext == "epub":
return _extract_epub_metadata(file_path)
elif ext == "pdf":
return _extract_pdf_metadata(file_path)
elif ext in ("mp3", "m4b", "m4a", "aac", "flac", "ogg", "wma", "opus"):
return _extract_audio_metadata(file_path)
return {}
def _extract_epub_metadata(path: Path) -> dict:
try:
with zipfile.ZipFile(str(path)) as zf:
# Locate OPF from container.xml
with zf.open("META-INF/container.xml") as f:
croot = ET.parse(f).getroot()
ns_c = {"c": "urn:oasis:names:tc:opendocument:xmlns:container"}
rf = croot.find(".//c:rootfile", ns_c)
if rf is None:
return {}
opf_path = rf.get("full-path", "")
with zf.open(opf_path) as f:
oroot = ET.parse(f).getroot()
ns = {
"dc": "http://purl.org/dc/elements/1.1/",
"opf": "http://www.idpf.org/2007/opf",
}
def dc(tag):
el = oroot.find(f".//dc:{tag}", ns)
return el.text.strip() if el is not None and el.text else None
# ISBN from dc:identifier
isbn10 = isbn13 = None
for el in oroot.findall(".//dc:identifier", ns):
scheme = (el.get("{http://www.idpf.org/2007/opf}scheme") or "").lower()
val = re.sub(r"[-\s]", "", el.text or "")
if val.isdigit():
if len(val) == 13 and isbn13 is None:
isbn13 = val
elif len(val) == 10 and isbn10 is None:
isbn10 = val
elif "isbn" in scheme:
if val.isdigit() and len(val) == 13:
isbn13 = val
elif val.isdigit() and len(val) == 10:
isbn10 = val
# Creators: primary author is first without refine role or role=aut
authors = []
for el in oroot.findall(".//dc:creator", ns):
if el.text:
authors.append(el.text.strip())
author = authors[0] if authors else None
date_raw = dc("date")
pub_date = date_raw[:4] if date_raw else None
return {
"title": dc("title"),
"author": author,
"publisher": dc("publisher"),
"language": dc("language"),
"description": dc("description"),
"published_date": pub_date,
"isbn": isbn10,
"isbn13": isbn13,
}
except Exception as exc:
logger.debug("EPUB metadata extraction failed: %s", exc)
return {}
def _extract_pdf_metadata(path: Path) -> dict:
try:
from pypdf import PdfReader
reader = PdfReader(str(path))
info = reader.metadata or {}
def clean(val):
return val.strip() if isinstance(val, str) and val.strip() else None
raw_date = info.get("/CreationDate", "")
pub_date = None
if raw_date and len(raw_date) >= 6:
# D:YYYYMMDDHHmmSS format
digits = re.sub(r"[^0-9]", "", raw_date[:10])
if len(digits) >= 4:
pub_date = digits[:4]
return {
"title": clean(info.get("/Title")),
"author": clean(info.get("/Author")),
"publisher": clean(info.get("/Creator") or info.get("/Producer")),
"description": clean(info.get("/Subject")),
"published_date": pub_date,
}
except Exception as exc:
logger.debug("PDF metadata extraction failed: %s", exc)
return {}
def _extract_audio_metadata(path: Path) -> dict:
"""Extract metadata from MP3, M4B, FLAC, and other audio formats."""
try:
from mutagen import File
audio = File(str(path))
if audio is None:
return {}
# Helper to safely get tag values
def get_tag(key, fallback_keys=None):
val = audio.get(key)
if val:
return str(val[0]) if isinstance(val, list) and val else str(val)
if fallback_keys:
for fk in fallback_keys:
val = audio.get(fk)
if val:
return str(val[0]) if isinstance(val, list) and val else str(val)
return None
duration = None
try:
if audio.info and hasattr(audio.info, 'length'):
duration = int(audio.info.length)
except Exception:
pass
return {
"title": get_tag("TIT2", ["©nam", "Title"]), # Title
"author": get_tag("TPE1", ["©ART", "Artist"]), # Performer/Artist
"narrator": get_tag("TPE2", ["©NAR"]), # Narrator/Band
"description": get_tag("TIT3", ["©cmt", "Description"]), # Subtitle/Comments
"publisher": get_tag("TPUB", ["©pub", "Publisher"]), # Publisher
"published_date": get_tag("TDRC", ["©day", "Year"]), # Recording date/Year
"duration": duration,
}
except Exception as exc:
logger.debug("Audio metadata extraction failed: %s", exc)
return {}
from flask import (
Flask,
jsonify,
request,
send_file,
send_from_directory,
redirect,
session,
abort,
)
from werkzeug.utils import secure_filename
from sqlalchemy.orm import subqueryload
from models import db, Book, Settings, EmailAddress, Tag, BookTag
from auth import login_required, register_auth_routes
import scraper
import covers as cover_mgr
import mailer
import renamer
# Set the root logger to INFO so that INFO+ records are captured from the start.
# logging.basicConfig() is a no-op when any handler is already registered, so
# we configure the root logger explicitly.
_LOG_FORMAT = "%(asctime)s %(levelname)-8s %(name)s: %(message)s"
_root_logger = logging.getLogger()
_root_logger.setLevel(logging.INFO)
# Attach a StreamHandler so INFO+ records reach the terminal. Only add one if
# the root logger has no StreamHandler yet — gunicorn/uWSGI add their own
# handler before importing the app, so we skip it to avoid duplicate output.
if not any(isinstance(h, logging.StreamHandler) for h in _root_logger.handlers):
_console_handler = logging.StreamHandler()
_console_handler.setFormatter(logging.Formatter(_LOG_FORMAT))
_root_logger.addHandler(_console_handler)
# Silence chatty library loggers so DEBUG/INFO mode doesn't flood the output
# with irrelevant framework noise.
for _noisy_logger in ("werkzeug", "sqlalchemy.engine", "sqlalchemy.pool",
"urllib3", "PIL", "asyncio"):
logging.getLogger(_noisy_logger).setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
# In-memory log buffer — keeps the last N lines so the Logs tab has something
# to show. Size is intentionally modest: even at DEBUG the suppressed library
# loggers mean we only store app-level records.
_LOG_BUFFER_CAPACITY = 500
class _LogBuffer(logging.Handler):
def __init__(self, capacity: int = _LOG_BUFFER_CAPACITY):
super().__init__()
self._buf: list[str] = []
self._cap = capacity
def emit(self, record: logging.LogRecord) -> None:
self._buf.append(self.format(record))
if len(self._buf) > self._cap:
self._buf = self._buf[-self._cap:]
def get_lines(self) -> list[str]:
return list(self._buf)
_log_buffer = _LogBuffer()
_log_buffer.setFormatter(logging.Formatter(_LOG_FORMAT))
logging.getLogger().addHandler(_log_buffer)
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
BOOKS_DIR = DATA_DIR / "books"
COVERS_DIR = DATA_DIR / "covers"
ALLOWED_EXTENSIONS = {"epub", "pdf", "mobi", "azw", "azw3", "fb2", "djvu", "cbz", "cbr", "txt",
"mp3", "m4b", "m4a", "aac", "flac", "ogg", "wma", "opus"}
AUDIOBOOK_EXTENSIONS = {"mp3", "m4b", "m4a", "aac", "flac", "ogg", "wma", "opus"}
MAX_UPLOAD_MB = 128
MAX_AUDIOBOOK_MB = 500 # Larger limit for audiobooks
# Magic-byte signatures for formats where we can reliably verify content.
# Extensions not listed here are accepted on extension alone (txt, fb2, mobi, etc.
# have no universal single-byte signature that is safe to enforce).
_MAGIC_BYTES: dict[str, list[bytes]] = {
"epub": [b"PK\x03\x04"], # EPUB is a ZIP archive
"pdf": [b"%PDF"],
"cbz": [b"PK\x03\x04"], # CBZ is a ZIP archive
"cbr": [b"Rar!\x1a\x07\x00", # RAR v4
b"Rar!\x1a\x07\x01\x00", # RAR v5
b"PK\x03\x04"], # some CBRs are actually ZIPs
"djvu": [b"AT&TFORM"],
"mp3": [b"\xff\xfb", b"\xff\xfa", b"ID3"], # MP3 syncword or ID3 tag
"m4b": [b"\x00\x00\x00\x18ftypM4B"], # M4B atom signature
"m4a": [b"\x00\x00\x00\x20ftypisom"], # M4A ISO Base Media signature
"flac": [b"fLaC"], # FLAC signature
"ogg": [b"OggS"], # OGG signature
}
_MAGIC_READ_BYTES = 8 # max prefix length we need to read
def _magic_ok(file_storage, ext: str) -> bool:
"""Return True if the uploaded file's header matches the expected format."""
sigs = _MAGIC_BYTES.get(ext)
if not sigs:
return True # no check defined for this extension
header = file_storage.read(_MAGIC_READ_BYTES)
file_storage.seek(0)
return any(header.startswith(sig) for sig in sigs)
_EMAIL_RE = re.compile(r'^[^@\s]+@[^@\s]+\.[^@\s]+$')
def _valid_email(value: str) -> bool:
return bool(_EMAIL_RE.match(value))
def _safe_int(value, default: int) -> int:
"""Convert *value* to int, returning *default* on failure."""
try:
return int(value)
except (TypeError, ValueError):
return default
def _cleanup_empty_dirs(directory: Path) -> None:
"""Remove *directory* and its parent if both are empty and not BOOKS_DIR."""
try:
for folder in [directory, directory.parent]:
if folder != BOOKS_DIR and folder.exists() and not any(folder.iterdir()):
folder.rmdir()
except Exception as exc:
logger.debug("Could not remove empty directory %s: %s", directory, exc)
# ---------------------------------------------------------------------------
# Update check
# ---------------------------------------------------------------------------
_UPDATE_CHECK_TTL = 3600 # seconds
_update_check_cache: tuple[float, dict] | None = None
def _check_for_update() -> dict:
"""Query GHCR for the latest image creation date and compare to BUILD_DATE."""
global _update_check_cache
now = time.time()
if _update_check_cache and (now - _update_check_cache[0]) < _UPDATE_CHECK_TTL:
return _update_check_cache[1]
build_date = os.environ.get("BUILD_DATE", "").strip()
if not build_date:
result: dict = {"update_available": False, "reason": "no_build_date"}
_update_check_cache = (now, result)
return result
ghcr_image = os.environ.get("GHCR_IMAGE", "ghcr.io/sweatyeggs69/bookie").strip()
# Expect format: registry/owner/image (e.g. ghcr.io/sweatyeggs69/bookie)
slash_idx = ghcr_image.find("/")
if slash_idx == -1:
result = {"update_available": False, "reason": "invalid_image"}
_update_check_cache = (now, result)
return result
registry = ghcr_image[:slash_idx]
image_path = ghcr_image[slash_idx + 1:]
try:
# 1. Obtain an anonymous pull token from the registry
token_url = f"https://{registry}/token?scope=repository:{image_path}:pull"
with urllib.request.urlopen(token_url, timeout=10) as resp:
token_data = json.loads(resp.read())
token = token_data.get("token") or token_data.get("access_token", "")
# 2. Fetch the manifest for the 'latest' tag
manifest_url = f"https://{registry}/v2/{image_path}/manifests/latest"
manifest_req = urllib.request.Request(
manifest_url,
headers={
"Authorization": f"Bearer {token}",
"Accept": (
"application/vnd.oci.image.manifest.v1+json,"
"application/vnd.docker.distribution.manifest.v2+json"
),
},
)
with urllib.request.urlopen(manifest_req, timeout=10) as resp:
manifest = json.loads(resp.read())
config_digest = manifest.get("config", {}).get("digest", "")
if not config_digest:
result = {"update_available": False, "reason": "no_config_digest"}
_update_check_cache = (now, result)
return result
# 3. Fetch the config blob to read the image creation timestamp
blob_url = f"https://{registry}/v2/{image_path}/blobs/{config_digest}"
blob_req = urllib.request.Request(
blob_url,
headers={"Authorization": f"Bearer {token}"},
)
with urllib.request.urlopen(blob_req, timeout=10) as resp:
config = json.loads(resp.read())
# Prefer the OCI label (set at pipeline start, same moment as BUILD_DATE)
# over config["created"] which is set when Docker build finishes (always later).
labels = config.get("config", {}).get("Labels") or {}
latest_created = labels.get("org.opencontainers.image.created", "") or config.get("created", "")
# ISO-8601 strings compare lexicographically
update_available = bool(latest_created and latest_created > build_date)
result = {
"update_available": update_available,
"current_build": build_date,
"latest_build": latest_created,
}
except Exception as exc:
logger.debug("Update check failed: %s", exc)
result = {"update_available": False, "reason": "check_failed"}
_update_check_cache = (now, result)
return result
def create_app():
_db_env = os.environ.get("DATABASE_URL")
if not _db_env:
DATA_DIR.mkdir(parents=True, exist_ok=True)
_legacy_db = DATA_DIR / LEGACY_DB_FILENAME
_default_db = DATA_DIR / DEFAULT_DB_FILENAME
if _legacy_db.exists() and not _default_db.exists():
_legacy_db.replace(_default_db)
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
"DATABASE_URL", f"sqlite:///{(DATA_DIR / DEFAULT_DB_FILENAME).absolute()}"
)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["MAX_CONTENT_LENGTH"] = MAX_UPLOAD_MB * 1024 * 1024
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY") or _get_or_create_secret_key()
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=30)
app.config["SESSION_COOKIE_HTTPONLY"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
_secure_env = os.environ.get("SESSION_COOKIE_SECURE", "").lower()
if _secure_env in ("0", "false", "no"):
app.config["SESSION_COOKIE_SECURE"] = False
elif _secure_env in ("1", "true", "yes"):
app.config["SESSION_COOKIE_SECURE"] = True
else:
app.config["SESSION_COOKIE_SECURE"] = not app.debug
db.init_app(app)
with app.app_context():
BOOKS_DIR.mkdir(parents=True, exist_ok=True)
COVERS_DIR.mkdir(parents=True, exist_ok=True)
db.create_all()
_migrate_db(app)
# Restore persisted log level (defaults to INFO on first run)
_saved_level = (Settings.get("log_level") or "INFO").upper()
_saved_numeric = getattr(logging, _saved_level, logging.INFO)
logging.getLogger().setLevel(_saved_numeric)
# Security headers
@app.after_request
def set_security_headers(response):
response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("X-Frame-Options", "SAMEORIGIN")
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
return response
# Register auth routes
register_auth_routes(app, Settings)
# -----------------------------------------------------------------------
# Frontend – serve React SPA
# -----------------------------------------------------------------------
_REACT_DIST = Path(__file__).parent / "static" / "dist"
@app.route("/static/site.webmanifest")
def web_manifest():
resp = send_from_directory("static", "site.webmanifest")
resp.headers["Content-Type"] = "application/manifest+json"
resp.headers["Cache-Control"] = "no-cache"
return resp
@app.route("/sw.js")
def service_worker():
"""Serve SW from root scope so it can control all pages."""
resp = send_from_directory("static", "sw.js")
resp.headers["Service-Worker-Allowed"] = "/"
resp.headers["Cache-Control"] = "no-cache"
return resp
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def serve_frontend(path):
# Never intercept API routes
if path.startswith("api/") or path.startswith("static/"):
abort(404)
target = _REACT_DIST / path
if path and target.exists() and target.is_file():
return send_from_directory(_REACT_DIST, path)
return send_from_directory(_REACT_DIST, "index.html")
# -----------------------------------------------------------------------
# Books – CRUD
# -----------------------------------------------------------------------
@app.route("/api/books", methods=["GET"])
@login_required
def list_books():
query = Book.query
search = request.args.get("q", "").strip()
if search:
# Escape LIKE metacharacters so they're treated as literals
escaped = search.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
like = f"%{escaped}%"
query = query.filter(
db.or_(
Book.title.ilike(like),
Book.author.ilike(like),
Book.series.ilike(like),
Book.isbn.ilike(like),
Book.isbn13.ilike(like),
)
)
fmt = request.args.get("format")
if fmt:
query = query.filter(Book.file_format == fmt.lower())
series_filter = request.args.get("series")
if series_filter:
query = query.filter(Book.series == series_filter)
lang = request.args.get("language")
if lang:
query = query.filter(Book.language == lang)
tag = request.args.get("tag")
if tag:
query = query.join(BookTag, BookTag.book_id == Book.id).join(Tag, Tag.id == BookTag.tag_id).filter(Tag.name == tag)
_SORT_COLS = {"author", "title", "series", "published_date", "date_added", "file_size", "rating"}
sort = request.args.get("sort", "author")
if sort not in _SORT_COLS:
sort = "author"
order = request.args.get("order", "asc")
if sort == "series":
# Sort nulls last, then by series name, then by series order
if order == "desc":
query = query.order_by(
db.case((Book.series.is_(None), 1), else_=0).asc(),
Book.series.desc(),
db.case((Book.series_order.is_(None), 1), else_=0).asc(),
Book.series_order.desc(),
)
else:
query = query.order_by(
db.case((Book.series.is_(None), 1), else_=0).asc(),
Book.series.asc(),
db.case((Book.series_order.is_(None), 1), else_=0).asc(),
Book.series_order.asc(),
)
elif sort == "author":
# Author primary, then series name + order as secondary (nulls last), then title
if order == "desc":
query = query.order_by(
Book.author.desc(),
db.case((Book.series.is_(None), 1), else_=0).asc(),
Book.series.asc(),
db.case((Book.series_order.is_(None), 1), else_=0).asc(),
Book.series_order.asc(),
Book.title.desc(),
)
else:
query = query.order_by(
Book.author.asc(),
db.case((Book.series.is_(None), 1), else_=0).asc(),
Book.series.asc(),
db.case((Book.series_order.is_(None), 1), else_=0).asc(),
Book.series_order.asc(),
Book.title.asc(),
)
elif sort == "title":
# Sort by title, stripping leading articles (A, An, The)
sort_key = db.case(
(Book.title.ilike("the %"), db.func.substr(Book.title, 5)),
(Book.title.ilike("an %"), db.func.substr(Book.title, 4)),
(Book.title.ilike("a %"), db.func.substr(Book.title, 3)),
else_=Book.title,
)
query = query.order_by(sort_key.desc() if order == "desc" else sort_key.asc())
else:
col = getattr(Book, sort, None)
if col is not None:
query = query.order_by(col.desc() if order == "desc" else col.asc())
page = max(1, request.args.get("page", 1, type=int))
per_page = min(max(1, request.args.get("per_page", 40, type=int)), 200)
paginated = query.paginate(page=page, per_page=per_page, error_out=False)
return jsonify({
"books": [b.to_dict() for b in paginated.items],
"total": paginated.total,
"pages": paginated.pages,
"page": page,
})
@app.route("/api/books/<int:book_id>", methods=["GET"])
@login_required
def get_book(book_id):
book = Book.query.get_or_404(book_id)
return jsonify(book.to_dict())
@app.route("/api/books/scan", methods=["POST"])
@login_required
def scan_books():
"""Walk BOOKS_DIR, register new files, and remove DB entries for deleted files."""
# ── Remove stale records (file deleted from disk) ──────────────────
removed = 0
for book in Book.query.all():
if not (BOOKS_DIR / book.filename).exists():
cover_mgr.delete_cover(book.id)
db.session.delete(book)
removed += 1
db.session.commit()
# ── Register new files ─────────────────────────────────────────────
known = {b.filename for b in Book.query.with_entities(Book.filename).all()}
auto_meta = Settings.get("auto_metadata", "false") == "true"
added = 0
for path in BOOKS_DIR.rglob("*"):
if not path.is_file():
continue
ext = path.suffix.lstrip(".").lower()
if ext not in ALLOWED_EXTENSIONS:
continue
rel = str(path.relative_to(BOOKS_DIR))
if rel in known:
continue
book = Book(
filename=rel,
file_format=ext,
file_size=path.stat().st_size,
title=path.stem,
is_audiobook=ext in AUDIOBOOK_EXTENSIONS,
)
db.session.add(book)
db.session.flush()
# Extract embedded cover
cover_data = None
if ext == "epub":
cover_data = cover_mgr.extract_cover_from_epub(str(path))
elif ext == "pdf":
cover_data = cover_mgr.extract_cover_from_pdf(str(path))
if cover_data:
cf = cover_mgr.save_cover(book.id, cover_data)
if cf:
book.cover_filename = cf
# Extract and apply embedded metadata (title, author, ISBN, …)
embedded = extract_embedded_metadata(path, ext)
if any(embedded.values()):
_apply_metadata(book, embedded, replace_missing_only=False)
# Auto-fetch from online sources if the setting is on
if auto_meta:
try:
_auto_fetch_metadata(book)
except Exception as exc:
logger.warning("Auto-fetch failed for scanned book %s: %s", rel, exc)
# Apply rename/organize scheme
try:
_rename_and_organize(book, path)
except Exception as exc:
logger.warning("Rename failed for scanned book %s: %s", rel, exc)
added += 1
known.add(book.filename) # use updated filename after rename
db.session.commit()
return jsonify({"added": added, "removed": removed})
@app.route("/api/books/upload", methods=["POST"])
@login_required
def upload_book():
if "file" not in request.files:
return jsonify({"error": "No file provided"}), 400
file = request.files["file"]
if not file.filename:
return jsonify({"error": "Empty filename"}), 400
ext = file.filename.rsplit(".", 1)[-1].lower() if "." in file.filename else ""
if ext not in ALLOWED_EXTENSIONS:
return jsonify({"error": f"Unsupported format: {ext}"}), 400
if not _magic_ok(file, ext):
return jsonify({"error": f"File content does not match declared format (.{ext})"}), 400
filename = secure_filename(file.filename)
dest = BOOKS_DIR / filename
counter = 1
stem = Path(filename).stem
while dest.exists():
filename = f"{stem}_{counter}.{ext}"
dest = BOOKS_DIR / filename
counter += 1
file.save(str(dest))
size = dest.stat().st_size
book = Book(
filename=filename,
file_format=ext,
file_size=size,
title=Path(filename).stem,
is_audiobook=ext in AUDIOBOOK_EXTENSIONS,
)
db.session.add(book)
db.session.commit()
# Extract embedded cover
cover_data = None
if ext == "epub":
cover_data = cover_mgr.extract_cover_from_epub(str(dest))
elif ext == "pdf":
cover_data = cover_mgr.extract_cover_from_pdf(str(dest))
if cover_data:
cf = cover_mgr.save_cover(book.id, cover_data)
if cf:
book.cover_filename = cf
db.session.commit()
# Apply embedded metadata first (title, author, ISBN, etc.)
embedded = extract_embedded_metadata(dest, ext)
if any(embedded.values()):
_apply_metadata(book, embedded, replace_missing_only=False)
# Auto-fetch from online sources to fill remaining gaps
auto_meta = Settings.get("auto_metadata", "false")
if auto_meta == "true":
_auto_fetch_metadata(book)
# Apply renaming scheme + folder organization
_rename_and_organize(book, dest)
return jsonify(book.to_dict()), 201
@app.route("/api/books/<int:book_id>", methods=["PUT"])
@login_required
def update_book(book_id):
book = Book.query.get_or_404(book_id)
data = request.get_json(silent=True)
if data is None:
data = {}
elif not isinstance(data, dict):
return jsonify({"error": "Invalid JSON payload"}), 400
fields = [
"title", "author", "published_date", "page_count",
"series", "series_order", "rating",
]
for f in fields:
if f not in data:
continue
val = data[f]
if f == "published_date" and isinstance(val, str):
val = val[:4] or None
# Guard float fields against NaN / Infinity which would corrupt sorting
if f in ("series_order", "rating") and val is not None:
try:
val = float(val)
except (TypeError, ValueError):
return jsonify({"error": f"Invalid value for {f}"}), 400
if not math.isfinite(val):
return jsonify({"error": f"{f} must be a finite number"}), 400
setattr(book, f, val)
db.session.commit()
# Re-apply rename/organize after metadata update
file_path = BOOKS_DIR / book.filename
if file_path.exists():
try:
_rename_and_organize(book, file_path)
except Exception as exc:
logger.warning("Rename after save failed for book %s: %s", book_id, exc)
return jsonify(book.to_dict())
@app.route("/api/books/<int:book_id>", methods=["DELETE"])
@login_required
def delete_book(book_id):
book = Book.query.get_or_404(book_id)
filepath = BOOKS_DIR / book.filename
parent = filepath.parent
if filepath.exists():
filepath.unlink()
_cleanup_empty_dirs(parent)
cover_mgr.delete_cover(book_id)
db.session.delete(book)
db.session.commit()
return jsonify({"success": True})
@app.route("/api/books/ids", methods=["GET"])
@login_required
def get_book_ids():
"""Return all book IDs matching the current filters (no pagination)."""
query = Book.query
search = request.args.get("q", "").strip()
if search:
escaped = search.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
like = f"%{escaped}%"
query = query.filter(db.or_(
Book.title.ilike(like), Book.author.ilike(like),
Book.series.ilike(like), Book.isbn.ilike(like), Book.isbn13.ilike(like),
))
fmt = request.args.get("format")
if fmt:
query = query.filter(Book.file_format == fmt.lower())
if series := request.args.get("series"):
query = query.filter(Book.series == series)
if tag := request.args.get("tag"):
query = query.join(BookTag, BookTag.book_id == Book.id).join(Tag, Tag.id == BookTag.tag_id).filter(Tag.name == tag)
return jsonify({"ids": [b.id for b in query.with_entities(Book.id).all()]})
@app.route("/api/books/bulk-fetch-metadata", methods=["POST"])
@login_required
def bulk_fetch_metadata():
"""Fetch metadata for a list of book IDs, one at a time."""
import time
ids = (request.get_json(silent=True) or {}).get("ids", [])
updated = 0
for book_id in ids:
book = Book.query.get(book_id)
if not book:
continue
_auto_fetch_metadata(book)
updated += 1
if updated < len(ids):
time.sleep(1) # be polite to metadata sources
return jsonify({"updated": updated})
@app.route("/api/books/bulk-delete", methods=["POST"])
@login_required
def bulk_delete_books():
ids = (request.get_json(silent=True) or {}).get("ids", [])
deleted = 0
for book_id in ids:
book = Book.query.get(book_id)
if not book:
continue
filepath = BOOKS_DIR / book.filename
parent = filepath.parent
if filepath.exists():
filepath.unlink()
_cleanup_empty_dirs(parent)
cover_mgr.delete_cover(book_id)
db.session.delete(book)
deleted += 1
db.session.commit()
return jsonify({"deleted": deleted})
@app.route("/api/books/bulk-tag", methods=["POST"])
@login_required
def bulk_add_tag():
data = request.get_json(silent=True) or {}
ids = data.get("ids", [])
tag_name = (data.get("tag") or "").strip()
if not tag_name:
return jsonify({"error": "tag required"}), 400
tag = Tag.query.filter_by(name=tag_name).first()
if not tag:
tag = Tag(name=tag_name)
db.session.add(tag)
db.session.flush()
added = 0
for book_id in ids:
exists = BookTag.query.filter_by(book_id=book_id, tag_id=tag.id).first()
if not exists:
db.session.add(BookTag(book_id=book_id, tag_id=tag.id))
added += 1
db.session.commit()
return jsonify({"added": added, "tag": tag.to_dict()})
@app.route("/api/books/bulk-untag", methods=["POST"])
@login_required
def bulk_remove_tag():
data = request.get_json(silent=True) or {}
ids = data.get("ids", [])
tag_name = (data.get("tag") or "").strip()
if not tag_name:
return jsonify({"error": "tag required"}), 400
tag = Tag.query.filter_by(name=tag_name).first()
if not tag:
return jsonify({"removed": 0})
removed = (
BookTag.query
.filter(BookTag.tag_id == tag.id, BookTag.book_id.in_(ids))
.delete(synchronize_session=False)
)
db.session.commit()
return jsonify({"removed": removed})
@app.route("/api/books/<int:book_id>/download", methods=["GET"])
@login_required
def download_book(book_id):
book = Book.query.get_or_404(book_id)
filepath = (BOOKS_DIR / book.filename).resolve()
if not filepath.is_relative_to(BOOKS_DIR.resolve()):
abort(400)
if not filepath.exists():
abort(404)
return send_file(str(filepath), as_attachment=True, download_name=Path(book.filename).name)
@app.route("/api/audiobooks/<int:book_id>/stream", methods=["GET"])
@login_required
def stream_audiobook(book_id):
"""Stream audiobook with range request support for seeking."""
book = Book.query.get_or_404(book_id)
if not book.is_audiobook:
abort(404)
filepath = (BOOKS_DIR / book.filename).resolve()
if not filepath.is_relative_to(BOOKS_DIR.resolve()):
abort(400)
if not filepath.exists():
abort(404)
# Flask/Werkzeug automatically handles range requests (Range header)
mimetype = f"audio/{book.audio_format}" if book.audio_format else "audio/mpeg"
return send_file(str(filepath), mimetype=mimetype)
@app.route("/api/audiobooks/<int:book_id>/metadata", methods=["GET"])
@login_required
def get_audiobook_metadata(book_id):
"""Get full audiobook metadata including chapters."""
book = Book.query.get_or_404(book_id)
if not book.is_audiobook:
abort(404)
return jsonify({
"id": book.id,
"title": book.title,
"author": book.author,
"narrator": book.narrator,
"duration": book.duration,
"format": book.audio_format,
"chapters": json.loads(book.chapters) if book.chapters else [],
"file_size": book.file_size,
})
@app.route("/api/books/<int:book_id>/rename", methods=["POST"])
@login_required
def rename_book(book_id):
"""Rename a specific book's file using a given scheme or custom template."""
book = Book.query.get_or_404(book_id)
data = request.get_json(silent=True) or {}
scheme = data.get("scheme", "author_title")
custom_tpl = data.get("custom_template", "")
meta = {
"title": book.title,
"author": book.author,
"published_date": book.published_date,
"publisher": book.publisher,
"isbn": book.isbn,
"isbn13": book.isbn13,
"language": book.language,
}
src = BOOKS_DIR / book.filename
if not src.exists():
return jsonify({"error": "File not found on disk"}), 404
new_path, new_name = renamer.rename_book_file(src, BOOKS_DIR, scheme, meta, custom_tpl)
book.filename = new_name
db.session.commit()
return jsonify({"success": True, "new_filename": new_name})
@app.route("/api/rename/preview", methods=["POST"])
@login_required
def rename_preview():
"""Preview how a naming scheme would rename a list of books."""
data = request.get_json(silent=True) or {}
scheme = data.get("scheme", "author_title")
custom_tpl = data.get("custom_template", "")
book_ids = data.get("book_ids", [])
template = renamer.get_scheme_template(scheme, custom_tpl)
previews = []
for bid in book_ids:
book = Book.query.get(bid)
if not book:
continue
meta = {
"title": book.title, "author": book.author,
"published_date": book.published_date, "publisher": book.publisher,
"isbn": book.isbn, "isbn13": book.isbn13, "language": book.language,
}
previews.append({
"id": book.id,
"original": book.filename,
"preview": renamer.apply_scheme(template, book.filename, meta),
})
return jsonify(previews)
@app.route("/api/rename/schemes", methods=["GET"])
@login_required
def list_schemes():
return jsonify({
"schemes": [
{"key": k, "label": v, "template": renamer.SCHEMES.get(k)}
for k, v in renamer.SCHEME_LABELS.items()
],
"placeholders": [{"placeholder": p, "description": d} for p, d in renamer.PLACEHOLDERS],
})
@app.route("/api/rename/bulk", methods=["POST"])
@login_required
def bulk_rename():
"""Rename all books using the current naming scheme and folder structure. apply=true to commit."""
data = request.get_json(silent=True) or {}
apply = data.get("apply", False)
scheme = Settings.get("rename_scheme", "original")
custom_tpl = Settings.get("rename_custom_template", "")
folder_mode = Settings.get("folder_organization", "flat")
books = Book.query.all()
results = []
errors = []
for book in books:
src = BOOKS_DIR / book.filename
if not src.exists():