tecuts commited on
Commit
b7c7178
·
verified ·
1 Parent(s): 35bc3c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -20
app.py CHANGED
@@ -111,40 +111,44 @@ async def fetch_data_for_url(request: Request):
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
  "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
121
  "Referer": "https://www.youtube.com/"
122
  }
123
 
 
 
124
  # 发送请求
125
- response = requests.get(url, headers=headers)
 
 
 
 
 
126
  response.raise_for_status()
127
 
128
- # 定义正则表达式模式
129
- pattern = r'var ytInitialPlayerResponse = (\{.*?(?=.*?streamingData)(?=.*?videoDetails).*?\}\}\}\});'
130
-
131
- # 查找匹配项
132
- match = re.search(pattern, response.text)
133
- logging.info(response.text)
134
-
135
- if match:
136
- # 提取匹配到的JSON数据
137
- json_str = match.group(1)
138
-
139
- # 去除末尾的分号
140
- json_str = json_str.rstrip(';')
141
-
142
- # 将JSON字符串转换为Python字典
143
- data = json.loads(json_str)
144
 
145
- return data
146
- else:
147
- return {"error": "No matching data found in the HTML response."}
148
 
149
  except requests.RequestException as e:
150
  return {"error": f"Request error: {str(e)}"}
 
111
  app.mount("/file", StaticFiles(directory=global_download_dir), name="downloads")
112
 
113
 
114
+ def extract_video_id(url):
115
+ # 定义正则表达式模式
116
+ pattern = r'(?:(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([a-zA-Z0-9_-]{11}))'
117
+
118
+ # 进行匹配
119
+ match = re.search(pattern, url)
120
+
121
+ if match:
122
+ return match.group(1)
123
+ else:
124
+ return None
125
+
126
+
127
  @app.get("/yt-audio")
128
  async def yt_audio(url: str):
129
  try:
130
  # 设置请求头
131
+ videoId = extract_video_id(url)
132
  headers = {
133
  "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",
134
  "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
135
  "Referer": "https://www.youtube.com/"
136
  }
137
 
138
+ body = f'{'context':{'client':{'clientName':'IOS','clientVersion':'19.14.3','deviceModel':'iPhone15,4'}},'videoId':{videoId}}'
139
+
140
  # 发送请求
141
+ response = requests.post(
142
+ url,
143
+ timeout=20,
144
+ json=body_json,
145
+ headers=headers
146
+ )
147
  response.raise_for_status()
148
 
149
+ logging.info(response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
+ return response
 
 
152
 
153
  except requests.RequestException as e:
154
  return {"error": f"Request error: {str(e)}"}