Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,12 +1,10 @@
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import json
|
| 4 |
-
import
|
| 5 |
import httpx
|
| 6 |
import random
|
| 7 |
import asyncio
|
| 8 |
-
import urllib.parse
|
| 9 |
-
import mimetypes
|
| 10 |
from bs4 import BeautifulSoup
|
| 11 |
from fastapi import FastAPI, HTTPException, Request
|
| 12 |
from fastapi.responses import StreamingResponse
|
|
@@ -24,19 +22,16 @@ ACCESS_KEY = os.getenv("ACCESS_KEY", "0000")
|
|
| 24 |
SERVICE_ACCOUNT_JSON_STR = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
|
| 25 |
ua = UserAgent(fallback='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
MEDIAFIRE_CACHE = {}
|
| 29 |
-
CACHE_TTL = 1800 # Cache သက်တမ်း စက္ကန့် 1800 (မိနစ် 30)
|
| 30 |
-
|
| 31 |
client = httpx.AsyncClient(
|
| 32 |
-
timeout=httpx.Timeout(
|
| 33 |
follow_redirects=True,
|
| 34 |
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20)
|
| 35 |
)
|
| 36 |
|
| 37 |
@app.get("/")
|
| 38 |
async def index():
|
| 39 |
-
return {"
|
| 40 |
|
| 41 |
def get_all_service_accounts():
|
| 42 |
if not SERVICE_ACCOUNT_JSON_STR: return []
|
|
@@ -49,6 +44,7 @@ async def get_token_for_account(cred_dict):
|
|
| 49 |
try:
|
| 50 |
scopes = ['https://www.googleapis.com/auth/drive.readonly']
|
| 51 |
creds = service_account.Credentials.from_service_account_info(cred_dict, scopes=scopes)
|
|
|
|
| 52 |
loop = asyncio.get_event_loop()
|
| 53 |
auth_req = google.auth.transport.requests.Request()
|
| 54 |
await loop.run_in_executor(None, creds.refresh, auth_req)
|
|
@@ -59,162 +55,101 @@ def get_google_file_id(url):
|
|
| 59 |
fid = re.search(r'/(?:d|file/d|open\?id=)/([a-zA-Z0-9_-]+)', url)
|
| 60 |
return fid.group(1) if fid else None
|
| 61 |
|
| 62 |
-
def get_clean_filename(url):
|
| 63 |
-
decoded_url = urllib.parse.unquote(url)
|
| 64 |
-
name = decoded_url.split('/')[-1].split('?')[0]
|
| 65 |
-
if not name or '.' not in name:
|
| 66 |
-
name = "video.mp4"
|
| 67 |
-
return name
|
| 68 |
-
|
| 69 |
@app.get("/download")
|
| 70 |
async def download_proxy(request: Request, url: str, key: str = None):
|
| 71 |
if key != ACCESS_KEY:
|
| 72 |
raise HTTPException(status_code=403, detail="Access Denied")
|
| 73 |
|
| 74 |
-
clean_url = urllib.parse.unquote(url)
|
| 75 |
-
filename = get_clean_filename(clean_url)
|
| 76 |
range_header = request.headers.get('range')
|
| 77 |
-
|
| 78 |
-
req_ua = ua.random
|
| 79 |
-
current_time = time.time()
|
| 80 |
|
| 81 |
-
# --- MediaFire
|
| 82 |
-
if "
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
if
|
| 87 |
try:
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
)
|
| 92 |
-
except HTTPException as e:
|
| 93 |
-
# အကယ်၍ Cached Link သည် သက်တမ်းကုန်သွား၍ 415 ပြန်လာပါက Cache ကိုဖျက်ပြီး အသစ်ပြန်ရှာမည်
|
| 94 |
-
if e.status_code == 415:
|
| 95 |
-
print(f"Cache expired for {clean_url}, refetching...")
|
| 96 |
-
del MEDIAFIRE_CACHE[clean_url]
|
| 97 |
-
else:
|
| 98 |
-
raise
|
| 99 |
-
|
| 100 |
-
# 2. Cache မရှိပါက သို့မဟုတ် Expire ဖြစ်သွားပါက အသစ်ပြန်ရှာခြင်း
|
| 101 |
-
try:
|
| 102 |
-
async with httpx.AsyncClient(headers={'User-Agent': req_ua}, follow_redirects=True) as temp_client:
|
| 103 |
-
page_res = await temp_client.get(clean_url)
|
| 104 |
-
if page_res.status_code != 200:
|
| 105 |
-
raise HTTPException(status_code=page_res.status_code, detail="MediaFire page access failed")
|
| 106 |
-
|
| 107 |
-
html_content = page_res.text
|
| 108 |
-
target_link = None
|
| 109 |
-
cookies = temp_client.cookies
|
| 110 |
-
|
| 111 |
-
match = re.search(r"https?://download[0-9]+\.mediafire\.com/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/[^\s'\"]+", html_content)
|
| 112 |
if match:
|
| 113 |
-
target_link = match.group(
|
| 114 |
-
|
| 115 |
-
if not target_link:
|
| 116 |
-
soup = BeautifulSoup(html_content, 'html.parser')
|
| 117 |
-
download_btn = soup.find('a', {'id': 'downloadButton'}) or soup.find('a', {'class': 'input_btn_p'})
|
| 118 |
-
if download_btn and download_btn.get('href'):
|
| 119 |
-
target_link = download_btn.get('href')
|
| 120 |
-
|
| 121 |
-
if target_link:
|
| 122 |
-
if target_link.startswith("//"): target_link = f"https:{target_link}"
|
| 123 |
-
elif target_link.startswith("/"): target_link = f"https://www.mediafire.com{target_link}"
|
| 124 |
-
|
| 125 |
-
# နောက်ထပ် Range Request များအတွက် Memory ထဲတွင် မှတ်သားထားခြင်း
|
| 126 |
-
MEDIAFIRE_CACHE[clean_url] = {
|
| 127 |
-
'link': target_link,
|
| 128 |
-
'ua': req_ua,
|
| 129 |
-
'cookies': dict(cookies),
|
| 130 |
-
'time': current_time
|
| 131 |
-
}
|
| 132 |
-
|
| 133 |
-
return await stream_file(target_link, range_header, filename, referer=clean_url, req_ua=req_ua, cookies=cookies)
|
| 134 |
else:
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
r = await client.send(req, stream=True)
|
| 158 |
-
if r.status_code in [200, 206]:
|
| 159 |
-
return await process_response(r, filename)
|
| 160 |
-
await r.aclose()
|
| 161 |
-
except: continue
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
|
|
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
if range_header: headers['Range'] = range_header
|
| 172 |
-
if referer: headers['Referer'] = referer
|
| 173 |
|
| 174 |
try:
|
| 175 |
-
req = client.build_request("GET", target_url, headers=headers
|
| 176 |
r = await client.send(req, stream=True)
|
| 177 |
-
|
| 178 |
-
ctype = r.headers.get('content-type', '').lower()
|
| 179 |
-
if 'text/html' in ctype:
|
| 180 |
-
await r.aclose()
|
| 181 |
-
raise HTTPException(status_code=415, detail="Invalid Media Type: HTML Received")
|
| 182 |
-
|
| 183 |
-
return await process_response(r, filename)
|
| 184 |
-
except HTTPException:
|
| 185 |
-
raise
|
| 186 |
except Exception as e:
|
| 187 |
-
print(f"Stream Error: {e}")
|
| 188 |
raise HTTPException(status_code=500, detail=str(e))
|
| 189 |
|
| 190 |
-
async def process_response(r
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
if filename.lower().endswith('.mkv'): mime_type = 'video/x-matroska'
|
| 194 |
-
elif filename.lower().endswith('.mp4'): mime_type = 'video/mp4'
|
| 195 |
-
else: mime_type = 'video/mp4'
|
| 196 |
-
|
| 197 |
-
safe_headers = ['content-length', 'content-range', 'accept-ranges', 'cache-control']
|
| 198 |
-
res_headers = {n: v for n, v in r.headers.items() if n.lower() in safe_headers}
|
| 199 |
-
|
| 200 |
-
res_headers['Content-Type'] = mime_type
|
| 201 |
-
res_headers['Accept-Ranges'] = 'bytes'
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
yield chunk
|
| 210 |
-
finally:
|
| 211 |
-
await r.aclose()
|
| 212 |
|
| 213 |
return StreamingResponse(
|
| 214 |
-
|
| 215 |
status_code=r.status_code,
|
| 216 |
-
headers=
|
| 217 |
-
media_type=
|
| 218 |
)
|
| 219 |
|
| 220 |
if __name__ == "__main__":
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import json
|
| 4 |
+
import base64
|
| 5 |
import httpx
|
| 6 |
import random
|
| 7 |
import asyncio
|
|
|
|
|
|
|
| 8 |
from bs4 import BeautifulSoup
|
| 9 |
from fastapi import FastAPI, HTTPException, Request
|
| 10 |
from fastapi.responses import StreamingResponse
|
|
|
|
| 22 |
SERVICE_ACCOUNT_JSON_STR = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
|
| 23 |
ua = UserAgent(fallback='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
|
| 24 |
|
| 25 |
+
# Global Async Client: Video ကျော်ကြည့်တဲ့အခါ Connection အသစ်တွေ မြန်မြန်ဆောက်နိုင်ဖို့
|
|
|
|
|
|
|
|
|
|
| 26 |
client = httpx.AsyncClient(
|
| 27 |
+
timeout=httpx.Timeout(20.0, read=None),
|
| 28 |
follow_redirects=True,
|
| 29 |
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20)
|
| 30 |
)
|
| 31 |
|
| 32 |
@app.get("/")
|
| 33 |
async def index():
|
| 34 |
+
return {"Online"}
|
| 35 |
|
| 36 |
def get_all_service_accounts():
|
| 37 |
if not SERVICE_ACCOUNT_JSON_STR: return []
|
|
|
|
| 44 |
try:
|
| 45 |
scopes = ['https://www.googleapis.com/auth/drive.readonly']
|
| 46 |
creds = service_account.Credentials.from_service_account_info(cred_dict, scopes=scopes)
|
| 47 |
+
# Token refresh ကို thread ထဲမှာ run ပါတယ် (Google library က sync ဖြစ်လို့)
|
| 48 |
loop = asyncio.get_event_loop()
|
| 49 |
auth_req = google.auth.transport.requests.Request()
|
| 50 |
await loop.run_in_executor(None, creds.refresh, auth_req)
|
|
|
|
| 55 |
fid = re.search(r'/(?:d|file/d|open\?id=)/([a-zA-Z0-9_-]+)', url)
|
| 56 |
return fid.group(1) if fid else None
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
@app.get("/download")
|
| 59 |
async def download_proxy(request: Request, url: str, key: str = None):
|
| 60 |
if key != ACCESS_KEY:
|
| 61 |
raise HTTPException(status_code=403, detail="Access Denied")
|
| 62 |
|
|
|
|
|
|
|
| 63 |
range_header = request.headers.get('range')
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
+
# --- MediaFire & Others ---
|
| 66 |
+
if "drive.google.com" not in url:
|
| 67 |
+
target_link = None
|
| 68 |
+
headers = {'User-Agent': ua.random, 'Accept-Language': 'en-US,en;q=0.9'}
|
| 69 |
+
|
| 70 |
+
if "mediafire.com" in url:
|
| 71 |
try:
|
| 72 |
+
headers['Referer'] = 'https://www.mediafire.com/'
|
| 73 |
+
r = await client.get(url, headers=headers)
|
| 74 |
+
# Regex ဖြင့် Direct Link ကို အမြန်ဆုံး ရှာဖွေခြင်း
|
| 75 |
+
match = re.search(r'href="(https?://download[^"]+)"', r.text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
if match:
|
| 77 |
+
target_link = match.group(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
else:
|
| 79 |
+
soup = BeautifulSoup(r.text, 'html.parser')
|
| 80 |
+
btn = soup.find('a', {'id': 'downloadButton'})
|
| 81 |
+
target_link = btn.get('href') if btn else None
|
| 82 |
+
except Exception as e:
|
| 83 |
+
print(f"MediaFire Error: {e}")
|
| 84 |
+
|
| 85 |
+
elif "dropbox.com" in url:
|
| 86 |
+
target_link = url.replace("?dl=0", "").split("?")[0] + "?dl=1"
|
| 87 |
+
|
| 88 |
+
elif "1drv.ms" in url or "onedrive.live.com" in url:
|
| 89 |
+
encoded_url = base64.b64encode(bytes(url, 'utf-8')).decode('utf-8').replace('=', '').replace('/', '_').replace('+', '-')
|
| 90 |
+
target_link = f"https://api.onedrive.com/v1.0/shares/u!{encoded_url}/root/content"
|
| 91 |
+
|
| 92 |
+
if not target_link:
|
| 93 |
+
raise HTTPException(status_code=400, detail="Could not resolve direct link")
|
| 94 |
+
|
| 95 |
+
return await stream_file(target_link, range_header)
|
| 96 |
+
|
| 97 |
+
# --- Google Drive ---
|
| 98 |
+
file_id = get_google_file_id(url)
|
| 99 |
+
if not file_id:
|
| 100 |
+
raise HTTPException(status_code=400, detail="Invalid Google Drive Link")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
accounts = get_all_service_accounts()
|
| 103 |
+
random.shuffle(accounts)
|
| 104 |
|
| 105 |
+
for account in accounts:
|
| 106 |
+
token = await get_token_for_account(account)
|
| 107 |
+
if not token: continue
|
| 108 |
|
| 109 |
+
api_link = f"https://www.googleapis.com/drive/v3/files/{file_id}?alt=media"
|
| 110 |
+
headers = {"Authorization": f"Bearer {token}"}
|
| 111 |
+
if range_header: headers['Range'] = range_header
|
| 112 |
+
|
| 113 |
+
try:
|
| 114 |
+
# Stream mode ဖြင့် ချိတ်ဆက်ခြင်း
|
| 115 |
+
req = client.build_request("GET", api_link, headers=headers)
|
| 116 |
+
r = await client.send(req, stream=True)
|
| 117 |
+
if r.status_code in [200, 206]:
|
| 118 |
+
return await process_response(r)
|
| 119 |
+
await r.aclose()
|
| 120 |
+
except: continue
|
| 121 |
+
|
| 122 |
+
# Public Fallback
|
| 123 |
+
public_url = f"https://drive.google.com/uc?export=download&id={file_id}"
|
| 124 |
+
return await stream_file(public_url, range_header)
|
| 125 |
+
|
| 126 |
+
async def stream_file(target_url, range_header):
|
| 127 |
+
headers = {'User-Agent': ua.random}
|
| 128 |
if range_header: headers['Range'] = range_header
|
|
|
|
| 129 |
|
| 130 |
try:
|
| 131 |
+
req = client.build_request("GET", target_url, headers=headers)
|
| 132 |
r = await client.send(req, stream=True)
|
| 133 |
+
return await process_response(r)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
except Exception as e:
|
|
|
|
| 135 |
raise HTTPException(status_code=500, detail=str(e))
|
| 136 |
|
| 137 |
+
async def process_response(r):
|
| 138 |
+
excluded = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
|
| 139 |
+
response_headers = {n: v for n, v in r.headers.items() if n.lower() not in excluded}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
+
# Video Seeking အတွက် မရှိမဖြစ်လိုအပ်သော Headers များ
|
| 142 |
+
response_headers['Accept-Ranges'] = 'bytes'
|
| 143 |
+
if 'Content-Length' in r.headers:
|
| 144 |
+
response_headers['Content-Length'] = r.headers['Content-Length']
|
| 145 |
+
if 'Content-Range' in r.headers:
|
| 146 |
+
response_headers['Content-Range'] = r.headers['Content-Range']
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
return StreamingResponse(
|
| 149 |
+
r.aiter_bytes(chunk_size=131072), # 128KB chunks for perfect buffering
|
| 150 |
status_code=r.status_code,
|
| 151 |
+
headers=response_headers,
|
| 152 |
+
media_type=r.headers.get('Content-Type', 'application/octet-stream')
|
| 153 |
)
|
| 154 |
|
| 155 |
if __name__ == "__main__":
|