MyanmarSwe commited on
Commit
473f30c
Β·
verified Β·
1 Parent(s): 5d42358

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +37 -67
main.py CHANGED
@@ -19,8 +19,6 @@ app = FastAPI()
19
  # --- Configurations ---
20
  ACCESS_KEY = os.getenv("ACCESS_KEY", "0000")
21
  SERVICE_ACCOUNT_JSON_STR = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
22
-
23
- # User-Agent Generator with fallback
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
  @app.get("/")
@@ -28,25 +26,18 @@ def index():
28
  return {"message": "Proxy is Online!", "usage": "/download?url=[LINK]&key=[YOUR_KEY]"}
29
 
30
  def get_all_service_accounts():
31
- if not SERVICE_ACCOUNT_JSON_STR:
32
- return []
33
  try:
34
  data = json.loads(SERVICE_ACCOUNT_JSON_STR)
35
  return data if isinstance(data, list) else [data]
36
- except Exception as e:
37
- print(f"JSON Parsing Error: {e}")
38
- return []
39
 
40
  def get_token_for_account(cred_dict):
41
  try:
42
- scopes = ['https://www.googleapis.com/auth/drive.readonly']
43
- creds = service_account.Credentials.from_service_account_info(cred_dict, scopes=scopes)
44
- auth_req = google.auth.transport.requests.Request()
45
- creds.refresh(auth_req)
46
  return creds.token
47
- except Exception as e:
48
- print(f"Auth Error for {cred_dict.get('client_email')}: {e}")
49
- return None
50
 
51
  def get_google_file_id(url):
52
  fid = re.search(r'/(?:d|file/d|open\?id=)/([a-zA-Z0-9_-]+)', url)
@@ -57,98 +48,77 @@ def download_proxy(request: Request, url: str, key: str = None):
57
  if key != ACCESS_KEY:
58
  raise HTTPException(status_code=403, detail="Access Denied")
59
 
 
 
60
  if "drive.google.com" not in url:
61
  target_link = None
62
- current_headers = {'User-Agent': ua.random, 'Accept-Language': 'en-US,en;q=0.9'}
63
 
64
  if "mediafire.com" in url:
65
  try:
66
- current_headers['Referer'] = 'https://www.mediafire.com/'
67
- r = requests.get(url, headers=current_headers, timeout=15)
68
  soup = BeautifulSoup(r.text, 'html.parser')
69
  btn = soup.find('a', {'id': 'downloadButton'})
70
  target_link = btn.get('href') if btn else None
71
- except Exception as e:
72
- print(f"MediaFire Error: {e}")
73
-
74
  elif "dropbox.com" in url:
75
  target_link = url.replace("?dl=0", "").split("?")[0] + "?dl=1"
76
-
77
  elif "1drv.ms" in url or "onedrive.live.com" in url:
78
  encoded_url = base64.b64encode(bytes(url, 'utf-8')).decode('utf-8').replace('=', '').replace('/', '_').replace('+', '-')
79
  target_link = f"https://api.onedrive.com/v1.0/shares/u!{encoded_url}/root/content"
80
 
81
- if not target_link:
82
- raise HTTPException(status_code=400, detail="Could not resolve direct link")
83
-
84
- return stream_file(target_link, request.headers.get('range'))
85
 
 
86
  file_id = get_google_file_id(url)
87
- if not file_id:
88
- raise HTTPException(status_code=400, detail="Invalid Google Drive Link")
89
-
90
  accounts = get_all_service_accounts()
91
  random.shuffle(accounts)
92
 
93
  for account in accounts:
94
  token = get_token_for_account(account)
95
  if not token: continue
96
-
97
  api_link = f"https://www.googleapis.com/drive/v3/files/{file_id}?alt=media"
98
  headers = {"Authorization": f"Bearer {token}"}
99
- if request.headers.get('range'):
100
- headers['Range'] = request.headers.get('range')
101
-
102
- try:
103
- r = requests.get(api_link, headers=headers, stream=True, allow_redirects=True, timeout=15)
104
- if r.status_code in [200, 206]:
105
- return process_response(r)
106
- except Exception as e:
107
- print(f"Account Request Error: {e}")
108
 
109
  # Public Fallback
110
- try:
111
- public_url = f"https://drive.google.com/uc?export=download&id={file_id}"
112
- headers = {'User-Agent': ua.random}
113
- if request.headers.get('range'):
114
- headers['Range'] = request.headers.get('range')
115
- r = requests.get(public_url, headers=headers, stream=True, allow_redirects=True, timeout=15)
116
- return process_response(r)
117
- except:
118
- raise HTTPException(status_code=500, detail="Download failed.")
119
 
120
  def stream_file(target_url, range_header):
121
  headers = {'User-Agent': ua.random}
122
- if range_header:
123
- headers['Range'] = range_header
124
- try:
125
- r = requests.get(target_url, headers=headers, stream=True, allow_redirects=True, timeout=15)
126
- return process_response(r)
127
- except Exception as e:
128
- raise HTTPException(status_code=500, detail=str(e))
129
 
130
  def process_response(r):
131
- excluded = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
132
- response_headers = {n: v for n, v in r.headers.items() if n.lower() not in excluded}
133
- response_headers['Accept-Ranges'] = 'bytes'
134
- if 'Content-Length' in r.headers:
135
- response_headers['Content-Length'] = r.headers['Content-Length']
136
- if 'Content-Range' in r.headers:
137
- response_headers['Content-Range'] = r.headers['Content-Range']
138
 
139
  def iterfile():
140
  try:
141
- # Chunk size α€€α€­α€― 5MB α€α€­α€―α€Έα€™α€Όα€Ύα€„α€·α€Ία€‘α€¬α€Έα€•α€«α€α€šα€Ί (Speed ပိုကောင်းစေရန်)
142
- for chunk in r.iter_content(chunk_size=10*1024*1024):
143
  if chunk: yield chunk
144
  finally:
145
  r.close()
146
 
147
  return StreamingResponse(
148
- iterfile(),
149
- status_code=r.status_code,
150
- headers=response_headers,
151
- media_type=r.headers.get('Content-Type', 'application/octet-stream')
152
  )
153
 
154
  if __name__ == "__main__":
 
19
  # --- Configurations ---
20
  ACCESS_KEY = os.getenv("ACCESS_KEY", "0000")
21
  SERVICE_ACCOUNT_JSON_STR = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
 
 
22
  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')
23
 
24
  @app.get("/")
 
26
  return {"message": "Proxy is Online!", "usage": "/download?url=[LINK]&key=[YOUR_KEY]"}
27
 
28
  def get_all_service_accounts():
29
+ if not SERVICE_ACCOUNT_JSON_STR: return []
 
30
  try:
31
  data = json.loads(SERVICE_ACCOUNT_JSON_STR)
32
  return data if isinstance(data, list) else [data]
33
+ except: return []
 
 
34
 
35
  def get_token_for_account(cred_dict):
36
  try:
37
+ creds = service_account.Credentials.from_service_account_info(cred_dict, scopes=['https://www.googleapis.com/auth/drive.readonly'])
38
+ creds.refresh(google.auth.transport.requests.Request())
 
 
39
  return creds.token
40
+ except: return None
 
 
41
 
42
  def get_google_file_id(url):
43
  fid = re.search(r'/(?:d|file/d|open\?id=)/([a-zA-Z0-9_-]+)', url)
 
48
  if key != ACCESS_KEY:
49
  raise HTTPException(status_code=403, detail="Access Denied")
50
 
51
+ range_header = request.headers.get('range')
52
+
53
  if "drive.google.com" not in url:
54
  target_link = None
55
+ headers = {'User-Agent': ua.random}
56
 
57
  if "mediafire.com" in url:
58
  try:
59
+ r = requests.get(url, headers=headers, timeout=15)
 
60
  soup = BeautifulSoup(r.text, 'html.parser')
61
  btn = soup.find('a', {'id': 'downloadButton'})
62
  target_link = btn.get('href') if btn else None
63
+ except: pass
 
 
64
  elif "dropbox.com" in url:
65
  target_link = url.replace("?dl=0", "").split("?")[0] + "?dl=1"
 
66
  elif "1drv.ms" in url or "onedrive.live.com" in url:
67
  encoded_url = base64.b64encode(bytes(url, 'utf-8')).decode('utf-8').replace('=', '').replace('/', '_').replace('+', '-')
68
  target_link = f"https://api.onedrive.com/v1.0/shares/u!{encoded_url}/root/content"
69
 
70
+ if not target_link: raise HTTPException(status_code=400, detail="Link resolution failed")
71
+ return stream_file(target_link, range_header)
 
 
72
 
73
+ # Google Drive Logic
74
  file_id = get_google_file_id(url)
 
 
 
75
  accounts = get_all_service_accounts()
76
  random.shuffle(accounts)
77
 
78
  for account in accounts:
79
  token = get_token_for_account(account)
80
  if not token: continue
 
81
  api_link = f"https://www.googleapis.com/drive/v3/files/{file_id}?alt=media"
82
  headers = {"Authorization": f"Bearer {token}"}
83
+ if range_header: headers['Range'] = range_header
84
+
85
+ r = requests.get(api_link, headers=headers, stream=True, timeout=15)
86
+ if r.status_code in [200, 206]: return process_response(r)
 
 
 
 
 
87
 
88
  # Public Fallback
89
+ public_url = f"https://drive.google.com/uc?export=download&id={file_id}"
90
+ h = {'User-Agent': ua.random}
91
+ if range_header: h['Range'] = range_header
92
+ r = requests.get(public_url, headers=h, stream=True, timeout=15)
93
+ return process_response(r)
 
 
 
 
94
 
95
  def stream_file(target_url, range_header):
96
  headers = {'User-Agent': ua.random}
97
+ if range_header: headers['Range'] = range_header
98
+ r = requests.get(target_url, headers=headers, stream=True, allow_redirects=True, timeout=20)
99
+ return process_response(r)
 
 
 
 
100
 
101
  def process_response(r):
102
+ # Video α€€α€»α€±α€¬α€Ία€€α€Όα€Šα€·α€Ία€œα€­α€―α€·α€›α€‘α€±α€¬α€„α€Ί Header များကို α€žα€±α€α€»α€¬α€•α€Όα€”α€Ία€•α€±α€Έα€α€Όα€„α€Ία€Έ
103
+ excluded = ['content-encoding', 'transfer-encoding', 'connection']
104
+ headers = {n: v for n, v in r.headers.items() if n.lower() not in excluded}
105
+
106
+ # Video Seek ထတွက် α€™α€›α€Ύα€­α€™α€–α€Όα€…α€Ία€œα€­α€―α€‘α€•α€Ία€žα€±α€¬ Header
107
+ headers['Accept-Ranges'] = 'bytes'
 
108
 
109
  def iterfile():
110
  try:
111
+ # Video streaming ထတွက် 1MB α€žα€Šα€Ί α€‘α€€α€±α€¬α€„α€Ία€Έα€†α€―α€Άα€Έα€–α€Όα€…α€Ία€žα€Šα€Ί (α€€α€»α€±α€¬α€Ία€€α€Όα€Šα€·α€Ία€œα€»α€Ύα€„α€Ί α€•α€­α€―α€™α€Όα€”α€Ία€žα€Šα€Ί)
112
+ for chunk in r.iter_content(chunk_size=1024*1024):
113
  if chunk: yield chunk
114
  finally:
115
  r.close()
116
 
117
  return StreamingResponse(
118
+ iterfile(),
119
+ status_code=r.status_code,
120
+ headers=headers,
121
+ media_type=r.headers.get('Content-Type', 'video/mp4')
122
  )
123
 
124
  if __name__ == "__main__":