Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
966 lines (718 loc) · 27.7 KB
/
Copy pathmain.py
File metadata and controls
966 lines (718 loc) · 27.7 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
import json
import math
import os
import select
import shutil
import signal
import sqlite3
import subprocess
import sys
import time
import traceback
from pathlib import Path
import bg_indexer
from rich.console import Console, Group
from rich.live import Live
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from src.ai import ai_search
from src.api import start as start_api, stop as stop_api
from src.colors import reset, bold, dim, red, green, yellow, cyan
from src.config import load_config, save_config
from src.dashboard import render as dash_render
from src.database import create_db, purge_broken
from src.download import download_release
from src.groups_menu import groups_menu
from src.nntp_client import NNTPClient
from src.nzb import generate_nzb
from src.paths import app_dir
from src.prompts import prompt
from src.sab import rotate_log
from src.search import count_all_releases, count_obfuscated, count_releases, get_articles, search_all_releases, search_obfuscated, search_releases
if sys.platform == "win32":
for _s in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__):
if _s is not None:
try:
_s.reconfigure(encoding = "utf-8", errors = "replace")
except (AttributeError, OSError, ValueError):
pass
#paths
BASE_DIR = app_dir()
PID_FILE = BASE_DIR / "bg_indexer.pid"
LOG_FILE = BASE_DIR / "bg_index.log"
STATUS_FILE = BASE_DIR / "status.json"
STATS_FILE = BASE_DIR / "stats.json"
console = Console()
#my logo
LOGO = r"""
█████╗ ████████╗ ██╗ █████╗ ███████╗
██╔══██╗╚══██╔══╝ ██║ ██╔══██╗ ██╔════╝
███████║ ██║ ██║ ███████║ ███████╗
██╔══██║ ██║ ██║ ██╔══██║ ╚════██║
██║ ██║ ██║ ███████╗ ██║ ██║ ███████║
╚═╝ ╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚══════╝
"""
def panel(content, border = "blue"):
return Panel(content, border_style = border)
def clear():
print("\x1b[2J\x1b[3J\x1b[H", end="", flush = True)
def fmt_size(size):
if size is None:
return "?"
if size <= 0:
return "0 B"
#try the units till it fits
for unit in ("B", "KB", "MB", "GB", "TB"):
if size < 1024:
return f"{size:.1f} {unit}"
size /= 1024
return f"{size:.1f} PB"
def fmt_date(value):
if not value:
return ""
return str(value)[:10]
def get_status():
try:
with open(STATUS_FILE) as f:
status = json.load(f)
except (OSError, json.JSONDecodeError):
return {"running": False, "group": ""}
pid = status.get("pid")
status["stale"] = not (isinstance(pid, int) and _is_indexer_pid(pid))
return status
def _win_indexer_pid(pid):
import ctypes
k32 = ctypes.WinDLL("kernel32")
void = ctypes.c_void_p
k32.OpenProcess.argtypes = (ctypes.c_uint32, ctypes.c_int, ctypes.c_uint32)
k32.OpenProcess.restype = void
k32.WaitForSingleObject.argtypes = (void, ctypes.c_uint32)
k32.QueryFullProcessImageNameW.argtypes = (void, ctypes.c_uint32, void, ctypes.POINTER(ctypes.c_uint32))
k32.CloseHandle.argtypes = (void,)
handle = k32.OpenProcess(0x00101000, False, pid)
if not handle:
return False
try:
#0x102
if k32.WaitForSingleObject(handle, 0) != 0x102:
return False
buf = ctypes.create_unicode_buffer(260)
size = ctypes.c_uint32(len(buf))
if not k32.QueryFullProcessImageNameW(handle, 0, ctypes.addressof(buf), ctypes.byref(size)):
return True
return os.path.basename(buf.value).lower() == os.path.basename(sys.executable).lower()
finally:
k32.CloseHandle(handle)
def _is_indexer_pid(pid):
if not isinstance(pid, int) or pid <= 0:
return False
if os.name == "nt":
return _win_indexer_pid(pid)
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
if Path("/proc").exists():
try:
cmdline = Path(f"/proc/{pid}/cmdline").read_bytes()
except OSError:
return False
return b"bg_indexer.py" in cmdline or b"--bg-indexer" in cmdline
return True
def indexer_alive():
if not PID_FILE.exists():
return False
try:
pid = int(PID_FILE.read_text().strip())
except ValueError:
PID_FILE.unlink(missing_ok = True)
return False
if _is_indexer_pid(pid):
return True
PID_FILE.unlink(missing_ok = True)
return False
def start_background_indexer():
if indexer_alive():
console.print("[yellow]indexer already running[/yellow]")
return False
try:
rotate_log(LOG_FILE)
log_file = LOG_FILE.open("a")
except OSError as e:
console.print(f"[red]couldnt start indexer: {e}[/red]")
return False
try:
if getattr(sys, "frozen", False):
cmd = [sys.executable, "--bg-indexer"]
else:
cmd = [sys.executable, "-u", str(Path(__file__).resolve().parent / "bg_indexer.py")]
subprocess.Popen(
cmd,
cwd = BASE_DIR,
stdin = subprocess.DEVNULL,
stdout = log_file,
stderr = subprocess.STDOUT,
start_new_session = True,
)
except OSError as e:
log_file.close()
console.print(f"[red]couldnt start indexer: {e}[/red]")
return False
log_file.close()
for _ in range(50):
if indexer_alive():
return True
time.sleep(0.1)
console.print(f"[red]indexer didnt come up, check {LOG_FILE.name}[/red]")
return False
def stop_background_indexer():
if not PID_FILE.exists():
return False
try:
pid = int(PID_FILE.read_text().strip())
except ValueError:
PID_FILE.unlink(missing_ok = True)
return False
if not _is_indexer_pid(pid):
PID_FILE.unlink(missing_ok = True)
return False
try:
os.kill(pid, signal.SIGTERM)
except OSError:
PID_FILE.unlink(missing_ok = True)
return False
#5 sec to comply or die
for _ in range(50):
if not _is_indexer_pid(pid):
PID_FILE.unlink(missing_ok = True)
return True
time.sleep(0.1)
#didnt exit in time soo kill him
try:
os.kill(pid, getattr(signal, "SIGKILL", 9))
except OSError:
pass
PID_FILE.unlink(missing_ok = True)
return True
def ask(text, default = None):
while True:
value = prompt(text).strip()
if not value:
return default if default is not None else 0
try:
return int(value)
except ValueError:
console.print("[red]that aint a number[/red]\n")
def show_results(releases, query, page, total_pages, total, page_size):
clear()
header = Text()
header.append(f"Search: {query}\n", style = "bold")
header.append(f"Page {page + 1} of {total_pages}\n")
start = page * page_size + 1
end = min((page + 1) * page_size, total)
header.append(f"Showing {start}-{end} of {total} results", style = "dim")
table = Table(show_header = True, header_style = "bold cyan", box = None, padding = (0, 2))
table.add_column("#", width = 4, justify = "right")
table.add_column("Name", ratio = 3)
table.add_column("Size", width = 10, justify = "right")
table.add_column("Parts", width = 8, justify = "right")
table.add_column("Date", width = 12)
table.add_column("Status", width = 10)
width = max(20, shutil.get_terminal_size().columns - 40)
for i, release in enumerate(releases, 1):
name = release[1]
if len(name) > width:
name = name[:width - 3] + "..."
broken = "[red][broken][/red]" if not release[6] else ""
table.add_row(
str(i),
name,
fmt_size(release[5]),
str(release[7]),
fmt_date(release[4]),
broken
)
console.print(panel(header, "cyan"))
console.print(table)
console.print("\n[dim]0. Back[/dim]")
if page > 0:
console.print("[cyan]p.[/cyan] Previous Page")
if page < total_pages - 1:
console.print("[cyan]n.[/cyan] Next Page")
console.print("[cyan]g.[/cyan] Go to Page")
def show_release(release, articles):
info = Text()
info.append(f"Release: {release[1]}\n", style = "bold")
info.append(f"poster: {release[3] or 'unknown'} posted: {fmt_date(release[4])}\n", style = "dim")
info.append(f"{fmt_size(release[5])} - {release[7]} parts - ")
if release[6]:
info.append("complete", style = "green")
else:
info.append("incomplete", style = "red")
info.append("\n")
console.print(panel(info))
if not articles:
return
files = {}
for a in articles:
files.setdefault(a[1] or "?", []).append(a)
table = Table(title = f"files ({len(files)})", show_header = False, box = None, padding = (0, 1))
table.add_column("name", style = "white")
table.add_column("parts", style = "dim")
shown = list(files.items())[:30]
width = max(20, shutil.get_terminal_size().columns - 20)
for filename, parts in shown:
present = len({p[2] for p in parts})
expected = max((p[3] for p in parts if p[3]), default = present)
name = filename if len(filename) <= width else filename[:width - 3] + "..."
table.add_row(name, f"{present}/{expected}")
console.print(table)
if len(files) > len(shown):
console.print(f" [dim]... and {len(files) - len(shown)} more[/dim]")
def setup():
console.print(panel("[red]no config found[/red]", "red"))
host = prompt("Host: ")
username = prompt("Username: ")
password = prompt("Password: ")
port = ask("Port (563): ", 563)
save_config(host, username, password, port, "")
console.print(panel("[yellow]group empty rn, select one from the Groups menu[/yellow]", "yellow"))
def do_search(config):
while True:
clear()
menu = Table(show_header = False, box = None, padding = (0, 2))
menu.add_column("num", style = "bold cyan", width = 3)
menu.add_column("label", style = "white")
menu.add_row("1.", "Current Group")
menu.add_row("2.", "All Groups")
menu.add_row("3.", "Obfuscated Posts")
menu.add_row("0.", "Back")
console.print(panel(menu, "green"))
scope = ask("\nChoice: ")
if scope not in (1, 2, 3):
return
if scope == 3:
query = "obfuscated"
else:
console.print("[dim]0. Back[/dim]\n")
query = prompt("Search: ").strip()
if not query or query == "0":
continue
page = 0
# terminal size
page_size = max(10, shutil.get_terminal_size().lines - 15)
while True:
try:
if scope == 1:
total = count_releases(query, config["group"])
releases = search_releases(query, config["group"], page, page_size)
elif scope == 2:
total = count_all_releases(query)
releases = search_all_releases(query, page, page_size)
else:
total = count_obfuscated()
releases = search_obfuscated(page, page_size)
except sqlite3.Error:
console.print(panel("[red]couldnt search, db error[/red]", "red"))
return
if not total:
console.print(panel("[red]no releases found[/red]", "red"))
if scope == 3:
return
query = prompt("\nSearch: ").strip()
if not query or query == "0":
break
page = 0
continue
total_pages = max(1, math.ceil(total / page_size))
if page > total_pages - 1:
page = total_pages - 1
continue
show_results(releases, query, page, total_pages, total, page_size)
choice = prompt("\nChoice: ").strip()
if choice == "0":
return
if choice == "p":
if page > 0:
page -= 1
else:
console.print("[dim]already on the first page[/dim]")
prompt("[enter]")
continue
if choice == "n":
if page < total_pages - 1:
page += 1
else:
console.print("[dim]already on the last page[/dim]")
prompt("[enter]")
continue
if choice == "g":
goto = prompt(f"Go to page (1-{total_pages}): ")
try:
target = int(goto)
except ValueError:
target = -1
if 1 <= target <= total_pages:
page = target - 1
else:
console.print(f"[red]page must be between 1 and {total_pages}[/red]")
prompt("[enter]")
continue
try:
selected = int(choice)
except ValueError:
console.print("[red]invalid[/red]")
prompt("[enter]")
continue
if selected < 1 or selected > len(releases):
console.print("[red]not on this page[/red]")
prompt("[enter]")
continue
release = releases[selected - 1]
choice_id = release[0]
articles = get_articles(choice_id)
while True:
clear()
#actions for the picked release
show_release(release, articles)
menu = Table(show_header = False, box = None, padding = (0, 2))
menu.add_column("num", style = "bold cyan", width = 3)
menu.add_column("label", style = "white")
menu.add_row("1.", "Download")
menu.add_row("2.", "Save NZB")
menu.add_row("0.", "Back")
console.print(menu)
choice = prompt("\nChoice: ").strip()
if choice == "1":
try:
ok = download_release(choice_id)
except Exception as e:
console.print(f"[red]couldnt queue download: {e}[/red]")
ok = False
if ok:
console.print(panel("[green]Download queued it is downloading in background.[/green]\n[dim]Finished files land ~/Downloads[/dim]", "green"))
prompt("[enter]")
break
if choice == "2":
try:
generate_nzb(choice_id)
except Exception as e:
console.print(f"[red]couldnt save nzb: {e}[/red]")
prompt("[enter]")
break
if choice == "0":
break
console.print("[red]invalid[/red]")
prompt("[enter]")
def do_settings():
clear()
config = load_config()
menu = Table(show_header = False, box = None, padding = (0, 2))
menu.add_column("num", style = "bold cyan", width = 3)
menu.add_column("label", style = "white")
menu.add_row("1.", "Change config")
menu.add_row("2.", f"Change indexer mode ({config.get('index_mode', 'dynamic')})")
menu.add_row("3.", "Purge broken releases")
menu.add_row("4.", "Wipe db and cache")
menu.add_row("5.", f"Change api port ({config.get('api_port', 9090)})")
menu.add_row("0.", "Back")
console.print(panel(menu, "blue"))
choice = ask("\nChoice: ")
if choice == 2:
while True:
clear()
#modes
modes = {1: "dynamic", 2: "live", 3: "backfill"}
menu = Table(show_header = False, box = None, padding = (0, 2))
menu.add_column("num", style = "bold cyan", width = 3)
menu.add_column("label", style = "white")
for k, v in modes.items():
menu.add_row(str(k), v)
menu.add_row("0.", "Back")
console.print(panel(menu, "blue"))
mode = ask("\nChoice: ")
if mode == 0:
return
if mode not in modes:
console.print("[red]that is not a number[/red]")
continue
save_config(
config["host"],
config["username"],
config.get("password", ""),
config["port"],
config["group"],
modes[mode],
)
console.print(f"[green]indexer mode set to {modes[mode]}[/green]")
return
if choice == 3:
try:
freed = purge_broken()
except sqlite3.Error as e:
console.print(f"[red]purge failed: {e}[/red]")
else:
if freed:
console.print(f"[green]deleted broken releases, freed {fmt_size(freed)}[/green]")
else:
console.print("[dim]nothing broken to purge[/dim]")
prompt("[enter]")
return
if choice == 4:
if indexer_alive():
console.print("[yellow]stop the indexer first[/yellow]")
prompt("[enter]")
return
files = [
Path(BASE_DIR) / "atlas.db",
Path(BASE_DIR) / "atlas.db-wal",
Path(BASE_DIR) / "atlas.db-shm",
PID_FILE,
LOG_FILE,
STATUS_FILE,
STATS_FILE,
]
for f in files:
f.unlink(missing_ok = True)
console.print("[green]wiped db and cache[/green]")
prompt("[enter]")
return
if choice == 5: #api setting
current = config.get("api_port", 9090)
port = ask(f"API port ({current}): ", current)
if port < 1 or port > 65535:
console.print("[red]port must be between 1 and 65535[/red]")
prompt("[enter]")
return
save_config(
config["host"],
config["username"],
config.get("password", ""),
config["port"],
config["group"],
config.get("index_mode", "dynamic"),
config.get("groups"),
port,
)
stop_api()
start_api(load_config())
console.print(f"[green]api moved to port {port}[/green]")
prompt("[enter]")
return
if choice != 1:
return
host = prompt("Host: ").strip() or config["host"]
username = prompt("Username: ").strip() or config["username"]
while True:
password = prompt("Password: ").strip()
if password:
break
console.print("[yellow]password cant be empty[/yellow]\n")
port = ask("Port (563): ", 563)
save_config(host, username, password, port, config["group"], config.get("index_mode", "dynamic"), config.get("groups"))
console.print("[green]saved[/green]")
def main():
create_db()
config = load_config()
if config:
console.print(panel(
f"[green]config loaded[/green]\n"
f"Server: {config['host']}\n"
f"Current Group: {config['group']}",
"cyan"
))
else:
setup()
config = load_config()
if not config:
console.print("[red]setup failed, no config found[/red]")
return
start_api(config)
while True:
clear()
indexing = indexer_alive()
status = get_status()
#build the status line
st = status.get("status", "stopped")
label = status.get("group") or config["group"]
err_count = status.get("error_count", 0)
idx_text = Text()
if indexing:
if st == "warning":
extra = f" ({err_count} errors)" if err_count else ""
idx_text.append(f"{label} ", style = "yellow")
idx_text.append("[WARNING]", style = "yellow bold")
idx_text.append(extra, style = "yellow")
elif status.get("idle"):
idx_text.append(f"{label} (idle)", style = "cyan")
else:
idx_text.append(f"{label} ", style = "green")
idx_text.append("[active]", style = "green bold")
elif st == "error":
if status.get("stale"):
idx_text.append("stopped (last run failed)", style = "dim")
else:
idx_text.append("FAILED (error)", style = "red bold")
elif st == "warning":
if status.get("stale"):
idx_text.append("stopped (last run: warning)", style = "dim")
else:
idx_text.append("stopped (warning)", style = "yellow")
else:
idx_text.append("stopped", style = "dim")
content = Text()
content.append(Text(LOGO, style = "bold cyan"))
content.append("\n")
content.append("Current Group : ", style = "bold")
content.append(config["group"])
content.append("\nIndexing : ", style = "bold")
content.append_text(idx_text)
menu = Table(show_header = False, box = None, padding = (0, 2))
menu.add_column("num", style = "bold cyan", width = 2)
menu.add_column("label", style = "white")
groups = config.get("groups") or []
if indexing:
menu.add_row("1.", "Stop Indexing")
else:
menu.add_row("1.", "Start Indexing")
menu.add_row("2.", "Search")
menu.add_row("3.", "Groups")
if len(groups) > 1:
menu.add_row("4.", "Remove group")
menu.add_row("5.", "Live Dashboard")
menu.add_row("6.", "AI Search")
menu.add_row("7.", "Settings")
menu.add_row("0.", "Exit")
full = Group(
content,
"",
menu,
)
console.print(panel(full, "cyan"))
choice = prompt("\nChoice: ")
if choice == "1":
if indexing:
stopped = stop_background_indexer()
console.print("[green]indexing stopped[/green]" if stopped else "[yellow]indexer wasnt running[/yellow]")
else:
if start_background_indexer():
console.print("[green]indexing started[/green]")
elif choice == "2":
do_search(config)
elif choice == "3":
groups_menu(config)
config = load_config()
elif choice == "4":
groups = config.get("groups") or []
if len(groups) > 1:
page = 0
while True:
clear()
start = page * 5
end = min(start + 5, len(groups))
total_pages = max(1, (len(groups) + 4) // 5)
console.print(panel(
f"[bold]Remove group[/bold]\n"
f"Page {page + 1} of {total_pages}\n"
f"[dim]Showing {start + 1}-{end} of {len(groups)} groups[/dim]",
"red"
))
table = Table(show_header = True, header_style = "bold cyan", box = None, padding = (0, 2))
table.add_column("#", width = 4, justify = "right")
table.add_column("Group", ratio = 1)
for i, group in enumerate(groups[start:end], 1):
table.add_row(str(i), group)
console.print(table)
console.print("\n[dim]0. Back[/dim]")
if page > 0:
console.print("[cyan]p.[/cyan] Previous Page")
if end < len(groups):
console.print("[cyan]n.[/cyan] Next Page")
choice = prompt("\nChoice: ").strip()
if choice == "0":
break
if choice == "p":
if page > 0:
page -= 1
else:
console.print("[dim]already on the first page[/dim]")
prompt("[enter]")
continue
if choice == "n":
if end < len(groups):
page += 1
else:
console.print("[dim]already on the last page[/dim]")
prompt("[enter]")
continue
try:
selected = int(choice)
except ValueError:
console.print("[red]invalid[/red]")
prompt("[enter]")
continue
if selected < 1 or selected > end - start:
console.print("[red]invalid[/red]")
prompt("[enter]")
continue
chosen = groups[start + selected - 1]
config["groups"] = [g for g in config["groups"] if g != chosen]
if config["group"] == chosen:
config["group"] = config["groups"][0] if config["groups"] else ""
save_config(
config["host"],
config["username"],
config.get("password", ""),
config["port"],
config["group"],
config.get("index_mode", "dynamic"),
config["groups"],
)
console.print(f"[green]removed {chosen}[/green]")
prompt("[enter]")
break
elif choice == "5":
try:
with Live(dash_render(80, 24), console = console, refresh_per_second = 2, screen = True) as live:
while True:
time.sleep(0.5)
w, h = live.console.size
live.update(dash_render(w, h))
except KeyboardInterrupt:
pass
elif choice == "6":
ai_search(config)
elif choice == "7":
do_settings()
config = load_config()
elif choice == "0":
#byee
console.print("\n[bold cyan]byee.[/bold cyan]")
break
if __name__ == "__main__":
if "--selftest" in sys.argv:
cfg = load_config()
if not cfg:
print("selftest: no config found (run Settings or set ATLAS_NNTP_* env)")
sys.exit(1)
client = NNTPClient(cfg["host"], cfg["username"], cfg.get("password", ""), cfg["port"])
print(f"selftest: {cfg['host']}:{cfg['port']} ssl={client.use_ssl} user={cfg['username']}")
try:
client.connect()
except Exception as e:
traceback.print_exc()
sys.exit(1)
print("selftest: connected OK")
client.disconnect()
sys.exit(0)
try:
if "--bg-indexer" in sys.argv:
bg_indexer.main()
sys.exit(0)
main()
except KeyboardInterrupt:
#byee
print("\nbyeee")