mc / server.py
ksshan918's picture
Update server.py
5dd3cb7 verified
Raw History Blame Contribute Delete
16.3 kB
from playwright.async_api import async_playwright, Browser, Playwright
from contextlib import asynccontextmanager
from typing import Optional
from cache_ import TTLCache, log as logger
from fastapi import FastAPI
from uvicorn import Config, Server
from requests.adapters import HTTPAdapter
import asyncio
import re
from urllib.parse import quote_plus, urljoin, urlparse, parse_qs
from cloudscraper import create_scraper
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
uvloop.install()
except Exception:
pass
# =============================================================
_cache = TTLCache(default_timeout=5 * 60) # 5mins
_browser: Optional[Browser] = None
_playwright: Optional[Playwright] = None
_NUM_PATTERN = re.compile(r"(\d+)")
# Fix: Mount a larger connection pool to prevent "Connection pool is full" warnings
_session = create_scraper()
_adapter = HTTPAdapter(
pool_connections=20, # number of connection pools (per host)
pool_maxsize=50, # max connections per pool
max_retries=3, # built-in retry on transient errors
)
_session.mount("https://", _adapter)
_session.mount("http://", _adapter)
# =============================================================
# ====================== PLAYWRIGHT ======================
_browser_lock = asyncio.Lock()
_browser: Optional[Browser] = None
_playwright: Optional[Playwright] = None
_browser_last_used = 0
_BROWSER_IDLE_TIMEOUT = 300 # 5 minutes
TOR_PROXY = "socks5://127.0.0.1:9050"
async def get_browser() -> Optional[Browser]:
"""Get or create a browser instance with proper locking."""
global _browser, _playwright, _browser_last_used
async with _browser_lock:
# Check if browser is still valid
if _browser is not None:
try:
# Test if browser is still connected
if not _browser.is_connected():
logger.warning("Browser disconnected, recreating...")
await _cleanup_playwright()
else:
_browser_last_used = asyncio.get_event_loop().time()
return _browser
except Exception as e:
logger.error(f"Browser connection check failed: {e}")
await _cleanup_playwright()
# Create new browser
try:
if _playwright is None:
_playwright = await async_playwright().start()
_browser = await _playwright.chromium.launch(
headless=True,
# proxy={"server": TOR_PROXY},
args=[
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-gpu",
"--no-zygote",
"--start-maximized",
"--disable-blink-features=AutomationControlled",
"--disable-features=IsolateOrigins,site-per-process",
"--disable-web-security",
"--disable-features=BlockInsecurePrivateNetworkRequests",
]
)
_browser_last_used = asyncio.get_event_loop().time()
logger.info("Browser launched successfully")
return _browser
except Exception as e:
logger.error(f"Failed to launch Playwright browser: {e}")
await _cleanup_playwright()
return None
async def _cleanup_playwright():
"""Robust cleanup even on partial failure."""
global _browser, _playwright
if _browser:
try:
await _browser.close()
except Exception as e:
logger.error(f"Error closing browser: {e}")
if _playwright:
try:
await _playwright.stop()
except Exception as e:
logger.error(f"Error stopping playwright: {e}")
_browser = None
_playwright = None
@asynccontextmanager
async def new_context(**context_kwargs):
"""Yields an isolated browser context with retry logic."""
max_retries = 3
retry_delay = 1
for attempt in range(max_retries):
browser = await get_browser()
if browser is None:
if attempt < max_retries - 1:
await asyncio.sleep(retry_delay * (attempt + 1))
continue
yield None
return
context = None
try:
# Set default context options
default_kwargs = {
"viewport": {"width": 1920, "height": 1080},
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
"ignore_https_errors": True,
"java_script_enabled": True,
}
default_kwargs.update(context_kwargs)
context = await browser.new_context(**default_kwargs)
yield context
break # Success, exit retry loop
except Exception as e:
logger.error(f"Context creation attempt {attempt + 1} failed: {e}")
if context:
try:
await context.close()
except:
pass
if attempt == max_retries - 1:
logger.error("All context creation attempts failed")
yield None
else:
# Force browser recreation on next attempt
async with _browser_lock:
await _cleanup_playwright()
await asyncio.sleep(retry_delay * (attempt + 1))
finally:
if context:
try:
await context.close()
except Exception as e:
logger.error(f"Error closing context: {e}")
# ======================= ALLMANGA =============================================
def parse_api_params(resp_url: str) -> int:
try:
filename = resp_url.split("/")[-1] # Gets "2.png"
match_ = re.search(r"(\d+)", filename) # Pattern FIRST, string SECOND
return int(match_.group(1)) if match_ else 0
except Exception:
return 0
def filter_list(images_url: str, image_len: int) -> list:
"""
images_url: https://ytimgf.youtube-anime.com/images133/rkbMRRccqy9hRKQfT/10/sub_1760311194/1.jpg
image_len: total number of images
"""
base_path = images_url[:images_url.rfind("/") + 1]
file_ext = images_url.split(".")[-1]
return [f"{base_path}{i}.{file_ext}" for i in range(1, image_len)]
async def allManga_pictures(url: str) -> list:
first_image: Optional[str] = None
div_ids: list = []
page = None
try:
async with new_context(ignore_https_errors=True) as context:
if context is None:
return []
page = await context.new_page()
await page.goto(url, wait_until="commit", timeout=15000)
await page.wait_for_load_state("networkidle")
await asyncio.sleep(2)
await page.evaluate("""
() => {
// Find all lazy images and set src from data-src
document.querySelectorAll('img[data-src]').forEach(img => {
img.src = img.getAttribute('data-src')
})
// Trigger intersection observer manually
document.querySelectorAll('img.lazy-img').forEach(img => {
img.classList.add('lazy-img-loaded')
if(img.getAttribute('data-src')) {
img.src = img.getAttribute('data-src')
}
})
}""")
await asyncio.sleep(7)
images = await page.evaluate("""
() => {
return [...document.querySelectorAll('img')]
.map(img => img.src)
.filter(src => src && src.includes('youtube-anime'))
}""")
try:
await page.close()
page = None
except:
pass
if not images:
return []
return [img for img in images if "/images" in img and "/sub" in img]
except Exception as e:
logger.error(f"Failed to get images: {e}")
return []
finally:
if page:
try:
await page.close()
except:
pass
# ========================== COMIX ========================================
API_CHAPTERS = (
"https://comix.to/api/v2/manga/{}/chapters?order[number]=desc&limit=100&page={}"
)
HEADERS = {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"content-type": "application/json",
"priority": "u=1, i",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
}
async def sniff_chapter_token(manga_url: str) -> dict:
"""
Use async Playwright to visit the manga page and intercept the first
chapter API request, returning the `time` and `_` token params.
Returns a dict like {"time": "1", "_": "xQm9t..."} or {} on failure.
"""
token_params = {}
async def handle_response(response):
if token_params:
return
url = response.url
if "/api/v2/manga/" in url and "/chapters" in url:
parsed = urlparse(url)
qs = parse_qs(parsed.query)
time_val = qs.get("time", [None])[0]
token_val = qs.get("_", [None])[0]
if time_val and token_val:
token_params["time"] = time_val
token_params["_"] = token_val
page = None
try:
async with new_context(ignore_https_errors=True) as context:
if context is None:
return token_params
page = await context.new_page()
page.on("response", handle_response)
try:
await page.goto(manga_url, wait_until="domcontentloaded", timeout=20000)
except Exception:
pass # timeout ok, we just need the chapter API response intercepted
await page.wait_for_timeout(5000)
token_params["html"] = await page.content()
try:
await page.close()
except Exception:
pass
except Exception as er:
logger.error(f"Error in sniff_chapter_token: {er}")
finally:
if page:
try:
await page.close()
except Exception:
pass
return token_params
def create_link(manga_id: str, page: int, token_params: dict) -> str:
base = API_CHAPTERS.format(manga_id, page)
if token_params:
base += f"&time={token_params['time']}&_={token_params['_']}"
return base
async def comix_chapters(url: str) -> dict:
try:
results = await sniff_chapter_token(url)
except Exception as e:
logger.error(f"Playwright failure for {url}: {e}")
results = {}
if "time" not in results:
return results
m = re.search(r"/title/([a-z0-9]+)-([^/]+)", url, re.IGNORECASE)
manga_id = m.group(1) if m else None
slug = m.group(2) if m else None
if not manga_id:
# Try another pattern
m = re.search(r"/title/([a-z0-9]+)", url, re.IGNORECASE)
manga_id = m.group(1) if m else None
if not manga_id:
logger.warning(f"Could not extract manga ID from: {url}")
return {}
results["chapters"] = []
page = 1
MAX_PAGES = 200 # Safety cap to prevent runaway loops
while page <= MAX_PAGES:
chapter_api = create_link(manga_id, page, results)
try:
# Fix: capture current value of chapter_api to avoid lambda late-binding bug
# Fix: add timeout=15 to prevent indefinite hangs
r = await asyncio.to_thread(
lambda api=chapter_api: _session.get(api, headers=HEADERS, timeout=15)
)
chapter_json = r.json()
except Exception as e:
logger.error(f"API Error at {chapter_api}: {e}")
break # Fix: break instead of continue to avoid infinite retry loop
if not isinstance(chapter_json, dict):
break
result_data = chapter_json.get("result")
if not isinstance(result_data, dict):
break
items = result_data.get("items", [])
if not items:
break
for chap in items:
chap_num = chap.get("number")
chap_id = chap.get("chapter_id")
scan_group = chap.get("scanlation_group") or {}
scanlator = scan_group.get("name") or ""
slug_val = (scan_group.get("slug") or "").lower()
chapter_url = f"https://comix.to/title/{manga_id}-{slug or 'manga'}/{chap_id}-chapter-{chap_num}"
info = {
"title": str(chap_num),
"url": chapter_url,
"group_name": scanlator,
"scanlator_slug": slug_val,
}
results["chapters"].append(info)
pag = result_data.get("pagination", {})
if pag and pag.get("current_page", 1) < pag.get("last_page", 1):
page += 1
else:
break
return results
# ===================================================
# FASTAPI
# ===================================================
from fastapi.responses import JSONResponse, Response
app = FastAPI()
@app.get("/")
async def main():
return "Make By @Wizard_bots (telegram.me/Wizard_bots) "
@app.get("/favicon.ico")
async def favicon():
# Return a 1x1 transparent PNG
return Response(content=b'\x00\x00\x00\x00', media_type="image/x-icon")
@app.get("/a")
async def all_request(url: str):
if not url.startswith("https://allmanga.to"):
return JSONResponse(
status_code=404,
content={"status": False, "message": "This Url is not Supported"}
)
try:
if url in _cache:
a_data = _cache[url]
else:
a_data = await allManga_pictures(url=url)
if not a_data:
return JSONResponse(
status_code=404,
content={"status": False, "message": "Failed to extract data"}
)
_cache[url] = a_data
return JSONResponse(
status_code=200,
content={"status": True, "results": a_data}
)
except asyncio.exceptions.TimeoutError:
return JSONResponse(
status_code=500,
content={"status": False, "message": "Time Out"}
)
except Exception as e:
logger.error(f"Error processing {url}: {e}")
return JSONResponse(
status_code=500,
content={"status": False, "message": "Internal server error"}
)
@app.get("/c")
async def cx_request(url: str):
if not url.startswith("https://comix.to/"):
return JSONResponse(
status_code=404,
content={"status": False, "message": "This Url is not Supported"}
)
try:
if url in _cache:
s = _cache[url]
else:
s = await comix_chapters(url)
if not s:
return JSONResponse(
status_code=404,
content={"status": False, "message": "Failed to extract data"}
)
_cache[url] = s
s['status'] = True
return JSONResponse(
status_code=200,
content=s
)
except Exception as er:
logger.error(er)
return JSONResponse(
status_code=500,
content={"status": False, "message": "Internal server error"}
)
@app.on_event("shutdown")
async def shutdown_event():
await _cleanup_playwright()
# =======================================================
# MAIN
# ======================================================
async def main_web():
from os import environ
port = int(environ.get("PORT", 7860))
config = Config(app, host="0.0.0.0", port=port, reload=False)
server = Server(config)
await server.serve()
if __name__ == "__main__":
asyncio.run(main_web())