feat: Add the ability to obtain direct file links

This commit is contained in:
shiyu
2025-08-27 12:23:26 +08:00
parent 202c2ed5af
commit d5d597a582
10 changed files with 322 additions and 64 deletions

View File

@@ -481,8 +481,12 @@ async def get_temp_link_secret_key() -> bytes:
async def generate_temp_link_token(path: str, expires_in: int = 3600) -> str:
"""为文件路径生成一个有时效的令牌"""
expiration_time = int(time.time() + expires_in)
"""为文件路径生成一个有时效的令牌。expires_in <= 0 表示永久"""
if expires_in <= 0:
expiration_time = "0"
else:
expiration_time = str(int(time.time() + expires_in))
message = f"{path}:{expiration_time}".encode('utf-8')
secret_key = await get_temp_link_secret_key()
signature = hmac.new(secret_key, message, hashlib.sha256).digest()
@@ -496,15 +500,16 @@ async def verify_temp_link_token(token: str) -> str:
try:
decoded_token = base64.urlsafe_b64decode(token).decode('utf-8')
path, expiration_time_str, signature_b64 = decoded_token.rsplit(':', 2)
expiration_time = int(expiration_time_str)
signature = base64.urlsafe_b64decode(signature_b64)
except (ValueError, TypeError, base64.binascii.Error):
raise HTTPException(status_code=400, detail="Invalid token format")
if time.time() > expiration_time:
raise HTTPException(status_code=410, detail="Link has expired")
if expiration_time_str != "0":
expiration_time = int(expiration_time_str)
if time.time() > expiration_time:
raise HTTPException(status_code=410, detail="Link has expired")
message = f"{path}:{expiration_time}".encode('utf-8')
message = f"{path}:{expiration_time_str}".encode('utf-8')
secret_key = await get_temp_link_secret_key()
expected_signature = hmac.new(secret_key, message, hashlib.sha256).digest()