-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgooningcli.py
More file actions
2918 lines (2530 loc) · 114 KB
/
Copy pathgooningcli.py
File metadata and controls
2918 lines (2530 loc) · 114 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
"""
gooningCLI - Multi-site hentai content downloader for Termux
"""
import os
import sys
import json
import time
import re
import hashlib
import subprocess
import shutil
import signal
import platform
import traceback
import logging
from pathlib import Path
from typing import Optional, Any
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urljoin, quote_plus
try:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
except ImportError:
print("[!] 'requests' not installed. Run: pip install requests")
sys.exit(1)
try:
from bs4 import BeautifulSoup
except ImportError:
BeautifulSoup = None
try:
from tqdm import tqdm
except ImportError:
tqdm = None
try:
from colorama import Fore, Style, init as colorama_init
colorama_init()
HAS_COLOR = True
except ImportError:
HAS_COLOR = False
class _NoColor:
def __getattr__(self, _): return ""
Fore = _NoColor()
Style = _NoColor()
# ============================================================
# CONSTANTS
# ============================================================
VERSION = "2.3.0"
AUTHOR = "or4acle"
APP_NAME = "gooningCLI"
CONFIG_DIR = os.path.expanduser("~/.gooningcli")
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")
HISTORY_FILE = os.path.join(CONFIG_DIR, "history.json")
BOOKMARKS_FILE = os.path.join(CONFIG_DIR, "bookmarks.json")
BLACKLIST_FILE = os.path.join(CONFIG_DIR, "blacklist.json")
DEFAULT_DOWNLOAD_DIR = os.path.expanduser("~/gooningcli_downloads")
# ============================================================
# SAFETY BLOCKLIST - Hardcoded, cannot be removed by user
# Blocks content involving minors, abuse, and extreme content
# ============================================================
SAFETY_BLOCKLIST = {
# ---------------------------------------------------------
# Minors / Underage / Youth
# ---------------------------------------------------------
"pedophile", "pedophilia", "minor", "minors", "underaged", "under-age", "under age",
"preteen", "pre-teen", "tween", "teenager", "teenagers",
"young", "younger", "child", "children", "childlike", "childish",
"kid", "kids", "kiddo", "schoolgirl", "schoolboy", "school kid", "schoolkid", "school-age",
"prepubescent", "pubescent", "juvenile",
"loli", "lolicon", "lolita", "rori", "rorikon",
"shota", "shotacon", "shouta", "shota-kon", "shotakon",
"elementary school", "middle school", "grade schooler", "kindergarten", "toddler",
"幼女", "幼児", "子供", "子ども", "児童", "未成年",
"少女", "少年", "女児", "男児", "小学生", "中学生", "高校生",
"ロリ", "ロリコン", "ショタ", "ショタコン",
"JK", "JC", "JS", "JD", # Joshi Kousei, Chugakusei, Shougakusei, Daigakusei
"女子小学生", "女子中学生", "女子高生",
"未熟", "幼い", "年下", "メスガキ", "ガキ", "園児", "幼稚園",
# ---------------------------------------------------------
# Abuse / Non-consensual / Coercion / Mind Control
# ---------------------------------------------------------
"rape", "raped", "raping", "rapist", "rapefantasy",
"nonconsensual", "non-consensual", "non consent", "non-consent",
"noncon", "non-con", "dubcon", "dub-con",
"coercion", "coerced", "coercive",
"forced", "forceful", "forced sex", "forced oral", "forced anal",
"unwilling", "reluctant", "without consent", "no consent",
"assault", "sexual assault", "abuse", "abusive", "harassment",
"molest", "molested", "molesting", "molestation",
"grooming", "blackmail", "blackmailed", "extortion",
"kidnapping", "kidnapped", "abduction", "abducted",
"hostage", "captivity", "imprisoned",
"drugged", "drugging", "sedated", "sedation", "unconscious", "drunk",
"mind break", "mind control", "brainwashing", "hypnosis", "hypnotized", "corruption",
"somnophilia", "sleeping", "time stop", # Very common tags in doujinshi for non-con
"痴漢", "強姦", "レイプ", "陵辱", "凌辱", "輪姦",
"非同意", "同意なし", "無理やり", "強制", "強要",
"脅迫", "監禁", "誘拐", "拉致", "性的暴行", "性的虐待",
"睡眠薬", "昏睡", "薬漬け", "暴行",
"洗脳", "催眠", "精神崩壊", "悪堕ち", "時間停止", "睡眠姦", "寝取られ", "NTR",
# ---------------------------------------------------------
# Incest / Family Taboo
# ---------------------------------------------------------
"incest", "incestu", "inbred", "inbreeding",
"brother", "sister", "siblings", "sibling", "stepbrother", "stepsister",
"stepfather", "stepmother", "stepson", "stepdaughter",
"father", "mother", "daughter", "son", "mom", "dad", "mommy", "daddy",
"family", "relative", "relatives", "cousin", "aunt", "uncle", "niece", "nephew",
"taboo", "family taboo",
"近親相姦", "近親", "兄妹", "姉弟", "兄弟", "姉妹", "親子", "家族",
"義父", "義母", "義兄", "義姉", "義弟", "義妹", "従兄弟", "従姉妹",
"妹", "姉", "母", "娘", "兄", "弟", "姪", "甥", "お母さん", "お父さん",
# ---------------------------------------------------------
# Extreme / Disturbing / Gore
# ---------------------------------------------------------
"gore", "gory", "blood", "bloody", "snuff", "ryona", "guro",
"corpse", "cadaver", "dead", "death", "dead body",
"decapitation", "beheading", "dismemberment", "disembowelment",
"evisceration", "mutilation", "amputation", "amputee", "torture", "torturing",
"sadism", "sadist", "masochism", "masochist",
"necrophilia", "necrophilic", "necro",
"bestiality", "bestial", "zoophilia", "zoophilic", "animal", "dog", "horse", "pig",
"cannibalism", "cannibal", "cannibalistic", "vore", "voreophilia",
"asphyxiation", "strangulation", "choking", "breath play", "hanging",
"グロ", "流血", "血まみれ", "スナッフ", "リョナ",
"死体", "屍体", "腐乱", "斬首", "首切り", "切断", "ダルマ",
"解体", "内臓", "腸", "損壊", "四肢切断",
"死姦", "獣姦", "食人", "人肉", "丸呑み",
"拷問", "虐待", "残虐", "サディズム", "マゾヒズム", "異常性癖", "猟奇",
"首絞め", "窒息",
# ---------------------------------------------------------
# Bodily / Extreme Fetish
# ---------------------------------------------------------
"urine", "urination", "pee", "piss", "watersports", "urolagnia", "golden shower",
"defecation", "feces", "faeces", "poop", "shit", "scat", "coprophilia", "coprophagy",
"diaper", "diapers", "adult baby", "baby diaper",
"menstrual", "menstruation", "period blood",
"emesis", "vomit", "vomiting", "vomited", "barf", "retching",
"fart", "farting",
"enema", "laxative", "insects", "bugs", "worms",
"排泄", "尿", "おしっこ", "小便", "大便", "便", "糞尿",
"おむつ", "オムツ", "生理", "月経", "嘔吐", "ゲロ", "放屁",
"失禁", "スカトロ", "食糞", "飲尿", "黄金水", "浣腸", "下剤", "虫", "寄生",
# ---------------------------------------------------------
# Exploitation themes / Prostitution
# ---------------------------------------------------------
"slavery", "slave", "enslaved", "enslavement",
"trafficking", "human trafficking", "sex trafficking",
"prostitution", "prostitute", "pimping", "pimp",
"exploitation", "exploitative", "compensated dating", "sugar daddy",
"kidnap", "kidnapped", "kidnapper",
"人身売買", "売春", "買春", "奴隷", "搾取", "援助交際", "援交", "パパ活", "JKビジネス",
# ---------------------------------------------------------
# Age regression / Infantilization
# ---------------------------------------------------------
"ageplay", "age_play", "age regression", "age_regression",
"regression", "infantilization", "infantilize", "infantilized",
"baby", "infant", "toddler", "newborn",
"diaper lover", "diaperfetish", "adult baby",
"退行", "幼児化", "赤ちゃん", "乳児", "幼児", "ベイビー", "アダルトベビー",
# ---------------------------------------------------------
# Self-harm / Suicide
# ---------------------------------------------------------
"suicide", "kill myself", "self-harm", "self harm",
"cutting", "cut myself", "wrist cutting", "overdose", "od",
"自殺", "自傷", "リスカ", "リストカット", "オーバードーズ", "OD",
# ---------------------------------------------------------
# Extra Japanese moderation & censorship tags
# ---------------------------------------------------------
"強制わいせつ", "児童ポルノ", "児童淫行",
"猥褻", "わいせつ", "アナル", "肛門", "緊縛", "拘束", "無修正"
}
def _is_safety_blocked(tags: list[str] = None, title: str = "", url: str = "") -> bool:
"""Check content against the hardcoded safety blocklist. Cannot be bypassed."""
check_strings = []
if tags:
check_strings.extend(t.lower().replace(" ", "_").replace("-", "_") for t in tags)
if title:
check_strings.append(title.lower())
if url:
check_strings.append(url.lower())
for text in check_strings:
for blocked in SAFETY_BLOCKLIST:
if blocked in text:
DLog.info(f"Safety filter triggered: '{blocked}' in '{text[:60]}'")
return True
return False
SPLASH_TEXTS = [
"Time to do some research...",
"For educational purposes only.",
"Scientific exploration begins now.",
"Opening the sacred archives...",
"Preparing the sacred texts...",
"Activating goon mode...",
"Warning: May cause productivity loss.",
"Your screen recorder is ready.",
"Loading important files...",
"Research in progress...",
"Premium content loading...",
"Just for the plot, I swear.",
"Tax deductible research.",
"Peer reviewed content.",
"Academic purposes only.",
"This is my art degree homework.",
"I need this for my thesis.",
"Cultural exploration mode.",
"Digital anthropology research.",
"Quality assurance testing.",
"Content verification in progress.",
"Downloading... for science.",
"My lawyer says this is educational.",
"The research requires more data.",
"Expanding the archive.",
"Critical research material incoming.",
"Loading culture...",
"Enhancing digital library.",
"Preserving digital art.",
"Cultural preservation initiative.",
"Academic database access granted.",
"Research mode: ENGAGED.",
"Downloading pure knowledge.",
"The things I do for science.",
"Professional content curator at work.",
"Advanced research techniques.",
"Definitely not what it looks like.",
"FBI open up... just kidding.",
"This requires a very specific skill set.",
"Data acquisition in progress.",
"Research materials loading...",
"Expanding the collection.",
"Archival research in progress.",
"Critical data incoming...",
"I call this 'field research'.",
"This is my job now.",
"Mandatory quality checks.",
"Vital information ahead.",
"Trust me, it's for the culture.",
]
BANNER = r"""
██████╗ ██████╗ ██████╗ ███╗ ██╗██╗███╗ ██╗ ██████╗ ██████╗██╗ ██╗
██╔════╝ ██╔═══██╗██╔═══██╗████╗ ██║██║████╗ ██║██╔════╝ ██╔════╝██║ ██║
██║ ███╗██║ ██║██║ ██║██╔██╗ ██║██║██╔██╗ ██║██║ ███╗██║ ██║ ██║
██║ ██║██║ ██║██║ ██║██║╚██╗██║██║██║╚██╗██║██║ ██║██║ ██║ ██║
╚██████╔╝╚██████╔╝╚██████╔╝██║ ╚████║██║██║ ╚████║╚██████╔╝╚██████╗███████╗██║
╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═════╝╚══════╝╚═╝
"""
# ============================================================
# SITE DEFINITIONS
# ============================================================
SITES = {
"1": {"name": "nhentai", "desc": "nhentai.net - Manga/Doujinshi", "type": "manga"},
"2": {"name": "hanime", "desc": "hanime.tv - Videos", "type": "video"},
"3": {"name": "hentaihaven", "desc": "hentaihaven.xxx - Videos (yt-dlp)", "type": "video"},
"4": {"name": "rule34", "desc": "rule34.xxx - Image board (API)", "type": "image"},
"5": {"name": "gelbooru", "desc": "gelbooru.com - Image board (API)", "type": "image"},
"6": {"name": "hitomi", "desc": "hitomi.la - Manga/Doujinshi", "type": "manga"},
"7": {"name": "danbooru", "desc": "danbooru.donmai.us - Image board (no auth)", "type": "image"},
"8": {"name": "konachan", "desc": "konachan.com - Image board (no auth)", "type": "image"},
"9": {"name": "nhentai-lolicon", "desc": "nhentai.net - Lolicon tag", "type": "manga"},
"10": {"name": "nhentai-incest", "desc": "nhentai.net - Incest tag", "type": "manga"},
"11": {"name": "all", "desc": "All supported sites", "type": "all"},
}
THEMES = {
"default": {"header": Fore.CYAN, "accent": Fore.MAGENTA, "success": Fore.GREEN,
"warning": Fore.YELLOW, "error": Fore.RED, "text": Fore.WHITE},
"fire": {"header": Fore.RED, "accent": Fore.YELLOW, "success": Fore.GREEN,
"warning": Fore.YELLOW, "error": Fore.RED, "text": Fore.WHITE},
"ocean": {"header": Fore.BLUE, "accent": Fore.CYAN, "success": Fore.GREEN,
"warning": Fore.YELLOW, "error": Fore.RED, "text": Fore.WHITE},
"matrix": {"header": Fore.GREEN, "accent": Fore.GREEN, "success": Fore.GREEN,
"warning": Fore.YELLOW, "error": Fore.RED, "text": Fore.GREEN},
"mono": {"header": Fore.WHITE, "accent": Fore.WHITE, "success": Fore.WHITE,
"warning": Fore.WHITE, "error": Fore.WHITE, "text": Fore.WHITE},
"pink": {"header": Fore.MAGENTA, "accent": Fore.MAGENTA, "success": Fore.GREEN,
"warning": Fore.YELLOW, "error": Fore.RED, "text": Fore.WHITE},
}
# ============================================================
# CONFIG / HISTORY / BOOKMARKS / BLACKLIST MANAGEMENT
# ============================================================
class ConfigManager:
def __init__(self):
os.makedirs(CONFIG_DIR, exist_ok=True)
self.config = self._load(CONFIG_FILE, {
"theme": "default",
"download_dir": DEFAULT_DOWNLOAD_DIR,
"max_workers": 5,
"proxy": "",
"rate_limit": 0.5,
"default_site": "all",
"nhentai_mirrors": ["nhentai.net"],
"auto_zip": False,
"auto_cbz": False,
"notify": True,
"debug": False,
})
self.history = self._load(HISTORY_FILE, {"downloads": []})
self.bookmarks = self._load(BOOKMARKS_FILE, {"bookmarks": []})
self.blacklist = self._load(BLACKLIST_FILE, {"tags": [], "ids": []})
def _load(self, path: str, default: Any) -> Any:
if os.path.exists(path):
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
pass
return default
def save_config(self):
self._save(CONFIG_FILE, self.config)
def save_history(self):
self._save(HISTORY_FILE, self.history)
def save_bookmarks(self):
self._save(BOOKMARKS_FILE, self.bookmarks)
def save_blacklist(self):
self._save(BLACKLIST_FILE, self.blacklist)
def _save(self, path: str, data: Any):
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def add_history(self, entry: dict):
entry["date"] = datetime.now().isoformat()
self.history["downloads"].append(entry)
self.save_history()
def add_bookmark(self, entry: dict):
entry["date_added"] = datetime.now().isoformat()
self.bookmarks["bookmarks"].append(entry)
self.save_bookmarks()
def remove_bookmark(self, index: int) -> bool:
if 0 <= index < len(self.bookmarks["bookmarks"]):
self.bookmarks["bookmarks"].pop(index)
self.save_bookmarks()
return True
return False
def is_blacklisted(self, tags: list[str] = None, gallery_id: str = None) -> bool:
if gallery_id and gallery_id in self.blacklist.get("ids", []):
return True
if tags:
bl_tags = set(t.lower() for t in self.blacklist.get("tags", []))
if any(t.lower() in bl_tags for t in tags):
return True
return False
cfg = ConfigManager()
# ============================================================
# UTILITY FUNCTIONS
# ============================================================
THEME = THEMES.get(cfg.config.get("theme", "default"), THEMES["default"])
# ============================================================
# DEBUG LOGGER
# ============================================================
class DLog:
"""Developer mode logger. Outputs to terminal AND logs to file when debug is enabled."""
LOG_FILE = os.path.join(CONFIG_DIR, "debug.log")
@staticmethod
def _write_file(level: str, msg: str):
if not DLog.is_enabled():
return
try:
os.makedirs(CONFIG_DIR, exist_ok=True)
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
with open(DLog.LOG_FILE, "a", encoding="utf-8") as f:
f.write(f"[{ts}] [{level}] {msg}\n")
except Exception:
pass
@staticmethod
def is_enabled() -> bool:
return cfg.config.get("debug", False)
@staticmethod
def log(msg: str):
if DLog.is_enabled():
cprint(f" [DEBUG] {msg}", Fore.BLUE if HAS_COLOR else "")
DLog._write_file("DEBUG", msg)
@staticmethod
def request(method: str, url: str, status: int = 0, elapsed: float = 0, extra: str = ""):
if DLog.is_enabled():
status_str = f" -> {status}" if status else ""
time_str = f" ({elapsed:.1f}ms)" if elapsed else ""
extra_str = f" | {extra}" if extra else ""
line = f" [HTTP] {method} {url}{status_str}{time_str}{extra_str}"
cprint(line, Fore.BLUE if HAS_COLOR else "")
DLog._write_file("HTTP", f"{method} {url}{status_str}{time_str}{extra_str}")
@staticmethod
def error(msg: str, exc: Exception = None):
if DLog.is_enabled():
cprint(f" [ERROR] {msg}", Fore.RED if HAS_COLOR else "")
tb_str = ""
if exc:
for line in traceback.format_exception(type(exc), exc, exc.__traceback__):
for sub in line.strip().split("\n"):
cprint(f" {sub}", Fore.RED if HAS_COLOR else "")
tb_str += sub + "\n"
DLog._write_file("ERROR", f"{msg}\n{tb_str}")
@staticmethod
def file(op: str, path: str, size: int = 0):
if DLog.is_enabled():
size_str = f" ({size} bytes)" if size else ""
cprint(f" [FILE] {op}: {path}{size_str}", Fore.BLUE if HAS_COLOR else "")
DLog._write_file("FILE", f"{op}: {path}{size_str}")
@staticmethod
def info(msg: str):
if DLog.is_enabled():
cprint(f" [INFO] {msg}", Fore.BLUE if HAS_COLOR else "")
DLog._write_file("INFO", msg)
def cprint(text: str, color: str = ""):
if HAS_COLOR and color:
print(f"{color}{text}{Style.RESET_ALL}")
else:
print(text)
def show_banner():
os.system("cls" if os.name == "nt" else "clear")
cprint(BANNER, THEME["header"])
cprint(f" v{VERSION}", THEME["warning"])
cprint(f" made by {AUTHOR}", THEME["accent"])
if cfg.config.get("debug", False):
cprint(" [DEV MODE]", THEME["error"])
cprint(f" Log: {DLog.LOG_FILE}", THEME["text"])
splash = SPLASH_TEXTS[hash(str(time.time())) % len(SPLASH_TEXTS)]
cprint(f' "{splash}"', THEME["text"])
print()
def input_prompt(msg: str, default: str = "") -> str:
suffix = f" [{default}]" if default else ""
val = input(f"{THEME['success']}> {msg}{suffix}: {Style.RESET_ALL}").strip()
return val if val else default
def retry_with_backoff(func, max_retries: int = 3, base_delay: float = 2.0, description: str = ""):
last_err = None
for attempt in range(max_retries):
start = time.time()
try:
result = func()
elapsed = (time.time() - start) * 1000
DLog.request("GET", description or "request", elapsed=elapsed)
return result
except requests.exceptions.HTTPError as e:
elapsed = (time.time() - start) * 1000
status = getattr(e.response, "status_code", 0)
DLog.error(f"HTTP {status} on {description} (attempt {attempt + 1}/{max_retries}, {elapsed:.0f}ms)", e)
if status == 429:
delay = base_delay * (2 ** attempt)
cprint(f" [!] Rate limited. Waiting {delay:.0f}s...", THEME["warning"])
time.sleep(delay)
last_err = e
continue
if 500 <= status < 600:
delay = base_delay * (2 ** attempt)
if description:
cprint(f" [!] Server error on {description}. Retry in {delay:.0f}s...", THEME["warning"])
time.sleep(delay)
last_err = e
continue
raise
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
delay = base_delay * (2 ** attempt)
DLog.error(f"Connection error on {description} (attempt {attempt + 1}/{max_retries})", e)
if description:
cprint(f" [!] Connection error on {description}. Retry in {delay:.0f}s...", THEME["warning"])
time.sleep(delay)
last_err = e
continue
except Exception as e:
DLog.error(f"Unexpected error on {description}", e)
raise
if last_err:
raise last_err
def file_hash(filepath: str) -> str:
h = hashlib.md5()
with open(filepath, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
return h.hexdigest()
def is_termux() -> bool:
return "TERMUX_VERSION" in os.environ or "com.termux" in os.environ
def send_notification(title: str, message: str):
if is_termux() and cfg.config.get("notify", True):
try:
subprocess.run(
["termux-notification", "--title", title, "--content", message],
timeout=5, capture_output=True
)
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
def set_wallpaper(filepath: str):
if is_termux():
try:
subprocess.run(["termux-wallpaper", filepath], timeout=10, capture_output=True)
cprint("[*] Wallpaper set!", THEME["success"])
return True
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
cprint("[!] Wallpaper only works on Termux with termux-api installed.", THEME["warning"])
return False
def create_session() -> requests.Session:
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
})
proxy = cfg.config.get("proxy", "")
if proxy:
session.proxies = {"http": proxy, "https": proxy}
DLog.log(f"Proxy configured: {proxy}")
retries = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
adapter = HTTPAdapter(max_retries=retries)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
# ============================================================
# NHENTAI DOWNLOADER
# ============================================================
class NHentaiDownloader:
API_BASE = "https://nhentai.net/api/v2"
IMAGE_SERVERS = [
"https://i1.nhentai.net",
"https://i2.nhentai.net",
"https://i3.nhentai.net",
"https://i4.nhentai.net",
]
def __init__(self):
self.session = create_session()
self.max_workers = cfg.config.get("max_workers", 5)
self.rate_limit = cfg.config.get("rate_limit", 0.5)
def search(self, query: str, page: int = 1, sort: str = "") -> dict:
params: dict[str, Any] = {"query": query, "page": page}
if sort:
params["sort"] = sort
DLog.info(f"nhentai search: query={query}, page={page}, sort={sort}")
r = retry_with_backoff(
lambda: self.session.get(f"{self.API_BASE}/search", params=params, timeout=15),
description=f"search '{query}'"
)
r.raise_for_status()
data = r.json()
DLog.info(f"nhentai search returned {len(data.get('result', []))} results, total={data.get('total', 0)}")
return data
def get_gallery(self, gallery_id: int) -> dict:
DLog.info(f"nhentai get_gallery: id={gallery_id}")
r = retry_with_backoff(
lambda: self.session.get(f"{self.API_BASE}/galleries/{gallery_id}", timeout=15),
description=f"gallery {gallery_id}"
)
r.raise_for_status()
return r.json()
def get_random(self) -> dict:
r = retry_with_backoff(
lambda: self.session.get(f"{self.API_BASE}/galleries/random", timeout=15),
description="random gallery"
)
r.raise_for_status()
data = r.json()
return self.get_gallery(data["id"])
def get_popular(self) -> list[dict]:
r = retry_with_backoff(
lambda: self.session.get(f"{self.API_BASE}/galleries/popular", timeout=15),
description="popular galleries"
)
r.raise_for_status()
return r.json()
def get_page_urls(self, gallery: dict) -> list[str]:
media_id = gallery.get("media_id", "")
pages = gallery.get("pages", [])
urls = []
for i, page in enumerate(pages):
path = page.get("path", "")
ext = path.split(".")[-1] if "." in path else "jpg"
server = self.IMAGE_SERVERS[i % len(self.IMAGE_SERVERS)]
urls.append(f"{server}/galleries/{media_id}/{i + 1}.{ext}")
return urls
def _download_one(self, args: tuple) -> tuple[int, bool]:
i, url, output_dir = args
ext = url.split(".")[-1].split("?")[0]
filepath = os.path.join(output_dir, f"{i + 1:03d}.{ext}")
if os.path.exists(filepath) and os.path.getsize(filepath) > 0:
DLog.log(f"Skipped (exists): {filepath}")
return (i, True)
try:
DLog.request("GET", url)
start = time.time()
r = self.session.get(url, timeout=30)
elapsed = (time.time() - start) * 1000
r.raise_for_status()
content_length = int(r.headers.get("content-length", 0))
with open(filepath, "wb") as f:
f.write(r.content)
actual_size = os.path.getsize(filepath)
DLog.file("WRITE", filepath, actual_size)
DLog.request("GET", url, status=r.status_code, elapsed=elapsed,
extra=f"size={actual_size}, expected={content_length}")
if content_length and actual_size != content_length:
DLog.error(f"Size mismatch: got {actual_size}, expected {content_length} for {url}")
os.remove(filepath)
return (i, False)
return (i, True)
except Exception as e:
DLog.error(f"Download failed: {url}", e)
if os.path.exists(filepath):
os.remove(filepath)
return (i, False)
def download_gallery(self, gallery_id: int, output_dir: str) -> bool:
gallery = self.get_gallery(gallery_id)
if not gallery:
return False
title = gallery.get("title", {}).get("english") or \
gallery.get("title", {}).get("pretty") or \
f"gallery_{gallery_id}"
title = re.sub(r'[\\/:*?"<>|]', '_', title)[:80]
tags = [t.get("name", "") for t in gallery.get("tags", [])]
if _is_safety_blocked(tags=tags, title=title):
cprint(f" [!] Blocked (safety): {title}", THEME["warning"])
DLog.info(f"Safety blocked nhentai gallery {gallery_id}: {title}")
return False
if cfg.is_blacklisted(tags=tags, gallery_id=str(gallery_id)):
cprint(f" [!] Skipped (blacklisted): {title}", THEME["warning"])
return False
pages = self.get_page_urls(gallery)
if not pages:
cprint(f" [!] No pages for {gallery_id}", THEME["error"])
return False
gallery_dir = os.path.join(output_dir, f"nhentai_{gallery_id}_{title}")
os.makedirs(gallery_dir, exist_ok=True)
cprint(f" [{gallery_id}] {title} ({len(pages)} pages)", THEME["accent"])
time.sleep(self.rate_limit)
tasks = [(i, url, gallery_dir) for i, url in enumerate(pages)]
success = 0
with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
futures = {executor.submit(self._download_one, t): t for t in tasks}
for future in as_completed(futures):
_, ok = future.result()
if ok:
success += 1
cprint(f" -> {success}/{len(pages)} pages downloaded", THEME["success"])
cfg.add_history({
"id": str(gallery_id),
"site": "nhentai",
"title": title,
"tags": tags,
"path": gallery_dir,
"type": "manga",
"pages": len(pages),
})
if cfg.config.get("auto_zip"):
_zip_folder(gallery_dir)
if cfg.config.get("auto_cbz"):
_cbz_folder(gallery_dir)
return True
def search_and_download(self, query: str, count: int, output_dir: str, sort: str = ""):
cprint(f"\n [nhentai] Searching for '{query}'...", THEME["header"])
try:
result = self.search(query, sort=sort)
except Exception as e:
cprint(f" [!] Search failed: {e}", THEME["error"])
return
galleries = result.get("result", [])
total = result.get("total", 0)
cprint(f" Found {total} results, downloading up to {count}", THEME["success"])
downloaded = 0
for gallery in galleries:
if downloaded >= count:
break
gid = gallery.get("id")
if gid and self.download_gallery(gid, output_dir):
downloaded += 1
cprint(f"\n [nhentai] Downloaded {downloaded} galleries", THEME["success"])
def show_info(self, gallery_id: int):
gallery = self.get_gallery(gallery_id)
if not gallery:
cprint(f" [!] Gallery {gallery_id} not found", THEME["error"])
return
title = gallery.get("title", {}).get("english") or \
gallery.get("title", {}).get("pretty") or "Unknown"
tags = [t.get("name", "") for t in gallery.get("tags", [])]
artist = next((t["name"] for t in gallery.get("tags", []) if t.get("type") == "artist"), "Unknown")
language = next((t["name"] for t in gallery.get("tags", []) if t.get("type") == "language"), "Unknown")
print()
cprint(f" Title: {title}", THEME["text"])
cprint(f" ID: {gallery_id}", THEME["text"])
cprint(f" Pages: {gallery.get('num_pages', '?')}", THEME["text"])
cprint(f" Favorites:{gallery.get('num_favorites', '?')}", THEME["text"])
cprint(f" Artist: {artist}", THEME["text"])
cprint(f" Language: {language}", THEME["text"])
cprint(f" Tags: {', '.join(tags[:15])}", THEME["text"])
print()
# ============================================================
# HANIME DOWNLOADER
# ============================================================
class HanimeDownloader:
BASE_URL = "https://hanime.tv"
def __init__(self):
self.session = create_session()
self.session.headers["Referer"] = self.BASE_URL
self.rate_limit = cfg.config.get("rate_limit", 0.5)
def search(self, query: str) -> list[dict]:
results = []
DLog.info(f"hanime search: query={query}")
for endpoint in ["/api/v2/search", "/api/v1/search", "/search", "/search/query"]:
try:
DLog.request("GET", f"{self.BASE_URL}{endpoint}?q={query}")
start = time.time()
r = self.session.get(f"{self.BASE_URL}{endpoint}", params={"q": query}, timeout=15)
elapsed = (time.time() - start) * 1000
DLog.request("GET", f"{self.BASE_URL}{endpoint}", status=r.status_code, elapsed=elapsed)
if r.status_code in (404, 500, 502, 503):
DLog.info(f"hanime endpoint {endpoint} returned {r.status_code}, trying next")
continue
r.raise_for_status()
try:
data = r.json()
for item in data.get("results", data.get("data", data.get("videos", [])))[:20]:
slug = item.get("slug", item.get("id", ""))
title = item.get("name", item.get("title", slug))
if slug:
results.append({"slug": slug, "title": title})
except (json.JSONDecodeError, ValueError):
if BeautifulSoup:
soup = BeautifulSoup(r.text, "html.parser")
for a in soup.select("a[href*='/watch/']"):
href = a.get("href", "")
slug = href.rstrip("/").split("/")[-1]
title = a.get_text(strip=True) or slug
if slug and title and len(title) > 1:
results.append({"slug": slug, "title": title})
if results:
return results[:20]
except Exception as e:
DLog.info(f"hanime endpoint {endpoint} failed: {e}")
continue
return results
def get_video_url(self, slug: str) -> Optional[str]:
url = f"{self.BASE_URL}/watch/{slug}"
DLog.info(f"hanime get_video_url: slug={slug}, url={url}")
try:
start = time.time()
r = self.session.get(url, timeout=15)
elapsed = (time.time() - start) * 1000
DLog.request("GET", url, status=r.status_code, elapsed=elapsed)
r.raise_for_status()
if BeautifulSoup:
soup = BeautifulSoup(r.text, "html.parser")
for script in soup.find_all("script"):
text = script.string or ""
for pattern in [
r'"video_url"\s*:\s*"([^"]+)"',
r'"file"\s*:\s*"([^"]+\.mp4[^"]*)"',
r'videoUrl\s*=\s*["\']([^"\']+)',
]:
match = re.search(pattern, text)
if match:
vid_url = match.group(1).replace("\\u0026", "&")
DLog.info(f"hanime found video URL (bs4): {vid_url[:80]}...")
return vid_url
html = r.text
for pattern in [
r'"video_url"\s*:\s*"([^"]+)"',
r'"file"\s*:\s*"([^"]+\.mp4[^"]*)"',
r'source\s+src="([^"]+\.mp4[^"]*)"',
]:
match = re.search(pattern, html)
if match:
vid_url = match.group(1).replace("\\u0026", "&")
DLog.info(f"hanime found video URL (regex): {vid_url[:80]}...")
return vid_url
DLog.error(f"hanime: no video URL pattern matched for {slug}")
except Exception as e:
DLog.error(f"hanime get_video_url failed: {slug}", e)
cprint(f" [!] Error fetching {slug}: {e}", THEME["error"])
return None
def download_video(self, slug: str, output_dir: str) -> bool:
video_url = self.get_video_url(slug)
if not video_url:
cprint(f" [!] No video URL for {slug}", THEME["error"])
return False
filepath = os.path.join(output_dir, f"hanime_{slug}.mp4")
if os.path.exists(filepath) and os.path.getsize(filepath) > 0:
cprint(f" [~] Already exists: {slug}", THEME["warning"])
return True
cprint(f" Downloading: {slug}", THEME["accent"])
DLog.request("GET", video_url, extra="stream=True")
try:
start = time.time()
r = self.session.get(video_url, timeout=120, stream=True)
r.raise_for_status()
total = int(r.headers.get("content-length", 0))
DLog.info(f"hanime video response: status={r.status_code}, content-length={total}")
downloaded = 0
with open(filepath, "wb") as f:
if tqdm and total:
with tqdm(total=total, unit="B", unit_scale=True, desc=slug[:30]) as pbar:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
downloaded += len(chunk)
pbar.update(len(chunk))
else:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
downloaded += len(chunk)
if total:
pct = (downloaded / total) * 100
sys.stdout.write(f"\r [{pct:.1f}%] {downloaded}/{total}")
sys.stdout.flush()
print()
if total and os.path.getsize(filepath) != total:
os.remove(filepath)
cprint(f" [!] Incomplete download, retrying...", THEME["warning"])
return self.download_video(slug, output_dir)
cfg.add_history({
"id": slug,
"site": "hanime",
"title": slug,
"path": filepath,
"type": "video",
"size": os.path.getsize(filepath),
})
return True
except Exception as e:
cprint(f"\n [!] Download error: {e}", THEME["error"])
if os.path.exists(filepath):
os.remove(filepath)
return False
def search_and_download(self, query: str, count: int, output_dir: str):
cprint(f"\n [hanime] Searching for '{query}'...", THEME["header"])
results = self.search(query)
if not results:
cprint(" [!] No results found", THEME["error"])
return
cprint(f" Found {len(results)} results", THEME["success"])
for i, item in enumerate(results[:count]):
cprint(f" {i + 1}. {item['title'][:60]}", THEME["text"])
downloaded = 0
for item in results:
if downloaded >= count:
break
if _is_safety_blocked(title=item.get("title", "")):
cprint(f" [!] Blocked (safety): {item.get('title', '')[:50]}", THEME["warning"])
DLog.info(f"Safety blocked hanime: {item.get('title', '')}")
continue
time.sleep(self.rate_limit)
if self.download_video(item["slug"], output_dir):
downloaded += 1
cprint(f"\n [hanime] Downloaded {downloaded} videos", THEME["success"])
# ============================================================
# HENTAIHAVEN DOWNLOADER (with yt-dlp)
# ============================================================
class HentaiHavenDownloader:
BASE_URL = "https://hentaihaven.xxx"
def __init__(self):
self.session = create_session()
self.rate_limit = cfg.config.get("rate_limit", 0.5)
def search(self, query: str) -> list[dict]:
results = []
DLog.info(f"hentaihaven search: query={query}")
try:
for params in [
{"s": query, "post_type": "wp-manga"},
{"s": query},
]:
DLog.request("GET", f"{self.BASE_URL}?s={query}")
start = time.time()
r = self.session.get(self.BASE_URL, params=params, timeout=15)
elapsed = (time.time() - start) * 1000
DLog.request("GET", self.BASE_URL, status=r.status_code, elapsed=elapsed)
r.raise_for_status()
if BeautifulSoup:
soup = BeautifulSoup(r.text, "html.parser")
for a in soup.select("a[href]"):
href = a.get("href", "")
title = a.get_text(strip=True)
if not title or len(title) < 3:
continue
if "hentaihaven" in href and "/series/" in href:
slug = href.rstrip("/").split("/")[-1] or href.rstrip("/").split("/")[-2]
results.append({"slug": slug, "title": title, "url": href})
elif "hentaihaven" in href and href.rstrip("/").count("/") >= 3:
slug = href.rstrip("/").split("/")[-2] if href.endswith("/") else href.rstrip("/").split("/")[-1]
if slug and slug not in ("www", "http:", "https:"):
results.append({"slug": slug, "title": title, "url": href})
seen = set()
unique = []
for r_item in results:
key = r_item.get("slug", r_item.get("url"))
if key not in seen:
seen.add(key)
unique.append(r_item)
results = unique
if results:
break