manga-proxy / app.py
thanakon48155's picture
Update app.py
249f596 verified
Raw History Blame Contribute Delete
5.2 kB
from fastapi import FastAPI, Query, Response, HTTPException
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
import httpx
import logging
import asyncio
from playwright.async_api import async_playwright
async def apply_stealth(page):
try:
from playwright_stealth import stealth_async
await stealth_async(page)
except ImportError:
from playwright_stealth import Stealth
await Stealth().apply_stealth_async(page)
app = FastAPI(title="OpenNovel Proxy Server")
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("scraper")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["GET", "OPTIONS"],
allow_headers=["*"],
)
BROWSER_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
'Accept-Language': 'th-TH,th;q=0.9,en-US;q=0.8,en;q=0.7',
'Referer': 'https://www.google.com/'
}
@app.get("/", response_class=HTMLResponse)
def index():
return """
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><style>body { font-family: sans-serif; background: #f9fafb; max-width: 600px; margin: 80px auto; padding: 30px; border-radius: 16px; background: white; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); } h1 { color: #4f46e5; } code { background: #f3f4f6; padding: 4px 8px; border-radius: 6px; font-family: monospace; color: #db2777; } .status { color: #10b981; font-weight: bold; margin-bottom: 20px; }</style></head>
<body>
<h1>OpenNovel Proxy Server V5 🚀</h1>
<div class="status">🟢 Online (แก้ไขบั๊กและอัปเกรดระบบ AI Stealth สมบูรณ์ 100%)</div>
</body>
</html>
"""
@app.get("/scrape")
async def scrape(url: str = Query(..., description="The manga URL to scrape")):
if not url.startswith(("http://", "https://")):
raise HTTPException(status_code=400, detail="Invalid URL protocol")
logger.info(f"Scraping with Playwright Stealth: {url}")
try:
async with async_playwright() as p:
browser = await p.chromium.launch(
headless=True,
args=[
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-blink-features=AutomationControlled',
'--disable-infobars',
'--window-size=1280,800'
]
)
context = await browser.new_context(
user_agent=BROWSER_HEADERS['User-Agent'],
viewport={'width': 1280, 'height': 800},
device_scale_factor=1,
has_touch=False,
is_mobile=False
)
page = await context.new_page()
# ใช้งานโหมด Stealth เพื่อหลบการตรวจจับบอทขั้นสุด
await apply_stealth(page)
# เปิดหน้าเว็บ
await page.goto(url, wait_until="domcontentloaded", timeout=45000)
# จำลองพฤติกรรมมนุษย์ (เลื่อนจอลงเพื่อให้ lazy load ทำงานและผ่าน challenge)
await page.mouse.wheel(0, 1000)
await page.wait_for_timeout(3000)
await page.mouse.wheel(0, 1000)
await page.wait_for_timeout(5000)
# พยายามคลิกปุ่ม "Verify you are human" ของ Cloudflare ถ้ามี
try:
frames = page.frames
for frame in frames:
if 'cloudflare' in frame.url or 'turnstile' in frame.url:
await frame.click('input[type="checkbox"]', timeout=2000)
except:
pass
await page.wait_for_timeout(3000)
content = await page.content()
await browser.close()
return Response(content=content, media_type="text/html; charset=utf-8", status_code=200)
except Exception as e:
raise HTTPException(status_code=502, detail=str(e))
@app.get("/proxy")
async def proxy_image(url: str = None, referer: str = None):
if not url: return Response(content="Missing 'url'", status_code=400)
headers = BROWSER_HEADERS.copy()
if referer: headers['Referer'] = referer
try:
async def fetch_and_stream():
async with httpx.AsyncClient(follow_redirects=True, verify=False) as client:
req = client.build_request("GET", url, headers=headers)
r = await client.send(req, stream=True)
for chunk in r.aiter_bytes(): yield chunk
return StreamingResponse(fetch_and_stream(), media_type="image/jpeg")
except Exception as e:
return Response(content=f"Error proxying image: {str(e)}", status_code=500)