-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2915 lines (2665 loc) · 142 KB
/
main.py
File metadata and controls
2915 lines (2665 loc) · 142 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
#!/usr/bin/env python3
"""AutoBook desktop workspace. Run with: uv run main.py"""
from __future__ import annotations
import io
import platform
import subprocess
import threading
import tkinter as tk
from tkinter import messagebox
from collections import Counter
from pathlib import Path
from typing import Any, Callable
import customtkinter as ctk
import requests
from PIL import Image
from app.devices import copy_to_device, detect_devices
from app.document_tools import convert_book_format, convert_books, export_library_web_preview, repair_book_file, run_ocr_for_book, run_ocr_for_books
from app.web_companion import start_server as start_web_companion_server
from app.library import (
LIBRARY_DIR,
add_to_library,
apply_bulk_update,
cancel_download_job,
clear_finished_queue_jobs,
clear_search_cache,
delete_books,
enqueue_download_job,
export_library_snapshot,
get_all_books,
get_library_analytics,
get_book,
get_book_path,
get_device_profiles,
get_download_history,
get_download_queue,
import_library_snapshot,
generate_companion_feed,
get_recommendations,
get_search_cache_stats,
get_settings,
get_transfer_history,
get_usage_events,
get_optional_tooling,
get_next_queued_job,
list_local_plugins,
list_collections,
list_tags,
load_search_cache,
organize_library_files,
record_usage_event,
save_device_profile,
save_search_cache,
scan_library_health,
reorder_download_job,
record_download_history,
record_transfer_history,
remove_from_library,
retry_download_job,
search_books_in_library,
set_book_collections,
set_book_notes_and_tags,
set_reading_status,
toggle_favorite,
update_book,
update_download_job,
update_settings,
delete_device_profile,
import_plugin_manifest,
toggle_plugin_enabled,
)
from app.ai_tools import ai_enrich_book, ai_generate_search_suggestions, ai_generate_tags, ai_is_configured
from app.logging_utils import LOG_FILE, log_exception, log_info, setup_logging
from app.search import BookResult, book_result_from_dict, book_result_to_dict, download_link_from_dict, resolve_external_download, search_books
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("dark-blue")
_NAV_BG = "#0F172A"
_APP_BG = "#0B1220"
_SURFACE = "#111827"
_SURFACE_ALT = "#1F2937"
_CARD_BG = "#162033"
_CARD_BORDER = "#273449"
_TEXT = "#E5EEF9"
_TEXT_MUTED = "#93A4BC"
_TEXT_SOFT = "#6F839E"
_ACCENT = "#2F6FED"
_ACCENT_HOVER = "#275DCA"
_ACCENT_SOFT = "#17305F"
_SUCCESS = "#17B26A"
_WARNING = "#F59E0B"
_DANGER = "#D64545"
_DANGER_HOVER = "#B83838"
_THEME_PRESETS = {
"Corporate Blue": {
"_NAV_BG": "#0F172A",
"_APP_BG": "#0B1220",
"_SURFACE": "#111827",
"_SURFACE_ALT": "#1F2937",
"_CARD_BG": "#162033",
"_CARD_BORDER": "#273449",
"_TEXT": "#E5EEF9",
"_TEXT_MUTED": "#93A4BC",
"_TEXT_SOFT": "#6F839E",
"_ACCENT": "#2F6FED",
"_ACCENT_HOVER": "#275DCA",
"_ACCENT_SOFT": "#17305F",
},
"Slate Green": {
"_NAV_BG": "#101A18",
"_APP_BG": "#0A1211",
"_SURFACE": "#13201D",
"_SURFACE_ALT": "#1B2B27",
"_CARD_BG": "#18312A",
"_CARD_BORDER": "#2A443D",
"_TEXT": "#E7F3EF",
"_TEXT_MUTED": "#9BB9AF",
"_TEXT_SOFT": "#729086",
"_ACCENT": "#2F8F6B",
"_ACCENT_HOVER": "#277558",
"_ACCENT_SOFT": "#184438",
},
}
_UA = {
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
)
}
_I18N = {
"English": {
"Catalog Search": "Catalog Search",
"Library": "Library",
"Download History": "Download History",
"Analytics": "Analytics",
"Devices": "Devices",
"Settings": "Settings",
"Trending titles": "Trending titles",
"Auto categories": "Auto categories",
"Recent usage events": "Recent usage events",
"Interface language": "Interface language",
"Enable local usage telemetry": "Enable local usage telemetry",
"Open File": "Open File",
"Send to Device": "Send to Device",
"Remove": "Remove",
"Edit": "Edit",
"Repair": "Repair",
"Run OCR": "Run OCR",
"Convert": "Convert",
"AI Enrich": "AI Enrich",
"Library Health Scan": "Library Health Scan",
"Search": "Search",
"Filters": "Filters",
"Advanced Filters": "Advanced Filters",
"AI Suggestions": "AI Suggestions",
"Favorites only": "Favorites only",
"Bulk mode": "Bulk mode",
"Favorite Selected": "Favorite Selected",
"Set Reading": "Set Reading",
"Add Collection": "Add Collection",
"Batch OCR": "Batch OCR",
"Batch Convert": "Batch Convert",
"Remove Selected": "Remove Selected",
"Download queue": "Download queue",
"Run Queue": "Run Queue",
"Clear Finished": "Clear Finished",
"Allowed sources": "Allowed sources",
"Allowed formats": "Allowed formats",
"Allowed actions": "Allowed actions",
"Device profiles": "Device profiles",
"Save Settings": "Save Settings",
"Open Log File": "Open Log File",
"Export Snapshot": "Export Snapshot",
"Import Snapshot": "Import Snapshot",
"Run Organize": "Run Organize",
"Health Scan": "Health Scan",
"Companion Feed": "Companion Feed",
"Clear Cache": "Clear Cache",
"Web Preview": "Web Preview",
"Launch Web App": "Launch Web App",
"Import Plugin": "Import Plugin",
"Add Profile": "Add Profile",
"Delete Profile": "Delete Profile",
"Refresh": "Refresh",
"Welcome to AutoBook": "Welcome to AutoBook",
"Start Using AutoBook": "Start Using AutoBook",
"Ready for search.": "Ready for search.",
"Discovery workspace": "Discovery workspace",
"No direct file available": "No direct file available",
"Recommended from your library": "Recommended from your library",
"No queued downloads.": "No queued downloads.",
"Save": "Save",
"Cancel": "Cancel",
"Toggle": "Toggle",
},
"Turkish": {
"Catalog Search": "Katalog Arama",
"Library": "Kütüphane",
"Download History": "İndirme Geçmişi",
"Analytics": "Analitik",
"Devices": "Cihazlar",
"Settings": "Ayarlar",
"Trending titles": "Öne çıkan kitaplar",
"Auto categories": "Otomatik kategoriler",
"Recent usage events": "Son kullanım olayları",
"Interface language": "Arayüz dili",
"Enable local usage telemetry": "Yerel kullanım telemetrisini etkinleştir",
"Open File": "Dosyayı Aç",
"Send to Device": "Cihaza Gönder",
"Remove": "Kaldır",
"Edit": "Düzenle",
"Repair": "Onar",
"Run OCR": "OCR Çalıştır",
"Convert": "Dönüştür",
"AI Enrich": "AI Zenginleştir",
"Library Health Scan": "Kütüphane Sağlık Taraması",
"Search": "Ara",
"Filters": "Filtreler",
"Advanced Filters": "Gelişmiş Filtreler",
"AI Suggestions": "AI Önerileri",
"Favorites only": "Sadece favoriler",
"Bulk mode": "Toplu işlem modu",
"Favorite Selected": "Seçileni Favorile",
"Set Reading": "Okuma Durumu Ver",
"Add Collection": "Koleksiyon Ekle",
"Batch OCR": "Toplu OCR",
"Batch Convert": "Toplu Dönüştür",
"Remove Selected": "Seçileni Kaldır",
"Download queue": "İndirme kuyruğu",
"Run Queue": "Kuyruğu Çalıştır",
"Clear Finished": "Bitenleri Temizle",
"Allowed sources": "İzin verilen kaynaklar",
"Allowed formats": "İzin verilen formatlar",
"Allowed actions": "İzin verilen aksiyonlar",
"Device profiles": "Cihaz profilleri",
"Save Settings": "Ayarları Kaydet",
"Open Log File": "Log Dosyasını Aç",
"Export Snapshot": "Anlık Görüntü Dışa Aktar",
"Import Snapshot": "Anlık Görüntü İçe Aktar",
"Run Organize": "Düzenlemeyi Çalıştır",
"Health Scan": "Sağlık Taraması",
"Companion Feed": "Companion Feed",
"Clear Cache": "Önbelleği Temizle",
"Web Preview": "Web Önizleme",
"Launch Web App": "Web Uygulamasını Başlat",
"Import Plugin": "Plugin İçe Aktar",
"Add Profile": "Profil Ekle",
"Delete Profile": "Profili Sil",
"Refresh": "Yenile",
"Welcome to AutoBook": "AutoBook'a Hos Geldin",
"Start Using AutoBook": "AutoBook'u Kullanmaya Basla",
"Ready for search.": "Arama icin hazir.",
"Discovery workspace": "Kesif alani",
"No direct file available": "Dogrudan dosya baglantisi yok",
"Recommended from your library": "Kutuphane onerileri",
"No queued downloads.": "Kuyrukta indirme yok.",
"Save": "Kaydet",
"Cancel": "Iptal",
"Toggle": "Degistir",
},
}
def _load_cover(url: str, size: tuple[int, int] = (100, 150)) -> ctk.CTkImage | None:
if not url:
return None
try:
response = requests.get(url, timeout=8, headers=_UA)
response.raise_for_status()
img = Image.open(io.BytesIO(response.content))
return ctk.CTkImage(light_image=img, dark_image=img, size=size)
except Exception:
log_exception(f"Cover load failed for url={url!r}")
return None
def _safe_filename(title: str, fmt: str) -> str:
safe = "".join(ch if ch.isalnum() or ch in " -_" else "" for ch in title)[:80].strip()
return f"{safe}.{fmt}" if safe else f"book.{fmt}"
def _rating_stars(rating: float) -> str:
full = int(rating)
half = 1 if rating - full >= 0.3 else 0
empty = 5 - full - half
return "★" * full + ("½" if half else "") + "☆" * empty
class ScrollableFrame(tk.Frame):
"""Canvas-based scrollable container with explicit trackpad routing."""
_instances: list["ScrollableFrame"] = []
_bindings_installed = False
def __init__(self, master, fg_color=_APP_BG, **kwargs):
super().__init__(master, bg=fg_color, **kwargs)
self._canvas = tk.Canvas(
self,
bg=fg_color,
cursor="arrow",
borderwidth=0,
highlightthickness=0,
)
self._scrollbar = tk.Scrollbar(self, orient="vertical", command=self._canvas.yview)
self._canvas.configure(yscrollcommand=self._scrollbar.set)
self._canvas.pack(side="left", fill="both", expand=True)
self._scrollbar.pack(side="right", fill="y")
self.inner = tk.Frame(self._canvas, bg=fg_color)
self._window_id = self._canvas.create_window((0, 0), window=self.inner, anchor="nw")
self._canvas.bind("<Configure>", self._on_canvas_configure)
self.inner.bind("<Configure>", self._on_inner_configure)
ScrollableFrame._instances.append(self)
self._install_global_bindings()
def winfo_children(self):
return self.inner.winfo_children()
def _on_canvas_configure(self, event=None):
width = self._canvas.winfo_width()
if width > 10:
self._canvas.itemconfigure(self._window_id, width=width)
self._canvas.configure(scrollregion=self._canvas.bbox("all"))
def _on_inner_configure(self, _event=None):
self._canvas.configure(scrollregion=self._canvas.bbox("all"))
@classmethod
def _install_global_bindings(cls) -> None:
if cls._bindings_installed:
return
root = tk._get_default_root()
if root is None:
return
for sequence in ("<MouseWheel>", "<Button-4>", "<Button-5>", "<Shift-MouseWheel>"):
root.bind_all(sequence, cls._dispatch_scroll, add="+")
cls._bindings_installed = True
def _owns_widget(self, widget: tk.Misc | None) -> bool:
current = widget
while current is not None:
if current in {self, self._canvas, self.inner}:
return True
current = current.master
return False
@classmethod
def _dispatch_scroll(cls, event) -> str | None:
root = tk._get_default_root()
if root is None:
return None
widget = root.winfo_containing(root.winfo_pointerx(), root.winfo_pointery()) or event.widget
for instance in list(cls._instances):
if not instance.winfo_exists():
try:
cls._instances.remove(instance)
except ValueError:
pass
continue
if instance._owns_widget(widget):
return instance._on_mousewheel(event)
return None
def _on_mousewheel(self, event) -> str:
try:
if getattr(event, "num", None) == 4:
delta = -1
elif getattr(event, "num", None) == 5:
delta = 1
else:
raw_delta = int(getattr(event, "delta", 0))
if raw_delta == 0:
return "break"
if platform.system() == "Darwin":
delta = -max(1, min(12, abs(raw_delta)))
if raw_delta < 0:
delta = abs(delta)
else:
delta = -max(1, min(8, abs(raw_delta) // 120 or 1)) if raw_delta > 0 else max(1, min(8, abs(raw_delta) // 120 or 1))
self._canvas.yview_scroll(delta, "units")
except Exception:
log_exception("Trackpad scroll dispatch failed")
return "break"
class AutoBookApp(ctk.CTk):
def __init__(self) -> None:
super().__init__()
self.logger = setup_logging()
self.settings = get_settings()
self._apply_theme_preset(self.settings.get("theme_preset", "Corporate Blue"))
self.title("AutoBook Workspace")
self.geometry("1280x860")
self.minsize(1020, 680)
self.configure(fg_color=_APP_BG)
self._image_refs: list[ctk.CTkImage] = []
self.inline_status: ctk.CTkLabel | None = None
self.nav_buttons: dict[str, ctk.CTkButton] = {}
self.current_search_results: list[BookResult] = []
self.selected_book_ids: set[str] = set()
self.queue_processing = False
self._build_shell()
self.after(150, self._show_onboarding_if_needed)
self._show_search()
def _t(self, text: str) -> str:
language = self.settings.get("interface_language", "English")
return _I18N.get(language, {}).get(text, text)
def _apply_theme_preset(self, preset_name: str) -> None:
preset = _THEME_PRESETS.get(preset_name, _THEME_PRESETS["Corporate Blue"])
globals().update(preset)
def _notify(self, title: str, message: str) -> None:
if not self.settings.get("notifications_enabled", True):
return
try:
messagebox.showinfo(title, message)
except Exception:
log_exception("Notification display failed")
def _track(self, event: str, **details: Any) -> None:
try:
if not self.settings.get("telemetry_enabled", True):
return
record_usage_event(event, **details)
except Exception:
log_exception(f"Usage telemetry failed event={event!r}")
def _build_shell(self) -> None:
sidebar = ctk.CTkFrame(self, width=255, corner_radius=0, fg_color=_NAV_BG)
sidebar.pack(side="left", fill="y")
sidebar.pack_propagate(False)
brand = ctk.CTkFrame(sidebar, fg_color="transparent")
brand.pack(fill="x", padx=22, pady=(24, 18))
ctk.CTkLabel(brand, text="AutoBook", font=ctk.CTkFont(size=28, weight="bold"), text_color=_TEXT).pack(anchor="w")
ctk.CTkLabel(
brand,
text="Acquisition and library workspace",
font=ctk.CTkFont(size=13),
text_color=_TEXT_MUTED,
).pack(anchor="w", pady=(4, 0))
nav = ctk.CTkFrame(sidebar, fg_color="transparent")
nav.pack(fill="x", padx=16, pady=(8, 0))
for key, label, cmd in [
("search", self._t("Catalog Search"), self._show_search),
("library", self._t("Library"), self._show_library),
("history", self._t("Download History"), self._show_history),
("analytics", self._t("Analytics"), self._show_analytics),
("devices", self._t("Devices"), self._show_devices),
("settings", self._t("Settings"), self._show_settings),
]:
self._add_nav_button(nav, key, label, cmd)
footer = ctk.CTkFrame(sidebar, fg_color=_SURFACE, corner_radius=18)
footer.pack(side="bottom", fill="x", padx=16, pady=16)
ctk.CTkLabel(footer, text="Observability", font=ctk.CTkFont(size=12, weight="bold"), text_color=_TEXT_MUTED).pack(
anchor="w", padx=14, pady=(12, 2)
)
ctk.CTkLabel(
footer,
text=f"Application log: {LOG_FILE.name}",
font=ctk.CTkFont(size=12),
text_color=_TEXT_SOFT,
justify="left",
wraplength=190,
).pack(anchor="w", padx=14, pady=(0, 14))
self.content = ctk.CTkFrame(self, corner_radius=0, fg_color=_APP_BG)
self.content.pack(side="right", fill="both", expand=True)
self.content.pack_propagate(False)
def _build_shell_refresh(self) -> None:
for child in self.winfo_children():
child.destroy()
self.nav_buttons = {}
self._build_shell()
self._show_settings()
def _show_onboarding_if_needed(self) -> None:
if self.settings.get("onboarding_completed", False):
return
dialog = ctk.CTkToplevel(self)
dialog.title("Welcome to AutoBook")
dialog.geometry("560x360")
dialog.configure(fg_color=_SURFACE)
dialog.transient(self)
dialog.grab_set()
ctk.CTkLabel(dialog, text=self._t("Welcome to AutoBook"), font=ctk.CTkFont(size=24, weight="bold"), text_color=_TEXT).pack(anchor="w", padx=24, pady=(24, 8))
for line in [
"1. Search the catalog and download a book.",
"2. Organize titles with collections and favorites.",
"3. Use OCR, conversion, device transfer and analytics as needed.",
]:
ctk.CTkLabel(dialog, text=line, font=ctk.CTkFont(size=14), text_color=_TEXT_MUTED, justify="left").pack(anchor="w", padx=24, pady=4)
ctk.CTkButton(
dialog,
text=self._t("Start Using AutoBook"),
width=180,
height=40,
fg_color=_ACCENT,
hover_color=_ACCENT_HOVER,
corner_radius=14,
text_color=_TEXT,
command=lambda: (update_settings(onboarding_completed=True), self._refresh_settings_cache(), dialog.destroy()),
).pack(anchor="w", padx=24, pady=(18, 0))
def _add_nav_button(self, parent: ctk.CTkFrame, key: str, label: str, command: Callable[[], None]) -> None:
button = ctk.CTkButton(
parent,
text=label,
command=command,
height=46,
corner_radius=14,
anchor="w",
fg_color="transparent",
hover_color=_SURFACE_ALT,
text_color=_TEXT_MUTED,
font=ctk.CTkFont(size=14, weight="bold"),
)
button.pack(fill="x", pady=4)
self.nav_buttons[key] = button
def _set_active_nav(self, key: str) -> None:
for button_key, button in self.nav_buttons.items():
active = button_key == key
button.configure(
fg_color=_ACCENT_SOFT if active else "transparent",
hover_color=_ACCENT_SOFT if active else _SURFACE_ALT,
text_color=_TEXT if active else _TEXT_MUTED,
)
def _clear_content(self) -> None:
self._image_refs.clear()
self.inline_status = None
for widget in self.content.winfo_children():
widget.destroy()
def _set_status(self, message: str) -> None:
if self.inline_status:
try:
self.inline_status.configure(text=message)
except Exception:
log_exception("Status label update failed")
def _refresh_settings_cache(self) -> None:
self.settings = get_settings()
def _allowed_formats(self) -> set[str]:
formats = self.settings.get("allowed_formats", ["EPUB", "PDF"])
if not isinstance(formats, list):
return {"EPUB", "PDF"}
return {str(item).upper() for item in formats}
def _action_allowed(self, action: str) -> bool:
allowed = self.settings.get("allowed_actions", ["download", "transfer", "ocr", "convert", "ai"])
if not isinstance(allowed, list):
return True
return action in allowed
def _active_device_profile(self) -> dict[str, str]:
active = self.settings.get("active_device_profile", "Default")
for profile in get_device_profiles():
if profile.get("name") == active:
return profile
return get_device_profiles()[0]
def _execute_download_job(self, selected_link: Any, book: BookResult) -> tuple[str, str]:
allowed_formats = self._allowed_formats()
if selected_link.format.upper() not in allowed_formats:
raise RuntimeError(f"{selected_link.format.upper()} downloads are disabled by policy.")
ordered_links = [selected_link] + [link for link in book.downloads if link.url != selected_link.url and link.format == selected_link.format]
last_error = "Unknown download error."
for link in ordered_links:
response = None
dest: Path | None = None
try:
urls = [link.url]
if "/ads.php?md5=" in link.url:
resolved = resolve_external_download(link.url)
if resolved:
urls = [resolved]
else:
last_error = "External source could not resolve the direct download link."
continue
elif "archive.org" in link.url:
alt = link.url.replace("//dn", "//ia").replace(".ca.archive.org", ".us.archive.org")
if alt != link.url:
urls.append(alt)
for url in urls:
try:
response = requests.get(url, stream=True, timeout=60, headers=_UA, allow_redirects=True)
if response.status_code >= 400:
last_error = f"Server returned status {response.status_code}."
response.close()
response = None
continue
content_type = response.headers.get("Content-Type", "")
if "text/html" in content_type and link.format in ("epub", "pdf"):
last_error = "Received an HTML page instead of a downloadable file."
response.close()
response = None
continue
break
except requests.RequestException as exc:
last_error = str(exc)
log_exception("Download request failed")
response = None
if response is None:
continue
filename = _safe_filename(book.title, link.format)
dest = LIBRARY_DIR / filename
index = 1
while dest.exists():
filename = _safe_filename(f"{book.title}_{index}", link.format)
dest = LIBRARY_DIR / filename
index += 1
with open(dest, "wb") as handle:
wrote_data = False
for chunk in response.iter_content(8192):
if chunk:
handle.write(chunk)
wrote_data = True
if not wrote_data:
raise RuntimeError("No file data was received from the source.")
collections: list[str] = []
default_collection = self.settings.get("default_collection", "").strip()
if default_collection:
collections = [default_collection]
add_to_library(
filename,
book.title,
book.author,
link.format,
book.cover_url,
book.source,
language=book.language,
year=book.year,
rating=book.rating,
ratings_count=book.ratings_count,
description=book.description,
subjects=book.subjects,
collections=collections,
)
record_download_history(
title=book.title,
author=book.author,
source=book.source,
fmt=link.format.upper(),
status="success",
filename=filename,
message="Download completed.",
)
self._track("download_success", title=book.title, source=book.source, format=link.format.upper())
log_info(f"Downloaded book title={book.title!r} format={link.format!r}")
return filename, f'"{book.title}" added to the library.'
except Exception as exc:
log_exception("Download pipeline failed")
last_error = str(exc)
if dest and dest.exists():
dest.unlink(missing_ok=True)
finally:
if response is not None:
response.close()
record_download_history(
title=book.title,
author=book.author,
source=book.source,
fmt=selected_link.format.upper(),
status="failed",
message=last_error,
)
self._track("download_failed", title=book.title, source=book.source, format=selected_link.format.upper())
raise RuntimeError(last_error)
def _enqueue_download(self, selected_link: Any, book: BookResult) -> None:
try:
job = enqueue_download_job(
{
"book": book_result_to_dict(book),
"link": {
"url": selected_link.url,
"format": selected_link.format,
"mirror": getattr(selected_link, "mirror", ""),
},
}
)
self._track("queue_enqueued", title=book.title, format=selected_link.format.upper())
self._set_status(f'Queued "{book.title}" for download.')
if self.settings.get("queue_autostart", True):
self._start_queue_processing()
except Exception:
log_exception("Queue enqueue failed")
self._set_status("Could not enqueue the download. Check the log for details.")
def _start_queue_processing(self) -> None:
if self.queue_processing:
return
self.queue_processing = True
def _runner() -> None:
try:
while True:
job = get_next_queued_job()
if not job:
break
update_download_job(job["id"], status="running")
book = book_result_from_dict(job.get("book", {}))
link = download_link_from_dict(job.get("link", {}))
try:
_filename, message = self._execute_download_job(link, book)
update_download_job(job["id"], status="success", message=message)
self.after(0, lambda msg=message: self._set_status(msg))
except Exception as exc:
update_download_job(job["id"], status="failed", message=str(exc))
self.after(0, lambda err=str(exc): self._set_status(f"Queued download failed: {err}"))
finally:
self.queue_processing = False
threading.Thread(target=_runner, daemon=True, name="download-queue").start()
def _clear_queue_finished(self) -> None:
try:
removed = clear_finished_queue_jobs()
self._track("queue_cleared", removed=removed)
self._set_status(f"Removed {removed} finished queue item(s).")
if hasattr(self, "_show_history"):
self._show_history()
except Exception:
log_exception("Queue cleanup failed")
self._set_status("Could not clear finished queue items.")
def _queue_cancel(self, job_id: str) -> None:
try:
cancel_download_job(job_id)
self._track("queue_cancelled", job_id=job_id)
self._show_history()
self._set_status("Queue item cancelled.")
except Exception:
log_exception("Queue cancel failed")
self._set_status("Could not cancel queue item.")
def _queue_retry(self, job_id: str) -> None:
try:
retry_download_job(job_id)
self._track("queue_retried", job_id=job_id)
self._show_history()
self._set_status("Queue item set back to queued.")
except Exception:
log_exception("Queue retry failed")
self._set_status("Could not retry queue item.")
def _queue_reorder(self, job_id: str, direction: str) -> None:
try:
reorder_download_job(job_id, direction)
self._track("queue_reordered", job_id=job_id, direction=direction)
self._show_history()
self._set_status("Queue order updated.")
except Exception:
log_exception("Queue reorder failed")
self._set_status("Could not reorder queue item.")
def _create_header(self, title: str, subtitle: str, action_text: str | None = None, action_command: Callable[[], None] | None = None) -> None:
header = ctk.CTkFrame(self.content, fg_color="transparent")
header.pack(fill="x", padx=28, pady=(14, 8))
text_col = ctk.CTkFrame(header, fg_color="transparent")
text_col.pack(side="left", fill="x", expand=True)
ctk.CTkLabel(text_col, text=title, font=ctk.CTkFont(size=24, weight="bold"), text_color=_TEXT).pack(anchor="w")
ctk.CTkLabel(text_col, text=subtitle, font=ctk.CTkFont(size=12), text_color=_TEXT_MUTED).pack(anchor="w", pady=(2, 0))
if action_text and action_command:
ctk.CTkButton(
header,
text=action_text,
command=action_command,
width=102,
height=34,
corner_radius=12,
fg_color=_SURFACE,
hover_color=_SURFACE_ALT,
border_width=1,
border_color=_CARD_BORDER,
text_color=_TEXT,
).pack(side="right")
def _summary_row(self, items: list[tuple[str, str]]) -> None:
row = ctk.CTkFrame(self.content, fg_color="transparent")
row.pack(fill="x", padx=28, pady=(0, 10))
columns = 2 if len(items) >= 4 else max(1, len(items))
for col in range(columns):
row.grid_columnconfigure(col, weight=1)
for idx, (label, value) in enumerate(items):
card = ctk.CTkFrame(row, fg_color=_SURFACE, corner_radius=18, border_width=1, border_color=_CARD_BORDER)
grid_row = idx // columns
grid_col = idx % columns
card.grid(row=grid_row, column=grid_col, sticky="nsew", padx=6, pady=6)
ctk.CTkLabel(card, text=label, font=ctk.CTkFont(size=12, weight="bold"), text_color=_TEXT_SOFT).pack(
anchor="w", padx=14, pady=(10, 2)
)
ctk.CTkLabel(card, text=value, font=ctk.CTkFont(size=20, weight="bold"), text_color=_TEXT).pack(
anchor="w", padx=14, pady=(0, 10)
)
def _make_surface(self, parent: Any, pady: tuple[int, int] = (0, 0)) -> ctk.CTkFrame:
frame = ctk.CTkFrame(parent, fg_color=_SURFACE, corner_radius=18, border_width=1, border_color=_CARD_BORDER)
frame.pack(fill="x", padx=28, pady=pady)
return frame
def _show_empty_state(self, title: str, body: str, action_text: str | None = None, action_cmd: Callable[[], None] | None = None) -> None:
card = ctk.CTkFrame(self.content, fg_color=_SURFACE, corner_radius=22, border_width=1, border_color=_CARD_BORDER)
card.pack(fill="x", padx=28, pady=(10, 20))
ctk.CTkLabel(card, text=title, font=ctk.CTkFont(size=22, weight="bold"), text_color=_TEXT).pack(anchor="w", padx=24, pady=(22, 8))
ctk.CTkLabel(
card,
text=body,
font=ctk.CTkFont(size=14),
text_color=_TEXT_MUTED,
justify="left",
wraplength=820,
).pack(anchor="w", padx=24, pady=(0, 18))
if action_text and action_cmd:
ctk.CTkButton(
card,
text=action_text,
command=action_cmd,
width=180,
height=38,
corner_radius=14,
fg_color=_ACCENT,
hover_color=_ACCENT_HOVER,
text_color=_TEXT,
).pack(anchor="w", padx=24, pady=(0, 22))
def _make_badge(self, parent: Any, text: str, fg_color: str = _ACCENT_SOFT) -> None:
ctk.CTkLabel(
parent,
text=text,
fg_color=fg_color,
corner_radius=10,
text_color=_TEXT,
font=ctk.CTkFont(size=11, weight="bold"),
padx=10,
pady=4,
).pack(side="left", padx=(0, 8))
def _render_stat_bars(self, parent: Any, values: dict[str, int]) -> None:
if not values:
ctk.CTkLabel(parent, text="No data yet.", font=ctk.CTkFont(size=13), text_color=_TEXT_MUTED).pack(anchor="w", padx=18, pady=(0, 16))
return
top = max(values.values()) if values else 1
for key, count in values.items():
row = ctk.CTkFrame(parent, fg_color="transparent")
row.pack(fill="x", padx=18, pady=5)
ctk.CTkLabel(row, text=str(key), font=ctk.CTkFont(size=13), text_color=_TEXT, width=180, anchor="w").pack(side="left")
bar_wrap = ctk.CTkFrame(row, fg_color="transparent")
bar_wrap.pack(side="left", fill="x", expand=True, padx=(0, 12))
ctk.CTkProgressBar(bar_wrap, progress_color=_ACCENT, fg_color=_CARD_BG).pack(fill="x")
progress = bar_wrap.winfo_children()[0]
progress.set(0 if top == 0 else count / top)
ctk.CTkLabel(row, text=str(count), font=ctk.CTkFont(size=13, weight="bold"), text_color=_TEXT_MUTED, width=48, anchor="e").pack(side="right")
def _estimated_content_width(self, fallback: int = 1100) -> int:
width = self.content.winfo_width() if hasattr(self, "content") else 0
return width if width > 100 else fallback
def _load_cover_async(self, url: str, label: ctk.CTkLabel, size: tuple[int, int] = (100, 150)) -> None:
def _work() -> None:
image = _load_cover(url, size)
if image:
self._image_refs.append(image)
self.after(0, lambda: label.configure(image=image, text=""))
threading.Thread(target=_work, daemon=True, name="cover-loader").start()
def _run_background(
self,
work: Callable[[], Any],
on_success: Callable[[Any], None],
*,
status_message: str = "",
user_error: str = "Operation failed.",
success_status: str | None = None,
) -> None:
if status_message:
self._set_status(status_message)
self.update_idletasks()
def _runner() -> None:
try:
result = work()
self.after(0, lambda: on_success(result))
if success_status:
self.after(0, lambda: self._set_status(success_status))
except Exception as exc:
log_exception(user_error)
self.after(0, lambda: self._set_status(f"{user_error} {exc}"))
threading.Thread(target=_runner, daemon=True, name="autobook-worker").start()
def _search_summary_items(self) -> list[tuple[str, str]]:
return [("Indexed Sources", "4"), ("Local Titles", str(len(get_all_books()))), ("Log File", LOG_FILE.name)]
def _library_summary_items(self, books: list[dict[str, Any]]) -> list[tuple[str, str]]:
formats = {book.get("format", "").upper() for book in books if book.get("format")}
favorites = sum(1 for book in books if book.get("favorite"))
reading = sum(1 for book in books if book.get("reading_status") == "Reading")
return [("Titles", str(len(books))), ("Formats", str(len(formats))), ("Favorites", str(favorites)), ("Reading", str(reading))]
def _history_summary_items(self, history: list[dict[str, Any]]) -> list[tuple[str, str]]:
success = sum(1 for item in history if item.get("status") == "success")
failed = sum(1 for item in history if item.get("status") == "failed")
return [("Events", str(len(history))), ("Success", str(success)), ("Failed", str(failed))]
def _device_summary_items(self, devices: list[Any]) -> list[tuple[str, str]]:
counts = Counter(device.kind for device in devices)
return [
("Detected Devices", str(len(devices))),
("E-Readers", str(counts.get("ereader", 0) + counts.get("mtp", 0))),
("Tablets", str(counts.get("ipad", 0))),
]
# Search page
def _show_search(self) -> None:
self._set_active_nav("search")
self._clear_content()
self._refresh_settings_cache()
self._track("view_search")
self._create_header("Catalog Search", "Find titles and stay in the result stream.")
panel = self._make_surface(self.content, (0, 8))
search_row = ctk.CTkFrame(panel, fg_color="transparent")
search_row.pack(fill="x", padx=18, pady=(14, 10))
search_row.grid_columnconfigure(0, weight=1)
self.search_entry = ctk.CTkEntry(
search_row,
placeholder_text="Examples: Crime and Punishment, Stefan Zweig, science fiction",
height=46,
corner_radius=14,
border_color=_CARD_BORDER,
fg_color=_CARD_BG,
text_color=_TEXT,
placeholder_text_color=_TEXT_SOFT,
)
self.search_entry.grid(row=0, column=0, sticky="ew", padx=(0, 10))
self.search_entry.bind("<Return>", lambda _event: self._do_search())
ctk.CTkButton(
search_row,
text=self._t("Search"),
width=128,
height=46,
corner_radius=14,
fg_color=_ACCENT,
hover_color=_ACCENT_HOVER,
text_color=_TEXT,
font=ctk.CTkFont(size=14, weight="bold"),
command=self._do_search,
).grid(row=0, column=1, sticky="e")
toolbar_row = ctk.CTkFrame(panel, fg_color="transparent")
toolbar_row.pack(fill="x", padx=18, pady=(0, 10))
self.search_filters_visible = tk.BooleanVar(value=False)
ctk.CTkButton(
toolbar_row,
text=self._t("Advanced Filters"),
width=140,
height=32,
corner_radius=12,
fg_color=_SURFACE_ALT,
hover_color=_CARD_BG,
border_width=1,
border_color=_CARD_BORDER,
text_color=_TEXT,
command=self._toggle_search_filters,
).pack(side="left")
ctk.CTkButton(
toolbar_row,
text=self._t("AI Suggestions"),
width=126,
height=32,
corner_radius=12,
fg_color=_SURFACE_ALT,