MyanmarSwe commited on
Commit
a5a0c5c
·
verified ·
1 Parent(s): 50e694b

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +32 -26
main.py CHANGED
@@ -9,7 +9,7 @@ import urllib.parse
9
  import mimetypes
10
  from bs4 import BeautifulSoup
11
  from fastapi import FastAPI, HTTPException, Request
12
- from fastapi.responses import StreamingResponse, RedirectResponse
13
  from fake_useragent import UserAgent
14
  import uvicorn
15
 
@@ -26,8 +26,9 @@ ua = UserAgent(fallback='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/5
26
 
27
  # MediaFire Cache
28
  MEDIAFIRE_CACHE = {}
29
- CACHE_TTL = 3600
30
 
 
31
  client = httpx.AsyncClient(
32
  timeout=httpx.Timeout(60.0, read=None),
33
  follow_redirects=True,
@@ -62,9 +63,7 @@ def get_google_file_id(url):
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
- return "video.mp4"
67
- return name
68
 
69
  @app.get("/download")
70
  async def download_proxy(request: Request, url: str, key: str = None):
@@ -76,7 +75,7 @@ async def download_proxy(request: Request, url: str, key: str = None):
76
  range_header = request.headers.get('range')
77
  current_time = time.time()
78
 
79
- # --- MediaFire Section (Redirect with Path Trick) ---
80
  if "mediafire.com" in clean_url:
81
  target_link = None
82
  cached = MEDIAFIRE_CACHE.get(clean_url)
@@ -86,37 +85,31 @@ async def download_proxy(request: Request, url: str, key: str = None):
86
 
87
  if not target_link:
88
  try:
89
- # Scrape Direct Link
90
- async with httpx.AsyncClient(headers={'User-Agent': ua.random}, follow_redirects=True) as temp_client:
 
 
 
 
 
 
 
91
  r = await temp_client.get(clean_url)
92
  if r.status_code == 200:
93
  match = re.search(r"https?://download[0-9]+\.mediafire\.com/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/[^\s'\"]+", r.text)
94
  if match:
95
  target_link = match.group(0).replace('"', '').replace("'", "")
96
- else:
97
- soup = BeautifulSoup(r.text, 'html.parser')
98
- btn = soup.find('a', {'id': 'downloadButton'}) or soup.find('a', {'class': 'input_btn_p'})
99
- if btn: target_link = btn.get('href')
100
-
101
  if target_link:
102
- if target_link.startswith("//"): target_link = f"https:{target_link}"
103
  MEDIAFIRE_CACHE[clean_url] = {'link': target_link, 'time': current_time}
104
  except: pass
105
 
106
  if target_link:
107
- # Player က Video လို့သိအောင် Link ကို ပုံစံပြောင်းပြီး Redirect လုပ်ခြင်း
108
- # MediaFire link ထဲမှာ filename ကို Path အနေနဲ့ ကပ်ပေးလိုက်တာပါ (ဒါကို Player က ပိုကြိုက်ပါတယ်)
109
- if "?" in target_link:
110
- redirect_url = f"{target_link}&file={urllib.parse.quote(filename)}"
111
- else:
112
- # Link ရဲ့ အဆုံးမှာ /filename.mp4 ကပ်ပေးခြင်း (MediaFire server က ဒါကို ignore လုပ်လေ့ရှိပါတယ်)
113
- redirect_url = f"{target_link}/{urllib.parse.quote(filename)}"
114
-
115
- return RedirectResponse(url=redirect_url)
116
  else:
117
- raise HTTPException(status_code=404, detail="MediaFire direct link not found.")
118
 
119
- # --- Google Drive Section (Proxy as usual) ---
120
  elif "drive.google.com" in clean_url:
121
  file_id = get_google_file_id(clean_url)
122
  if not file_id: raise HTTPException(status_code=400, detail="Invalid GD Link")
@@ -144,13 +137,26 @@ async def download_proxy(request: Request, url: str, key: str = None):
144
  else:
145
  return await stream_file(clean_url, range_header, filename)
146
 
147
- async def stream_file(target_url, range_header, filename):
148
  headers = {'User-Agent': ua.random}
149
  if range_header: headers['Range'] = range_header
 
 
150
  try:
151
  req = client.build_request("GET", target_url, headers=headers)
152
  r = await client.send(req, stream=True)
 
 
 
 
 
 
 
 
 
 
153
  return await process_response(r, filename)
 
154
  except Exception as e:
155
  raise HTTPException(status_code=500, detail=str(e))
156
 
 
9
  import mimetypes
10
  from bs4 import BeautifulSoup
11
  from fastapi import FastAPI, HTTPException, Request
12
+ from fastapi.responses import StreamingResponse
13
  from fake_useragent import UserAgent
14
  import uvicorn
15
 
 
26
 
27
  # MediaFire Cache
28
  MEDIAFIRE_CACHE = {}
29
+ CACHE_TTL = 1800
30
 
31
+ # Persistent Client for connection pooling
32
  client = httpx.AsyncClient(
33
  timeout=httpx.Timeout(60.0, read=None),
34
  follow_redirects=True,
 
63
  def get_clean_filename(url):
64
  decoded_url = urllib.parse.unquote(url)
65
  name = decoded_url.split('/')[-1].split('?')[0]
66
+ return name if (name and '.' in name) else "video.mp4"
 
 
67
 
68
  @app.get("/download")
69
  async def download_proxy(request: Request, url: str, key: str = None):
 
75
  range_header = request.headers.get('range')
76
  current_time = time.time()
77
 
78
+ # --- MediaFire Section ---
79
  if "mediafire.com" in clean_url:
80
  target_link = None
81
  cached = MEDIAFIRE_CACHE.get(clean_url)
 
85
 
86
  if not target_link:
87
  try:
88
+ # Browser အစစ်လိုမျိုး Header တွေထည့်ပြီး Scrape လုပ်ခြင်း
89
+ headers = {
90
+ 'User-Agent': ua.random,
91
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
92
+ 'Accept-Language': 'en-US,en;q=0.5',
93
+ 'Connection': 'keep-alive',
94
+ 'Upgrade-Insecure-Requests': '1'
95
+ }
96
+ async with httpx.AsyncClient(headers=headers, follow_redirects=True) as temp_client:
97
  r = await temp_client.get(clean_url)
98
  if r.status_code == 200:
99
  match = re.search(r"https?://download[0-9]+\.mediafire\.com/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/[^\s'\"]+", r.text)
100
  if match:
101
  target_link = match.group(0).replace('"', '').replace("'", "")
102
+
 
 
 
 
103
  if target_link:
 
104
  MEDIAFIRE_CACHE[clean_url] = {'link': target_link, 'time': current_time}
105
  except: pass
106
 
107
  if target_link:
108
+ return await stream_file(target_link, range_header, filename, referer=clean_url)
 
 
 
 
 
 
 
 
109
  else:
110
+ raise HTTPException(status_code=404, detail="Could not find direct link")
111
 
112
+ # --- Google Drive Section ---
113
  elif "drive.google.com" in clean_url:
114
  file_id = get_google_file_id(clean_url)
115
  if not file_id: raise HTTPException(status_code=400, detail="Invalid GD Link")
 
137
  else:
138
  return await stream_file(clean_url, range_header, filename)
139
 
140
+ async def stream_file(target_url, range_header, filename, referer=None):
141
  headers = {'User-Agent': ua.random}
142
  if range_header: headers['Range'] = range_header
143
+ if referer: headers['Referer'] = referer # MediaFire အတွက် Referer ထည့်ပေးခြင်း
144
+
145
  try:
146
  req = client.build_request("GET", target_url, headers=headers)
147
  r = await client.send(req, stream=True)
148
+
149
+ # အကယ်၍ MediaFire က Block ပြီး HTML ပြန်ပို့ရင် Cache ကိုဖျက်ပြီး အသစ်ပြန်လုပ်ရန်
150
+ if "text/html" in r.headers.get("Content-Type", "").lower() and r.status_code == 200:
151
+ await r.aclose()
152
+ # Cache ရှင်းလင်းခြင်း
153
+ for key, val in list(MEDIAFIRE_CACHE.items()):
154
+ if val['link'] == target_url:
155
+ del MEDIAFIRE_CACHE[key]
156
+ raise HTTPException(status_code=415, detail="MediaFire detection triggered. Retrying...")
157
+
158
  return await process_response(r, filename)
159
+ except HTTPException: raise
160
  except Exception as e:
161
  raise HTTPException(status_code=500, detail=str(e))
162