Update app.py
Browse files
app.py
CHANGED
|
@@ -11,6 +11,7 @@ import tempfile
|
|
| 11 |
import os
|
| 12 |
import uuid
|
| 13 |
import gc # Import the garbage collector module
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
app = FastAPI()
|
|
@@ -109,6 +110,44 @@ async def fetch_data_for_url(request: Request):
|
|
| 109 |
# Mount StaticFiles to serve files from the global download directory
|
| 110 |
app.mount("/file", StaticFiles(directory=global_download_dir), name="downloads")
|
| 111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
# Middleware to set the correct MIME type
|
| 113 |
@app.middleware("http")
|
| 114 |
async def set_mime_type_middleware(request: Request, call_next):
|
|
|
|
| 11 |
import os
|
| 12 |
import uuid
|
| 13 |
import gc # Import the garbage collector module
|
| 14 |
+
import json
|
| 15 |
|
| 16 |
|
| 17 |
app = FastAPI()
|
|
|
|
| 110 |
# Mount StaticFiles to serve files from the global download directory
|
| 111 |
app.mount("/file", StaticFiles(directory=global_download_dir), name="downloads")
|
| 112 |
|
| 113 |
+
|
| 114 |
+
@app.get("/yt-audio")
|
| 115 |
+
async def yt_audio(url: str):
|
| 116 |
+
try:
|
| 117 |
+
# 设置请求头
|
| 118 |
+
headers = {
|
| 119 |
+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15"
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
# 发送请求
|
| 123 |
+
response = requests.get(url, headers=headers)
|
| 124 |
+
response.raise_for_status()
|
| 125 |
+
|
| 126 |
+
# 定义正则表达式模式
|
| 127 |
+
pattern = r'var ytInitialPlayerResponse = (\{.*?(?=.*?streamingData)(?=.*?videoDetails).*?\}\}\}\});'
|
| 128 |
+
|
| 129 |
+
# 查找匹配项
|
| 130 |
+
match = re.search(pattern, response.text)
|
| 131 |
+
|
| 132 |
+
if match:
|
| 133 |
+
# 提取匹配到的JSON数据
|
| 134 |
+
json_str = match.group(1)
|
| 135 |
+
|
| 136 |
+
# 去除末尾的分号
|
| 137 |
+
json_str = json_str.rstrip(';')
|
| 138 |
+
|
| 139 |
+
# 将JSON字符串转换为Python字典
|
| 140 |
+
data = json.loads(json_str)
|
| 141 |
+
|
| 142 |
+
return data
|
| 143 |
+
else:
|
| 144 |
+
return {"error": "No matching data found in the HTML response."}
|
| 145 |
+
|
| 146 |
+
except requests.RequestException as e:
|
| 147 |
+
return {"error": f"Request error: {str(e)}"}
|
| 148 |
+
except json.JSONDecodeError as e:
|
| 149 |
+
return {"error": f"JSON decoding error: {str(e)}"}
|
| 150 |
+
|
| 151 |
# Middleware to set the correct MIME type
|
| 152 |
@app.middleware("http")
|
| 153 |
async def set_mime_type_middleware(request: Request, call_next):
|