-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
392 lines (323 loc) · 13.6 KB
/
api.py
File metadata and controls
392 lines (323 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
#!/usr/bin/env python3
"""
视频解析下载 API 服务 (FastAPI 版本)
支持抖音、哔哩哔哩、小红书、快手、好看视频等平台
"""
import os
import time
from typing import Optional
from contextlib import asynccontextmanager
import requests
from requests.adapters import HTTPAdapter
from requests.exceptions import RequestException, ChunkedEncodingError, ConnectionError
from urllib3.util.retry import Retry
from fastapi import FastAPI, Request, Header
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from configs.logging_config import logger
from configs.general_constants import (
DOMAIN_TO_NAME, MINI_PROGRAM_LEGAL_DOMAIN,
SAVE_VIDEO_PATH, DOMAIN, check_essential_dirs
)
from utils.web_fetcher import WebFetcher, UrlParser
from utils.vigenere_cipher import VigenereCipher
from src.downloader_factory import DownloaderFactory
# ==================== Pydantic 模型 ====================
class ParseRequest(BaseModel):
"""解析请求模型"""
text: str
class DownloadRequest(BaseModel):
"""下载请求模型"""
video_url: str
video_id: str
class APIResponse(BaseModel):
"""统一响应模型"""
retcode: int
retdesc: str
data: Optional[dict] = None
ranking: Optional[dict] = None
succ: bool
# ==================== 工具函数 ====================
def make_response(retcode: int, retdesc: str, data: dict = None,
ranking: dict = None, succ: bool = False) -> dict:
"""生成统一的响应格式"""
return {
'retcode': retcode,
'retdesc': retdesc,
'data': data,
'ranking': ranking,
'succ': succ
}
def validate_timestamp(request_timestamp: int) -> bool:
"""验证时间戳是否在合理的时间窗口内"""
current_timestamp = int(time.time() * 1000)
time_window = 5 * 60 * 1000 # 5分钟的时间窗口
return abs(current_timestamp - request_timestamp) <= time_window
def validate_request_headers(
x_timestamp: str,
x_gclt_text: str,
x_egct_text: str,
*args
) -> Optional[dict]:
"""
验证请求头和参数
Returns:
None 如果验证通过,否则返回错误响应字典
"""
# 检查是否有缺失的参数
missing_params = [param for param in args if not param]
if missing_params:
logger.error(f'Missing parameters in request')
return make_response(400, 'Missing parameters in request', None, None, False)
if not x_timestamp:
logger.error('Missing timestamp in request')
return make_response(400, 'Missing timestamp in request', None, None, False)
try:
if not validate_timestamp(int(x_timestamp)):
logger.error('Invalid timestamp')
return make_response(400, 'Invalid timestamp', None, None, False)
except ValueError:
logger.error('Invalid timestamp format')
return make_response(400, 'Invalid timestamp format', None, None, False)
if not VigenereCipher(x_timestamp).verify_decryption(x_egct_text, x_gclt_text):
logger.error('Decryption verification failed')
return make_response(400, 'Decryption verification failed', None, None, False)
return None
# ==================== 应用生命周期 ====================
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理"""
# 启动时执行
logger.info("Starting Video Parser API Service (FastAPI)...")
check_essential_dirs()
yield
# 关闭时执行
logger.info("Shutting down Video Parser API Service...")
# ==================== 创建 FastAPI 应用 ====================
app = FastAPI(
title="视频解析下载 API",
description="支持抖音、哔哩哔哩、小红书、快手、好看视频等平台的视频解析下载服务",
version="2.0.0",
lifespan=lifespan
)
# CORS 中间件
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 静态文件服务
static_dir = os.path.join(os.path.dirname(__file__), "static")
if not os.path.exists(static_dir):
os.makedirs(static_dir, exist_ok=True)
app.mount("/static", StaticFiles(directory=static_dir), name="static")
# ==================== API 路由 ====================
@app.get("/")
async def root():
"""根路由 - 健康检查"""
return {"status": "ok", "message": "Video Parser API is running (FastAPI)"}
@app.get("/health")
async def health_check():
"""健康检查接口"""
return {"status": "healthy", "timestamp": int(time.time() * 1000)}
@app.post("/api/parse")
async def parse_video(
body: ParseRequest,
x_timestamp: str = Header(default="", alias="X-Timestamp"),
x_gclt_text: str = Header(default="", alias="X-GCLT-Text"),
x_egct_text: str = Header(default="", alias="X-EGCT-Text"),
wx_open_id: str = Header(default="Guest", alias="WX-OPEN-ID"),
):
"""
解析视频链接
从分享链接中提取视频信息,包括标题、封面、视频直链等
"""
try:
text = body.text
# 验证请求
validation_error = validate_request_headers(x_timestamp, x_gclt_text, x_egct_text, text)
if validation_error:
return JSONResponse(status_code=400, content=validation_error)
# 提取URL
extracted_url = UrlParser.get_url(text)
logger.info(f'extracted_url: {extracted_url}')
if not extracted_url:
logger.error('No valid URL found in text')
return JSONResponse(
status_code=400,
content=make_response(400, '未找到有效的视频链接', None, None, False)
)
# 获取重定向URL
redirect_url = WebFetcher.fetch_redirect_url(extracted_url)
logger.info(f'redirect_url: {redirect_url}')
# 如果重定向失败,直接使用原始URL
if not redirect_url:
redirect_url = extracted_url
logger.info(f'Using original URL: {redirect_url}')
platform = DOMAIN_TO_NAME.get(UrlParser.get_domain(redirect_url))
video_id = UrlParser.get_video_id(redirect_url)
real_url = UrlParser.extract_video_address(redirect_url)
logger.info(f'platform: {platform}, video_id: {video_id}, real_url: {real_url}')
if not platform:
logger.error(f'This link is not supported for extraction: {real_url}')
return JSONResponse(
status_code=400,
content=make_response(400, '该链接尚未支持提取', None, None, False)
)
title = cover_url = video_url = None
downloader = None
# 小红书平台特殊处理(重试机制)
if platform == '小红书':
max_attempts = 5
attempts = 0
while attempts < max_attempts:
downloader = DownloaderFactory.create_downloader(platform, real_url)
title = downloader.get_title_content()
video_url = downloader.get_real_video_url()
cover_url = downloader.get_cover_photo_url()
if video_url:
break
attempts += 1
logger.debug(f"Attempt {attempts} failed. Retrying...")
if not video_url:
logger.error("Failed to retrieve video URL after 5 attempts.")
else:
downloader = DownloaderFactory.create_downloader(platform, real_url)
title = downloader.get_title_content()
video_url = downloader.get_real_video_url()
cover_url = downloader.get_cover_photo_url()
# 转换为 HTTPS
updated_video_url = UrlParser.convert_to_https(video_url)
updated_cover_url = UrlParser.convert_to_https(cover_url)
data_dict = {
'video_id': video_id,
'platform': platform,
'title': title,
'video_url': updated_video_url,
'cover_url': updated_cover_url
}
# B站视频需要额外返回音频URL
if platform == '哔哩哔哩' and downloader and hasattr(downloader, 'get_audio_url'):
audio_url = downloader.get_audio_url()
if audio_url:
data_dict['audio_url'] = UrlParser.convert_to_https(audio_url)
logger.debug(f'{wx_open_id} {platform} Parse Success')
return JSONResponse(
status_code=200,
content=make_response(200, '成功', data_dict, None, True)
)
except Exception as e:
logger.error(f"Parse error: {e}")
import traceback
traceback.print_exc()
return JSONResponse(
status_code=500,
content=make_response(500, '功能太火爆啦,请稍后再试', None, None, False)
)
@app.post("/api/download")
async def download_video(
body: DownloadRequest,
x_timestamp: str = Header(default="", alias="X-Timestamp"),
x_gclt_text: str = Header(default="", alias="X-GCLT-Text"),
x_egct_text: str = Header(default="", alias="X-EGCT-Text"),
wx_open_id: str = Header(default="Guest", alias="WX-OPEN-ID"),
):
"""
获取视频下载链接
对于某些平台,需要服务器端下载并返回可访问的链接
"""
try:
request_video_url = body.video_url
request_video_id = body.video_id
# 验证请求
validation_error = validate_request_headers(x_timestamp, x_gclt_text, x_egct_text, request_video_url)
if validation_error:
return JSONResponse(status_code=400, content=validation_error)
# 判断视频链接的域名是否为小程序的合法域名
domain = UrlParser.get_domain(request_video_url)
logger.debug(f'Checking domain: {domain}')
if domain in MINI_PROGRAM_LEGAL_DOMAIN:
# 如果是,直接返回视频链接
logger.debug(f'{wx_open_id} 直接返回视频链接')
return JSONResponse(
status_code=200,
content=make_response(200, '成功', {'download_url': request_video_url}, None, True)
)
else:
# 如果不是,服务器端下载视频并保存
video_filename = f'{request_video_id}.mp4'
video_path = os.path.join(SAVE_VIDEO_PATH, video_filename)
# 如果 DOMAIN 未配置,使用本地测试地址
current_domain = DOMAIN or "http://localhost:5001"
if not os.path.exists(video_path):
logger.info(f"Starting server-side download for {request_video_url}")
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
'Referer': 'https://www.pearvideo.com/'
}
# 如果是梨视频,必须带 Referer
if "pearvideo.com" in request_video_url:
headers['Referer'] = 'https://www.pearvideo.com/'
# 创建带重试机制的session
session = requests.Session()
retries = Retry(
total=5,
backoff_factor=1,
status_forcelist=[500, 502, 503, 504],
allowed_methods=["GET"]
)
session.mount('http://', HTTPAdapter(max_retries=retries))
session.mount('https://', HTTPAdapter(max_retries=retries))
try:
response = session.get(request_video_url, headers=headers, stream=True, timeout=120)
response.raise_for_status()
except (RequestException, ConnectionError) as e:
logger.error(f'{wx_open_id} Failed to connect: {e}')
return JSONResponse(
status_code=200,
content=make_response(200, '服务器下载失败,返回原始链接', {'download_url': request_video_url}, None, True)
)
try:
# 保存视频到服务器
with open(video_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
except (ChunkedEncodingError, IOError) as e:
logger.error(f'{wx_open_id} Failed to save video: {e}')
# 删除可能不完整的文件
if os.path.exists(video_path):
os.remove(video_path)
return JSONResponse(
status_code=200,
content=make_response(200, '服务器下载失败,返回原始链接', {'download_url': request_video_url}, None, True)
)
# 返回视频的 URL
download_url = f'{current_domain}/static/videos/{video_filename}'
logger.debug(f'{wx_open_id} 返回视频地址: {download_url}')
return JSONResponse(
status_code=200,
content=make_response(200, '成功', {'download_url': download_url}, None, True)
)
except Exception as e:
logger.error(f"Download error: {e}")
import traceback
traceback.print_exc()
return JSONResponse(
status_code=500,
content=make_response(500, '功能太火爆啦,请稍后再试', None, None, False)
)
# ==================== 主程序入口 ====================
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"api:app",
host="0.0.0.0",
port=5001,
reload=True,
log_level="info"
)