Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
|
@@ -6,6 +6,7 @@ import httpx
|
|
| 6 |
import random
|
| 7 |
import asyncio
|
| 8 |
import urllib.parse
|
|
|
|
| 9 |
from bs4 import BeautifulSoup
|
| 10 |
from fastapi import FastAPI, HTTPException, Request
|
| 11 |
from fastapi.responses import StreamingResponse
|
|
@@ -23,9 +24,8 @@ ACCESS_KEY = os.getenv("ACCESS_KEY", "0000")
|
|
| 23 |
SERVICE_ACCOUNT_JSON_STR = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
|
| 24 |
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')
|
| 25 |
|
| 26 |
-
# Global Async Client
|
| 27 |
client = httpx.AsyncClient(
|
| 28 |
-
timeout=httpx.Timeout(
|
| 29 |
follow_redirects=True,
|
| 30 |
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20)
|
| 31 |
)
|
|
@@ -55,106 +55,132 @@ def get_google_file_id(url):
|
|
| 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 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
|
| 69 |
-
if "drive.google.com" not in url:
|
| 70 |
-
target_link = None
|
| 71 |
-
headers = {'User-Agent': ua.random, 'Accept-Language': 'en-US,en;q=0.9'}
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
btn = soup.find('a', {'id': 'downloadButton'})
|
| 85 |
-
if btn and btn.get('href'):
|
| 86 |
-
# ပေးလာတဲ့ href မှာ https:// မပါရင် မူလ URL နဲ့ ပေါင်းပြီး အပြည့်အစုံဖြစ်အောင် ပြုလုပ်ခြင်း
|
| 87 |
-
target_link = urllib.parse.urljoin(url, btn.get('href'))
|
| 88 |
-
except Exception as e:
|
| 89 |
-
print(f"MediaFire Error: {e}")
|
| 90 |
-
|
| 91 |
-
elif "dropbox.com" in url:
|
| 92 |
-
target_link = url.replace("?dl=0", "").split("?")[0] + "?dl=1"
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
# --- Google Drive ---
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
r = await client.send(req, stream=True)
|
| 122 |
-
if r.status_code in [200, 206]:
|
| 123 |
-
return await process_response(r)
|
| 124 |
-
await r.aclose()
|
| 125 |
-
except: continue
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
return await stream_file(public_url, range_header)
|
| 130 |
|
| 131 |
-
async def stream_file(target_url, range_header):
|
| 132 |
headers = {'User-Agent': ua.random}
|
| 133 |
if range_header: headers['Range'] = range_header
|
|
|
|
| 134 |
|
| 135 |
try:
|
| 136 |
req = client.build_request("GET", target_url, headers=headers)
|
| 137 |
r = await client.send(req, stream=True)
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
except Exception as e:
|
| 140 |
-
print(f"Stream Error for {target_url}: {e}")
|
| 141 |
raise HTTPException(status_code=500, detail=str(e))
|
| 142 |
|
| 143 |
-
async def process_response(r):
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
| 146 |
|
|
|
|
|
|
|
| 147 |
response_headers['Accept-Ranges'] = 'bytes'
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
response_headers['Content-Disposition'] = 'attachment'
|
| 154 |
|
| 155 |
async def stream_generator():
|
| 156 |
try:
|
| 157 |
-
async for chunk in r.aiter_bytes(chunk_size=
|
| 158 |
yield chunk
|
| 159 |
finally:
|
| 160 |
await r.aclose()
|
|
@@ -163,7 +189,7 @@ async def process_response(r):
|
|
| 163 |
stream_generator(),
|
| 164 |
status_code=r.status_code,
|
| 165 |
headers=response_headers,
|
| 166 |
-
media_type=
|
| 167 |
)
|
| 168 |
|
| 169 |
if __name__ == "__main__":
|
|
|
|
| 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 |
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 |
client = httpx.AsyncClient(
|
| 28 |
+
timeout=httpx.Timeout(60.0, read=None),
|
| 29 |
follow_redirects=True,
|
| 30 |
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20)
|
| 31 |
)
|
|
|
|
| 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 |
+
def get_mime_from_filename(filename):
|
| 59 |
+
"""ဖိုင်နာမည်ကိုကြည့်ပြီး Content-Type သတ်မှတ်ခြင်း"""
|
| 60 |
+
mime, _ = mimetypes.guess_type(filename)
|
| 61 |
+
if not mime:
|
| 62 |
+
if filename.lower().endswith('.mkv'): return 'video/x-matroska'
|
| 63 |
+
if filename.lower().endswith('.mp4'): return 'video/mp4'
|
| 64 |
+
if filename.lower().endswith('.avi'): return 'video/x-msvideo'
|
| 65 |
+
return 'video/mp4' # Default for players
|
| 66 |
+
return mime
|
| 67 |
+
|
| 68 |
@app.get("/download")
|
| 69 |
async def download_proxy(request: Request, url: str, key: str = None):
|
| 70 |
if key != ACCESS_KEY:
|
| 71 |
raise HTTPException(status_code=403, detail="Access Denied")
|
| 72 |
|
| 73 |
+
clean_url = urllib.parse.unquote(url)
|
| 74 |
+
while "%" in clean_url:
|
| 75 |
+
prev_url = clean_url
|
| 76 |
+
clean_url = urllib.parse.unquote(clean_url)
|
| 77 |
+
if prev_url == clean_url: break
|
| 78 |
|
| 79 |
+
# URL ထဲမှ ဖိုင်နာမည်ကို ထုတ်ယူခြင်း
|
| 80 |
+
filename = "video.mp4"
|
| 81 |
+
path_parts = clean_url.split('/')
|
| 82 |
+
for part in reversed(path_parts):
|
| 83 |
+
if '.' in part and len(part) > 4:
|
| 84 |
+
filename = part.split('?')[0]
|
| 85 |
+
break
|
| 86 |
|
| 87 |
+
range_header = request.headers.get('range')
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
# --- MediaFire ---
|
| 90 |
+
if "mediafire.com" in clean_url:
|
| 91 |
+
try:
|
| 92 |
+
r = await client.get(clean_url, headers={'User-Agent': ua.random})
|
| 93 |
+
if r.status_code != 200:
|
| 94 |
+
raise HTTPException(status_code=r.status_code, detail="MediaFire page error")
|
| 95 |
+
|
| 96 |
+
target_link = None
|
| 97 |
+
match = re.search(r"https?://download[0-9]+\.mediafire\.com/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/[^\s'\"]+", r.text)
|
| 98 |
+
if match:
|
| 99 |
+
target_link = match.group(0).replace('"', '').replace("'", "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
if not target_link:
|
| 102 |
+
soup = BeautifulSoup(r.text, 'html.parser')
|
| 103 |
+
btn = soup.find('a', {'id': 'downloadButton'})
|
| 104 |
+
if btn: target_link = btn.get('href')
|
| 105 |
+
|
| 106 |
+
if target_link:
|
| 107 |
+
if target_link.startswith("//"): target_link = f"https:{target_link}"
|
| 108 |
+
elif target_link.startswith("/"): target_link = f"https://www.mediafire.com{target_link}"
|
| 109 |
+
|
| 110 |
+
if not target_link:
|
| 111 |
+
raise HTTPException(status_code=404, detail="Direct link extraction failed")
|
| 112 |
+
|
| 113 |
+
return await stream_file(target_link, range_header, filename, referer=clean_url)
|
| 114 |
+
except Exception as e:
|
| 115 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 116 |
|
| 117 |
# --- Google Drive ---
|
| 118 |
+
elif "drive.google.com" in clean_url:
|
| 119 |
+
file_id = get_google_file_id(clean_url)
|
| 120 |
+
if not file_id:
|
| 121 |
+
raise HTTPException(status_code=400, detail="Invalid Google Drive Link")
|
| 122 |
+
|
| 123 |
+
accounts = get_all_service_accounts()
|
| 124 |
+
random.shuffle(accounts)
|
| 125 |
+
|
| 126 |
+
for account in accounts:
|
| 127 |
+
token = await get_token_for_account(account)
|
| 128 |
+
if not token: continue
|
| 129 |
+
api_link = f"https://www.googleapis.com/drive/v3/files/{file_id}?alt=media"
|
| 130 |
+
headers = {"Authorization": f"Bearer {token}"}
|
| 131 |
+
if range_header: headers['Range'] = range_header
|
| 132 |
+
try:
|
| 133 |
+
req = client.build_request("GET", api_link, headers=headers)
|
| 134 |
+
r = await client.send(req, stream=True)
|
| 135 |
+
if r.status_code in [200, 206]:
|
| 136 |
+
# Google API က Content-Type အမှန်ပြန်ပေးလေ့ရှိသည်
|
| 137 |
+
return await process_response(r, filename)
|
| 138 |
+
await r.aclose()
|
| 139 |
+
except: continue
|
| 140 |
|
| 141 |
+
public_url = f"https://drive.google.com/uc?export=download&id={file_id}"
|
| 142 |
+
return await stream_file(public_url, range_header, filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
+
else:
|
| 145 |
+
return await stream_file(clean_url, range_header, filename)
|
|
|
|
| 146 |
|
| 147 |
+
async def stream_file(target_url, range_header, filename, referer=None):
|
| 148 |
headers = {'User-Agent': ua.random}
|
| 149 |
if range_header: headers['Range'] = range_header
|
| 150 |
+
if referer: headers['Referer'] = referer
|
| 151 |
|
| 152 |
try:
|
| 153 |
req = client.build_request("GET", target_url, headers=headers)
|
| 154 |
r = await client.send(req, stream=True)
|
| 155 |
+
|
| 156 |
+
# အကယ်၍ HTML ပြန်လာပါက ဗီဒီယိုမဟုတ်ဟု ယူဆပြီး Error ပြရန်
|
| 157 |
+
content_type = r.headers.get('content-type', '').lower()
|
| 158 |
+
if 'text/html' in content_type:
|
| 159 |
+
await r.aclose()
|
| 160 |
+
raise HTTPException(status_code=415, detail="Invalid Media: Received HTML instead of Video")
|
| 161 |
+
|
| 162 |
+
return await process_response(r, filename)
|
| 163 |
except Exception as e:
|
|
|
|
| 164 |
raise HTTPException(status_code=500, detail=str(e))
|
| 165 |
|
| 166 |
+
async def process_response(r, filename):
|
| 167 |
+
mime_type = get_mime_from_filename(filename)
|
| 168 |
+
|
| 169 |
+
# Player အတွက် လိုအပ်သော Header များကို သန့်စင်ခြင်း
|
| 170 |
+
safe_headers = ['content-length', 'content-range', 'accept-ranges']
|
| 171 |
+
response_headers = {n: v for n, v in r.headers.items() if n.lower() in safe_headers}
|
| 172 |
|
| 173 |
+
# အရေးကြီးသော Header များကို အတင်းအကျပ်သတ်မှတ်ခြင်း
|
| 174 |
+
response_headers['Content-Type'] = mime_type
|
| 175 |
response_headers['Accept-Ranges'] = 'bytes'
|
| 176 |
+
|
| 177 |
+
# nPlayer အတွက် filename header
|
| 178 |
+
quoted_filename = urllib.parse.quote(filename)
|
| 179 |
+
response_headers['Content-Disposition'] = f'inline; filename="{quoted_filename}"'
|
|
|
|
|
|
|
| 180 |
|
| 181 |
async def stream_generator():
|
| 182 |
try:
|
| 183 |
+
async for chunk in r.aiter_bytes(chunk_size=262144):
|
| 184 |
yield chunk
|
| 185 |
finally:
|
| 186 |
await r.aclose()
|
|
|
|
| 189 |
stream_generator(),
|
| 190 |
status_code=r.status_code,
|
| 191 |
headers=response_headers,
|
| 192 |
+
media_type=mime_type
|
| 193 |
)
|
| 194 |
|
| 195 |
if __name__ == "__main__":
|