-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmd_gui.py
More file actions
3243 lines (2687 loc) · 129 KB
/
md_gui.py
File metadata and controls
3243 lines (2687 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import shutil
import zipfile
import sys
import os
import io
import re
import json
import base64
import time
import random
import requests
import threading
import concurrent.futures
import unicodedata
import traceback
from urllib.parse import urljoin, urlparse
from PIL import Image
try:
from pillow_heif import register_heif_opener
register_heif_opener()
except ImportError:
pass
from bs4 import BeautifulSoup
try:
from curl_cffi import requests as requests_cf
except ImportError:
requests_cf = None
try:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as SeleniumOptions
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import UnexpectedAlertPresentException, NoAlertPresentException
from webdriver_manager.chrome import ChromeDriverManager
from seleniumbase import Driver
try:
import undetected_chromedriver as uc
uc_available = True
except ImportError:
uc_available = False
selenium_available = True
except ImportError:
selenium_available = False
uc_available = False
from pathlib import Path
from typing import List, Optional
from baozimh_client_v2 import BaozimhClient, DownloadEvent
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QLineEdit, QPushButton, QLabel,
QTreeWidget, QTreeWidgetItem, QSplitter, QTextEdit,
QCheckBox, QProgressBar, QMessageBox, QFileDialog,
QListWidget, QAbstractItemView, QFrame, QSizePolicy,
QHeaderView, QMenu, QDialog, QDialogButtonBox, QListWidgetItem,
QComboBox, QScrollArea, QStackedWidget)
from PySide6.QtCore import Qt, QThread, Signal, QObject, QEvent, QSize, Property, QRect, QEasingCurve, QPropertyAnimation
from PySide6.QtGui import QPixmap, QImage, QFont, QIcon, QAction, QColor, QPalette, QActionGroup, QPainter, QBrush, QPen, QLinearGradient
from PySide6.QtSvgWidgets import QSvgWidget
from PySide6.QtSvg import QSvgRenderer
import icons
from stylesheet import STYLESHEET, SURFACE_0, SURFACE_1, SURFACE_2, SURFACE_3, BORDER, ACCENT, ACCENT_DIM, TEXT_PRIMARY, TEXT_SECONDARY, TEXT_MUTED, SUCCESS, WARNING, INFO
from widgets import ToggleSwitch, ChipWidget, DownloadButton, StatusBadge, SegmentedControl, WelcomeWidget, LoadingPage
try:
import zhconv
except ImportError:
zhconv = None
class ScalableImageLabel(QLabel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._original_pixmap = None
self._last_resize_time = 0
self.setAlignment(Qt.AlignCenter)
self.setMinimumSize(150, 225)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.setStyleSheet("border: 1px solid #444; background-color: #1a1a1a; border-radius: 4px;")
def set_pixmap(self, pixmap):
self._original_pixmap = pixmap
self.update_display()
def resizeEvent(self, event):
current_time = time.time()
if current_time - self._last_resize_time > 0.05:
self.update_display()
self._last_resize_time = current_time
super().resizeEvent(event)
def update_display(self):
if not self.isVisible(): return
if self._original_pixmap and not self._original_pixmap.isNull():
try:
scaled = self._original_pixmap.scaled(
self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation
)
super().setPixmap(scaled)
except:
pass
else:
super().setText("No Cover")
class GroupFilterDialog(QDialog):
def __init__(self, groups, parent=None):
super().__init__(parent)
self.setWindowTitle("Filter Groups")
self.resize(300, 400)
self.layout = QVBoxLayout(self)
self.list_widget = QListWidget()
self.layout.addWidget(self.list_widget)
self.groups = sorted(list(groups))
btn_layout = QHBoxLayout()
btn_all = QPushButton("All")
btn_all.clicked.connect(self.select_all)
btn_none = QPushButton("None")
btn_none.clicked.connect(self.select_none)
btn_layout.addWidget(btn_all)
btn_layout.addWidget(btn_none)
self.layout.addLayout(btn_layout)
for g in self.groups:
item = QListWidgetItem(g)
item.setCheckState(Qt.Checked)
self.list_widget.addItem(item)
self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.button_box.accepted.connect(self.accept)
self.button_box.rejected.connect(self.reject)
self.layout.addWidget(self.button_box)
self.setStyleSheet("""
QDialog { background-color: #2d2d2d; color: #fff; }
QListWidget { background-color: #252526; color: #fff; border: 1px solid #444; }
QListWidget::item:hover { background-color: #3e3e42; }
""")
def select_all(self):
for i in range(self.list_widget.count()):
self.list_widget.item(i).setCheckState(Qt.Checked)
def select_none(self):
for i in range(self.list_widget.count()):
self.list_widget.item(i).setCheckState(Qt.Unchecked)
def get_selected_groups(self):
selected = []
for i in range(self.list_widget.count()):
item = self.list_widget.item(i)
if item.checkState() == Qt.Checked:
selected.append(item.text())
return selected
class LibraryDialog(QDialog):
def __init__(self, library_data, parent=None):
super().__init__(parent)
self.setWindowTitle("Library")
self.resize(500, 600)
self.layout = QVBoxLayout(self)
self.library_data = library_data
self.list_widget = QListWidget()
self.list_widget.itemDoubleClicked.connect(self.load_selected)
self.layout.addWidget(self.list_widget)
self.refresh_list()
btn_layout = QHBoxLayout()
self.btn_load = QPushButton("Load")
self.btn_load.clicked.connect(self.load_selected)
self.btn_remove = QPushButton("Remove")
self.btn_remove.clicked.connect(self.remove_selected)
self.btn_close = QPushButton("Close")
self.btn_close.clicked.connect(self.reject)
btn_layout.addWidget(self.btn_load)
btn_layout.addWidget(self.btn_remove)
btn_layout.addWidget(self.btn_close)
self.layout.addLayout(btn_layout)
self.setStyleSheet("""
QDialog { background-color: #2d2d2d; color: #fff; }
QListWidget { background-color: #252526; color: #fff; border: 1px solid #444; }
QListWidget::item:hover { background-color: #3e3e42; }
QListWidget::item:selected { background-color: #007acc; }
""")
def refresh_list(self):
self.list_widget.clear()
for mid, data in self.library_data.items():
title = data.get('title', 'Unknown')
suffix = ""
if data.get('has_update'):
suffix = " [UPDATE!]"
item = QListWidgetItem(f"{title}{suffix}")
item.setData(Qt.UserRole, mid)
self.list_widget.addItem(item)
def load_selected(self):
item = self.list_widget.currentItem()
if item:
mid = item.data(Qt.UserRole)
self.parent().load_manga_from_library(mid)
self.accept()
def remove_selected(self):
item = self.list_widget.currentItem()
if item:
mid = item.data(Qt.UserRole)
if mid in self.library_data:
del self.library_data[mid]
self.refresh_list()
def excepthook(exc_type, exc_value, exc_traceback):
tb = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
print("CRITICAL ERROR:", tb)
if QApplication.instance():
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("An unexpected error occurred.")
msg.setInformativeText(str(exc_value))
msg.setDetailedText(tb)
msg.setWindowTitle("Error")
msg.exec()
sys.excepthook = excepthook
API = "https://api.mangadex.org"
BAOZIMH_BASE = "https://www.baozimh.com"
BAOZI_CLIENT = BaozimhClient()
HAPPYMH_BASE = "https://m.happymh.com"
SETTINGS_FILE = "settings.json"
LIBRARY_FILE = "library.json"
def sort_chapters_newest_first(chapters):
"""Sort by chapter number DESC (highest first)"""
def extract_number(chapter):
# Extract number from title or chapter field: "第41话" → 41, "Ch 97" → 97
text = str(chapter.get('title', '')) + " " + str(chapter.get('chapter', ''))
num_match = re.search(r'(\d+(?:\.\d+)?)', text)
try:
return float(num_match.group(1)) if num_match else 0.0
except:
return 0.0
return sorted(chapters, key=extract_number, reverse=True)
def extract_newtoki_images_pro(driver):
"""Community-tested data-* attribute extraction"""
soup = BeautifulSoup(driver.page_source, 'html.parser')
img_tags = soup.select("p img")
image_urls = []
data_pattern = re.compile(r"^data-[a-zA-Z0-9]{1,20}$")
for img in img_tags:
# PRIORITY: data-* attributes first
found_data = False
for attr_name, attr_value in img.attrs.items():
if data_pattern.match(attr_name) and attr_value.startswith("http"):
image_urls.append(attr_value)
found_data = True
break
if not found_data:
# FALLBACK: src
if img.get('src') and img['src'].startswith("http") and "loading-image.gif" not in img['src']:
image_urls.append(img['src'])
# Dedupe
return list(dict.fromkeys(image_urls))
def test_url_works(url, timeout=3):
"""HEAD request + multiple fallbacks"""
try:
resp = requests.head(url, timeout=timeout, allow_redirects=True)
return resp.status_code == 200 and 'image' in resp.headers.get('content-type', '').lower()
except:
try:
resp = requests.get(url, timeout=timeout, stream=True)
if resp.status_code == 200:
# Read a bit of content to verify it's an image
chunk = next(resp.iter_content(1024), b'')
return len(chunk) > 100
return False
except:
return False
def baozimh_universal_watermark_bypass(img_url):
"""SIMPLE - path extraction only (FINAL FIX)"""
if not img_url: return img_url
path = re.sub(r'^https?://[^/]+', '', img_url)
return f"https://static-tw.baozimh.com{path}"
def extract_images_with_autoscroll(driver, max_scrolls=10):
"""Scroll + Wait + Extract ALL images (lazy-loaded)"""
print("🔄 Auto-scrolling to load ALL images...")
last_height = driver.execute_script("return document.body.scrollHeight")
scroll_count = 0
while scroll_count < max_scrolls:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
scroll_count += 1
soup = BeautifulSoup(driver.page_source, 'html.parser')
image_urls = []
selectors = [
'img[src*="baozimh"]', 'img[src*="baozicdn"]', 'img[src*=".jpg"]',
'img[src*=".png"]', 'img[src*=".webp"]', 'p img', '.content img',
'div.reader img', '[class*="image"] img', 'img.lazy',
'img.comic-contain_ui-Image_img'
]
for selector in selectors:
try:
imgs = soup.select(selector)
for img in imgs:
src = img.get('data-src') or img.get('src') or img.get('data-lazy') or img.get('data-original')
if src and src.startswith('http'):
image_urls.append(src)
except: pass
image_urls = list(dict.fromkeys(image_urls))
print(f"✅ Found {len(image_urls)} images after scrolling")
return image_urls
def is_last_page_baozimh(driver):
"""DETECT icon-xiayibu = END (FINAL FIX)"""
soup = BeautifulSoup(driver.page_source, 'html.parser')
return bool(soup.select_one('span.iconfont.icon-xiayibu'))
def extract_complete_baozimh_chapter_final(driver):
"""FIXED: Stops at icon-xiayibu + duplicate detection"""
all_images = []
visited_urls = set()
page_num = 1
last_page_images = []
consecutive_empty = 0
base_url = driver.current_url
while page_num <= 15: # Reasonable max
current_url = driver.current_url
pure_url = current_url.split('#')[0].split('?')[0]
if pure_url in visited_urls:
print("🔄 LOOP DETECTED - ENDING")
break
visited_urls.add(pure_url)
print(f"📄 Page {page_num}: {current_url}")
# AUTO-SCROLL + EXTRACT
page_images = extract_images_with_autoscroll(driver)
# LAST PAGE CHECKS
if is_last_page_baozimh(driver):
# Still add these images if they aren't complete duplicates
if page_images:
clean_images = [baozimh_universal_watermark_bypass(url) for url in page_images]
for img in clean_images:
if img not in all_images:
all_images.append(img)
print("🎉 LAST PAGE CONFIRMED!")
break
if page_images:
clean_images = [baozimh_universal_watermark_bypass(url) for url in page_images]
# Dedupe while adding
for img in clean_images:
if img not in all_images:
all_images.append(img)
print(f" → {len(page_images)} images found (total: {len(all_images)})")
consecutive_empty = 0
else:
consecutive_empty += 1
print(" → EMPTY PAGE")
if consecutive_empty >= 2:
print("✅ NO PROGRESS - ENDING")
break
last_page_images = page_images
# NEXT LINK
soup = BeautifulSoup(driver.page_source, 'html.parser')
next_link = soup.select_one('div.next_chapter a[href*="_"], .next-page a, a[href*="下一頁"]')
if next_link:
next_href = next_link.get('href')
next_url = urljoin(current_url, next_href)
if next_url.split('#')[0] not in visited_urls and "#bottom" not in next_href:
print(f"🔗 Next link found: {next_url}")
driver.get(next_url)
page_num += 1
time.sleep(2)
continue
# SEQUENTIAL PREDICTION
if '_2.html' in pure_url:
predicted = re.sub(r'_(\d+)\.html$', lambda m: f"_{int(m.group(1))+1}.html", pure_url)
elif not re.search(r'_\d+\.html$', pure_url):
predicted = pure_url.replace('.html', '_2.html')
else:
predicted = re.sub(r'_(\d+)\.html$', lambda m: f"_{int(m.group(1))+1}.html", pure_url)
if predicted and predicted not in visited_urls:
print(f"🔮 Predicting next page: {predicted}")
driver.get(predicted)
time.sleep(2)
if "404" in driver.title:
break
page_num += 1
continue
break
driver.get(base_url)
return list(dict.fromkeys(all_images))
def extract_complete_baozimh_chapter(driver):
return extract_complete_baozimh_chapter_final(driver)
def api_get(path: str, params: dict | None = None) -> dict:
url = API.rstrip("/") + "/" + path.lstrip("/")
try:
r = requests.get(url, params=params, timeout=30)
r.raise_for_status()
return r.json()
except Exception as e:
print(f"API Error: {e}")
return {}
def _normalize_text(s: Optional[str]) -> str:
if not s: return ""
s = unicodedata.normalize("NFKD", s)
s = "".join(ch for ch in s if not unicodedata.combining(ch))
s = s.lower()
s = re.sub(r"[^a-z0-9]+", " ", s)
return re.sub(r"\s+", " ", s).strip()
def _all_title_candidates(attrs: dict) -> List[str]:
titles = set()
if not attrs: return []
title_map = attrs.get("title") or {}
for v in title_map.values():
if v: titles.add(str(v))
alt = attrs.get("altTitles") or []
for entry in alt:
if isinstance(entry, dict):
for v in entry.values():
if v: titles.add(str(v))
elif isinstance(entry, str):
titles.add(entry)
return list(titles)
def _matches_query(query_norm: str, title_norm: str) -> bool:
if not query_norm or not title_norm: return False
if query_norm in title_norm: return True
q_tokens = query_norm.split()
t_tokens = set(title_norm.split())
return all(token in t_tokens for token in q_tokens)
def search_manga(title: str, limit: int = 100) -> List[dict]:
title = (title or "").strip()
if not title: return []
query_norm = _normalize_text(title)
collected_raw = []
direct_id = None
url_match = re.search(r"mangadex\.org/title/([a-fA-F0-9\-]+)", title)
if url_match:
direct_id = url_match.group(1)
try:
resp = api_get(f"/manga/{direct_id}", params={"includes[]": ["cover_art"]})
data = resp.get("data")
if data:
collected_raw = [data]
except: pass
else:
try:
params = {"title": title, "limit": min(limit, 100), "includes[]": ["cover_art"]}
resp = api_get("/manga", params=params)
collected_raw.extend(resp.get("data", []))
except: pass
if not collected_raw or len(collected_raw) < 5:
tokens = [t for t in re.split(r"[^A-Za-z0-9]+", title) if t]
if tokens:
try:
params = {"title": " ".join(tokens[:4]), "limit": 100, "includes[]": ["cover_art"]}
resp = api_get("/manga", params=params)
for r in resp.get("data", []):
if not any(existing['id'] == r['id'] for existing in collected_raw):
collected_raw.append(r)
except: pass
results = []
seen_ids = set()
for item in collected_raw:
manga_id = item.get("id")
if not manga_id or manga_id in seen_ids: continue
attrs = item.get("attributes", {}) or {}
candidates = _all_title_candidates(attrs)
matched = False
if direct_id and direct_id == manga_id:
matched = True
else:
for cand in candidates:
if _matches_query(query_norm, _normalize_text(cand)):
matched = True
break
display_title_map = attrs.get("title") or {}
default_title = display_title_map.get("en") or next(iter(display_title_map.values()), None) or (candidates[0] if candidates else "Unknown")
cover_filename = None
for rel in item.get("relationships", []) or []:
if rel.get("type") == "cover_art":
cover_filename = rel.get("attributes", {}).get("fileName")
break
results.append({
"id": manga_id,
"title": default_title,
"attributes": attrs,
"status": attrs.get("status"),
"description": (attrs.get("description") or {}).get("en", "No description"),
"cover_filename": cover_filename,
"matched": matched,
"available_languages": attrs.get("availableTranslatedLanguages", [])
})
seen_ids.add(manga_id)
results.sort(key=lambda r: (0 if r.get("matched") else 1, (r.get("title") or "").lower()))
return results[:limit]
def fetch_chapters_for_manga(manga_id: str, langs: Optional[List[str]] = None) -> List[dict]:
chapters = []
limit = 100
offset = 0
while True:
params = {
"manga": manga_id, "limit": limit, "offset": offset,
"order[chapter]": "asc", "includes[]": "scanlation_group"
}
if langs: params["translatedLanguage[]"] = langs
resp = api_get("/chapter", params=params)
page_results = resp.get("data", [])
if not page_results: break
for r in page_results:
attrs = r.get("attributes", {}) or {}
groups = []
for rel in r.get("relationships", []) or []:
if rel.get("type") == "scanlation_group":
name = rel.get("attributes", {}).get("name")
if name: groups.append(name)
chapters.append({
"id": r.get("id"),
"chapter": attrs.get("chapter", ""),
"title": attrs.get("title", ""),
"volume": attrs.get("volume", ""),
"language": attrs.get("translatedLanguage", ""),
"publishAt": attrs.get("publishAt", ""),
"groups": list(set(groups)),
"attributes": attrs
})
offset += len(page_results)
if len(page_results) < limit or offset >= 5000: break
return chapters
def format_date(iso_str):
if not iso_str: return ""
try:
return iso_str.split("T")[0]
except:
return iso_str
def get_chapter_info(chapter_id: str) -> dict:
return api_get(f"/chapter/{chapter_id}").get("data", {})
def get_at_home_base(chapter_id: str) -> dict:
return api_get(f"/at-home/server/{chapter_id}")
def craft_image_urls(base_url: str, chapter_attrs: dict, use_data_saver: bool = True) -> List[str]:
hash_ = chapter_attrs.get("hash")
if use_data_saver:
files = chapter_attrs.get("dataSaver") or []
mode = "data-saver"
else:
files = chapter_attrs.get("data") or []
mode = "data"
if not hash_ or not files: return []
base = base_url.rstrip("/")
return [f"{base}/{mode}/{hash_}/{fname}" for fname in files]
def get_anilist_chinese_title(query: str) -> Optional[str]:
url = 'https://graphql.anilist.co'
query_graphql = '''
query ($search: String) {
Page(page: 1, perPage: 5) {
media(search: $search, type: MANGA, sort: SEARCH_MATCH) {
title {
romaji
english
native
}
synonyms
}
}
}
'''
variables = {'search': query}
try:
r = requests.post(url, json={'query': query_graphql, 'variables': variables}, timeout=5)
if r.status_code == 200:
data = r.json()
media_list = data.get('data', {}).get('Page', {}).get('media', [])
query_lower = query.lower()
for media in media_list:
titles = media.get('title', {})
native = titles.get('native')
if not native:
continue
# Check if query matches any title/synonym
candidates = [
titles.get('english'),
titles.get('romaji'),
titles.get('native')
] + (media.get('synonyms') or [])
matched = False
for cand in candidates:
if cand and query_lower in cand.lower():
matched = True
break
if matched:
return native
except Exception as e:
print(f"Error: {e}")
pass
return None
def fetch_baozimh_response(url: str, params: dict | None = None) -> requests.Response | None:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
try:
r = requests.get(url, params=params, headers=headers, timeout=10, allow_redirects=True)
r.raise_for_status()
return r
except Exception as e:
print(f"Baozimh Error {url}: {e}")
return None
def fetch_baozimh_html(url: str, params: dict | None = None) -> str | None:
r = fetch_baozimh_response(url, params)
return r.text if r else None
HAPPYMH_SESSION = None
SESSION_LOCK = threading.Lock()
def get_happymh_session(impersonate: Optional[str] = None):
global HAPPYMH_SESSION
with SESSION_LOCK:
if HAPPYMH_SESSION is None:
if requests_cf:
# Initialize session with impersonation if provided
HAPPYMH_SESSION = requests_cf.Session(impersonate=impersonate)
cookie_file = Path("happymh_cookies.json")
if cookie_file.exists():
try:
with open(cookie_file, "r") as f:
HAPPYMH_SESSION.cookies.update(json.load(f))
except: pass
else:
HAPPYMH_SESSION = requests.Session()
return HAPPYMH_SESSION
def fetch_happymh_response(url: str, referer: Optional[str] = None):
session = get_happymh_session(impersonate="chrome124")
ref = referer or HAPPYMH_BASE
# Use curl_cffi for Cloudflare bypass if available
if requests_cf and isinstance(session, requests_cf.Session):
try:
# Use chrome124 impersonation to match recent UA
r = session.get(
url,
impersonate="chrome124",
timeout=20,
headers={
"Referer": ref,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
"Sec-Ch-Ua": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
"Sec-Ch-Ua-Mobile": "?0",
"Sec-Ch-Ua-Platform": '"Windows"',
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-User": "?1",
"Upgrade-Insecure-Requests": "1"
}
)
r.raise_for_status()
return r
except Exception as e:
print(f"Happymh CF Error: {e}")
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
"Referer": ref,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"
}
try:
r = session.get(url, headers=headers, timeout=20)
r.raise_for_status()
return r
except Exception as e:
print(f"Happymh Standard Error: {e}")
return None
def fetch_happymh_html(url: str, referer: Optional[str] = None) -> Optional[str]:
# Network request for Cloudflare bypass
r = fetch_happymh_response(url, referer=referer)
if r:
return r.text
return None
def search_happymh(query: str) -> List[dict]:
query = (query or "").strip()
if not query: return []
# 1. Direct URL Match
if "happymh.com/manga/" in query:
manga_id = query.split("/")[-1]
try:
html = fetch_happymh_html(query)
if html:
soup = BeautifulSoup(html, "html.parser")
title_tag = soup.select_one(".mg-title") or soup.select_one("h1") or soup.select_one(".MuiTypography-h3") or soup.select_one(".MuiTypography-h4")
title = title_tag.get_text(strip=True) if title_tag else manga_id
cover_tag = soup.select_one(".mg-banner img") or soup.select_one(".mg-poster img") or soup.select_one(".MuiCardMedia-root") or soup.select_one("img[src*='poster']")
cover_url = cover_tag.get("src") or cover_tag.get("data-src") if cover_tag else ""
return [{
"id": manga_id,
"title": title,
"attributes": {"title": {"en": title, "zh": title}},
"status": "Ongoing",
"description": "Loaded from URL (Happymh)",
"cover_filename": None,
"cover_url": cover_url,
"available_languages": ["zh"],
"source": "happymh"
}]
except:
pass
return [{
"id": manga_id,
"title": "Direct URL Match (Happymh)",
"attributes": {"title": {"en": "Direct URL Match", "zh": "Direct URL Match"}},
"status": "Unknown",
"description": "Direct URL",
"cover_filename": None,
"cover_url": None,
"available_languages": ["zh"],
"source": "happymh"
}]
# 2. Search logic
alt_query = get_anilist_chinese_title(query)
search_q = alt_query if alt_query else query
url = f"{HAPPYMH_BASE}/sssearch?v={search_q}"
html = fetch_happymh_html(url)
if not html: return []
soup = BeautifulSoup(html, "html.parser")
results = []
cards = soup.select("a[href^='/manga/'], *[data-href^='/manga/']")
for card in cards:
try:
href = card.get("href") or card.get("data-href")
manga_id = href.split("/")[-1]
if not manga_id or manga_id in [r['id'] for r in results]:
continue
title_tag = card.select_one(".MuiTypography-root") or card.select_one("div") or card.select_one(".mg-manga-name")
title_text = title_tag.get_text(strip=True) if title_tag else "Unknown"
img_tag = card.find("img")
cover_url = img_tag.get("src") or img_tag.get("data-src") if img_tag else ""
results.append({
"id": manga_id,
"title": title_text,
"attributes": {"title": {"en": title_text, "zh": title_text}},
"status": "Unknown",
"description": "Found on Happymh",
"cover_filename": None,
"cover_url": cover_url,
"available_languages": ["zh"],
"source": "happymh"
})
except:
continue
return results
def get_happymh_chapters_dynamic(url):
"""CORRECT SeleniumBase UC - works for ANY series"""
if not selenium_available:
print("DEBUG: Selenium not available for portable detection")
return []
from seleniumbase import Driver
series_slug = url.split('/')[-1]
print(f"DEBUG: Launching SeleniumBase UC for {series_slug}")
# CORRECT SeleniumBase UC syntax - NO invalid parameters
driver = Driver(
uc=True, # Undetected Chrome
headless=False, # Visible for debugging
disable_csp=True,
undetectable=True,
browser="chrome",
user_data_dir=None # NO cache!
)
try:
# Navigate to series page
print(f"DEBUG: Loading {url}")
driver.get(url)
# Cloudflare clearance (universal)
print("Waiting for Cloudflare clearance...")
try:
WebDriverWait(driver, 10).until_not(
lambda d: "Just a moment" in d.title
)
except:
# Simple sleep fallback
time.sleep(10)
# CONFIRM page loaded or manual intervention
if "Just a moment" in driver.title:
print("\n" + "="*50)
print("CLOUDFLARE STILL BLOCKING - manual intervention needed")
print("Solve Cloudflare manually in the browser window.")
print("Once the manga page appears, press ENTER in this console...")
print("="*50 + "\n")
input("Solve Cloudflare manually → Press ENTER...")
# Extract chapters DYNAMICALLY (no static files)
soup = BeautifulSoup(driver.page_source, 'html.parser')
chapters = []
# Multiple selectors for chapter lists to be robust
selectors = [
"ul.chapter-list li a",
".chapter-item a",
"li a[href*='mangaread']",
".chapter li a",
"a[href*='/mangaread/']",
"div.MuiListItemButton-root[data-href*='/mangaread/']"
]
seen_ids = set()
for selector in selectors:
links = soup.select(selector)
for link in links:
href = link.get("href") or link.get("data-href")
if not href or href in seen_ids: continue
# CRITICAL: Match THIS SERIES ONLY to avoid mixed results
if series_slug not in href and "/mangaread/" not in href: continue
link_text = link.get_text(" ", strip=True)
if any(x in link_text for x in ["吐槽", "收藏", "问题反馈", "下一话", "上一话", "返回", "目录"]):
continue
seen_ids.add(href)
num_match = re.search(r'(?:第|Ch|Chapter\s*)?(\d+(?:\.\d+)?)', link_text)
chap_num = num_match.group(1) if num_match else "0"
chapters.append({
"id": href,
"chapter": chap_num,
"title": link_text,
"language": "zh",
"groups": [],
"publishAt": "",
"volume": "",
"source": "happymh"
})
if chapters:
break
print(f"✅ DYNAMIC: Found {len(chapters)} chapters for {series_slug}")
def chap_sort_key(c):
try:
return float(c['chapter'])
except:
return 0.0
# Sort descending by default (usually what users want)
chapters.sort(key=chap_sort_key, reverse=True)
# Dedupe by ID just in case
return list({c['id']: c for c in chapters}.values())
except Exception as e:
print(f"SELENIUM ERROR: {e}")
return []
finally:
driver.quit()
def fetch_chapters_happymh(manga_id: str) -> List[dict]:
url = f"{HAPPYMH_BASE}/manga/{manga_id}"
# SINGLE ATTEMPT - NO RETRIES
chapters = get_happymh_chapters_dynamic(url)
if chapters:
return chapters
print("❌ DYNAMIC FAILED - Falling back to manual instructions")
print("Please:")
print("1. Open https://m.happymh.com/manga/[series] manually")
print("2. Solve Cloudflare")
print("3. Copy chapter URLs from page source or try again")
return []
def get_happymh_images(chapter_url_path: str, manga_url: Optional[str] = None) -> List[str]:
if chapter_url_path.startswith("/"):
url = f"{HAPPYMH_BASE}{chapter_url_path}"
else:
url = chapter_url_path
html = fetch_happymh_html(url, referer=manga_url)
if not html: return []
images_with_order = []
soup = BeautifulSoup(html, "html.parser")
# --- Method 1: Priority scan for id="scanX" ---
# This is the most reliable way to get the correct order as per user suggestion
scan_tags = soup.select("img[id^='scan']")
for tag in scan_tags:
src = tag.get("src") or tag.get("data-src") or tag.get("data-original")
if src and src.startswith("http"):