Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
|
@@ -8,7 +8,7 @@ from fastapi import FastAPI, HTTPException, Request
|
|
| 8 |
from fastapi.responses import StreamingResponse
|
| 9 |
import uvicorn
|
| 10 |
|
| 11 |
-
# Google Auth Libraries
|
| 12 |
from google.oauth2 import service_account
|
| 13 |
import google.auth.transport.requests
|
| 14 |
|
|
@@ -16,7 +16,6 @@ app = FastAPI()
|
|
| 16 |
|
| 17 |
# --- Configurations ---
|
| 18 |
ACCESS_KEY = os.getenv("ACCESS_KEY", "786969")
|
| 19 |
-
# Service Account ရဲ့ JSON ဖိုင်ထဲက စာသားအကုန်လုံးကို Copy ကူးပြီး Secret ထဲမှာ ထည့်ရပါမည်
|
| 20 |
SERVICE_ACCOUNT_JSON_STR = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
|
| 21 |
|
| 22 |
@app.get("/")
|
|
@@ -24,97 +23,98 @@ def index():
|
|
| 24 |
return {"message": "Proxy is Online!", "usage": "/download?url=[LINK]&key=[YOUR_KEY]"}
|
| 25 |
|
| 26 |
def get_google_access_token():
|
| 27 |
-
"""Service Account JSON ကို အသုံးပြု၍ Access Token ရယူခြင်း"""
|
| 28 |
if not SERVICE_ACCOUNT_JSON_STR:
|
| 29 |
-
print("Missing GOOGLE_SERVICE_ACCOUNT_JSON credential!")
|
| 30 |
return None
|
| 31 |
-
|
| 32 |
try:
|
| 33 |
-
# Secret ထဲမှ JSON string ကို Dictionary အဖြစ် ပြောင်းလဲခြင်း
|
| 34 |
creds_dict = json.loads(SERVICE_ACCOUNT_JSON_STR)
|
| 35 |
-
|
| 36 |
-
# Scopes သတ်မှတ်ခြင်း (Drive ကို ဖတ်ရန်)
|
| 37 |
scopes = ['https://www.googleapis.com/auth/drive.readonly']
|
| 38 |
-
|
| 39 |
-
# Service Account Credentials တည်ဆောက်ခြင်း
|
| 40 |
-
creds = service_account.Credentials.from_service_account_info(
|
| 41 |
-
creds_dict,
|
| 42 |
-
scopes=scopes
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
# Token အသစ်တောင်းခံခြင်း
|
| 46 |
auth_req = google.auth.transport.requests.Request()
|
| 47 |
creds.refresh(auth_req)
|
| 48 |
-
|
| 49 |
return creds.token
|
| 50 |
except Exception as e:
|
| 51 |
print(f"Service Account Auth Error: {e}")
|
| 52 |
return None
|
| 53 |
|
| 54 |
def get_direct_url(url):
|
|
|
|
| 55 |
if "drive.google.com" in url:
|
| 56 |
fid = re.search(r'/(?:d|file/d|open\?id=)/([a-zA-Z0-9_-]+)', url)
|
| 57 |
if not fid:
|
| 58 |
-
return None, None
|
| 59 |
file_id = fid.group(1)
|
| 60 |
|
| 61 |
access_token = get_google_access_token()
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
return None, None
|
| 67 |
|
| 68 |
elif "mediafire.com" in url:
|
| 69 |
try:
|
| 70 |
r = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=10)
|
| 71 |
soup = BeautifulSoup(r.text, 'html.parser')
|
| 72 |
btn = soup.find('a', {'id': 'downloadButton'})
|
| 73 |
-
return btn.get('href')
|
| 74 |
-
except:
|
| 75 |
-
return None, None
|
| 76 |
|
| 77 |
elif "dropbox.com" in url:
|
| 78 |
-
return url.replace("?dl=0", "").split("?")[0] + "?dl=1", None
|
| 79 |
|
| 80 |
elif "1drv.ms" in url or "onedrive.live.com" in url:
|
| 81 |
encoded_url = base64.b64encode(bytes(url, 'utf-8')).decode('utf-8').replace('=', '').replace('/', '_').replace('+', '-')
|
| 82 |
-
return f"https://api.onedrive.com/v1.0/shares/u!{encoded_url}/root/content", None
|
| 83 |
|
| 84 |
-
return None, None
|
| 85 |
|
| 86 |
@app.get("/download")
|
| 87 |
async def download_proxy(request: Request, url: str, key: str = None):
|
| 88 |
-
# Proxy Password စစ်ဆေးခြင်း
|
| 89 |
if key != ACCESS_KEY:
|
| 90 |
raise HTTPException(status_code=403, detail="Access Denied")
|
| 91 |
|
| 92 |
-
target_link, token = get_direct_url(url)
|
| 93 |
if not target_link:
|
| 94 |
-
raise HTTPException(status_code=400, detail="Invalid Link
|
| 95 |
|
| 96 |
-
# Header ပြင်ဆင်ခြင်း
|
| 97 |
headers = {}
|
| 98 |
range_header = request.headers.get('range')
|
| 99 |
if range_header:
|
| 100 |
headers['Range'] = range_header
|
| 101 |
|
| 102 |
-
# Token ရှိပါက Bearer Token ထည့်ပေးခြင်း
|
| 103 |
if token:
|
| 104 |
headers['Authorization'] = f"Bearer {token}"
|
| 105 |
|
| 106 |
session = requests.Session()
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
-
# Header
|
| 118 |
excluded = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
|
| 119 |
response_headers = {n: v for n, v in r.headers.items() if n.lower() not in excluded}
|
| 120 |
response_headers['Accept-Ranges'] = 'bytes'
|
|
|
|
| 8 |
from fastapi.responses import StreamingResponse
|
| 9 |
import uvicorn
|
| 10 |
|
| 11 |
+
# Google Auth Libraries
|
| 12 |
from google.oauth2 import service_account
|
| 13 |
import google.auth.transport.requests
|
| 14 |
|
|
|
|
| 16 |
|
| 17 |
# --- Configurations ---
|
| 18 |
ACCESS_KEY = os.getenv("ACCESS_KEY", "786969")
|
|
|
|
| 19 |
SERVICE_ACCOUNT_JSON_STR = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
|
| 20 |
|
| 21 |
@app.get("/")
|
|
|
|
| 23 |
return {"message": "Proxy is Online!", "usage": "/download?url=[LINK]&key=[YOUR_KEY]"}
|
| 24 |
|
| 25 |
def get_google_access_token():
|
|
|
|
| 26 |
if not SERVICE_ACCOUNT_JSON_STR:
|
|
|
|
| 27 |
return None
|
|
|
|
| 28 |
try:
|
|
|
|
| 29 |
creds_dict = json.loads(SERVICE_ACCOUNT_JSON_STR)
|
|
|
|
|
|
|
| 30 |
scopes = ['https://www.googleapis.com/auth/drive.readonly']
|
| 31 |
+
creds = service_account.Credentials.from_service_account_info(creds_dict, scopes=scopes)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
auth_req = google.auth.transport.requests.Request()
|
| 33 |
creds.refresh(auth_req)
|
|
|
|
| 34 |
return creds.token
|
| 35 |
except Exception as e:
|
| 36 |
print(f"Service Account Auth Error: {e}")
|
| 37 |
return None
|
| 38 |
|
| 39 |
def get_direct_url(url):
|
| 40 |
+
"""Link အမျိုးအစားအလိုက် URL၊ Token နှင့် File ID တို့ကို ပြန်ပေးရန်"""
|
| 41 |
if "drive.google.com" in url:
|
| 42 |
fid = re.search(r'/(?:d|file/d|open\?id=)/([a-zA-Z0-9_-]+)', url)
|
| 43 |
if not fid:
|
| 44 |
+
return None, None, None
|
| 45 |
file_id = fid.group(1)
|
| 46 |
|
| 47 |
access_token = get_google_access_token()
|
| 48 |
+
# ပထမဦးစွာ Service Account Link ကို ပြန်ပေးမည်
|
| 49 |
+
target = f"https://www.googleapis.com/drive/v3/files/{file_id}?alt=media"
|
| 50 |
+
return target, access_token, file_id
|
|
|
|
|
|
|
| 51 |
|
| 52 |
elif "mediafire.com" in url:
|
| 53 |
try:
|
| 54 |
r = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=10)
|
| 55 |
soup = BeautifulSoup(r.text, 'html.parser')
|
| 56 |
btn = soup.find('a', {'id': 'downloadButton'})
|
| 57 |
+
return btn.get('href'), None, None
|
| 58 |
+
except: return None, None, None
|
|
|
|
| 59 |
|
| 60 |
elif "dropbox.com" in url:
|
| 61 |
+
return url.replace("?dl=0", "").split("?")[0] + "?dl=1", None, None
|
| 62 |
|
| 63 |
elif "1drv.ms" in url or "onedrive.live.com" in url:
|
| 64 |
encoded_url = base64.b64encode(bytes(url, 'utf-8')).decode('utf-8').replace('=', '').replace('/', '_').replace('+', '-')
|
| 65 |
+
return f"https://api.onedrive.com/v1.0/shares/u!{encoded_url}/root/content", None, None
|
| 66 |
|
| 67 |
+
return None, None, None
|
| 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 |
+
target_link, token, file_id = get_direct_url(url)
|
| 75 |
if not target_link:
|
| 76 |
+
raise HTTPException(status_code=400, detail="Invalid Link")
|
| 77 |
|
|
|
|
| 78 |
headers = {}
|
| 79 |
range_header = request.headers.get('range')
|
| 80 |
if range_header:
|
| 81 |
headers['Range'] = range_header
|
| 82 |
|
|
|
|
| 83 |
if token:
|
| 84 |
headers['Authorization'] = f"Bearer {token}"
|
| 85 |
|
| 86 |
session = requests.Session()
|
| 87 |
+
|
| 88 |
+
# ၁။ Service Account ဖြင့် အရင်ကြိုးစားကြည့်မည်
|
| 89 |
+
r = session.get(target_link, headers=headers, stream=True, allow_redirects=True)
|
| 90 |
+
|
| 91 |
+
# ၂။ အကယ်၍ 404 တက်ခဲ့လျှင် (Public File ဖြစ်နိုင်သဖြင့်) Fallback လုပ်မည်
|
| 92 |
+
if r.status_code == 404 and "drive.google.com" in url and file_id:
|
| 93 |
+
print(f"SA 404. Trying Public Fallback for: {file_id}")
|
| 94 |
|
| 95 |
+
# Public Link သုံးမည်ဖြစ်၍ Authorization ကို ဖယ်ထုတ်ရပါမည်
|
| 96 |
+
public_headers = {k: v for k, v in headers.items() if k.lower() != 'authorization'}
|
| 97 |
+
public_url = f"https://drive.google.com/uc?export=download&id={file_id}"
|
| 98 |
+
|
| 99 |
+
# Public Link ကို စမ်းခေါ်ခြင်း
|
| 100 |
+
r = session.get(public_url, headers=public_headers, stream=True, allow_redirects=True)
|
| 101 |
+
|
| 102 |
+
# GDrive 100MB+ Virus Scan Confirm ကျော်ရန် Logic
|
| 103 |
+
if "text/html" in r.headers.get('Content-Type', '').lower():
|
| 104 |
+
confirm_token = None
|
| 105 |
+
for k, v in session.cookies.items():
|
| 106 |
+
if k.startswith("download_warning"):
|
| 107 |
+
confirm_token = v
|
| 108 |
+
break
|
| 109 |
+
|
| 110 |
+
if confirm_token:
|
| 111 |
+
r = session.get(f"{public_url}&confirm={confirm_token}", headers=public_headers, stream=True)
|
| 112 |
+
|
| 113 |
+
# Error ဆက်ရှိနေသေးပါက
|
| 114 |
+
if r.status_code >= 400:
|
| 115 |
+
raise HTTPException(status_code=r.status_code, detail=f"Failed to fetch file: {r.status_code}")
|
| 116 |
|
| 117 |
+
# Header ပြန်ပို့ရန် ပြင်ဆင်ခြင်း
|
| 118 |
excluded = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
|
| 119 |
response_headers = {n: v for n, v in r.headers.items() if n.lower() not in excluded}
|
| 120 |
response_headers['Accept-Ranges'] = 'bytes'
|