sigh
This commit is contained in:
@@ -35,8 +35,10 @@ body {
|
|||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
height: 100vh;
|
|
||||||
overflow: hidden;
|
height: auto !important;
|
||||||
|
min-height: 100vh;
|
||||||
|
overflow-y: auto !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -51,7 +53,7 @@ DESKTOP STYLES (REWORKED & CONSOLIDATED)
|
|||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
flex-grow: 1;
|
flex-grow: 1;
|
||||||
height: 100vh;
|
height: 100vh;
|
||||||
overflow: hidden;
|
overflow-x: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.desktop-main {
|
.desktop-main {
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
1227
animex/manga.html
1227
animex/manga.html
File diff suppressed because it is too large
Load Diff
@@ -8,7 +8,7 @@
|
|||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
|
||||||
<link rel="stylesheet" href="Resources/styles.css">
|
|
||||||
<style>
|
<style>
|
||||||
/* =========================================
|
/* =========================================
|
||||||
1. VARIABLES & RESET (From Reference)
|
1. VARIABLES & RESET (From Reference)
|
||||||
@@ -46,14 +46,17 @@
|
|||||||
html {
|
html {
|
||||||
-webkit-font-smoothing: antialiased;
|
-webkit-font-smoothing: antialiased;
|
||||||
-moz-osx-font-smoothing: grayscale;
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
overflow-y: auto !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
background-color: var(--background-primary);
|
background-color: var(--background-primary);
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
font-family: 'Inter', sans-serif;
|
||||||
line-height: 1.6;
|
line-height: 1.6;
|
||||||
overflow-x: hidden;
|
/* Change overflow-x: hidden to allow vertical scrolling */
|
||||||
|
overflow-x: hidden;
|
||||||
|
overflow-y: auto !important;
|
||||||
min-height: 100vh;
|
min-height: 100vh;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,7 +71,8 @@
|
|||||||
========================================= */
|
========================================= */
|
||||||
.app-container {
|
.app-container {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
min-height: 100vh;
|
/* Ensure it doesn't trap height */
|
||||||
|
min-height: 100vh;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
@@ -78,7 +82,9 @@
|
|||||||
max-width: 1200px;
|
max-width: 1200px;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
flex-grow: 1;
|
/* Remove flex-grow if it's causing layout issues,
|
||||||
|
or ensure it allows expansion */
|
||||||
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.section-title {
|
.section-title {
|
||||||
@@ -381,7 +387,7 @@
|
|||||||
.horizontal-scroll-container {
|
.horizontal-scroll-container {
|
||||||
display: flex;
|
display: flex;
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
overflow-y: hidden;
|
overflow-y: auto !important;
|
||||||
padding: 10px 0 25px 0;
|
padding: 10px 0 25px 0;
|
||||||
-webkit-overflow-scrolling: touch;
|
-webkit-overflow-scrolling: touch;
|
||||||
gap: 15px;
|
gap: 15px;
|
||||||
|
|||||||
@@ -1235,7 +1235,7 @@
|
|||||||
|
|
||||||
async function loadData() {
|
async function loadData() {
|
||||||
try {
|
try {
|
||||||
const detRes = await fetch(`https://api.jikan.moe/v4/anime/${currentMalId}/full`);
|
const detRes = await fetch(`/proxy?url=https://api.jikan.moe/v4/anime/${currentMalId}/full`);
|
||||||
animeDetails = (await detRes.json()).data;
|
animeDetails = (await detRes.json()).data;
|
||||||
renderDetails(animeDetails);
|
renderDetails(animeDetails);
|
||||||
|
|
||||||
@@ -1253,7 +1253,7 @@
|
|||||||
const heroSection = document.querySelector(".series-hero-section");
|
const heroSection = document.querySelector(".series-hero-section");
|
||||||
heroSection.style.backgroundImage = `url('${anime.images.jpg.large_image_url}')`;
|
heroSection.style.backgroundImage = `url('${anime.images.jpg.large_image_url}')`;
|
||||||
|
|
||||||
fetch(`${serverUrl}/anime/${currentMalId}/banner`)
|
fetch(`/anime/${currentMalId}/banner`)
|
||||||
.then((r) => {
|
.then((r) => {
|
||||||
if (!r.ok) throw new Error("Banner fetch failed");
|
if (!r.ok) throw new Error("Banner fetch failed");
|
||||||
return r.blob();
|
return r.blob();
|
||||||
@@ -1592,7 +1592,7 @@
|
|||||||
}
|
}
|
||||||
div.innerHTML = `
|
div.innerHTML = `
|
||||||
<div class="episode-thumbnail">
|
<div class="episode-thumbnail">
|
||||||
<img src="${ep.attributes.thumbnail?.original || "https://placehold.co/320x180"}" loading="lazy">
|
<img src="${'/proxy-image?url=' + ep.attributes.thumbnail?.original || "https://placehold.co/320x180"}" loading="lazy">
|
||||||
</div>
|
</div>
|
||||||
<div class="episode-info">
|
<div class="episode-info">
|
||||||
<div class="episode-title">${ep.attributes.canonicalTitle || "Episode " + num}</div>
|
<div class="episode-title">${ep.attributes.canonicalTitle || "Episode " + num}</div>
|
||||||
@@ -1642,7 +1642,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function fetchRecs() {
|
async function fetchRecs() {
|
||||||
const res = await fetch(`https://api.jikan.moe/v4/anime/${currentMalId}/recommendations`);
|
const res = await fetch(`/proxy?url=https://api.jikan.moe/v4/anime/${currentMalId}/recommendations`);
|
||||||
const data = (await res.json()).data;
|
const data = (await res.json()).data;
|
||||||
const grid = document.getElementById("recommendations-grid");
|
const grid = document.getElementById("recommendations-grid");
|
||||||
if (!data) return;
|
if (!data) return;
|
||||||
@@ -1659,7 +1659,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function fetchRelated() {
|
async function fetchRelated() {
|
||||||
const res = await fetch(`https://api.jikan.moe/v4/anime/${currentMalId}/relations`);
|
const res = await fetch(`/proxy?url=https://api.jikan.moe/v4/anime/${currentMalId}/relations`);
|
||||||
const data = (await res.json()).data;
|
const data = (await res.json()).data;
|
||||||
const container = document.getElementById("related-container");
|
const container = document.getElementById("related-container");
|
||||||
if (data) {
|
if (data) {
|
||||||
@@ -1674,7 +1674,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="tile-title">${item.name}</div>
|
<div class="tile-title">${item.name}</div>
|
||||||
`;
|
`;
|
||||||
fetch(`https://api.jikan.moe/v4/${item.type}/${item.mal_id}`).then((r) => r.json()).then((d) => {
|
fetch(`/proxy?url=https://api.jikan.moe/v4/${item.type}/${item.mal_id}`).then((r) => r.json()).then((d) => {
|
||||||
if (d.data?.images?.jpg?.image_url) a.querySelector("img").src = d.data.images.jpg.image_url;
|
if (d.data?.images?.jpg?.image_url) a.querySelector("img").src = d.data.images.jpg.image_url;
|
||||||
});
|
});
|
||||||
container.appendChild(a);
|
container.appendChild(a);
|
||||||
|
|||||||
232
app.py
232
app.py
@@ -31,7 +31,7 @@ from fpdf import FPDF
|
|||||||
import base64
|
import base64
|
||||||
|
|
||||||
# --- Tunnel Configuration ---
|
# --- Tunnel Configuration ---
|
||||||
TUNNEL_TOKEN = os.environ.get("TUNNEL_TOKEN", "change-this-secret-token")
|
TUNNEL_TOKEN = os.environ.get("TUNNEL_TOKEN", "PICUrl123")
|
||||||
active_tunnel: Optional[WebSocket] = None
|
active_tunnel: Optional[WebSocket] = None
|
||||||
pending_requests: Dict[str, asyncio.Future] = {}
|
pending_requests: Dict[str, asyncio.Future] = {}
|
||||||
|
|
||||||
@@ -103,9 +103,11 @@ class HybridClient:
|
|||||||
self.content = b""
|
self.content = b""
|
||||||
self.text = self.content.decode('utf-8', errors='ignore')
|
self.text = self.content.decode('utf-8', errors='ignore')
|
||||||
|
|
||||||
def json(self):
|
def json(self):
|
||||||
return json.loads(self.text)
|
try:
|
||||||
|
return json.loads(self.text)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return None
|
||||||
def raise_for_status(self):
|
def raise_for_status(self):
|
||||||
if self.status_code >= 400:
|
if self.status_code >= 400:
|
||||||
raise httpx.HTTPStatusError(f"Error {self.status_code}", request=None, response=self)
|
raise httpx.HTTPStatusError(f"Error {self.status_code}", request=None, response=self)
|
||||||
@@ -791,14 +793,15 @@ async def get_movie_thumbnail(mal_id: int):
|
|||||||
async def get_anime_characters(mal_id: int):
|
async def get_anime_characters(mal_id: int):
|
||||||
# AniList GraphQL logic
|
# AniList GraphQL logic
|
||||||
r = await hybrid_client.post(ANILIST_URL, json={"query": VA_QUERY, "variables": {"idMal": mal_id, "page": 1}})
|
r = await hybrid_client.post(ANILIST_URL, json={"query": VA_QUERY, "variables": {"idMal": mal_id, "page": 1}})
|
||||||
|
if r is None:
|
||||||
|
raise HTTPException(status_code=500, detail="Failed to get response from AniList API for characters.")
|
||||||
media = r.json().get("data", {}).get("Media")
|
media = r.json().get("data", {}).get("Media")
|
||||||
if not media: raise HTTPException(status_code=404)
|
if not media: raise HTTPException(status_code=404)
|
||||||
chars = []
|
chars = []
|
||||||
for edge in media["characters"]["edges"]:
|
for edge in media["characters"]["edges"]:
|
||||||
chars.append({"role": edge["role"], "character": {"name": edge["node"]["name"]["full"], "image": edge["node"]["image"]["large"]},
|
chars.append({"role": edge["role"], "character": {"name": edge["node"]["name"]["full"], "image": edge["node"]["image"]["large"]},
|
||||||
"voice_actors": [{"name": v["name"]["full"], "image": v["image"]["large"]} for v in edge["voiceActors"]]})
|
"voice_actors": [{"name": v["name"]["full"], "image": v["image"]["large"]} for v in edge["voiceActors"]]})
|
||||||
return {"mal_id": mal_id, "characters": chars}
|
return {"mal_id": mal_id, "characters": chars}
|
||||||
|
|
||||||
@app.get("/anime/{mal_id}/seasons")
|
@app.get("/anime/{mal_id}/seasons")
|
||||||
async def get_anime_seasons_endpoint(mal_id: int):
|
async def get_anime_seasons_endpoint(mal_id: int):
|
||||||
cache_key = f"seasons:{mal_id}"
|
cache_key = f"seasons:{mal_id}"
|
||||||
@@ -812,6 +815,8 @@ async def get_anime_seasons_endpoint(mal_id: int):
|
|||||||
@app.get("/anime/{mal_id}/banner")
|
@app.get("/anime/{mal_id}/banner")
|
||||||
async def get_anime_banner(mal_id: int, cover: bool = False):
|
async def get_anime_banner(mal_id: int, cover: bool = False):
|
||||||
r = await hybrid_client.post(ANILIST_URL, json={"query": ANILIST_QUERY, "variables": {"malId": mal_id}})
|
r = await hybrid_client.post(ANILIST_URL, json={"query": ANILIST_QUERY, "variables": {"malId": mal_id}})
|
||||||
|
if r is None:
|
||||||
|
raise HTTPException(status_code=500, detail="Failed to get response from AniList API for banner.")
|
||||||
media = r.json().get("data", {}).get("Media", {})
|
media = r.json().get("data", {}).get("Media", {})
|
||||||
url = (media.get("coverImage", {}).get("extraLarge") if cover else media.get("bannerImage"))
|
url = (media.get("coverImage", {}).get("extraLarge") if cover else media.get("bannerImage"))
|
||||||
if not url: raise HTTPException(status_code=404)
|
if not url: raise HTTPException(status_code=404)
|
||||||
@@ -831,25 +836,23 @@ async def get_manga_banner(mal_id: int, cover: bool = False):
|
|||||||
|
|
||||||
@app.get("/chapters/{mal_id}")
|
@app.get("/chapters/{mal_id}")
|
||||||
async def get_manga_chapters_module(mal_id: int):
|
async def get_manga_chapters_module(mal_id: int):
|
||||||
|
all_modules_results = {}
|
||||||
|
|
||||||
for mid, mdata in loaded_modules.items():
|
for mid, mdata in loaded_modules.items():
|
||||||
if module_states.get(mid) and "MANGA_READER" in mdata["info"].get("type", []):
|
if module_states.get(mid) and "MANGA_READER" in mdata["info"].get("type",[]):
|
||||||
try:
|
try:
|
||||||
mdata["instance"].httpx = hybrid_client
|
mdata["instance"].httpx = hybrid_client
|
||||||
chaps = await mdata["instance"].get_chapters(mal_id)
|
chaps = await mdata["instance"].get_chapters(mal_id)
|
||||||
if chaps: return {"chapters": chaps, "source_module": mid}
|
if chaps is not None:
|
||||||
except: pass
|
all_modules_results[mid] = chaps
|
||||||
raise HTTPException(status_code=404)
|
except Exception as e:
|
||||||
|
print(f"Error fetching chapters from {mid}: {e}")
|
||||||
@app.get("/retrieve/{mal_id}/{chapter_num}")
|
pass
|
||||||
async def get_manga_images_module(mal_id: int, chapter_num: str):
|
|
||||||
for mid, mdata in loaded_modules.items():
|
if all_modules_results:
|
||||||
if module_states.get(mid) and "MANGA_READER" in mdata["info"].get("type", []):
|
return {"modules": all_modules_results}
|
||||||
try:
|
|
||||||
mdata["instance"].httpx = hybrid_client
|
raise HTTPException(status_code=404, detail="No chapters found from any module")
|
||||||
imgs = await mdata["instance"].get_chapter_images(mal_id, chapter_num)
|
|
||||||
if imgs: return imgs
|
|
||||||
except: pass
|
|
||||||
raise HTTPException(status_code=404)
|
|
||||||
|
|
||||||
@app.get("/download")
|
@app.get("/download")
|
||||||
async def get_download_link(mal_id: int, episode: int, dub: bool = False, quality: str = "720p"):
|
async def get_download_link(mal_id: int, episode: int, dub: bool = False, quality: str = "720p"):
|
||||||
@@ -918,20 +921,86 @@ async def download_manga_chapter_as_pdf_full(source: str, manga_id: str, chapter
|
|||||||
|
|
||||||
return Response(content=bytes(pdf.output(dest='S')), media_type="application/pdf")
|
return Response(content=bytes(pdf.output(dest='S')), media_type="application/pdf")
|
||||||
|
|
||||||
|
def extract_artists(song: dict) -> list[str]:
|
||||||
|
artists = song.get("artists") or []
|
||||||
|
return [a.get("name") for a in artists if a.get("name")]
|
||||||
|
|
||||||
@app.get("/api/themes/{mal_id}")
|
@app.get("/api/themes/{mal_id}")
|
||||||
async def get_themes_full(mal_id: int):
|
async def get_themes(mal_id: int):
|
||||||
# Restored Artist extraction and sorting logic
|
"""
|
||||||
url = f"{ANIMETHEMES_API}/anime?filter[site]=MyAnimeList&filter[external_id]={mal_id}&include=animethemes.song.artists,animethemes.animethemeentries.videos"
|
Fetches themes for a specific MyAnimeList ID.
|
||||||
r = await hybrid_client.get(url)
|
Resolves MAL ID -> AnimeThemes ID -> Flattens Video List.
|
||||||
anime = r.json().get("anime", [{}])[0]
|
"""
|
||||||
themes = []
|
try:
|
||||||
for t in anime.get("animethemes", []):
|
resp = await hybrid_client.get(
|
||||||
artists = [a.get("name") for a in t.get("song", {}).get("artists", [])]
|
f"{ANIMETHEMES_API}/anime",
|
||||||
for e in t.get("animethemeentries", []):
|
params={
|
||||||
for v in e.get("videos", []):
|
"filter[has]": "resources",
|
||||||
themes.append({"title": t.get("song", {}).get("title"), "artists": artists, "type": t["type"], "url": v["link"], "res": v.get("resolution", 0), "nc": v.get("nc", False)})
|
"filter[site]": "MyAnimeList",
|
||||||
themes.sort(key=lambda x: (x["nc"], x["res"]), reverse=True)
|
"filter[external_id]": mal_id,
|
||||||
return themes
|
"include": "animethemes.song.artists,animethemes.animethemeentries.videos",
|
||||||
|
"page[size]": 1
|
||||||
|
},
|
||||||
|
timeout=10.0
|
||||||
|
)
|
||||||
|
|
||||||
|
if resp.status_code != 200:
|
||||||
|
raise HTTPException(status_code=resp.status_code, detail="Upstream API error")
|
||||||
|
|
||||||
|
data = resp.json()
|
||||||
|
anime_list = data.get("anime", [])
|
||||||
|
|
||||||
|
if not anime_list:
|
||||||
|
return []
|
||||||
|
|
||||||
|
anime = anime_list[0]
|
||||||
|
themes = []
|
||||||
|
seen = set()
|
||||||
|
|
||||||
|
for theme in anime.get("animethemes", []):
|
||||||
|
song = theme.get("song", {})
|
||||||
|
theme_type = theme.get("type")
|
||||||
|
slug = theme.get("slug")
|
||||||
|
|
||||||
|
artists = extract_artists(song)
|
||||||
|
|
||||||
|
for entry in theme.get("animethemeentries", []):
|
||||||
|
for video in entry.get("videos", []):
|
||||||
|
url = video.get("link")
|
||||||
|
if not url:
|
||||||
|
continue
|
||||||
|
|
||||||
|
key = (
|
||||||
|
url,
|
||||||
|
video.get("resolution", 0),
|
||||||
|
video.get("title", "")
|
||||||
|
)
|
||||||
|
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
|
||||||
|
themes.append({
|
||||||
|
"title": song.get("title") or "Unknown",
|
||||||
|
"artists": artists, # ← NEW
|
||||||
|
"type": theme_type,
|
||||||
|
"slug": slug,
|
||||||
|
"url": url,
|
||||||
|
"res": video.get("resolution", 0),
|
||||||
|
"nc": video.get("nc", False),
|
||||||
|
"source": video.get("source"),
|
||||||
|
})
|
||||||
|
|
||||||
|
themes.sort(
|
||||||
|
key=lambda x: (x["nc"], x["res"]),
|
||||||
|
reverse=True
|
||||||
|
)
|
||||||
|
|
||||||
|
return themes
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error fetching themes: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
@app.get("/modules/streaming", response_model=List[Dict[str, Any]])
|
@app.get("/modules/streaming", response_model=List[Dict[str, Any]])
|
||||||
def get_streaming_modules():
|
def get_streaming_modules():
|
||||||
@@ -1039,6 +1108,101 @@ async def get_iframe_source(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/read/{source}/{manga_id}/{chapter_id}", response_class=HTMLResponse)
|
||||||
|
async def read_manga_chapter_source(source: str, manga_id: str, chapter_id: str):
|
||||||
|
"""
|
||||||
|
Serves the HTML reader interface for a given source (jikan or mangadex).
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
with open("templates/reader.html", "r", encoding="utf-8") as f:
|
||||||
|
return HTMLResponse(content=f.read())
|
||||||
|
except FileNotFoundError:
|
||||||
|
raise HTTPException(status_code=404, detail="Reader UI not found.")
|
||||||
|
|
||||||
|
async def _get_manga_images_from_modules(
|
||||||
|
mal_id: int,
|
||||||
|
chapter_num: str,
|
||||||
|
profile_id: Optional[str]
|
||||||
|
) -> Optional[List[str]]:
|
||||||
|
|
||||||
|
sorted_modules = []
|
||||||
|
processed_module_ids = set()
|
||||||
|
|
||||||
|
for module_id, module_data in sorted(loaded_modules.items()):
|
||||||
|
if module_id not in processed_module_ids:
|
||||||
|
sorted_modules.append((module_id, module_data))
|
||||||
|
|
||||||
|
for module_id, module_data in sorted_modules:
|
||||||
|
module_info = module_data.get("info", {})
|
||||||
|
|
||||||
|
module_type = module_info.get("type")
|
||||||
|
is_manga_reader = (isinstance(module_type, list) and "MANGA_READER" in module_type) or \
|
||||||
|
(isinstance(module_type, str) and module_type == "MANGA_READER")
|
||||||
|
|
||||||
|
if module_states.get(module_id) and is_manga_reader:
|
||||||
|
print(f"Attempting to fetch chapter images from module: {module_id}")
|
||||||
|
try:
|
||||||
|
images_func = getattr(module_data["instance"], "get_chapter_images", None)
|
||||||
|
if not images_func:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# ✅ INJECT TUNNEL CLIENT — same as the explicit module path does
|
||||||
|
module_data["instance"].httpx = hybrid_client
|
||||||
|
|
||||||
|
images = await images_func(mal_id, chapter_num)
|
||||||
|
if images is not None:
|
||||||
|
print(f"Success! Got {len(images)} images from {module_id}")
|
||||||
|
return images
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Module {module_id} failed with an error: {e}")
|
||||||
|
traceback.print_exc()
|
||||||
|
return None
|
||||||
|
|
||||||
|
@app.get("/retrieve/{mal_id}/{chapter_num}")
|
||||||
|
async def get_manga_chapter_images(
|
||||||
|
mal_id: int,
|
||||||
|
chapter_num: str,
|
||||||
|
profile_id: Optional[str] = Query(None, description="ID of the active user profile"),
|
||||||
|
ext: Optional[str] = Query(None, description="The ID of the extension to use"),
|
||||||
|
module: Optional[str] = Query(None, description="The specific module to pull images from")
|
||||||
|
):
|
||||||
|
# --- Handle Extension Request ---
|
||||||
|
if ext:
|
||||||
|
if ext in loaded_extensions:
|
||||||
|
ext_data = loaded_extensions[ext]
|
||||||
|
try:
|
||||||
|
images_func = getattr(ext_data["instance"], "get_chapter_images", None)
|
||||||
|
if images_func:
|
||||||
|
print(f"Attempting to fetch chapter images from extension: {ext}")
|
||||||
|
images = await images_func(mal_id, chapter_num)
|
||||||
|
if images is not None:
|
||||||
|
return images
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=f"Extension {ext} failed: {e}")
|
||||||
|
else:
|
||||||
|
raise HTTPException(status_code=404, detail=f"Extension '{ext}' not found.")
|
||||||
|
|
||||||
|
# --- Handle Explicit Module Routing ---
|
||||||
|
if module and module in loaded_modules:
|
||||||
|
mod_data = loaded_modules[module]
|
||||||
|
if module_states.get(module) and "MANGA_READER" in mod_data["info"].get("type", []):
|
||||||
|
try:
|
||||||
|
images_func = getattr(mod_data["instance"], "get_chapter_images", None)
|
||||||
|
if images_func:
|
||||||
|
mod_data["instance"].httpx = hybrid_client
|
||||||
|
images = await images_func(mal_id, chapter_num)
|
||||||
|
if images is not None:
|
||||||
|
return images
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Module {module} failed: {e}")
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
# --- Handle Module Request (Fallback Iteration if no specific module is passed) ---
|
||||||
|
images = await _get_manga_images_from_modules(mal_id, chapter_num, profile_id)
|
||||||
|
if images is not None:
|
||||||
|
return images
|
||||||
|
|
||||||
|
raise HTTPException(status_code=404, detail="Could not retrieve chapter images from any enabled module or extension.")
|
||||||
|
|
||||||
# --- Serve Frontend ---
|
# --- Serve Frontend ---
|
||||||
app.mount("/data", StaticFiles(directory="data"), name="data")
|
app.mount("/data", StaticFiles(directory="data"), name="data")
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
1
data/cache/generic/54780122401b794955a2a36d1577af3d.json
vendored
Normal file
1
data/cache/generic/54780122401b794955a2a36d1577af3d.json
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"payload": {"entries": [{"anilist_id": 153288, "mal_id": 52588, "title_romaji": "Kaijuu 8-gou", "title_english": "Kaiju No. 8", "title_native": "\u602a\u7363\uff18\u53f7", "format": "TV", "start_date": {"year": 2024, "month": 4, "day": 13}, "season": "SPRING", "season_year": 2024, "episodes": 12, "relation_type_from_parent": null, "inferred_part": null, "is_season": true, "is_final_from_title": false, "title_display": "Kaiju No. 8", "_start_tuple": [2024, 4, 13], "is_final_season": false}, {"anilist_id": 178754, "mal_id": 59177, "title_romaji": "Kaijuu 8-gou 2nd Season", "title_english": "Kaiju No. 8 Season 2", "title_native": "\u602a\u7363\uff18\u53f7 \u7b2c\uff12\u671f", "format": "TV", "start_date": {"year": 2025, "month": 7, "day": 19}, "season": "SUMMER", "season_year": 2025, "episodes": 11, "relation_type_from_parent": null, "inferred_part": 2, "is_season": true, "is_final_from_title": false, "title_display": "Kaiju No. 8 Season 2", "_start_tuple": [2025, 7, 19], "is_final_season": false}, {"anilist_id": 204362, "mal_id": 63136, "title_romaji": "Kaijuu 8-gou: Kanketsu-hen", "title_english": null, "title_native": "\u602a\u7363\uff18\u53f7 \u5b8c\u7d50\u7de8", "format": null, "start_date": {"year": null, "month": null, "day": null}, "season": null, "season_year": null, "episodes": null, "relation_type_from_parent": null, "inferred_part": null, "is_season": false, "is_final_from_title": false, "title_display": "Kaijuu 8-gou: Kanketsu-hen", "_start_tuple": [0, 0, 0], "is_final_season": false}, {"anilist_id": 179998, "mal_id": 59489, "title_romaji": "Kaijuu 8-gou Movie", "title_english": "Kaiju No. 8: Mission Recon", "title_native": "\u602a\u73638\u53f7 \u7b2c1\u671f\u7dcf\u96c6\u7de8", "format": "MOVIE", "start_date": {"year": 2025, "month": 3, "day": 28}, "season": "WINTER", "season_year": 2025, "episodes": 1, "relation_type_from_parent": null, "inferred_part": null, "is_season": false, "is_final_from_title": false, "title_display": "Kaiju No. 8: Mission Recon", "_start_tuple": [2025, 3, 28], "is_final_season": false}], "season_groups": [{"season_index": 1, "group_label": "Season 1", "parts": [{"short_label": "S1", "title": "Kaiju No. 8", "mal_id": 52588, "anilist_id": 153288, "start_date": {"year": 2024, "month": 4, "day": 13}, "format": "TV", "is_final": false}]}, {"season_index": 2, "group_label": "Season 2", "parts": [{"short_label": "S2", "title": "Kaiju No. 8 Season 2", "mal_id": 59177, "anilist_id": 178754, "start_date": {"year": 2025, "month": 7, "day": 19}, "format": "TV", "is_final": false}]}], "extras": [{"title": "Kaijuu 8-gou: Kanketsu-hen", "mal_id": 63136, "anilist_id": 204362, "format": null, "start_date": {"year": null, "month": null, "day": null}}, {"title": "Kaiju No. 8: Mission Recon", "mal_id": 59489, "anilist_id": 179998, "format": "MOVIE", "start_date": {"year": 2025, "month": 3, "day": 28}}]}, "_timestamp": 1774929755.5327868}
|
||||||
1
data/cache/generic/551b726f849ec197a63db121fa7eb7ac.json
vendored
Normal file
1
data/cache/generic/551b726f849ec197a63db121fa7eb7ac.json
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"payload": {"entries": [{"anilist_id": 178754, "mal_id": 59177, "title_romaji": "Kaijuu 8-gou 2nd Season", "title_english": "Kaiju No. 8 Season 2", "title_native": "\u602a\u7363\uff18\u53f7 \u7b2c\uff12\u671f", "format": "TV", "start_date": {"year": 2025, "month": 7, "day": 19}, "season": "SUMMER", "season_year": 2025, "episodes": 11, "relation_type_from_parent": null, "inferred_part": 2, "is_season": true, "is_final_from_title": false, "title_display": "Kaiju No. 8 Season 2", "_start_tuple": [2025, 7, 19], "is_final_season": false}, {"anilist_id": 204362, "mal_id": 63136, "title_romaji": "Kaijuu 8-gou: Kanketsu-hen", "title_english": null, "title_native": "\u602a\u7363\uff18\u53f7 \u5b8c\u7d50\u7de8", "format": null, "start_date": {"year": null, "month": null, "day": null}, "season": null, "season_year": null, "episodes": null, "relation_type_from_parent": null, "inferred_part": null, "is_season": false, "is_final_from_title": false, "title_display": "Kaijuu 8-gou: Kanketsu-hen", "_start_tuple": [0, 0, 0], "is_final_season": false}, {"anilist_id": 179998, "mal_id": 59489, "title_romaji": "Kaijuu 8-gou Movie", "title_english": "Kaiju No. 8: Mission Recon", "title_native": "\u602a\u73638\u53f7 \u7b2c1\u671f\u7dcf\u96c6\u7de8", "format": "MOVIE", "start_date": {"year": 2025, "month": 3, "day": 28}, "season": "WINTER", "season_year": 2025, "episodes": 1, "relation_type_from_parent": null, "inferred_part": null, "is_season": false, "is_final_from_title": false, "title_display": "Kaiju No. 8: Mission Recon", "_start_tuple": [2025, 3, 28], "is_final_season": false}, {"anilist_id": 153288, "mal_id": 52588, "title_romaji": "Kaijuu 8-gou", "title_english": "Kaiju No. 8", "title_native": "\u602a\u7363\uff18\u53f7", "format": "TV", "start_date": {"year": 2024, "month": 4, "day": 13}, "season": "SPRING", "season_year": 2024, "episodes": 12, "relation_type_from_parent": null, "inferred_part": null, "is_season": true, "is_final_from_title": false, "title_display": "Kaiju No. 8", "_start_tuple": [2024, 4, 13], "is_final_season": false}], "season_groups": [{"season_index": 1, "group_label": "Season 1", "parts": [{"short_label": "S1", "title": "Kaiju No. 8", "mal_id": 52588, "anilist_id": 153288, "start_date": {"year": 2024, "month": 4, "day": 13}, "format": "TV", "is_final": false}]}, {"season_index": 2, "group_label": "Season 2", "parts": [{"short_label": "S2", "title": "Kaiju No. 8 Season 2", "mal_id": 59177, "anilist_id": 178754, "start_date": {"year": 2025, "month": 7, "day": 19}, "format": "TV", "is_final": false}]}], "extras": [{"title": "Kaijuu 8-gou: Kanketsu-hen", "mal_id": 63136, "anilist_id": 204362, "format": null, "start_date": {"year": null, "month": null, "day": null}}, {"title": "Kaiju No. 8: Mission Recon", "mal_id": 59489, "anilist_id": 179998, "format": "MOVIE", "start_date": {"year": 2025, "month": 3, "day": 28}}]}, "_timestamp": 1774929794.0022862}
|
||||||
1
data/cache/generic/6f730969bda2b13d01d60d7e664cc052.json
vendored
Normal file
1
data/cache/generic/6f730969bda2b13d01d60d7e664cc052.json
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"payload": {"entries": [], "season_groups": [], "extras": []}, "_timestamp": 1774915035.3131928}
|
||||||
1
data/cache/generic/756e38501b60b1cb3a6e0864fa3f4dd8.json
vendored
Normal file
1
data/cache/generic/756e38501b60b1cb3a6e0864fa3f4dd8.json
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"payload": {"entries": [], "season_groups": [], "extras": []}, "_timestamp": 1774915405.991542}
|
||||||
1
data/cache/generic/8891ae7c88ab5f75dd9771bfd0532621.json
vendored
Normal file
1
data/cache/generic/8891ae7c88ab5f75dd9771bfd0532621.json
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"payload": {"entries": [{"anilist_id": 204362, "mal_id": 63136, "title_romaji": "Kaijuu 8-gou: Kanketsu-hen", "title_english": null, "title_native": "\u602a\u7363\uff18\u53f7 \u5b8c\u7d50\u7de8", "format": null, "start_date": {"year": null, "month": null, "day": null}, "season": null, "season_year": null, "episodes": null, "relation_type_from_parent": null, "inferred_part": null, "is_season": false, "is_final_from_title": false, "title_display": "Kaijuu 8-gou: Kanketsu-hen", "_start_tuple": [0, 0, 0], "is_final_season": false}, {"anilist_id": 178754, "mal_id": 59177, "title_romaji": "Kaijuu 8-gou 2nd Season", "title_english": "Kaiju No. 8 Season 2", "title_native": "\u602a\u7363\uff18\u53f7 \u7b2c\uff12\u671f", "format": "TV", "start_date": {"year": 2025, "month": 7, "day": 19}, "season": "SUMMER", "season_year": 2025, "episodes": 11, "relation_type_from_parent": null, "inferred_part": 2, "is_season": true, "is_final_from_title": false, "title_display": "Kaiju No. 8 Season 2", "_start_tuple": [2025, 7, 19], "is_final_season": false}, {"anilist_id": 179998, "mal_id": 59489, "title_romaji": "Kaijuu 8-gou Movie", "title_english": "Kaiju No. 8: Mission Recon", "title_native": "\u602a\u73638\u53f7 \u7b2c1\u671f\u7dcf\u96c6\u7de8", "format": "MOVIE", "start_date": {"year": 2025, "month": 3, "day": 28}, "season": "WINTER", "season_year": 2025, "episodes": 1, "relation_type_from_parent": null, "inferred_part": null, "is_season": false, "is_final_from_title": false, "title_display": "Kaiju No. 8: Mission Recon", "_start_tuple": [2025, 3, 28], "is_final_season": false}, {"anilist_id": 153288, "mal_id": 52588, "title_romaji": "Kaijuu 8-gou", "title_english": "Kaiju No. 8", "title_native": "\u602a\u7363\uff18\u53f7", "format": "TV", "start_date": {"year": 2024, "month": 4, "day": 13}, "season": "SPRING", "season_year": 2024, "episodes": 12, "relation_type_from_parent": null, "inferred_part": null, "is_season": true, "is_final_from_title": false, "title_display": "Kaiju No. 8", "_start_tuple": [2024, 4, 13], "is_final_season": false}], "season_groups": [{"season_index": 1, "group_label": "Season 1", "parts": [{"short_label": "S1", "title": "Kaiju No. 8", "mal_id": 52588, "anilist_id": 153288, "start_date": {"year": 2024, "month": 4, "day": 13}, "format": "TV", "is_final": false}]}, {"season_index": 2, "group_label": "Season 2", "parts": [{"short_label": "S2", "title": "Kaiju No. 8 Season 2", "mal_id": 59177, "anilist_id": 178754, "start_date": {"year": 2025, "month": 7, "day": 19}, "format": "TV", "is_final": false}]}], "extras": [{"title": "Kaijuu 8-gou: Kanketsu-hen", "mal_id": 63136, "anilist_id": 204362, "format": null, "start_date": {"year": null, "month": null, "day": null}}, {"title": "Kaiju No. 8: Mission Recon", "mal_id": 59489, "anilist_id": 179998, "format": "MOVIE", "start_date": {"year": 2025, "month": 3, "day": 28}}]}, "_timestamp": 1774929784.310032}
|
||||||
1
data/cache/generic/efb9ddcfa5f557dbea234b50f1405d99.json
vendored
Normal file
1
data/cache/generic/efb9ddcfa5f557dbea234b50f1405d99.json
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"payload": {"entries": [], "season_groups": [], "extras": []}, "_timestamp": 1774915396.871178}
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "AnimeKai Streamer",
|
"name": "AnimeKai Streamer",
|
||||||
"version": "1.2.1",
|
"version": "1.3.0",
|
||||||
"author": "Animex",
|
"author": "Animex",
|
||||||
"description": "Resolves AnimeKai.to streams using backend encrypted APIs. Fully optimized for Cloud Tunneling.",
|
"description": "Resolves AnimeKai.to streams using backend encrypted APIs via Cloud Tunnel. Supports Sub and Dub. No Selenium.",
|
||||||
"type": ["ANIME_STREAMER"],
|
"type": ["ANIME_STREAMER"],
|
||||||
"requirements":["httpx", "beautifulsoup4"]
|
"requirements": ["httpx", "beautifulsoup4"]
|
||||||
}
|
}
|
||||||
|
|
||||||
---
|
---
|
||||||
import re
|
import re
|
||||||
import httpx
|
import httpx
|
||||||
@@ -36,37 +35,37 @@ HEADERS = {
|
|||||||
# ENCRYPT / DECRYPT HELPERS
|
# ENCRYPT / DECRYPT HELPERS
|
||||||
# =========================
|
# =========================
|
||||||
|
|
||||||
async def enc_kai(client, text: str) -> str:
|
async def enc_kai(text: str) -> str:
|
||||||
r = await client.get(
|
r = await httpx.get(
|
||||||
f"{ENC_API}/enc-kai",
|
f"{ENC_API}/enc-kai",
|
||||||
params={"text": text},
|
params={"text": text},
|
||||||
headers=HEADERS,
|
timeout=10,
|
||||||
timeout=10
|
headers=HEADERS
|
||||||
)
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
return r.json()["result"]
|
return r.json()["result"]
|
||||||
|
|
||||||
|
|
||||||
async def dec_kai(client, text: str) -> str:
|
async def dec_kai(text: str) -> str:
|
||||||
r = await client.post(
|
r = await httpx.post(
|
||||||
f"{ENC_API}/dec-kai",
|
f"{ENC_API}/dec-kai",
|
||||||
json={"text": text},
|
json={"text": text},
|
||||||
headers=HEADERS,
|
timeout=10,
|
||||||
timeout=10
|
headers=HEADERS
|
||||||
)
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
return r.json()["result"]
|
return r.json()["result"]
|
||||||
|
|
||||||
|
|
||||||
async def dec_mega(client, text: str) -> Dict:
|
async def dec_mega(text: str) -> Dict:
|
||||||
r = await client.post(
|
r = await httpx.post(
|
||||||
f"{ENC_API}/dec-mega",
|
f"{ENC_API}/dec-mega",
|
||||||
json={
|
json={
|
||||||
"text": text,
|
"text": text,
|
||||||
"agent": HEADERS["User-Agent"]
|
"agent": HEADERS["User-Agent"]
|
||||||
},
|
},
|
||||||
headers=HEADERS,
|
timeout=15,
|
||||||
timeout=15
|
headers=HEADERS
|
||||||
)
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
return r.json()
|
return r.json()
|
||||||
@@ -75,9 +74,9 @@ async def dec_mega(client, text: str) -> Dict:
|
|||||||
# INTERNAL LOGIC
|
# INTERNAL LOGIC
|
||||||
# =========================
|
# =========================
|
||||||
|
|
||||||
async def get_anime_id(client, slug: str) -> str:
|
async def get_anime_id(slug: str) -> tuple[str, dict]:
|
||||||
# slug is actually mal_id (int)
|
# slug is actually mal_id (int or str)
|
||||||
resp = await client.get(f"{DB_URL}?mal_id={slug}", headers=HEADERS)
|
resp = await httpx.get(f"{DB_URL}?mal_id={slug}", headers=HEADERS)
|
||||||
resp.raise_for_status()
|
resp.raise_for_status()
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
if not data or not data[0].get("info", {}).get("kai_id"):
|
if not data or not data[0].get("info", {}).get("kai_id"):
|
||||||
@@ -85,19 +84,29 @@ async def get_anime_id(client, slug: str) -> str:
|
|||||||
return data[0]["info"]["kai_id"], data[0]
|
return data[0]["info"]["kai_id"], data[0]
|
||||||
|
|
||||||
|
|
||||||
async def get_episode_token(data: dict, episode: int) -> str:
|
async def get_episode_token(data: dict, episode: int, dub: bool) -> str:
|
||||||
# Always fetch the sub ("1") token for the episode
|
# "1" = Sub, "2" = Dub in this specific database structure
|
||||||
try:
|
primary_key = "2" if dub else "1"
|
||||||
token = data["episodes"]["1"][str(episode)]["token"]
|
fallback_key = "1" if dub else "2"
|
||||||
except Exception:
|
|
||||||
raise RuntimeError("Episode token not found in JSON response")
|
ep_str = str(episode)
|
||||||
return token
|
episodes_data = data.get("episodes", {})
|
||||||
|
|
||||||
|
# Try requested language first
|
||||||
|
if primary_key in episodes_data and ep_str in episodes_data[primary_key]:
|
||||||
|
return episodes_data[primary_key][ep_str]["token"]
|
||||||
|
|
||||||
|
# Fallback to the other language if requested isn't available
|
||||||
|
if fallback_key in episodes_data and ep_str in episodes_data[fallback_key]:
|
||||||
|
return episodes_data[fallback_key][ep_str]["token"]
|
||||||
|
|
||||||
|
raise RuntimeError(f"Episode token not found for episode {episode}")
|
||||||
|
|
||||||
|
|
||||||
async def get_server_id(client, ep_token: str, dub: bool) -> str:
|
async def get_server_id(ep_token: str, dub: bool) -> List[str]:
|
||||||
enc = await enc_kai(client, ep_token)
|
enc = await enc_kai(ep_token)
|
||||||
|
|
||||||
html = await client.get(
|
html = await httpx.get(
|
||||||
f"{BASE_URL}/ajax/links/list",
|
f"{BASE_URL}/ajax/links/list",
|
||||||
params={"token": ep_token, "_": enc},
|
params={"token": ep_token, "_": enc},
|
||||||
headers=HEADERS
|
headers=HEADERS
|
||||||
@@ -112,7 +121,7 @@ async def get_server_id(client, ep_token: str, dub: bool) -> str:
|
|||||||
# Determine which language group to use
|
# Determine which language group to use
|
||||||
# Default: sub (Hard Sub), or dub if requested
|
# Default: sub (Hard Sub), or dub if requested
|
||||||
lang_order = ["dub", "sub"] if dub else ["sub", "softsub", "dub"]
|
lang_order = ["dub", "sub"] if dub else ["sub", "softsub", "dub"]
|
||||||
all_server_ids =[]
|
all_server_ids = []
|
||||||
for lang in lang_order:
|
for lang in lang_order:
|
||||||
group_pattern = rf'<div class="server-items lang-group" data-id="{lang}"[^>]*>(.*?)</div>'
|
group_pattern = rf'<div class="server-items lang-group" data-id="{lang}"[^>]*>(.*?)</div>'
|
||||||
group_match = re.search(group_pattern, html_content, re.DOTALL)
|
group_match = re.search(group_pattern, html_content, re.DOTALL)
|
||||||
@@ -128,16 +137,16 @@ async def get_server_id(client, ep_token: str, dub: bool) -> str:
|
|||||||
return all_server_ids
|
return all_server_ids
|
||||||
|
|
||||||
|
|
||||||
async def resolve_stream_url(client, server_id: str) -> dict:
|
async def resolve_stream_url(server_id: str) -> dict:
|
||||||
enc = await enc_kai(client, server_id)
|
enc = await enc_kai(server_id)
|
||||||
|
|
||||||
view = await client.get(
|
view = await httpx.get(
|
||||||
f"{BASE_URL}/ajax/links/view",
|
f"{BASE_URL}/ajax/links/view",
|
||||||
params={"id": server_id, "_": enc},
|
params={"id": server_id, "_": enc},
|
||||||
headers=HEADERS
|
headers=HEADERS
|
||||||
)
|
)
|
||||||
|
|
||||||
decrypted = await dec_kai(client, view.json()["result"])
|
decrypted = await dec_kai(view.json()["result"])
|
||||||
print(f"decrypted (dec_kai): {decrypted}")
|
print(f"decrypted (dec_kai): {decrypted}")
|
||||||
|
|
||||||
skip = {}
|
skip = {}
|
||||||
@@ -153,15 +162,15 @@ async def resolve_stream_url(client, server_id: str) -> dict:
|
|||||||
parsed = urllib.parse.urlparse(media_url)
|
parsed = urllib.parse.urlparse(media_url)
|
||||||
referer = f"{parsed.scheme}://{parsed.netloc}"
|
referer = f"{parsed.scheme}://{parsed.netloc}"
|
||||||
|
|
||||||
media = await client.get(media_url, headers=HEADERS)
|
media = await httpx.get(media_url, headers=HEADERS)
|
||||||
mega = await dec_mega(client, media.json()["result"])
|
mega = await dec_mega(media.json()["result"])
|
||||||
print(mega)
|
print(mega)
|
||||||
|
|
||||||
sources = mega.get("result", {}).get("sources",[])
|
sources = mega.get("result", {}).get("sources", [])
|
||||||
tracks = mega.get("result", {}).get("tracks",[])
|
tracks = mega.get("result", {}).get("tracks", [])
|
||||||
|
|
||||||
# Find captions and thumbnails
|
# Find captions and thumbnails
|
||||||
captions =[t for t in tracks if t.get("kind") == "captions"]
|
captions = [t for t in tracks if t.get("kind") == "captions"]
|
||||||
thumbnails = [t for t in tracks if t.get("kind") == "thumbnails"]
|
thumbnails = [t for t in tracks if t.get("kind") == "thumbnails"]
|
||||||
|
|
||||||
if not sources:
|
if not sources:
|
||||||
@@ -180,32 +189,25 @@ async def resolve_stream_url(client, server_id: str) -> dict:
|
|||||||
# PUBLIC MODULE API
|
# PUBLIC MODULE API
|
||||||
# =========================
|
# =========================
|
||||||
|
|
||||||
async def get_iframe_source(
|
async def get_iframe_source(mal_id: int, episode: int, dub: bool) -> Optional[str]:
|
||||||
mal_id: int,
|
|
||||||
episode: int,
|
|
||||||
dub: bool
|
|
||||||
) -> Optional[str]:
|
|
||||||
"""
|
"""
|
||||||
Returns resolved m3u8 stream URL using the injected Tunneling HybridClient
|
Returns resolved m3u8 stream URL integrated into the player link
|
||||||
"""
|
"""
|
||||||
# The 'httpx' variable resolves to the injected HybridClient dynamically
|
|
||||||
# replaced during module processing in app.py's `get_iframe_source` endpoint.
|
|
||||||
client = httpx
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ani_id, anime_json = await get_anime_id(client, mal_id)
|
ani_id, anime_json = await get_anime_id(str(mal_id))
|
||||||
print(f"ani_id: {ani_id}")
|
print(f"ani_id: {ani_id}")
|
||||||
|
|
||||||
ep_token = await get_episode_token(anime_json, episode)
|
# Pass the dub parameter so it checks for the correct sub/dub token
|
||||||
|
ep_token = await get_episode_token(anime_json, episode, dub)
|
||||||
print(f"ep_token: {ep_token}")
|
print(f"ep_token: {ep_token}")
|
||||||
|
|
||||||
server_ids = await get_server_id(client, ep_token, dub)
|
server_ids = await get_server_id(ep_token, dub)
|
||||||
print(f"server_ids: {server_ids}")
|
print(f"server_ids: {server_ids}")
|
||||||
|
|
||||||
for sid in server_ids:
|
for sid in server_ids:
|
||||||
try:
|
try:
|
||||||
print(f"Trying server_id: {sid}")
|
print(f"Trying server_id: {sid}")
|
||||||
result = await resolve_stream_url(client, sid)
|
result = await resolve_stream_url(sid)
|
||||||
|
|
||||||
if result:
|
if result:
|
||||||
url = result["url"]
|
url = result["url"]
|
||||||
@@ -234,13 +236,11 @@ async def get_iframe_source(
|
|||||||
|
|
||||||
player_url += f"&id={mal_id}&episode={episode}&video={urllib.parse.quote(url)}"
|
player_url += f"&id={mal_id}&episode={episode}&video={urllib.parse.quote(url)}"
|
||||||
return player_url
|
return player_url
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Failed to resolve server {sid}: {e}")
|
print(f"Failed to resolve server {sid}: {e}")
|
||||||
|
|
||||||
print("All servers failed.")
|
print("All servers failed.")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
import traceback
|
import traceback
|
||||||
print(f"Exception in get_iframe_source: {type(e).__name__}: {e}")
|
print(f"Exception in get_iframe_source: {type(e).__name__}: {e}")
|
||||||
@@ -248,12 +248,7 @@ async def get_iframe_source(
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
async def get_download_link(
|
async def get_download_link(mal_id: int, episode: int, dub: bool, quality: str) -> Optional[str]:
|
||||||
mal_id: int,
|
|
||||||
episode: int,
|
|
||||||
dub: bool,
|
|
||||||
quality: str
|
|
||||||
) -> Optional[str]:
|
|
||||||
"""
|
"""
|
||||||
Alias for get_iframe_source (AnimeKai uses adaptive m3u8)
|
Alias for get_iframe_source (AnimeKai uses adaptive m3u8)
|
||||||
"""
|
"""
|
||||||
|
|||||||
203
modules/comix.module
Normal file
203
modules/comix.module
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
{
|
||||||
|
"name": "Comix Reader",
|
||||||
|
"version": "1.0.6",
|
||||||
|
"author": "Animex",
|
||||||
|
"description": "Comix.to Manga Reader - Double-Safe Nested Data Parsing.",
|
||||||
|
"type": "MANGA_READER",
|
||||||
|
"requirements": ["httpx", "re", "json"]
|
||||||
|
}
|
||||||
|
---
|
||||||
|
import re
|
||||||
|
import json
|
||||||
|
import urllib.parse
|
||||||
|
import inspect
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
# Exact headers from your working test client
|
||||||
|
HEADERS = {
|
||||||
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
||||||
|
'Accept': 'application/json, text/plain, */*',
|
||||||
|
'Referer': 'https://comix.to/'
|
||||||
|
}
|
||||||
|
async def _smart_fetch(method: str, url: str, **kwargs):
|
||||||
|
"""Uses injected HybridClient if available, otherwise falls back to real httpx."""
|
||||||
|
client_or_lib = globals().get('httpx')
|
||||||
|
|
||||||
|
func = getattr(client_or_lib, method.lower(), None)
|
||||||
|
if func and inspect.iscoroutinefunction(func):
|
||||||
|
resp = await func(url, **kwargs)
|
||||||
|
|
||||||
|
# Debug: dump raw response to see what we're actually getting
|
||||||
|
raw = getattr(resp, 'text', '') or ''
|
||||||
|
print(f"[Comix] _smart_fetch response preview: {raw[:300]}")
|
||||||
|
|
||||||
|
return resp
|
||||||
|
|
||||||
|
# Fallback: real httpx.AsyncClient
|
||||||
|
import httpx as _real_httpx
|
||||||
|
async with _real_httpx.AsyncClient(follow_redirects=True) as client:
|
||||||
|
resp = await getattr(client, method.lower())(url, **kwargs)
|
||||||
|
print(f"[Comix] _smart_fetch (direct) response preview: {resp.text[:300]}")
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
def get_nested(data, *keys, default=None):
|
||||||
|
"""Helper to safely traverse deeply nested dictionaries even if keys are None."""
|
||||||
|
for key in keys:
|
||||||
|
if isinstance(data, dict):
|
||||||
|
data = data.get(key)
|
||||||
|
else:
|
||||||
|
return default
|
||||||
|
return data if data is not None else default
|
||||||
|
|
||||||
|
async def get_title_from_mal(mal_id: int):
|
||||||
|
"""Fetches the title from MyAnimeList via Jikan."""
|
||||||
|
url = f"https://api.jikan.moe/v4/manga/{mal_id}"
|
||||||
|
try:
|
||||||
|
resp = await _smart_fetch("GET", url)
|
||||||
|
if not resp: return None
|
||||||
|
data = resp.json() if hasattr(resp, "json") else None
|
||||||
|
|
||||||
|
# Safe traversal of data['data']['title']
|
||||||
|
return get_nested(data, 'data', 'title')
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[Comix] MAL Fetch Error: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def search_manga(query: str):
|
||||||
|
"""Searches Comix.to and returns (hash_id, slug)."""
|
||||||
|
if not query: return None
|
||||||
|
url = f"https://comix.to/api/v2/manga?keyword={urllib.parse.quote(query)}&order[relevance]=desc"
|
||||||
|
try:
|
||||||
|
resp = await _smart_fetch("GET", url, headers=HEADERS)
|
||||||
|
print(f"[Comix] Search status: {resp.status_code}")
|
||||||
|
data = resp.json() if hasattr(resp, "json") else None
|
||||||
|
if data is None:
|
||||||
|
print(f"[Comix] Search response was not JSON. Raw: {resp.text[:200]}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Safely get first item from result -> items
|
||||||
|
items = get_nested(data, 'result', 'items', default=[])
|
||||||
|
if items and isinstance(items, list) and len(items) > 0:
|
||||||
|
first = items[0]
|
||||||
|
if isinstance(first, dict):
|
||||||
|
return first.get('hash_id'), first.get('slug')
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[Comix] Search Error: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def get_chapters(mal_id: int):
|
||||||
|
try:
|
||||||
|
print(f"[Comix] get_chapters called for MAL ID: {mal_id}")
|
||||||
|
|
||||||
|
title = await get_title_from_mal(mal_id)
|
||||||
|
print(f"[Comix] Resolved title: {title}")
|
||||||
|
if not title: return None
|
||||||
|
|
||||||
|
manga_info = await search_manga(title)
|
||||||
|
print(f"[Comix] Search result: {manga_info}")
|
||||||
|
if not manga_info: return None
|
||||||
|
|
||||||
|
hash_id, slug = manga_info
|
||||||
|
|
||||||
|
# Paginate since API caps at 100 per request
|
||||||
|
all_items = []
|
||||||
|
offset = 0
|
||||||
|
seen_ids = set()
|
||||||
|
|
||||||
|
all_items = []
|
||||||
|
page = 1
|
||||||
|
|
||||||
|
while True:
|
||||||
|
url = f"https://comix.to/api/v2/manga/{hash_id}/chapters?order[number]=asc&limit=100&page={page}"
|
||||||
|
resp = await _smart_fetch("GET", url, headers=HEADERS)
|
||||||
|
|
||||||
|
data = resp.json() if hasattr(resp, "json") else None
|
||||||
|
if data is None or data.get("status") != 200:
|
||||||
|
print(f"[Comix] Bad response on page {page}: {data.get('message') if data else resp.text[:200]}")
|
||||||
|
break
|
||||||
|
|
||||||
|
items = get_nested(data, 'result', 'items', default=[])
|
||||||
|
pagination = get_nested(data, 'result', 'pagination', default={})
|
||||||
|
last_page = pagination.get('last_page', 1)
|
||||||
|
|
||||||
|
if not items:
|
||||||
|
break
|
||||||
|
|
||||||
|
all_items.extend(items)
|
||||||
|
print(f"[Comix] Page {page}/{last_page} — got {len(items)} chapters, total so far: {len(all_items)}")
|
||||||
|
|
||||||
|
if page >= last_page:
|
||||||
|
break
|
||||||
|
|
||||||
|
page += 1
|
||||||
|
|
||||||
|
seen_numbers = {}
|
||||||
|
formatted = []
|
||||||
|
for item in all_items:
|
||||||
|
if not isinstance(item, dict): continue
|
||||||
|
num = str(item.get('number', '0'))
|
||||||
|
if num not in seen_numbers:
|
||||||
|
seen_numbers[num] = True
|
||||||
|
formatted.append({
|
||||||
|
"title": item.get('name') or f"Chapter {num}",
|
||||||
|
"url": f"{hash_id}:{slug}:{item.get('chapter_id')}",
|
||||||
|
"chapter_number": num,
|
||||||
|
"is_external": False
|
||||||
|
})
|
||||||
|
|
||||||
|
def safe_float(v):
|
||||||
|
try: return float(v)
|
||||||
|
except: return 0.0
|
||||||
|
|
||||||
|
formatted.sort(key=lambda x: safe_float(x['chapter_number']), reverse=True)
|
||||||
|
return formatted
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[Comix] Chapter Fetch Exception: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def get_chapter_images(mal_id: int, chapter_num: str):
|
||||||
|
"""Public API: Scrapes image URLs from the chapter page."""
|
||||||
|
try:
|
||||||
|
chapters = await get_chapters(mal_id)
|
||||||
|
if not chapters: return None
|
||||||
|
|
||||||
|
target_chapter = None
|
||||||
|
target_f = None
|
||||||
|
try: target_f = float(chapter_num)
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
for ch in chapters:
|
||||||
|
if target_f is not None:
|
||||||
|
try:
|
||||||
|
if float(ch["chapter_number"]) == target_f:
|
||||||
|
target_chapter = ch
|
||||||
|
break
|
||||||
|
except: pass
|
||||||
|
if ch["chapter_number"] == str(chapter_num):
|
||||||
|
target_chapter = ch
|
||||||
|
break
|
||||||
|
|
||||||
|
if not target_chapter: return None
|
||||||
|
|
||||||
|
hash_id, slug, chapter_id = target_chapter["url"].split(":")
|
||||||
|
url = f"https://comix.to/title/{hash_id}-{slug}/{chapter_id}-chapter-{chapter_num}"
|
||||||
|
|
||||||
|
resp = await _smart_fetch("GET", url, headers=HEADERS)
|
||||||
|
if not resp or not hasattr(resp, "text"): return None
|
||||||
|
|
||||||
|
regex = r'["\\]*images["\\]*\s*:\s*(\[[^\]]*\])'
|
||||||
|
match = re.search(regex, resp.text, re.DOTALL)
|
||||||
|
|
||||||
|
if match:
|
||||||
|
raw_json = match.group(1).replace('\\"', '"')
|
||||||
|
images_data = json.loads(raw_json)
|
||||||
|
if isinstance(images_data, list):
|
||||||
|
return [img['url'] for img in images_data if isinstance(img, dict) and 'url' in img]
|
||||||
|
|
||||||
|
return []
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[Comix] Scraper Error: {e}")
|
||||||
|
return None
|
||||||
@@ -1,184 +1,165 @@
|
|||||||
{
|
{
|
||||||
"name": "MangaDex Reader",
|
"name": "MangaDex Reader",
|
||||||
"version": "1.0.0",
|
"version": "1.1.5",
|
||||||
"author": "Animex",
|
"author": "Animex",
|
||||||
"description": "Fetches manga chapters and page images from MangaDex using their v5 API.",
|
"description": "MangaDex Reader - Forced Hosted Chapters Mode (Bypasses External Links).",
|
||||||
"type": "MANGA_READER",
|
"type": "MANGA_READER",
|
||||||
"requirements": ["httpx"]
|
"requirements": ["httpx"]
|
||||||
}
|
}
|
||||||
---
|
---
|
||||||
import asyncio
|
import asyncio
|
||||||
import httpx
|
import httpx
|
||||||
|
import inspect
|
||||||
|
import urllib.parse
|
||||||
from typing import Optional, List, Dict, Any
|
from typing import Optional, List, Dict, Any
|
||||||
|
|
||||||
# --- Helper Functions ---
|
# =========================
|
||||||
|
# SMART TUNNEL HELPER
|
||||||
|
# =========================
|
||||||
|
|
||||||
def _uses_hybrid_client() -> bool:
|
async def _smart_fetch(method: str, url: str, **kwargs) -> Any:
|
||||||
return not hasattr(httpx, "AsyncClient")
|
func = getattr(httpx, method.lower())
|
||||||
|
if inspect.iscoroutinefunction(func):
|
||||||
|
return await func(url, **kwargs)
|
||||||
|
async with httpx.AsyncClient(follow_redirects=True) as client:
|
||||||
|
return await getattr(client, method.lower())(url, **kwargs)
|
||||||
|
|
||||||
async def _fetch_json(url: str, params: Dict[str, Any] = None, headers: Dict[str, str] = None, timeout: int = 10) -> Dict[str, Any]:
|
async def _fetch_json(url: str, params: Dict[str, Any] = None, headers: Dict[str, str] = None, timeout: int = 15) -> Dict[str, Any]:
|
||||||
if _uses_hybrid_client():
|
try:
|
||||||
resp = await httpx.get(url, params=params, headers=headers, timeout=timeout)
|
resp = await _smart_fetch("GET", url, params=params, headers=headers, timeout=timeout)
|
||||||
else:
|
resp.raise_for_status()
|
||||||
async with httpx.AsyncClient() as client:
|
data = resp.json()
|
||||||
resp = await client.get(url, params=params, headers=headers, timeout=timeout)
|
return data
|
||||||
resp.raise_for_status()
|
except Exception as e:
|
||||||
return resp.json()
|
print(f" [MangaDex Debug] Request failed: {url}")
|
||||||
|
raise
|
||||||
|
|
||||||
async def get_title_from_mal(mal_id: int, client: httpx.AsyncClient) -> Optional[str]:
|
# =========================
|
||||||
"""
|
# INTERNAL LOGIC
|
||||||
Fetches the primary English or Romaji title from Jikan (MAL API)
|
# =========================
|
||||||
to use for searching MangaDex.
|
|
||||||
"""
|
async def get_title_from_mal(mal_id: int) -> Optional[str]:
|
||||||
url = f"https://api.jikan.moe/v4/manga/{mal_id}"
|
url = f"https://api.jikan.moe/v4/manga/{mal_id}"
|
||||||
try:
|
try:
|
||||||
data = await _fetch_json(url)
|
data = await _fetch_json(url)
|
||||||
# Prefer English title for search accuracy, fallback to default title
|
|
||||||
return data.get("data", {}).get("title_english") or data.get("data", {}).get("title")
|
return data.get("data", {}).get("title_english") or data.get("data", {}).get("title")
|
||||||
except Exception as e:
|
except Exception: return None
|
||||||
print(f"MangaDex-Module: Jikan API error: {e}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
async def find_mangadex_id(mal_id: int, title: str, client: httpx.AsyncClient) -> Optional[str]:
|
async def find_mangadex_id(mal_id: int, title: str) -> Optional[str]:
|
||||||
"""
|
search_url = (
|
||||||
Searches MangaDex for the title and verifies the MAL ID in the metadata
|
f"https://api.mangadex.org/manga"
|
||||||
to ensure we have the correct manga.
|
f"?title={urllib.parse.quote(title)}&limit=5"
|
||||||
"""
|
f"&contentRating[]=safe&contentRating[]=suggestive&contentRating[]=erotica&contentRating[]=pornographic"
|
||||||
search_url = "https://api.mangadex.org/manga"
|
)
|
||||||
params = {
|
|
||||||
"title": title,
|
|
||||||
"limit": 10,
|
|
||||||
"order[relevance]": "desc"
|
|
||||||
}
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
data = await _fetch_json(search_url, params=params)
|
data = await _fetch_json(search_url)
|
||||||
results = data.get("data", [])
|
for manga in data.get("data", []):
|
||||||
|
if manga.get("attributes", {}).get("links", {}).get("mal") == str(mal_id):
|
||||||
for manga in results:
|
|
||||||
attributes = manga.get("attributes", {})
|
|
||||||
links = attributes.get("links", {})
|
|
||||||
|
|
||||||
# Check if the MAL ID provided in MangaDex metadata matches our target
|
|
||||||
# Note: links['mal'] is a string in their API
|
|
||||||
if links.get("mal") == str(mal_id):
|
|
||||||
return manga["id"]
|
return manga["id"]
|
||||||
|
return data["data"][0]["id"] if data.get("data") else None
|
||||||
# Fallback: If no strict MAL ID match found, return the first result
|
except Exception: return None
|
||||||
# if the titles are very similar (basic loose match)
|
|
||||||
if results:
|
|
||||||
print(f"MangaDex-Module: Strict MAL ID match failed. Defaulting to top search result: {results[0]['attributes']['title']}")
|
|
||||||
return results[0]["id"]
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
except Exception as e:
|
# =========================
|
||||||
print(f"MangaDex-Module: Search failed: {e}")
|
# PUBLIC MODULE API
|
||||||
return None
|
# =========================
|
||||||
|
|
||||||
# --- Main Module Functions ---
|
|
||||||
|
|
||||||
async def get_chapters(mal_id: int) -> Optional[List[Dict[str, Any]]]:
|
async def get_chapters(mal_id: int) -> Optional[List[Dict[str, Any]]]:
|
||||||
"""
|
title = await get_title_from_mal(mal_id)
|
||||||
Asynchronously gets a list of chapters for a given MyAnimeList ID
|
if not title: return None
|
||||||
via MangaDex API.
|
md_id = await find_mangadex_id(mal_id, title)
|
||||||
"""
|
if not md_id: return None
|
||||||
title = await get_title_from_mal(mal_id, httpx)
|
|
||||||
if not title:
|
|
||||||
print("MangaDex-Module: Could not retrieve title from MAL.")
|
|
||||||
return None
|
|
||||||
|
|
||||||
md_id = await find_mangadex_id(mal_id, title, httpx)
|
print(f" [MangaDex Debug] Fetching HOSTED ONLY feed for MD_ID: {md_id}")
|
||||||
if not md_id:
|
|
||||||
print(f"MangaDex-Module: Could not find MangaDex ID for MAL ID {mal_id}")
|
# CRITICAL CHANGE: includeExternalChapters=0 forces the API to return
|
||||||
return None
|
# chapters actually hosted on MangaDex servers, ignoring official external redirects.
|
||||||
|
feed_url = (
|
||||||
feed_url = f"https://api.mangadex.org/manga/{md_id}/feed"
|
f"https://api.mangadex.org/manga/{md_id}/feed"
|
||||||
params = {
|
f"?translatedLanguage[]=en"
|
||||||
"translatedLanguage[]": "en",
|
f"&limit=500"
|
||||||
"order[chapter]": "desc",
|
f"&contentRating[]=safe&contentRating[]=suggestive&contentRating[]=erotica&contentRating[]=pornographic"
|
||||||
"limit": 500,
|
f"&order[chapter]=asc"
|
||||||
"includes[]": "scanlation_group"
|
f"&includes[]=scanlation_group"
|
||||||
}
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
data = await _fetch_json(feed_url, params=params)
|
data = await _fetch_json(feed_url)
|
||||||
chapters = data.get("data", [])
|
raw_chapters = data.get("data", [])
|
||||||
|
print(f" [MangaDex Debug] Found {len(raw_chapters)} HOSTED chapters.")
|
||||||
|
|
||||||
|
formatted = []
|
||||||
|
seen_numbers = set()
|
||||||
|
|
||||||
formatted_chapters = []
|
for ch in raw_chapters:
|
||||||
seen_chapters = set()
|
|
||||||
|
|
||||||
for ch in chapters:
|
|
||||||
attr = ch.get("attributes", {})
|
attr = ch.get("attributes", {})
|
||||||
chapter_num = attr.get("chapter")
|
num = attr.get("chapter")
|
||||||
|
|
||||||
if chapter_num is None:
|
if num is None or num in seen_numbers:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# Find scanlation group name
|
||||||
|
group_name = "Unknown Group"
|
||||||
|
for rel in ch.get("relationships", []):
|
||||||
|
if rel["type"] == "scanlation_group":
|
||||||
|
group_name = rel.get("attributes", {}).get("name", "Unknown Group")
|
||||||
|
break
|
||||||
|
|
||||||
if chapter_num in seen_chapters:
|
seen_numbers.add(num)
|
||||||
continue
|
formatted.append({
|
||||||
seen_chapters.add(chapter_num)
|
"title": f"Ch. {num} - {attr.get('title') or group_name}",
|
||||||
|
"url": ch["id"],
|
||||||
chapter_title = attr.get("title") or f"Chapter {chapter_num}"
|
"chapter_number": str(num),
|
||||||
formatted_chapters.append({
|
"is_external": False
|
||||||
"title": chapter_title,
|
|
||||||
"url": ch["id"],
|
|
||||||
"chapter_number": str(chapter_num)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
return formatted_chapters
|
def safe_float(v):
|
||||||
|
try: return float(v)
|
||||||
|
except: return 0.0
|
||||||
|
|
||||||
|
formatted.sort(key=lambda x: safe_float(x['chapter_number']), reverse=True)
|
||||||
|
return formatted
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"MangaDex-Module: Error fetching chapters: {e}")
|
print(f" [MangaDex Debug] Feed Error: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def get_chapter_images(mal_id: int, chapter_num: str) -> Optional[List[str]]:
|
async def get_chapter_images(mal_id: int, chapter_num: str) -> Optional[List[str]]:
|
||||||
"""
|
print(f"🎬 MangaDex: Retrieving Images for MAL:{mal_id} Chapter:{chapter_num}")
|
||||||
Asynchronously gets page image URLs for a specific chapter number.
|
|
||||||
Note: 'chapter_num' is used to look up the UUID from the chapter list logic.
|
|
||||||
"""
|
|
||||||
# 1. We need the Chapter UUID. Re-using get_chapters to map Num -> UUID.
|
|
||||||
# In a production app, you might cache the chapter list to avoid this extra call.
|
|
||||||
all_chapters = await get_chapters(mal_id)
|
all_chapters = await get_chapters(mal_id)
|
||||||
if not all_chapters:
|
if not all_chapters:
|
||||||
|
print("❌ MangaDex: No hosted chapters found in feed.")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
chapter_uuid = None
|
target = str(chapter_num)
|
||||||
for ch in all_chapters:
|
# Match via float to handle "1" vs "1.0"
|
||||||
if ch.get("chapter_number") == str(chapter_num):
|
chapter_data = None
|
||||||
chapter_uuid = ch.get("url") # This contains the UUID from get_chapters
|
try:
|
||||||
break
|
target_f = float(target)
|
||||||
|
chapter_data = next((ch for ch in all_chapters if float(ch["chapter_number"]) == target_f), None)
|
||||||
if not chapter_uuid:
|
except:
|
||||||
print(f"MangaDex-Module: Chapter {chapter_num} not found for MAL ID {mal_id}")
|
chapter_data = next((ch for ch in all_chapters if ch["chapter_number"] == target), None)
|
||||||
|
|
||||||
|
if not chapter_data:
|
||||||
|
print(f"❌ MangaDex: Chapter {target} is not available in hosted mode.")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# 2. Call MangaDex At-Home API to get image metadata
|
chapter_uuid = chapter_data["url"]
|
||||||
async with httpx.AsyncClient() as client:
|
print(f"🔗 MangaDex: Target UUID: {chapter_uuid}")
|
||||||
try:
|
|
||||||
at_home_url = f"https://api.mangadex.org/at-home/server/{chapter_uuid}"
|
|
||||||
resp = await client.get(at_home_url, timeout=10)
|
|
||||||
resp.raise_for_status()
|
|
||||||
|
|
||||||
data = resp.json()
|
|
||||||
base_url = data.get("baseUrl")
|
|
||||||
chapter_hash = data.get("chapter", {}).get("hash")
|
|
||||||
# 'data' contains full quality, 'dataSaver' contains compressed
|
|
||||||
filenames = data.get("chapter", {}).get("data", [])
|
|
||||||
|
|
||||||
if not base_url or not chapter_hash or not filenames:
|
try:
|
||||||
print("MangaDex-Module: Incomplete data received from At-Home API.")
|
at_home_url = f"https://api.mangadex.org/at-home/server/{chapter_uuid}"
|
||||||
return []
|
data = await _fetch_json(at_home_url)
|
||||||
|
|
||||||
|
base_url = data.get("baseUrl")
|
||||||
|
chapter_hash = data.get("chapter", {}).get("hash")
|
||||||
|
filenames = data.get("chapter", {}).get("data", [])
|
||||||
|
|
||||||
# 3. Construct direct image URLs
|
if not filenames:
|
||||||
# Format: {baseUrl}/data/{hash}/{filename}
|
print(f"⚠️ MangaDex: No images found in At-Home response.")
|
||||||
image_links = [
|
return []
|
||||||
f"{base_url}/data/{chapter_hash}/{filename}"
|
|
||||||
for filename in filenames
|
|
||||||
]
|
|
||||||
|
|
||||||
return image_links
|
|
||||||
|
|
||||||
except Exception as e:
|
print(f"✅ MangaDex: Found {len(filenames)} images.")
|
||||||
print(f"MangaDex-Module: Error fetching images: {e}")
|
return [f"{base_url}/data/{chapter_hash}/{f}" for f in filenames]
|
||||||
return None
|
except Exception as e:
|
||||||
|
print(f"❌ MangaDex: At-Home API failed: {e}")
|
||||||
|
return None
|
||||||
Reference in New Issue
Block a user